OSDN Git Service

bb7c167ebe04308014bf15e44b98cc53cee40694
[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
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 "obstack.h"
34 #include "tree.h"
35 #include "intl.h"
36 #include "pointer-set.h"
37 #include "flags.h"
38 #include "c-common.h"
39 #include "cp-tree.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "except.h"
45 #include "toplev.h"
46 #include "rtl.h"
47 #include "timevar.h"
48 #include "tree-iterator.h"
49 #include "vecprim.h"
50
51 /* The type of functions taking a tree, and some additional data, and
52    returning an int.  */
53 typedef int (*tree_fn_t) (tree, void*);
54
55 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
56    instantiations have been deferred, either because their definitions
57    were not yet available, or because we were putting off doing the work.  */
58 struct GTY (()) pending_template {
59   struct pending_template *next;
60   struct tinst_level *tinst;
61 };
62
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
65
66 int processing_template_parmlist;
67 static int template_header_count;
68
69 static GTY(()) tree saved_trees;
70 static VEC(int,heap) *inline_parm_levels;
71
72 static GTY(()) struct tinst_level *current_tinst_level;
73
74 static GTY(()) tree saved_access_scope;
75
76 /* Live only within one (recursive) call to tsubst_expr.  We use
77    this to pass the statement expression node from the STMT_EXPR
78    to the EXPR_STMT that is its result.  */
79 static tree cur_stmt_expr;
80
81 /* A map from local variable declarations in the body of the template
82    presently being instantiated to the corresponding instantiated
83    local variables.  */
84 static htab_t local_specializations;
85
86 typedef struct GTY(()) spec_entry
87 {
88   tree tmpl;
89   tree args;
90   tree spec;
91 } spec_entry;
92
93 static GTY ((param_is (spec_entry)))
94   htab_t decl_specializations;
95
96 static GTY ((param_is (spec_entry)))
97   htab_t type_specializations;
98
99 /* Contains canonical template parameter types. The vector is indexed by
100    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
101    TREE_LIST, whose TREE_VALUEs contain the canonical template
102    parameters of various types and levels.  */
103 static GTY(()) VEC(tree,gc) *canonical_template_parms;
104
105 #define UNIFY_ALLOW_NONE 0
106 #define UNIFY_ALLOW_MORE_CV_QUAL 1
107 #define UNIFY_ALLOW_LESS_CV_QUAL 2
108 #define UNIFY_ALLOW_DERIVED 4
109 #define UNIFY_ALLOW_INTEGER 8
110 #define UNIFY_ALLOW_OUTER_LEVEL 16
111 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
112 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
113
114 static void push_access_scope (tree);
115 static void pop_access_scope (tree);
116 static bool resolve_overloaded_unification (tree, tree, tree, tree,
117                                             unification_kind_t, int);
118 static int try_one_overload (tree, tree, tree, tree, tree,
119                              unification_kind_t, int, bool);
120 static int unify (tree, tree, tree, tree, int);
121 static void add_pending_template (tree);
122 static int push_tinst_level (tree);
123 static void pop_tinst_level (void);
124 static tree reopen_tinst_level (struct tinst_level *);
125 static tree tsubst_initializer_list (tree, tree);
126 static tree get_class_bindings (tree, tree, tree);
127 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
128                                    bool, bool);
129 static void tsubst_enum (tree, tree, tree);
130 static tree add_to_template_args (tree, tree);
131 static tree add_outermost_template_args (tree, tree);
132 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
133 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
134                                              tree);
135 static int type_unification_real (tree, tree, tree, const tree *,
136                                   unsigned int, int, unification_kind_t, int);
137 static void note_template_header (int);
138 static tree convert_nontype_argument_function (tree, tree);
139 static tree convert_nontype_argument (tree, tree);
140 static tree convert_template_argument (tree, tree, tree,
141                                        tsubst_flags_t, int, tree);
142 static int for_each_template_parm (tree, tree_fn_t, void*,
143                                    struct pointer_set_t*, bool);
144 static tree expand_template_argument_pack (tree);
145 static tree build_template_parm_index (int, int, int, tree, tree);
146 static bool inline_needs_template_parms (tree);
147 static void push_inline_template_parms_recursive (tree, int);
148 static tree retrieve_local_specialization (tree);
149 static void register_local_specialization (tree, tree);
150 static hashval_t hash_specialization (const void *p);
151 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
152 static int mark_template_parm (tree, void *);
153 static int template_parm_this_level_p (tree, void *);
154 static tree tsubst_friend_function (tree, tree);
155 static tree tsubst_friend_class (tree, tree);
156 static int can_complete_type_without_circularity (tree);
157 static tree get_bindings (tree, tree, tree, bool);
158 static int template_decl_level (tree);
159 static int check_cv_quals_for_unify (int, tree, tree);
160 static void template_parm_level_and_index (tree, int*, int*);
161 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
162 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
163 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
164 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
165 static void regenerate_decl_from_template (tree, tree);
166 static tree most_specialized_class (tree, tree);
167 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
168 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
169 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
170 static bool check_specialization_scope (void);
171 static tree process_partial_specialization (tree);
172 static void set_current_access_from_decl (tree);
173 static tree get_template_base (tree, tree, tree, tree);
174 static tree try_class_unification (tree, tree, tree, tree);
175 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
176                                            tree, tree);
177 static bool template_template_parm_bindings_ok_p (tree, tree);
178 static int template_args_equal (tree, tree);
179 static void tsubst_default_arguments (tree);
180 static tree for_each_template_parm_r (tree *, int *, void *);
181 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
182 static void copy_default_args_to_explicit_spec (tree);
183 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
184 static int eq_local_specializations (const void *, const void *);
185 static bool dependent_template_arg_p (tree);
186 static bool any_template_arguments_need_structural_equality_p (tree);
187 static bool dependent_type_p_r (tree);
188 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
189 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
191 static tree tsubst_decl (tree, tree, tsubst_flags_t);
192 static void perform_typedefs_access_check (tree tmpl, tree targs);
193 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
194                                                         location_t);
195 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
196 static tree listify (tree);
197 static tree listify_autos (tree, tree);
198
199 /* Make the current scope suitable for access checking when we are
200    processing T.  T can be FUNCTION_DECL for instantiated function
201    template, or VAR_DECL for static member variable (need by
202    instantiate_decl).  */
203
204 static void
205 push_access_scope (tree t)
206 {
207   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
208               || TREE_CODE (t) == VAR_DECL);
209
210   if (DECL_FRIEND_CONTEXT (t))
211     push_nested_class (DECL_FRIEND_CONTEXT (t));
212   else if (DECL_CLASS_SCOPE_P (t))
213     push_nested_class (DECL_CONTEXT (t));
214   else
215     push_to_top_level ();
216
217   if (TREE_CODE (t) == FUNCTION_DECL)
218     {
219       saved_access_scope = tree_cons
220         (NULL_TREE, current_function_decl, saved_access_scope);
221       current_function_decl = t;
222     }
223 }
224
225 /* Restore the scope set up by push_access_scope.  T is the node we
226    are processing.  */
227
228 static void
229 pop_access_scope (tree t)
230 {
231   if (TREE_CODE (t) == FUNCTION_DECL)
232     {
233       current_function_decl = TREE_VALUE (saved_access_scope);
234       saved_access_scope = TREE_CHAIN (saved_access_scope);
235     }
236
237   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
238     pop_nested_class ();
239   else
240     pop_from_top_level ();
241 }
242
243 /* Do any processing required when DECL (a member template
244    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
245    to DECL, unless it is a specialization, in which case the DECL
246    itself is returned.  */
247
248 tree
249 finish_member_template_decl (tree decl)
250 {
251   if (decl == error_mark_node)
252     return error_mark_node;
253
254   gcc_assert (DECL_P (decl));
255
256   if (TREE_CODE (decl) == TYPE_DECL)
257     {
258       tree type;
259
260       type = TREE_TYPE (decl);
261       if (type == error_mark_node)
262         return error_mark_node;
263       if (MAYBE_CLASS_TYPE_P (type)
264           && CLASSTYPE_TEMPLATE_INFO (type)
265           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
266         {
267           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
268           check_member_template (tmpl);
269           return tmpl;
270         }
271       return NULL_TREE;
272     }
273   else if (TREE_CODE (decl) == FIELD_DECL)
274     error ("data member %qD cannot be a member template", decl);
275   else if (DECL_TEMPLATE_INFO (decl))
276     {
277       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
278         {
279           check_member_template (DECL_TI_TEMPLATE (decl));
280           return DECL_TI_TEMPLATE (decl);
281         }
282       else
283         return decl;
284     }
285   else
286     error ("invalid member template declaration %qD", decl);
287
288   return error_mark_node;
289 }
290
291 /* Create a template info node.  */
292
293 tree
294 build_template_info (tree template_decl, tree template_args)
295 {
296   tree result = make_node (TEMPLATE_INFO);
297   TI_TEMPLATE (result) = template_decl;
298   TI_ARGS (result) = template_args;
299   return result;
300 }
301
302 /* Return the template info node corresponding to T, whatever T is.  */
303
304 tree
305 get_template_info (const_tree t)
306 {
307   tree tinfo = NULL_TREE;
308
309   if (!t || t == error_mark_node)
310     return NULL;
311
312   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
313     tinfo = DECL_TEMPLATE_INFO (t);
314
315   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
316     t = TREE_TYPE (t);
317
318   if (TAGGED_TYPE_P (t))
319     tinfo = TYPE_TEMPLATE_INFO (t);
320
321   return tinfo;
322 }
323
324 /* Returns the template nesting level of the indicated class TYPE.
325
326    For example, in:
327      template <class T>
328      struct A
329      {
330        template <class U>
331        struct B {};
332      };
333
334    A<T>::B<U> has depth two, while A<T> has depth one.
335    Both A<T>::B<int> and A<int>::B<U> have depth one, if
336    they are instantiations, not specializations.
337
338    This function is guaranteed to return 0 if passed NULL_TREE so
339    that, for example, `template_class_depth (current_class_type)' is
340    always safe.  */
341
342 int
343 template_class_depth (tree type)
344 {
345   int depth;
346
347   for (depth = 0;
348        type && TREE_CODE (type) != NAMESPACE_DECL;
349        type = (TREE_CODE (type) == FUNCTION_DECL)
350          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
351     {
352       tree tinfo = get_template_info (type);
353
354       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
355           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
356         ++depth;
357     }
358
359   return depth;
360 }
361
362 /* Subroutine of maybe_begin_member_template_processing.
363    Returns true if processing DECL needs us to push template parms.  */
364
365 static bool
366 inline_needs_template_parms (tree decl)
367 {
368   if (! DECL_TEMPLATE_INFO (decl))
369     return false;
370
371   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
372           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
373 }
374
375 /* Subroutine of maybe_begin_member_template_processing.
376    Push the template parms in PARMS, starting from LEVELS steps into the
377    chain, and ending at the beginning, since template parms are listed
378    innermost first.  */
379
380 static void
381 push_inline_template_parms_recursive (tree parmlist, int levels)
382 {
383   tree parms = TREE_VALUE (parmlist);
384   int i;
385
386   if (levels > 1)
387     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
388
389   ++processing_template_decl;
390   current_template_parms
391     = tree_cons (size_int (processing_template_decl),
392                  parms, current_template_parms);
393   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
394
395   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
396                NULL);
397   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
398     {
399       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
400
401       if (parm == error_mark_node)
402         continue;
403
404       gcc_assert (DECL_P (parm));
405
406       switch (TREE_CODE (parm))
407         {
408         case TYPE_DECL:
409         case TEMPLATE_DECL:
410           pushdecl (parm);
411           break;
412
413         case PARM_DECL:
414           {
415             /* Make a CONST_DECL as is done in process_template_parm.
416                It is ugly that we recreate this here; the original
417                version built in process_template_parm is no longer
418                available.  */
419             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
420                                     CONST_DECL, DECL_NAME (parm),
421                                     TREE_TYPE (parm));
422             DECL_ARTIFICIAL (decl) = 1;
423             TREE_CONSTANT (decl) = 1;
424             TREE_READONLY (decl) = 1;
425             DECL_INITIAL (decl) = DECL_INITIAL (parm);
426             SET_DECL_TEMPLATE_PARM_P (decl);
427             pushdecl (decl);
428           }
429           break;
430
431         default:
432           gcc_unreachable ();
433         }
434     }
435 }
436
437 /* Restore the template parameter context for a member template or
438    a friend template defined in a class definition.  */
439
440 void
441 maybe_begin_member_template_processing (tree decl)
442 {
443   tree parms;
444   int levels = 0;
445
446   if (inline_needs_template_parms (decl))
447     {
448       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
449       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
450
451       if (DECL_TEMPLATE_SPECIALIZATION (decl))
452         {
453           --levels;
454           parms = TREE_CHAIN (parms);
455         }
456
457       push_inline_template_parms_recursive (parms, levels);
458     }
459
460   /* Remember how many levels of template parameters we pushed so that
461      we can pop them later.  */
462   VEC_safe_push (int, heap, inline_parm_levels, levels);
463 }
464
465 /* Undo the effects of maybe_begin_member_template_processing.  */
466
467 void
468 maybe_end_member_template_processing (void)
469 {
470   int i;
471   int last;
472
473   if (VEC_length (int, inline_parm_levels) == 0)
474     return;
475
476   last = VEC_pop (int, inline_parm_levels);
477   for (i = 0; i < last; ++i)
478     {
479       --processing_template_decl;
480       current_template_parms = TREE_CHAIN (current_template_parms);
481       poplevel (0, 0, 0);
482     }
483 }
484
485 /* Return a new template argument vector which contains all of ARGS,
486    but has as its innermost set of arguments the EXTRA_ARGS.  */
487
488 static tree
489 add_to_template_args (tree args, tree extra_args)
490 {
491   tree new_args;
492   int extra_depth;
493   int i;
494   int j;
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_NEW (spec_entry);
891                   **slot = elt;
892                 }
893               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (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_NEW (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     default:
1557       switch (tclass)
1558         {
1559         case tcc_type:
1560           if (TYPE_CANONICAL (arg))
1561             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1562                                           val);
1563           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1564             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1565           /* Otherwise just compare the types during lookup.  */
1566           return val;
1567
1568         case tcc_declaration:
1569         case tcc_constant:
1570           return iterative_hash_expr (arg, val);
1571
1572         default:
1573           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1574           {
1575             unsigned n = TREE_OPERAND_LENGTH (arg);
1576             for (i = 0; i < n; ++i)
1577               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1578             return val;
1579           }
1580         }
1581     }
1582   gcc_unreachable ();
1583   return 0;
1584 }
1585
1586 /* Unregister the specialization SPEC as a specialization of TMPL.
1587    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1588    if the SPEC was listed as a specialization of TMPL.
1589
1590    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1591
1592 bool
1593 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1594 {
1595   spec_entry **slot;
1596   spec_entry elt;
1597
1598   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1599   elt.args = TI_ARGS (tinfo);
1600   elt.spec = NULL_TREE;
1601
1602   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1603   if (*slot)
1604     {
1605       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1606       gcc_assert (new_spec != NULL_TREE);
1607       (*slot)->spec = new_spec;
1608       return 1;
1609     }
1610
1611   return 0;
1612 }
1613
1614 /* Compare an entry in the local specializations hash table P1 (which
1615    is really a pointer to a TREE_LIST) with P2 (which is really a
1616    DECL).  */
1617
1618 static int
1619 eq_local_specializations (const void *p1, const void *p2)
1620 {
1621   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1622 }
1623
1624 /* Hash P1, an entry in the local specializations table.  */
1625
1626 static hashval_t
1627 hash_local_specialization (const void* p1)
1628 {
1629   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1630 }
1631
1632 /* Like register_specialization, but for local declarations.  We are
1633    registering SPEC, an instantiation of TMPL.  */
1634
1635 static void
1636 register_local_specialization (tree spec, tree tmpl)
1637 {
1638   void **slot;
1639
1640   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1641                                    htab_hash_pointer (tmpl), INSERT);
1642   *slot = build_tree_list (spec, tmpl);
1643 }
1644
1645 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1646    specialized class.  */
1647
1648 bool
1649 explicit_class_specialization_p (tree type)
1650 {
1651   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1652     return false;
1653   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1654 }
1655
1656 /* Print the list of functions at FNS, going through all the overloads
1657    for each element of the list.  Alternatively, FNS can not be a
1658    TREE_LIST, in which case it will be printed together with all the
1659    overloads.
1660
1661    MORE and *STR should respectively be FALSE and NULL when the function
1662    is called from the outside.  They are used internally on recursive
1663    calls.  print_candidates manages the two parameters and leaves NULL
1664    in *STR when it ends.  */
1665
1666 static void
1667 print_candidates_1 (tree fns, bool more, const char **str)
1668 {
1669   tree fn, fn2;
1670   char *spaces = NULL;
1671
1672   for (fn = fns; fn; fn = OVL_NEXT (fn))
1673     if (TREE_CODE (fn) == TREE_LIST)
1674       {
1675         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1676         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1677           print_candidates_1 (TREE_VALUE (fn2),
1678                               TREE_CHAIN (fn2) || more, str);
1679       }
1680     else
1681       {
1682         if (!*str)
1683           {
1684             /* Pick the prefix string.  */
1685             if (!more && !OVL_NEXT (fns))
1686               {
1687                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1688                 continue;
1689               }
1690
1691             *str = _("candidates are:");
1692             spaces = get_spaces (*str);
1693           }
1694         error ("%s %+#D", *str, OVL_CURRENT (fn));
1695         *str = spaces ? spaces : *str;
1696       }
1697
1698   if (!more)
1699     {
1700       free (spaces);
1701       *str = NULL;
1702     }
1703 }
1704
1705 /* Print the list of candidate FNS in an error message.  */
1706
1707 void
1708 print_candidates (tree fns)
1709 {
1710   const char *str = NULL;
1711   print_candidates_1 (fns, false, &str);
1712   gcc_assert (str == NULL);
1713 }
1714
1715 /* Returns the template (one of the functions given by TEMPLATE_ID)
1716    which can be specialized to match the indicated DECL with the
1717    explicit template args given in TEMPLATE_ID.  The DECL may be
1718    NULL_TREE if none is available.  In that case, the functions in
1719    TEMPLATE_ID are non-members.
1720
1721    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1722    specialization of a member template.
1723
1724    The TEMPLATE_COUNT is the number of references to qualifying
1725    template classes that appeared in the name of the function. See
1726    check_explicit_specialization for a more accurate description.
1727
1728    TSK indicates what kind of template declaration (if any) is being
1729    declared.  TSK_TEMPLATE indicates that the declaration given by
1730    DECL, though a FUNCTION_DECL, has template parameters, and is
1731    therefore a template function.
1732
1733    The template args (those explicitly specified and those deduced)
1734    are output in a newly created vector *TARGS_OUT.
1735
1736    If it is impossible to determine the result, an error message is
1737    issued.  The error_mark_node is returned to indicate failure.  */
1738
1739 static tree
1740 determine_specialization (tree template_id,
1741                           tree decl,
1742                           tree* targs_out,
1743                           int need_member_template,
1744                           int template_count,
1745                           tmpl_spec_kind tsk)
1746 {
1747   tree fns;
1748   tree targs;
1749   tree explicit_targs;
1750   tree candidates = NULL_TREE;
1751   /* A TREE_LIST of templates of which DECL may be a specialization.
1752      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1753      corresponding TREE_PURPOSE is the set of template arguments that,
1754      when used to instantiate the template, would produce a function
1755      with the signature of DECL.  */
1756   tree templates = NULL_TREE;
1757   int header_count;
1758   struct cp_binding_level *b;
1759
1760   *targs_out = NULL_TREE;
1761
1762   if (template_id == error_mark_node || decl == error_mark_node)
1763     return error_mark_node;
1764
1765   fns = TREE_OPERAND (template_id, 0);
1766   explicit_targs = TREE_OPERAND (template_id, 1);
1767
1768   if (fns == error_mark_node)
1769     return error_mark_node;
1770
1771   /* Check for baselinks.  */
1772   if (BASELINK_P (fns))
1773     fns = BASELINK_FUNCTIONS (fns);
1774
1775   if (!is_overloaded_fn (fns))
1776     {
1777       error ("%qD is not a function template", fns);
1778       return error_mark_node;
1779     }
1780
1781   /* Count the number of template headers specified for this
1782      specialization.  */
1783   header_count = 0;
1784   for (b = current_binding_level;
1785        b->kind == sk_template_parms;
1786        b = b->level_chain)
1787     ++header_count;
1788
1789   for (; fns; fns = OVL_NEXT (fns))
1790     {
1791       tree fn = OVL_CURRENT (fns);
1792
1793       if (TREE_CODE (fn) == TEMPLATE_DECL)
1794         {
1795           tree decl_arg_types;
1796           tree fn_arg_types;
1797
1798           /* In case of explicit specialization, we need to check if
1799              the number of template headers appearing in the specialization
1800              is correct. This is usually done in check_explicit_specialization,
1801              but the check done there cannot be exhaustive when specializing
1802              member functions. Consider the following code:
1803
1804              template <> void A<int>::f(int);
1805              template <> template <> void A<int>::f(int);
1806
1807              Assuming that A<int> is not itself an explicit specialization
1808              already, the first line specializes "f" which is a non-template
1809              member function, whilst the second line specializes "f" which
1810              is a template member function. So both lines are syntactically
1811              correct, and check_explicit_specialization does not reject
1812              them.
1813
1814              Here, we can do better, as we are matching the specialization
1815              against the declarations. We count the number of template
1816              headers, and we check if they match TEMPLATE_COUNT + 1
1817              (TEMPLATE_COUNT is the number of qualifying template classes,
1818              plus there must be another header for the member template
1819              itself).
1820
1821              Notice that if header_count is zero, this is not a
1822              specialization but rather a template instantiation, so there
1823              is no check we can perform here.  */
1824           if (header_count && header_count != template_count + 1)
1825             continue;
1826
1827           /* Check that the number of template arguments at the
1828              innermost level for DECL is the same as for FN.  */
1829           if (current_binding_level->kind == sk_template_parms
1830               && !current_binding_level->explicit_spec_p
1831               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1832                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1833                                       (current_template_parms))))
1834             continue;
1835
1836           /* DECL might be a specialization of FN.  */
1837           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1838           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1839
1840           /* For a non-static member function, we need to make sure
1841              that the const qualification is the same.  Since
1842              get_bindings does not try to merge the "this" parameter,
1843              we must do the comparison explicitly.  */
1844           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1845               && !same_type_p (TREE_VALUE (fn_arg_types),
1846                                TREE_VALUE (decl_arg_types)))
1847             continue;
1848
1849           /* Skip the "this" parameter and, for constructors of
1850              classes with virtual bases, the VTT parameter.  A
1851              full specialization of a constructor will have a VTT
1852              parameter, but a template never will.  */ 
1853           decl_arg_types 
1854             = skip_artificial_parms_for (decl, decl_arg_types);
1855           fn_arg_types 
1856             = skip_artificial_parms_for (fn, fn_arg_types);
1857
1858           /* Check that the number of function parameters matches.
1859              For example,
1860                template <class T> void f(int i = 0);
1861                template <> void f<int>();
1862              The specialization f<int> is invalid but is not caught
1863              by get_bindings below.  */
1864           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1865             continue;
1866
1867           /* Function templates cannot be specializations; there are
1868              no partial specializations of functions.  Therefore, if
1869              the type of DECL does not match FN, there is no
1870              match.  */
1871           if (tsk == tsk_template)
1872             {
1873               if (compparms (fn_arg_types, decl_arg_types))
1874                 candidates = tree_cons (NULL_TREE, fn, candidates);
1875               continue;
1876             }
1877
1878           /* See whether this function might be a specialization of this
1879              template.  */
1880           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1881
1882           if (!targs)
1883             /* We cannot deduce template arguments that when used to
1884                specialize TMPL will produce DECL.  */
1885             continue;
1886
1887           /* Save this template, and the arguments deduced.  */
1888           templates = tree_cons (targs, fn, templates);
1889         }
1890       else if (need_member_template)
1891         /* FN is an ordinary member function, and we need a
1892            specialization of a member template.  */
1893         ;
1894       else if (TREE_CODE (fn) != FUNCTION_DECL)
1895         /* We can get IDENTIFIER_NODEs here in certain erroneous
1896            cases.  */
1897         ;
1898       else if (!DECL_FUNCTION_MEMBER_P (fn))
1899         /* This is just an ordinary non-member function.  Nothing can
1900            be a specialization of that.  */
1901         ;
1902       else if (DECL_ARTIFICIAL (fn))
1903         /* Cannot specialize functions that are created implicitly.  */
1904         ;
1905       else
1906         {
1907           tree decl_arg_types;
1908
1909           /* This is an ordinary member function.  However, since
1910              we're here, we can assume it's enclosing class is a
1911              template class.  For example,
1912
1913                template <typename T> struct S { void f(); };
1914                template <> void S<int>::f() {}
1915
1916              Here, S<int>::f is a non-template, but S<int> is a
1917              template class.  If FN has the same type as DECL, we
1918              might be in business.  */
1919
1920           if (!DECL_TEMPLATE_INFO (fn))
1921             /* Its enclosing class is an explicit specialization
1922                of a template class.  This is not a candidate.  */
1923             continue;
1924
1925           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1926                             TREE_TYPE (TREE_TYPE (fn))))
1927             /* The return types differ.  */
1928             continue;
1929
1930           /* Adjust the type of DECL in case FN is a static member.  */
1931           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1932           if (DECL_STATIC_FUNCTION_P (fn)
1933               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1934             decl_arg_types = TREE_CHAIN (decl_arg_types);
1935
1936           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1937                          decl_arg_types))
1938             /* They match!  */
1939             candidates = tree_cons (NULL_TREE, fn, candidates);
1940         }
1941     }
1942
1943   if (templates && TREE_CHAIN (templates))
1944     {
1945       /* We have:
1946
1947            [temp.expl.spec]
1948
1949            It is possible for a specialization with a given function
1950            signature to be instantiated from more than one function
1951            template.  In such cases, explicit specification of the
1952            template arguments must be used to uniquely identify the
1953            function template specialization being specialized.
1954
1955          Note that here, there's no suggestion that we're supposed to
1956          determine which of the candidate templates is most
1957          specialized.  However, we, also have:
1958
1959            [temp.func.order]
1960
1961            Partial ordering of overloaded function template
1962            declarations is used in the following contexts to select
1963            the function template to which a function template
1964            specialization refers:
1965
1966            -- when an explicit specialization refers to a function
1967               template.
1968
1969          So, we do use the partial ordering rules, at least for now.
1970          This extension can only serve to make invalid programs valid,
1971          so it's safe.  And, there is strong anecdotal evidence that
1972          the committee intended the partial ordering rules to apply;
1973          the EDG front end has that behavior, and John Spicer claims
1974          that the committee simply forgot to delete the wording in
1975          [temp.expl.spec].  */
1976       tree tmpl = most_specialized_instantiation (templates);
1977       if (tmpl != error_mark_node)
1978         {
1979           templates = tmpl;
1980           TREE_CHAIN (templates) = NULL_TREE;
1981         }
1982     }
1983
1984   if (templates == NULL_TREE && candidates == NULL_TREE)
1985     {
1986       error ("template-id %qD for %q+D does not match any template "
1987              "declaration", template_id, decl);
1988       if (header_count && header_count != template_count + 1)
1989         inform (input_location, "saw %d %<template<>%>, need %d for "
1990                 "specializing a member function template",
1991                 header_count, template_count + 1);
1992       return error_mark_node;
1993     }
1994   else if ((templates && TREE_CHAIN (templates))
1995            || (candidates && TREE_CHAIN (candidates))
1996            || (templates && candidates))
1997     {
1998       error ("ambiguous template specialization %qD for %q+D",
1999              template_id, decl);
2000       candidates = chainon (candidates, templates);
2001       print_candidates (candidates);
2002       return error_mark_node;
2003     }
2004
2005   /* We have one, and exactly one, match.  */
2006   if (candidates)
2007     {
2008       tree fn = TREE_VALUE (candidates);
2009       *targs_out = copy_node (DECL_TI_ARGS (fn));
2010       /* DECL is a re-declaration or partial instantiation of a template
2011          function.  */
2012       if (TREE_CODE (fn) == TEMPLATE_DECL)
2013         return fn;
2014       /* It was a specialization of an ordinary member function in a
2015          template class.  */
2016       return DECL_TI_TEMPLATE (fn);
2017     }
2018
2019   /* It was a specialization of a template.  */
2020   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2021   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2022     {
2023       *targs_out = copy_node (targs);
2024       SET_TMPL_ARGS_LEVEL (*targs_out,
2025                            TMPL_ARGS_DEPTH (*targs_out),
2026                            TREE_PURPOSE (templates));
2027     }
2028   else
2029     *targs_out = TREE_PURPOSE (templates);
2030   return TREE_VALUE (templates);
2031 }
2032
2033 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2034    but with the default argument values filled in from those in the
2035    TMPL_TYPES.  */
2036
2037 static tree
2038 copy_default_args_to_explicit_spec_1 (tree spec_types,
2039                                       tree tmpl_types)
2040 {
2041   tree new_spec_types;
2042
2043   if (!spec_types)
2044     return NULL_TREE;
2045
2046   if (spec_types == void_list_node)
2047     return void_list_node;
2048
2049   /* Substitute into the rest of the list.  */
2050   new_spec_types =
2051     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2052                                           TREE_CHAIN (tmpl_types));
2053
2054   /* Add the default argument for this parameter.  */
2055   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2056                          TREE_VALUE (spec_types),
2057                          new_spec_types);
2058 }
2059
2060 /* DECL is an explicit specialization.  Replicate default arguments
2061    from the template it specializes.  (That way, code like:
2062
2063      template <class T> void f(T = 3);
2064      template <> void f(double);
2065      void g () { f (); }
2066
2067    works, as required.)  An alternative approach would be to look up
2068    the correct default arguments at the call-site, but this approach
2069    is consistent with how implicit instantiations are handled.  */
2070
2071 static void
2072 copy_default_args_to_explicit_spec (tree decl)
2073 {
2074   tree tmpl;
2075   tree spec_types;
2076   tree tmpl_types;
2077   tree new_spec_types;
2078   tree old_type;
2079   tree new_type;
2080   tree t;
2081   tree object_type = NULL_TREE;
2082   tree in_charge = NULL_TREE;
2083   tree vtt = NULL_TREE;
2084
2085   /* See if there's anything we need to do.  */
2086   tmpl = DECL_TI_TEMPLATE (decl);
2087   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2088   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2089     if (TREE_PURPOSE (t))
2090       break;
2091   if (!t)
2092     return;
2093
2094   old_type = TREE_TYPE (decl);
2095   spec_types = TYPE_ARG_TYPES (old_type);
2096
2097   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2098     {
2099       /* Remove the this pointer, but remember the object's type for
2100          CV quals.  */
2101       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2102       spec_types = TREE_CHAIN (spec_types);
2103       tmpl_types = TREE_CHAIN (tmpl_types);
2104
2105       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2106         {
2107           /* DECL may contain more parameters than TMPL due to the extra
2108              in-charge parameter in constructors and destructors.  */
2109           in_charge = spec_types;
2110           spec_types = TREE_CHAIN (spec_types);
2111         }
2112       if (DECL_HAS_VTT_PARM_P (decl))
2113         {
2114           vtt = spec_types;
2115           spec_types = TREE_CHAIN (spec_types);
2116         }
2117     }
2118
2119   /* Compute the merged default arguments.  */
2120   new_spec_types =
2121     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2122
2123   /* Compute the new FUNCTION_TYPE.  */
2124   if (object_type)
2125     {
2126       if (vtt)
2127         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2128                                          TREE_VALUE (vtt),
2129                                          new_spec_types);
2130
2131       if (in_charge)
2132         /* Put the in-charge parameter back.  */
2133         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2134                                          TREE_VALUE (in_charge),
2135                                          new_spec_types);
2136
2137       new_type = build_method_type_directly (object_type,
2138                                              TREE_TYPE (old_type),
2139                                              new_spec_types);
2140     }
2141   else
2142     new_type = build_function_type (TREE_TYPE (old_type),
2143                                     new_spec_types);
2144   new_type = cp_build_type_attribute_variant (new_type,
2145                                               TYPE_ATTRIBUTES (old_type));
2146   new_type = build_exception_variant (new_type,
2147                                       TYPE_RAISES_EXCEPTIONS (old_type));
2148   TREE_TYPE (decl) = new_type;
2149 }
2150
2151 /* Check to see if the function just declared, as indicated in
2152    DECLARATOR, and in DECL, is a specialization of a function
2153    template.  We may also discover that the declaration is an explicit
2154    instantiation at this point.
2155
2156    Returns DECL, or an equivalent declaration that should be used
2157    instead if all goes well.  Issues an error message if something is
2158    amiss.  Returns error_mark_node if the error is not easily
2159    recoverable.
2160
2161    FLAGS is a bitmask consisting of the following flags:
2162
2163    2: The function has a definition.
2164    4: The function is a friend.
2165
2166    The TEMPLATE_COUNT is the number of references to qualifying
2167    template classes that appeared in the name of the function.  For
2168    example, in
2169
2170      template <class T> struct S { void f(); };
2171      void S<int>::f();
2172
2173    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2174    classes are not counted in the TEMPLATE_COUNT, so that in
2175
2176      template <class T> struct S {};
2177      template <> struct S<int> { void f(); }
2178      template <> void S<int>::f();
2179
2180    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2181    invalid; there should be no template <>.)
2182
2183    If the function is a specialization, it is marked as such via
2184    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2185    is set up correctly, and it is added to the list of specializations
2186    for that template.  */
2187
2188 tree
2189 check_explicit_specialization (tree declarator,
2190                                tree decl,
2191                                int template_count,
2192                                int flags)
2193 {
2194   int have_def = flags & 2;
2195   int is_friend = flags & 4;
2196   int specialization = 0;
2197   int explicit_instantiation = 0;
2198   int member_specialization = 0;
2199   tree ctype = DECL_CLASS_CONTEXT (decl);
2200   tree dname = DECL_NAME (decl);
2201   tmpl_spec_kind tsk;
2202
2203   if (is_friend)
2204     {
2205       if (!processing_specialization)
2206         tsk = tsk_none;
2207       else
2208         tsk = tsk_excessive_parms;
2209     }
2210   else
2211     tsk = current_tmpl_spec_kind (template_count);
2212
2213   switch (tsk)
2214     {
2215     case tsk_none:
2216       if (processing_specialization)
2217         {
2218           specialization = 1;
2219           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2220         }
2221       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2222         {
2223           if (is_friend)
2224             /* This could be something like:
2225
2226                template <class T> void f(T);
2227                class S { friend void f<>(int); }  */
2228             specialization = 1;
2229           else
2230             {
2231               /* This case handles bogus declarations like template <>
2232                  template <class T> void f<int>(); */
2233
2234               error ("template-id %qD in declaration of primary template",
2235                      declarator);
2236               return decl;
2237             }
2238         }
2239       break;
2240
2241     case tsk_invalid_member_spec:
2242       /* The error has already been reported in
2243          check_specialization_scope.  */
2244       return error_mark_node;
2245
2246     case tsk_invalid_expl_inst:
2247       error ("template parameter list used in explicit instantiation");
2248
2249       /* Fall through.  */
2250
2251     case tsk_expl_inst:
2252       if (have_def)
2253         error ("definition provided for explicit instantiation");
2254
2255       explicit_instantiation = 1;
2256       break;
2257
2258     case tsk_excessive_parms:
2259     case tsk_insufficient_parms:
2260       if (tsk == tsk_excessive_parms)
2261         error ("too many template parameter lists in declaration of %qD",
2262                decl);
2263       else if (template_header_count)
2264         error("too few template parameter lists in declaration of %qD", decl);
2265       else
2266         error("explicit specialization of %qD must be introduced by "
2267               "%<template <>%>", decl);
2268
2269       /* Fall through.  */
2270     case tsk_expl_spec:
2271       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2272       if (ctype)
2273         member_specialization = 1;
2274       else
2275         specialization = 1;
2276       break;
2277
2278     case tsk_template:
2279       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2280         {
2281           /* This case handles bogus declarations like template <>
2282              template <class T> void f<int>(); */
2283
2284           if (uses_template_parms (declarator))
2285             error ("function template partial specialization %qD "
2286                    "is not allowed", declarator);
2287           else
2288             error ("template-id %qD in declaration of primary template",
2289                    declarator);
2290           return decl;
2291         }
2292
2293       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2294         /* This is a specialization of a member template, without
2295            specialization the containing class.  Something like:
2296
2297              template <class T> struct S {
2298                template <class U> void f (U);
2299              };
2300              template <> template <class U> void S<int>::f(U) {}
2301
2302            That's a specialization -- but of the entire template.  */
2303         specialization = 1;
2304       break;
2305
2306     default:
2307       gcc_unreachable ();
2308     }
2309
2310   if (specialization || member_specialization)
2311     {
2312       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2313       for (; t; t = TREE_CHAIN (t))
2314         if (TREE_PURPOSE (t))
2315           {
2316             permerror (input_location, 
2317                        "default argument specified in explicit specialization");
2318             break;
2319           }
2320     }
2321
2322   if (specialization || member_specialization || explicit_instantiation)
2323     {
2324       tree tmpl = NULL_TREE;
2325       tree targs = NULL_TREE;
2326
2327       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2328       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2329         {
2330           tree fns;
2331
2332           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2333           if (ctype)
2334             fns = dname;
2335           else
2336             {
2337               /* If there is no class context, the explicit instantiation
2338                  must be at namespace scope.  */
2339               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2340
2341               /* Find the namespace binding, using the declaration
2342                  context.  */
2343               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2344                                            false, true);
2345               if (fns == error_mark_node || !is_overloaded_fn (fns))
2346                 {
2347                   error ("%qD is not a template function", dname);
2348                   fns = error_mark_node;
2349                 }
2350               else
2351                 {
2352                   tree fn = OVL_CURRENT (fns);
2353                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2354                                                 CP_DECL_CONTEXT (fn)))
2355                     error ("%qD is not declared in %qD",
2356                            decl, current_namespace);
2357                 }
2358             }
2359
2360           declarator = lookup_template_function (fns, NULL_TREE);
2361         }
2362
2363       if (declarator == error_mark_node)
2364         return error_mark_node;
2365
2366       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2367         {
2368           if (!explicit_instantiation)
2369             /* A specialization in class scope.  This is invalid,
2370                but the error will already have been flagged by
2371                check_specialization_scope.  */
2372             return error_mark_node;
2373           else
2374             {
2375               /* It's not valid to write an explicit instantiation in
2376                  class scope, e.g.:
2377
2378                    class C { template void f(); }
2379
2380                    This case is caught by the parser.  However, on
2381                    something like:
2382
2383                    template class C { void f(); };
2384
2385                    (which is invalid) we can get here.  The error will be
2386                    issued later.  */
2387               ;
2388             }
2389
2390           return decl;
2391         }
2392       else if (ctype != NULL_TREE
2393                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2394                    IDENTIFIER_NODE))
2395         {
2396           /* Find the list of functions in ctype that have the same
2397              name as the declared function.  */
2398           tree name = TREE_OPERAND (declarator, 0);
2399           tree fns = NULL_TREE;
2400           int idx;
2401
2402           if (constructor_name_p (name, ctype))
2403             {
2404               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2405
2406               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2407                   : !CLASSTYPE_DESTRUCTORS (ctype))
2408                 {
2409                   /* From [temp.expl.spec]:
2410
2411                      If such an explicit specialization for the member
2412                      of a class template names an implicitly-declared
2413                      special member function (clause _special_), the
2414                      program is ill-formed.
2415
2416                      Similar language is found in [temp.explicit].  */
2417                   error ("specialization of implicitly-declared special member function");
2418                   return error_mark_node;
2419                 }
2420
2421               name = is_constructor ? ctor_identifier : dtor_identifier;
2422             }
2423
2424           if (!DECL_CONV_FN_P (decl))
2425             {
2426               idx = lookup_fnfields_1 (ctype, name);
2427               if (idx >= 0)
2428                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2429             }
2430           else
2431             {
2432               VEC(tree,gc) *methods;
2433               tree ovl;
2434
2435               /* For a type-conversion operator, we cannot do a
2436                  name-based lookup.  We might be looking for `operator
2437                  int' which will be a specialization of `operator T'.
2438                  So, we find *all* the conversion operators, and then
2439                  select from them.  */
2440               fns = NULL_TREE;
2441
2442               methods = CLASSTYPE_METHOD_VEC (ctype);
2443               if (methods)
2444                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2445                      VEC_iterate (tree, methods, idx, ovl);
2446                      ++idx)
2447                   {
2448                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2449                       /* There are no more conversion functions.  */
2450                       break;
2451
2452                     /* Glue all these conversion functions together
2453                        with those we already have.  */
2454                     for (; ovl; ovl = OVL_NEXT (ovl))
2455                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2456                   }
2457             }
2458
2459           if (fns == NULL_TREE)
2460             {
2461               error ("no member function %qD declared in %qT", name, ctype);
2462               return error_mark_node;
2463             }
2464           else
2465             TREE_OPERAND (declarator, 0) = fns;
2466         }
2467
2468       /* Figure out what exactly is being specialized at this point.
2469          Note that for an explicit instantiation, even one for a
2470          member function, we cannot tell apriori whether the
2471          instantiation is for a member template, or just a member
2472          function of a template class.  Even if a member template is
2473          being instantiated, the member template arguments may be
2474          elided if they can be deduced from the rest of the
2475          declaration.  */
2476       tmpl = determine_specialization (declarator, decl,
2477                                        &targs,
2478                                        member_specialization,
2479                                        template_count,
2480                                        tsk);
2481
2482       if (!tmpl || tmpl == error_mark_node)
2483         /* We couldn't figure out what this declaration was
2484            specializing.  */
2485         return error_mark_node;
2486       else
2487         {
2488           tree gen_tmpl = most_general_template (tmpl);
2489
2490           if (explicit_instantiation)
2491             {
2492               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2493                  is done by do_decl_instantiation later.  */
2494
2495               int arg_depth = TMPL_ARGS_DEPTH (targs);
2496               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2497
2498               if (arg_depth > parm_depth)
2499                 {
2500                   /* If TMPL is not the most general template (for
2501                      example, if TMPL is a friend template that is
2502                      injected into namespace scope), then there will
2503                      be too many levels of TARGS.  Remove some of them
2504                      here.  */
2505                   int i;
2506                   tree new_targs;
2507
2508                   new_targs = make_tree_vec (parm_depth);
2509                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2510                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2511                       = TREE_VEC_ELT (targs, i);
2512                   targs = new_targs;
2513                 }
2514
2515               return instantiate_template (tmpl, targs, tf_error);
2516             }
2517
2518           /* If we thought that the DECL was a member function, but it
2519              turns out to be specializing a static member function,
2520              make DECL a static member function as well.  */
2521           if (DECL_STATIC_FUNCTION_P (tmpl)
2522               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2523             revert_static_member_fn (decl);
2524
2525           /* If this is a specialization of a member template of a
2526              template class, we want to return the TEMPLATE_DECL, not
2527              the specialization of it.  */
2528           if (tsk == tsk_template)
2529             {
2530               tree result = DECL_TEMPLATE_RESULT (tmpl);
2531               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2532               DECL_INITIAL (result) = NULL_TREE;
2533               if (have_def)
2534                 {
2535                   tree parm;
2536                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2537                   DECL_SOURCE_LOCATION (result)
2538                     = DECL_SOURCE_LOCATION (decl);
2539                   /* We want to use the argument list specified in the
2540                      definition, not in the original declaration.  */
2541                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2542                   for (parm = DECL_ARGUMENTS (result); parm;
2543                        parm = TREE_CHAIN (parm))
2544                     DECL_CONTEXT (parm) = result;
2545                 }
2546               return register_specialization (tmpl, gen_tmpl, targs,
2547                                               is_friend, 0);
2548             }
2549
2550           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2551           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2552
2553           /* Inherit default function arguments from the template
2554              DECL is specializing.  */
2555           copy_default_args_to_explicit_spec (decl);
2556
2557           /* This specialization has the same protection as the
2558              template it specializes.  */
2559           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2560           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2561
2562           /* 7.1.1-1 [dcl.stc]
2563
2564              A storage-class-specifier shall not be specified in an
2565              explicit specialization...
2566
2567              The parser rejects these, so unless action is taken here,
2568              explicit function specializations will always appear with
2569              global linkage.
2570
2571              The action recommended by the C++ CWG in response to C++
2572              defect report 605 is to make the storage class and linkage
2573              of the explicit specialization match the templated function:
2574
2575              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2576            */
2577           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2578             {
2579               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2580               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2581
2582               /* This specialization has the same linkage and visibility as
2583                  the function template it specializes.  */
2584               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2585               if (! TREE_PUBLIC (decl))
2586                 {
2587                   DECL_INTERFACE_KNOWN (decl) = 1;
2588                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2589                 }
2590               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2591               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2592                 {
2593                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2594                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2595                 }
2596             }
2597
2598           /* If DECL is a friend declaration, declared using an
2599              unqualified name, the namespace associated with DECL may
2600              have been set incorrectly.  For example, in:
2601
2602                template <typename T> void f(T);
2603                namespace N {
2604                  struct S { friend void f<int>(int); }
2605                }
2606
2607              we will have set the DECL_CONTEXT for the friend
2608              declaration to N, rather than to the global namespace.  */
2609           if (DECL_NAMESPACE_SCOPE_P (decl))
2610             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2611
2612           if (is_friend && !have_def)
2613             /* This is not really a declaration of a specialization.
2614                It's just the name of an instantiation.  But, it's not
2615                a request for an instantiation, either.  */
2616             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2617           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2618             /* This is indeed a specialization.  In case of constructors
2619                and destructors, we need in-charge and not-in-charge
2620                versions in V3 ABI.  */
2621             clone_function_decl (decl, /*update_method_vec_p=*/0);
2622
2623           /* Register this specialization so that we can find it
2624              again.  */
2625           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2626         }
2627     }
2628
2629   return decl;
2630 }
2631
2632 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2633    parameters.  These are represented in the same format used for
2634    DECL_TEMPLATE_PARMS.  */
2635
2636 int
2637 comp_template_parms (const_tree parms1, const_tree parms2)
2638 {
2639   const_tree p1;
2640   const_tree p2;
2641
2642   if (parms1 == parms2)
2643     return 1;
2644
2645   for (p1 = parms1, p2 = parms2;
2646        p1 != NULL_TREE && p2 != NULL_TREE;
2647        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2648     {
2649       tree t1 = TREE_VALUE (p1);
2650       tree t2 = TREE_VALUE (p2);
2651       int i;
2652
2653       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2654       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2655
2656       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2657         return 0;
2658
2659       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2660         {
2661           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2662           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2663
2664           /* If either of the template parameters are invalid, assume
2665              they match for the sake of error recovery. */
2666           if (parm1 == error_mark_node || parm2 == error_mark_node)
2667             return 1;
2668
2669           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2670             return 0;
2671
2672           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2673               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2674                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2675             continue;
2676           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2677             return 0;
2678         }
2679     }
2680
2681   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2682     /* One set of parameters has more parameters lists than the
2683        other.  */
2684     return 0;
2685
2686   return 1;
2687 }
2688
2689 /* Determine whether PARM is a parameter pack.  */
2690
2691 bool 
2692 template_parameter_pack_p (const_tree parm)
2693 {
2694   /* Determine if we have a non-type template parameter pack.  */
2695   if (TREE_CODE (parm) == PARM_DECL)
2696     return (DECL_TEMPLATE_PARM_P (parm) 
2697             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2698
2699   /* If this is a list of template parameters, we could get a
2700      TYPE_DECL or a TEMPLATE_DECL.  */ 
2701   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2702     parm = TREE_TYPE (parm);
2703
2704   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2705            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2706           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2707 }
2708
2709 /* Determine if T is a function parameter pack.  */
2710
2711 bool
2712 function_parameter_pack_p (const_tree t)
2713 {
2714   if (t && TREE_CODE (t) == PARM_DECL)
2715     return FUNCTION_PARAMETER_PACK_P (t);
2716   return false;
2717 }
2718
2719 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2720    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2721
2722 tree
2723 get_function_template_decl (const_tree primary_func_tmpl_inst)
2724 {
2725   if (! primary_func_tmpl_inst
2726       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2727       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2728     return NULL;
2729
2730   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2731 }
2732
2733 /* Return true iff the function parameter PARAM_DECL was expanded
2734    from the function parameter pack PACK.  */
2735
2736 bool
2737 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2738 {
2739   if (DECL_ARTIFICIAL (param_decl)
2740       || !function_parameter_pack_p (pack))
2741     return false;
2742
2743   /* The parameter pack and its pack arguments have the same
2744      DECL_PARM_INDEX.  */
2745   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2746 }
2747
2748 /* Determine whether ARGS describes a variadic template args list,
2749    i.e., one that is terminated by a template argument pack.  */
2750
2751 static bool 
2752 template_args_variadic_p (tree args)
2753 {
2754   int nargs;
2755   tree last_parm;
2756
2757   if (args == NULL_TREE)
2758     return false;
2759
2760   args = INNERMOST_TEMPLATE_ARGS (args);
2761   nargs = TREE_VEC_LENGTH (args);
2762
2763   if (nargs == 0)
2764     return false;
2765
2766   last_parm = TREE_VEC_ELT (args, nargs - 1);
2767
2768   return ARGUMENT_PACK_P (last_parm);
2769 }
2770
2771 /* Generate a new name for the parameter pack name NAME (an
2772    IDENTIFIER_NODE) that incorporates its */
2773
2774 static tree
2775 make_ith_pack_parameter_name (tree name, int i)
2776 {
2777   /* Munge the name to include the parameter index.  */
2778 #define NUMBUF_LEN 128
2779   char numbuf[NUMBUF_LEN];
2780   char* newname;
2781   int newname_len;
2782
2783   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2784   newname_len = IDENTIFIER_LENGTH (name)
2785                 + strlen (numbuf) + 2;
2786   newname = (char*)alloca (newname_len);
2787   snprintf (newname, newname_len,
2788             "%s#%i", IDENTIFIER_POINTER (name), i);
2789   return get_identifier (newname);
2790 }
2791
2792 /* Return true if T is a primary function
2793    or class template instantiation.  */
2794
2795 bool
2796 primary_template_instantiation_p (const_tree t)
2797 {
2798   if (!t)
2799     return false;
2800
2801   if (TREE_CODE (t) == FUNCTION_DECL)
2802     return DECL_LANG_SPECIFIC (t)
2803            && DECL_TEMPLATE_INSTANTIATION (t)
2804            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2805   else if (CLASS_TYPE_P (t))
2806     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2807            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2808   return false;
2809 }
2810
2811 /* Return true if PARM is a template template parameter.  */
2812
2813 bool
2814 template_template_parameter_p (const_tree parm)
2815 {
2816   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2817 }
2818
2819 /* Return the template parameters of T if T is a
2820    primary template instantiation, NULL otherwise.  */
2821
2822 tree
2823 get_primary_template_innermost_parameters (const_tree t)
2824 {
2825   tree parms = NULL, template_info = NULL;
2826
2827   if ((template_info = get_template_info (t))
2828       && primary_template_instantiation_p (t))
2829     parms = INNERMOST_TEMPLATE_PARMS
2830         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2831
2832   return parms;
2833 }
2834
2835 /* Returns the template arguments of T if T is a template instantiation,
2836    NULL otherwise.  */
2837
2838 tree
2839 get_template_innermost_arguments (const_tree t)
2840 {
2841   tree args = NULL, template_info = NULL;
2842
2843   if ((template_info = get_template_info (t))
2844       && TI_ARGS (template_info))
2845     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2846
2847   return args;
2848 }
2849
2850 /* Return the argument pack elements of T if T is a template argument pack,
2851    NULL otherwise.  */
2852
2853 tree
2854 get_template_argument_pack_elems (const_tree t)
2855 {
2856   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2857       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2858     return NULL;
2859
2860   return ARGUMENT_PACK_ARGS (t);
2861 }
2862
2863 /* Structure used to track the progress of find_parameter_packs_r.  */
2864 struct find_parameter_pack_data 
2865 {
2866   /* TREE_LIST that will contain all of the parameter packs found by
2867      the traversal.  */
2868   tree* parameter_packs;
2869
2870   /* Set of AST nodes that have been visited by the traversal.  */
2871   struct pointer_set_t *visited;
2872 };
2873
2874 /* Identifies all of the argument packs that occur in a template
2875    argument and appends them to the TREE_LIST inside DATA, which is a
2876    find_parameter_pack_data structure. This is a subroutine of
2877    make_pack_expansion and uses_parameter_packs.  */
2878 static tree
2879 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2880 {
2881   tree t = *tp;
2882   struct find_parameter_pack_data* ppd = 
2883     (struct find_parameter_pack_data*)data;
2884   bool parameter_pack_p = false;
2885
2886   /* Identify whether this is a parameter pack or not.  */
2887   switch (TREE_CODE (t))
2888     {
2889     case TEMPLATE_PARM_INDEX:
2890       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2891         parameter_pack_p = true;
2892       break;
2893
2894     case TEMPLATE_TYPE_PARM:
2895     case TEMPLATE_TEMPLATE_PARM:
2896       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2897         parameter_pack_p = true;
2898       break;
2899
2900     case PARM_DECL:
2901       if (FUNCTION_PARAMETER_PACK_P (t))
2902         {
2903           /* We don't want to walk into the type of a PARM_DECL,
2904              because we don't want to see the type parameter pack.  */
2905           *walk_subtrees = 0;
2906           parameter_pack_p = true;
2907         }
2908       break;
2909
2910     default:
2911       /* Not a parameter pack.  */
2912       break;
2913     }
2914
2915   if (parameter_pack_p)
2916     {
2917       /* Add this parameter pack to the list.  */
2918       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2919     }
2920
2921   if (TYPE_P (t))
2922     cp_walk_tree (&TYPE_CONTEXT (t), 
2923                   &find_parameter_packs_r, ppd, ppd->visited);
2924
2925   /* This switch statement will return immediately if we don't find a
2926      parameter pack.  */
2927   switch (TREE_CODE (t)) 
2928     {
2929     case TEMPLATE_PARM_INDEX:
2930       return NULL_TREE;
2931
2932     case BOUND_TEMPLATE_TEMPLATE_PARM:
2933       /* Check the template itself.  */
2934       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2935                     &find_parameter_packs_r, ppd, ppd->visited);
2936       /* Check the template arguments.  */
2937       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2938                     ppd->visited);
2939       *walk_subtrees = 0;
2940       return NULL_TREE;
2941
2942     case TEMPLATE_TYPE_PARM:
2943     case TEMPLATE_TEMPLATE_PARM:
2944       return NULL_TREE;
2945
2946     case PARM_DECL:
2947       return NULL_TREE;
2948
2949     case RECORD_TYPE:
2950       if (TYPE_PTRMEMFUNC_P (t))
2951         return NULL_TREE;
2952       /* Fall through.  */
2953
2954     case UNION_TYPE:
2955     case ENUMERAL_TYPE:
2956       if (TYPE_TEMPLATE_INFO (t))
2957         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2958                       &find_parameter_packs_r, ppd, ppd->visited);
2959
2960       *walk_subtrees = 0;
2961       return NULL_TREE;
2962
2963     case TEMPLATE_DECL:
2964       cp_walk_tree (&TREE_TYPE (t),
2965                     &find_parameter_packs_r, ppd, ppd->visited);
2966       return NULL_TREE;
2967  
2968     case TYPENAME_TYPE:
2969       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2970                    ppd, ppd->visited);
2971       *walk_subtrees = 0;
2972       return NULL_TREE;
2973       
2974     case TYPE_PACK_EXPANSION:
2975     case EXPR_PACK_EXPANSION:
2976       *walk_subtrees = 0;
2977       return NULL_TREE;
2978
2979     case INTEGER_TYPE:
2980       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2981                     ppd, ppd->visited);
2982       *walk_subtrees = 0;
2983       return NULL_TREE;
2984
2985     case IDENTIFIER_NODE:
2986       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2987                     ppd->visited);
2988       *walk_subtrees = 0;
2989       return NULL_TREE;
2990
2991     default:
2992       return NULL_TREE;
2993     }
2994
2995   return NULL_TREE;
2996 }
2997
2998 /* Determines if the expression or type T uses any parameter packs.  */
2999 bool
3000 uses_parameter_packs (tree t)
3001 {
3002   tree parameter_packs = NULL_TREE;
3003   struct find_parameter_pack_data ppd;
3004   ppd.parameter_packs = &parameter_packs;
3005   ppd.visited = pointer_set_create ();
3006   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3007   pointer_set_destroy (ppd.visited);
3008   return parameter_packs != NULL_TREE;
3009 }
3010
3011 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3012    representation a base-class initializer into a parameter pack
3013    expansion. If all goes well, the resulting node will be an
3014    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3015    respectively.  */
3016 tree 
3017 make_pack_expansion (tree arg)
3018 {
3019   tree result;
3020   tree parameter_packs = NULL_TREE;
3021   bool for_types = false;
3022   struct find_parameter_pack_data ppd;
3023
3024   if (!arg || arg == error_mark_node)
3025     return arg;
3026
3027   if (TREE_CODE (arg) == TREE_LIST)
3028     {
3029       /* The only time we will see a TREE_LIST here is for a base
3030          class initializer.  In this case, the TREE_PURPOSE will be a
3031          _TYPE node (representing the base class expansion we're
3032          initializing) and the TREE_VALUE will be a TREE_LIST
3033          containing the initialization arguments. 
3034
3035          The resulting expansion looks somewhat different from most
3036          expansions. Rather than returning just one _EXPANSION, we
3037          return a TREE_LIST whose TREE_PURPOSE is a
3038          TYPE_PACK_EXPANSION containing the bases that will be
3039          initialized.  The TREE_VALUE will be identical to the
3040          original TREE_VALUE, which is a list of arguments that will
3041          be passed to each base.  We do not introduce any new pack
3042          expansion nodes into the TREE_VALUE (although it is possible
3043          that some already exist), because the TREE_PURPOSE and
3044          TREE_VALUE all need to be expanded together with the same
3045          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3046          resulting TREE_PURPOSE will mention the parameter packs in
3047          both the bases and the arguments to the bases.  */
3048       tree purpose;
3049       tree value;
3050       tree parameter_packs = NULL_TREE;
3051
3052       /* Determine which parameter packs will be used by the base
3053          class expansion.  */
3054       ppd.visited = pointer_set_create ();
3055       ppd.parameter_packs = &parameter_packs;
3056       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3057                     &ppd, ppd.visited);
3058
3059       if (parameter_packs == NULL_TREE)
3060         {
3061           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3062           pointer_set_destroy (ppd.visited);
3063           return error_mark_node;
3064         }
3065
3066       if (TREE_VALUE (arg) != void_type_node)
3067         {
3068           /* Collect the sets of parameter packs used in each of the
3069              initialization arguments.  */
3070           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3071             {
3072               /* Determine which parameter packs will be expanded in this
3073                  argument.  */
3074               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3075                             &ppd, ppd.visited);
3076             }
3077         }
3078
3079       pointer_set_destroy (ppd.visited);
3080
3081       /* Create the pack expansion type for the base type.  */
3082       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3083       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3084       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3085
3086       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3087          they will rarely be compared to anything.  */
3088       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3089
3090       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3091     }
3092
3093   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3094     for_types = true;
3095
3096   /* Build the PACK_EXPANSION_* node.  */
3097   result = for_types
3098      ? cxx_make_type (TYPE_PACK_EXPANSION)
3099      : make_node (EXPR_PACK_EXPANSION);
3100   SET_PACK_EXPANSION_PATTERN (result, arg);
3101   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3102     {
3103       /* Propagate type and const-expression information.  */
3104       TREE_TYPE (result) = TREE_TYPE (arg);
3105       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3106     }
3107   else
3108     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3109        they will rarely be compared to anything.  */
3110     SET_TYPE_STRUCTURAL_EQUALITY (result);
3111
3112   /* Determine which parameter packs will be expanded.  */
3113   ppd.parameter_packs = &parameter_packs;
3114   ppd.visited = pointer_set_create ();
3115   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3116   pointer_set_destroy (ppd.visited);
3117
3118   /* Make sure we found some parameter packs.  */
3119   if (parameter_packs == NULL_TREE)
3120     {
3121       if (TYPE_P (arg))
3122         error ("expansion pattern %<%T%> contains no argument packs", arg);
3123       else
3124         error ("expansion pattern %<%E%> contains no argument packs", arg);
3125       return error_mark_node;
3126     }
3127   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3128
3129   return result;
3130 }
3131
3132 /* Checks T for any "bare" parameter packs, which have not yet been
3133    expanded, and issues an error if any are found. This operation can
3134    only be done on full expressions or types (e.g., an expression
3135    statement, "if" condition, etc.), because we could have expressions like:
3136
3137      foo(f(g(h(args)))...)
3138
3139    where "args" is a parameter pack. check_for_bare_parameter_packs
3140    should not be called for the subexpressions args, h(args),
3141    g(h(args)), or f(g(h(args))), because we would produce erroneous
3142    error messages. 
3143
3144    Returns TRUE and emits an error if there were bare parameter packs,
3145    returns FALSE otherwise.  */
3146 bool 
3147 check_for_bare_parameter_packs (tree t)
3148 {
3149   tree parameter_packs = NULL_TREE;
3150   struct find_parameter_pack_data ppd;
3151
3152   if (!processing_template_decl || !t || t == error_mark_node)
3153     return false;
3154
3155   if (TREE_CODE (t) == TYPE_DECL)
3156     t = TREE_TYPE (t);
3157
3158   ppd.parameter_packs = &parameter_packs;
3159   ppd.visited = pointer_set_create ();
3160   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3161   pointer_set_destroy (ppd.visited);
3162
3163   if (parameter_packs) 
3164     {
3165       error ("parameter packs not expanded with %<...%>:");
3166       while (parameter_packs)
3167         {
3168           tree pack = TREE_VALUE (parameter_packs);
3169           tree name = NULL_TREE;
3170
3171           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3172               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3173             name = TYPE_NAME (pack);
3174           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3175             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3176           else
3177             name = DECL_NAME (pack);
3178
3179           if (name)
3180             inform (input_location, "        %qD", name);
3181           else
3182             inform (input_location, "        <anonymous>");
3183
3184           parameter_packs = TREE_CHAIN (parameter_packs);
3185         }
3186
3187       return true;
3188     }
3189
3190   return false;
3191 }
3192
3193 /* Expand any parameter packs that occur in the template arguments in
3194    ARGS.  */
3195 tree
3196 expand_template_argument_pack (tree args)
3197 {
3198   tree result_args = NULL_TREE;
3199   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3200   int num_result_args = -1;
3201
3202   /* First, determine if we need to expand anything, and the number of
3203      slots we'll need.  */
3204   for (in_arg = 0; in_arg < nargs; ++in_arg)
3205     {
3206       tree arg = TREE_VEC_ELT (args, in_arg);
3207       if (arg == NULL_TREE)
3208         return args;
3209       if (ARGUMENT_PACK_P (arg))
3210         {
3211           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3212           if (num_result_args < 0)
3213             num_result_args = in_arg + num_packed;
3214           else
3215             num_result_args += num_packed;
3216         }
3217       else
3218         {
3219           if (num_result_args >= 0)
3220             num_result_args++;
3221         }
3222     }
3223
3224   /* If no expansion is necessary, we're done.  */
3225   if (num_result_args < 0)
3226     return args;
3227
3228   /* Expand arguments.  */
3229   result_args = make_tree_vec (num_result_args);
3230   for (in_arg = 0; in_arg < nargs; ++in_arg)
3231     {
3232       tree arg = TREE_VEC_ELT (args, in_arg);
3233       if (ARGUMENT_PACK_P (arg))
3234         {
3235           tree packed = ARGUMENT_PACK_ARGS (arg);
3236           int i, num_packed = TREE_VEC_LENGTH (packed);
3237           for (i = 0; i < num_packed; ++i, ++out_arg)
3238             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3239         }
3240       else
3241         {
3242           TREE_VEC_ELT (result_args, out_arg) = arg;
3243           ++out_arg;
3244         }
3245     }
3246
3247   return result_args;
3248 }
3249
3250 /* Checks if DECL shadows a template parameter.
3251
3252    [temp.local]: A template-parameter shall not be redeclared within its
3253    scope (including nested scopes).
3254
3255    Emits an error and returns TRUE if the DECL shadows a parameter,
3256    returns FALSE otherwise.  */
3257
3258 bool
3259 check_template_shadow (tree decl)
3260 {
3261   tree olddecl;
3262
3263   /* If we're not in a template, we can't possibly shadow a template
3264      parameter.  */
3265   if (!current_template_parms)
3266     return true;
3267
3268   /* Figure out what we're shadowing.  */
3269   if (TREE_CODE (decl) == OVERLOAD)
3270     decl = OVL_CURRENT (decl);
3271   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3272
3273   /* If there's no previous binding for this name, we're not shadowing
3274      anything, let alone a template parameter.  */
3275   if (!olddecl)
3276     return true;
3277
3278   /* If we're not shadowing a template parameter, we're done.  Note
3279      that OLDDECL might be an OVERLOAD (or perhaps even an
3280      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3281      node.  */
3282   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3283     return true;
3284
3285   /* We check for decl != olddecl to avoid bogus errors for using a
3286      name inside a class.  We check TPFI to avoid duplicate errors for
3287      inline member templates.  */
3288   if (decl == olddecl
3289       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3290     return true;
3291
3292   error ("declaration of %q+#D", decl);
3293   error (" shadows template parm %q+#D", olddecl);
3294   return false;
3295 }
3296
3297 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3298    ORIG_LEVEL, DECL, and TYPE.  */
3299
3300 static tree
3301 build_template_parm_index (int index,
3302                            int level,
3303                            int orig_level,
3304                            tree decl,
3305                            tree type)
3306 {
3307   tree t = make_node (TEMPLATE_PARM_INDEX);
3308   TEMPLATE_PARM_IDX (t) = index;
3309   TEMPLATE_PARM_LEVEL (t) = level;
3310   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3311   TEMPLATE_PARM_DECL (t) = decl;
3312   TREE_TYPE (t) = type;
3313   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3314   TREE_READONLY (t) = TREE_READONLY (decl);
3315
3316   return t;
3317 }
3318
3319 /* Find the canonical type parameter for the given template type
3320    parameter.  Returns the canonical type parameter, which may be TYPE
3321    if no such parameter existed.  */
3322 static tree
3323 canonical_type_parameter (tree type)
3324 {
3325   tree list;
3326   int idx = TEMPLATE_TYPE_IDX (type);
3327   if (!canonical_template_parms)
3328     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3329
3330   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3331     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3332
3333   list = VEC_index (tree, canonical_template_parms, idx);
3334   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3335     list = TREE_CHAIN (list);
3336
3337   if (list)
3338     return TREE_VALUE (list);
3339   else
3340     {
3341       VEC_replace(tree, canonical_template_parms, idx,
3342                   tree_cons (NULL_TREE, type, 
3343                              VEC_index (tree, canonical_template_parms, idx)));
3344       return type;
3345     }
3346 }
3347
3348 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3349    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3350    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3351    new one is created.  */
3352
3353 static tree
3354 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3355                             tsubst_flags_t complain)
3356 {
3357   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3358       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3359           != TEMPLATE_PARM_LEVEL (index) - levels))
3360     {
3361       tree orig_decl = TEMPLATE_PARM_DECL (index);
3362       tree decl, t;
3363
3364       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3365                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3366       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3367       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3368       DECL_ARTIFICIAL (decl) = 1;
3369       SET_DECL_TEMPLATE_PARM_P (decl);
3370
3371       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3372                                      TEMPLATE_PARM_LEVEL (index) - levels,
3373                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3374                                      decl, type);
3375       TEMPLATE_PARM_DESCENDANTS (index) = t;
3376       TEMPLATE_PARM_PARAMETER_PACK (t) 
3377         = TEMPLATE_PARM_PARAMETER_PACK (index);
3378
3379         /* Template template parameters need this.  */
3380       if (TREE_CODE (decl) == TEMPLATE_DECL)
3381         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3382           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3383            args, complain);
3384     }
3385
3386   return TEMPLATE_PARM_DESCENDANTS (index);
3387 }
3388
3389 /* Process information from new template parameter PARM and append it to the
3390    LIST being built.  This new parameter is a non-type parameter iff
3391    IS_NON_TYPE is true. This new parameter is a parameter
3392    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3393    PARM_LOC.  */
3394
3395 tree
3396 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3397                        bool is_parameter_pack)
3398 {
3399   tree decl = 0;
3400   tree defval;
3401   tree err_parm_list;
3402   int idx = 0;
3403
3404   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3405   defval = TREE_PURPOSE (parm);
3406
3407   if (list)
3408     {
3409       tree p = tree_last (list);
3410
3411       if (p && TREE_VALUE (p) != error_mark_node)
3412         {
3413           p = TREE_VALUE (p);
3414           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3415             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3416           else
3417             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3418         }
3419
3420       ++idx;
3421     }
3422   else
3423     idx = 0;
3424
3425   if (is_non_type)
3426     {
3427       parm = TREE_VALUE (parm);
3428
3429       SET_DECL_TEMPLATE_PARM_P (parm);
3430
3431       if (TREE_TYPE (parm) == error_mark_node)
3432         {
3433           err_parm_list = build_tree_list (defval, parm);
3434           TREE_VALUE (err_parm_list) = error_mark_node;
3435            return chainon (list, err_parm_list);
3436         }
3437       else
3438       {
3439         /* [temp.param]
3440
3441            The top-level cv-qualifiers on the template-parameter are
3442            ignored when determining its type.  */
3443         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3444         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3445           {
3446             err_parm_list = build_tree_list (defval, parm);
3447             TREE_VALUE (err_parm_list) = error_mark_node;
3448              return chainon (list, err_parm_list);
3449           }
3450
3451         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3452           {
3453             /* This template parameter is not a parameter pack, but it
3454                should be. Complain about "bare" parameter packs.  */
3455             check_for_bare_parameter_packs (TREE_TYPE (parm));
3456             
3457             /* Recover by calling this a parameter pack.  */
3458             is_parameter_pack = true;
3459           }
3460       }
3461
3462       /* A template parameter is not modifiable.  */
3463       TREE_CONSTANT (parm) = 1;
3464       TREE_READONLY (parm) = 1;
3465       decl = build_decl (parm_loc,
3466                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3467       TREE_CONSTANT (decl) = 1;
3468       TREE_READONLY (decl) = 1;
3469       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3470         = build_template_parm_index (idx, processing_template_decl,
3471                                      processing_template_decl,
3472                                      decl, TREE_TYPE (parm));
3473
3474       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3475         = is_parameter_pack;
3476     }
3477   else
3478     {
3479       tree t;
3480       parm = TREE_VALUE (TREE_VALUE (parm));
3481
3482       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3483         {
3484           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3485           /* This is for distinguishing between real templates and template
3486              template parameters */
3487           TREE_TYPE (parm) = t;
3488           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3489           decl = parm;
3490         }
3491       else
3492         {
3493           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3494           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3495           decl = build_decl (parm_loc,
3496                              TYPE_DECL, parm, t);
3497         }
3498
3499       TYPE_NAME (t) = decl;
3500       TYPE_STUB_DECL (t) = decl;
3501       parm = decl;
3502       TEMPLATE_TYPE_PARM_INDEX (t)
3503         = build_template_parm_index (idx, processing_template_decl,
3504                                      processing_template_decl,
3505                                      decl, TREE_TYPE (parm));
3506       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3507       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3508     }
3509   DECL_ARTIFICIAL (decl) = 1;
3510   SET_DECL_TEMPLATE_PARM_P (decl);
3511   pushdecl (decl);
3512   parm = build_tree_list (defval, parm);
3513   return chainon (list, parm);
3514 }
3515
3516 /* The end of a template parameter list has been reached.  Process the
3517    tree list into a parameter vector, converting each parameter into a more
3518    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3519    as PARM_DECLs.  */
3520
3521 tree
3522 end_template_parm_list (tree parms)
3523 {
3524   int nparms;
3525   tree parm, next;
3526   tree saved_parmlist = make_tree_vec (list_length (parms));
3527
3528   current_template_parms
3529     = tree_cons (size_int (processing_template_decl),
3530                  saved_parmlist, current_template_parms);
3531
3532   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3533     {
3534       next = TREE_CHAIN (parm);
3535       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3536       TREE_CHAIN (parm) = NULL_TREE;
3537     }
3538
3539   --processing_template_parmlist;
3540
3541   return saved_parmlist;
3542 }
3543
3544 /* end_template_decl is called after a template declaration is seen.  */
3545
3546 void
3547 end_template_decl (void)
3548 {
3549   reset_specialization ();
3550
3551   if (! processing_template_decl)
3552     return;
3553
3554   /* This matches the pushlevel in begin_template_parm_list.  */
3555   finish_scope ();
3556
3557   --processing_template_decl;
3558   current_template_parms = TREE_CHAIN (current_template_parms);
3559 }
3560
3561 /* Within the declaration of a template, return all levels of template
3562    parameters that apply.  The template parameters are represented as
3563    a TREE_VEC, in the form documented in cp-tree.h for template
3564    arguments.  */
3565
3566 static tree
3567 current_template_args (void)
3568 {
3569   tree header;
3570   tree args = NULL_TREE;
3571   int length = TMPL_PARMS_DEPTH (current_template_parms);
3572   int l = length;
3573
3574   /* If there is only one level of template parameters, we do not
3575      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3576      TREE_VEC containing the arguments.  */
3577   if (length > 1)
3578     args = make_tree_vec (length);
3579
3580   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3581     {
3582       tree a = copy_node (TREE_VALUE (header));
3583       int i;
3584
3585       TREE_TYPE (a) = NULL_TREE;
3586       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3587         {
3588           tree t = TREE_VEC_ELT (a, i);
3589
3590           /* T will be a list if we are called from within a
3591              begin/end_template_parm_list pair, but a vector directly
3592              if within a begin/end_member_template_processing pair.  */
3593           if (TREE_CODE (t) == TREE_LIST)
3594             {
3595               t = TREE_VALUE (t);
3596
3597               if (!error_operand_p (t))
3598                 {
3599                   if (TREE_CODE (t) == TYPE_DECL
3600                       || TREE_CODE (t) == TEMPLATE_DECL)
3601                     {
3602                       t = TREE_TYPE (t);
3603                       
3604                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3605                         {
3606                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3607                              with a single element, which expands T.  */
3608                           tree vec = make_tree_vec (1);
3609                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3610                           
3611                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3612                           SET_ARGUMENT_PACK_ARGS (t, vec);
3613                         }
3614                     }
3615                   else
3616                     {
3617                       t = DECL_INITIAL (t);
3618                       
3619                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3620                         {
3621                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3622                              with a single element, which expands T.  */
3623                           tree vec = make_tree_vec (1);
3624                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3625                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3626                           
3627                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3628                           SET_ARGUMENT_PACK_ARGS (t, vec);
3629                           TREE_TYPE (t) = type;
3630                         }
3631                     }
3632                   TREE_VEC_ELT (a, i) = t;
3633                 }
3634             }
3635         }
3636
3637       if (length > 1)
3638         TREE_VEC_ELT (args, --l) = a;
3639       else
3640         args = a;
3641     }
3642
3643   return args;
3644 }
3645
3646 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3647    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3648    a member template.  Used by push_template_decl below.  */
3649
3650 static tree
3651 build_template_decl (tree decl, tree parms, bool member_template_p)
3652 {
3653   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3654   DECL_TEMPLATE_PARMS (tmpl) = parms;
3655   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3656   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3657
3658   return tmpl;
3659 }
3660
3661 struct template_parm_data
3662 {
3663   /* The level of the template parameters we are currently
3664      processing.  */
3665   int level;
3666
3667   /* The index of the specialization argument we are currently
3668      processing.  */
3669   int current_arg;
3670
3671   /* An array whose size is the number of template parameters.  The
3672      elements are nonzero if the parameter has been used in any one
3673      of the arguments processed so far.  */
3674   int* parms;
3675
3676   /* An array whose size is the number of template arguments.  The
3677      elements are nonzero if the argument makes use of template
3678      parameters of this level.  */
3679   int* arg_uses_template_parms;
3680 };
3681
3682 /* Subroutine of push_template_decl used to see if each template
3683    parameter in a partial specialization is used in the explicit
3684    argument list.  If T is of the LEVEL given in DATA (which is
3685    treated as a template_parm_data*), then DATA->PARMS is marked
3686    appropriately.  */
3687
3688 static int
3689 mark_template_parm (tree t, void* data)
3690 {
3691   int level;
3692   int idx;
3693   struct template_parm_data* tpd = (struct template_parm_data*) data;
3694
3695   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3696     {
3697       level = TEMPLATE_PARM_LEVEL (t);
3698       idx = TEMPLATE_PARM_IDX (t);
3699     }
3700   else
3701     {
3702       level = TEMPLATE_TYPE_LEVEL (t);
3703       idx = TEMPLATE_TYPE_IDX (t);
3704     }
3705
3706   if (level == tpd->level)
3707     {
3708       tpd->parms[idx] = 1;
3709       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3710     }
3711
3712   /* Return zero so that for_each_template_parm will continue the
3713      traversal of the tree; we want to mark *every* template parm.  */
3714   return 0;
3715 }
3716
3717 /* Process the partial specialization DECL.  */
3718
3719 static tree
3720 process_partial_specialization (tree decl)
3721 {
3722   tree type = TREE_TYPE (decl);
3723   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3724   tree specargs = CLASSTYPE_TI_ARGS (type);
3725   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3726   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3727   tree inner_parms;
3728   int nargs = TREE_VEC_LENGTH (inner_args);
3729   int ntparms;
3730   int  i;
3731   int did_error_intro = 0;
3732   struct template_parm_data tpd;
3733   struct template_parm_data tpd2;
3734
3735   gcc_assert (current_template_parms);
3736
3737   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3738   ntparms = TREE_VEC_LENGTH (inner_parms);
3739
3740   /* We check that each of the template parameters given in the
3741      partial specialization is used in the argument list to the
3742      specialization.  For example:
3743
3744        template <class T> struct S;
3745        template <class T> struct S<T*>;
3746
3747      The second declaration is OK because `T*' uses the template
3748      parameter T, whereas
3749
3750        template <class T> struct S<int>;
3751
3752      is no good.  Even trickier is:
3753
3754        template <class T>
3755        struct S1
3756        {
3757           template <class U>
3758           struct S2;
3759           template <class U>
3760           struct S2<T>;
3761        };
3762
3763      The S2<T> declaration is actually invalid; it is a
3764      full-specialization.  Of course,
3765
3766           template <class U>
3767           struct S2<T (*)(U)>;
3768
3769      or some such would have been OK.  */
3770   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3771   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3772   memset (tpd.parms, 0, sizeof (int) * ntparms);
3773
3774   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3775   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3776   for (i = 0; i < nargs; ++i)
3777     {
3778       tpd.current_arg = i;
3779       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3780                               &mark_template_parm,
3781                               &tpd,
3782                               NULL,
3783                               /*include_nondeduced_p=*/false);
3784     }
3785   for (i = 0; i < ntparms; ++i)
3786     if (tpd.parms[i] == 0)
3787       {
3788         /* One of the template parms was not used in the
3789            specialization.  */
3790         if (!did_error_intro)
3791           {
3792             error ("template parameters not used in partial specialization:");
3793             did_error_intro = 1;
3794           }
3795
3796         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3797       }
3798
3799   /* [temp.class.spec]
3800
3801      The argument list of the specialization shall not be identical to
3802      the implicit argument list of the primary template.  */
3803   if (comp_template_args
3804       (inner_args,
3805        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3806                                                    (maintmpl)))))
3807     error ("partial specialization %qT does not specialize any template arguments", type);
3808
3809   /* [temp.class.spec]
3810
3811      A partially specialized non-type argument expression shall not
3812      involve template parameters of the partial specialization except
3813      when the argument expression is a simple identifier.
3814
3815      The type of a template parameter corresponding to a specialized
3816      non-type argument shall not be dependent on a parameter of the
3817      specialization. 
3818
3819      Also, we verify that pack expansions only occur at the
3820      end of the argument list.  */
3821   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3822   tpd2.parms = 0;
3823   for (i = 0; i < nargs; ++i)
3824     {
3825       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3826       tree arg = TREE_VEC_ELT (inner_args, i);
3827       tree packed_args = NULL_TREE;
3828       int j, len = 1;
3829
3830       if (ARGUMENT_PACK_P (arg))
3831         {
3832           /* Extract the arguments from the argument pack. We'll be
3833              iterating over these in the following loop.  */
3834           packed_args = ARGUMENT_PACK_ARGS (arg);
3835           len = TREE_VEC_LENGTH (packed_args);
3836         }
3837
3838       for (j = 0; j < len; j++)
3839         {
3840           if (packed_args)
3841             /* Get the Jth argument in the parameter pack.  */
3842             arg = TREE_VEC_ELT (packed_args, j);
3843
3844           if (PACK_EXPANSION_P (arg))
3845             {
3846               /* Pack expansions must come at the end of the
3847                  argument list.  */
3848               if ((packed_args && j < len - 1)
3849                   || (!packed_args && i < nargs - 1))
3850                 {
3851                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3852                     error ("parameter pack argument %qE must be at the "
3853                            "end of the template argument list", arg);
3854                   else
3855                     error ("parameter pack argument %qT must be at the "
3856                            "end of the template argument list", arg);
3857                 }
3858             }
3859
3860           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3861             /* We only care about the pattern.  */
3862             arg = PACK_EXPANSION_PATTERN (arg);
3863
3864           if (/* These first two lines are the `non-type' bit.  */
3865               !TYPE_P (arg)
3866               && TREE_CODE (arg) != TEMPLATE_DECL
3867               /* This next line is the `argument expression is not just a
3868                  simple identifier' condition and also the `specialized
3869                  non-type argument' bit.  */
3870               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3871             {
3872               if ((!packed_args && tpd.arg_uses_template_parms[i])
3873                   || (packed_args && uses_template_parms (arg)))
3874                 error ("template argument %qE involves template parameter(s)",
3875                        arg);
3876               else 
3877                 {
3878                   /* Look at the corresponding template parameter,
3879                      marking which template parameters its type depends
3880                      upon.  */
3881                   tree type = TREE_TYPE (parm);
3882
3883                   if (!tpd2.parms)
3884                     {
3885                       /* We haven't yet initialized TPD2.  Do so now.  */
3886                       tpd2.arg_uses_template_parms 
3887                         = (int *) alloca (sizeof (int) * nargs);
3888                       /* The number of parameters here is the number in the
3889                          main template, which, as checked in the assertion
3890                          above, is NARGS.  */
3891                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3892                       tpd2.level = 
3893                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3894                     }
3895
3896                   /* Mark the template parameters.  But this time, we're
3897                      looking for the template parameters of the main
3898                      template, not in the specialization.  */
3899                   tpd2.current_arg = i;
3900                   tpd2.arg_uses_template_parms[i] = 0;
3901                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3902                   for_each_template_parm (type,
3903                                           &mark_template_parm,
3904                                           &tpd2,
3905                                           NULL,
3906                                           /*include_nondeduced_p=*/false);
3907
3908                   if (tpd2.arg_uses_template_parms [i])
3909                     {
3910                       /* The type depended on some template parameters.
3911                          If they are fully specialized in the
3912                          specialization, that's OK.  */
3913                       int j;
3914                       for (j = 0; j < nargs; ++j)
3915                         if (tpd2.parms[j] != 0
3916                             && tpd.arg_uses_template_parms [j])
3917                           {
3918                             error ("type %qT of template argument %qE depends "
3919                                    "on template parameter(s)", 
3920                                    type,
3921                                    arg);
3922                             break;
3923                           }
3924                     }
3925                 }
3926             }
3927         }
3928     }
3929
3930   /* We should only get here once.  */
3931   gcc_assert (!COMPLETE_TYPE_P (type));
3932
3933   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3934     = tree_cons (specargs, inner_parms,
3935                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3936   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3937   return decl;
3938 }
3939
3940 /* Check that a template declaration's use of default arguments and
3941    parameter packs is not invalid.  Here, PARMS are the template
3942    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3943    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3944    specialization.
3945    
3946
3947    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3948    declaration (but not a definition); 1 indicates a declaration, 2
3949    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3950    emitted for extraneous default arguments.
3951
3952    Returns TRUE if there were no errors found, FALSE otherwise. */
3953
3954 bool
3955 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3956                          int is_partial, int is_friend_decl)
3957 {
3958   const char *msg;
3959   int last_level_to_check;
3960   tree parm_level;
3961   bool no_errors = true;
3962
3963   /* [temp.param]
3964
3965      A default template-argument shall not be specified in a
3966      function template declaration or a function template definition, nor
3967      in the template-parameter-list of the definition of a member of a
3968      class template.  */
3969
3970   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3971     /* You can't have a function template declaration in a local
3972        scope, nor you can you define a member of a class template in a
3973        local scope.  */
3974     return true;
3975
3976   if (current_class_type
3977       && !TYPE_BEING_DEFINED (current_class_type)
3978       && DECL_LANG_SPECIFIC (decl)
3979       && DECL_DECLARES_FUNCTION_P (decl)
3980       /* If this is either a friend defined in the scope of the class
3981          or a member function.  */
3982       && (DECL_FUNCTION_MEMBER_P (decl)
3983           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3984           : DECL_FRIEND_CONTEXT (decl)
3985           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3986           : false)
3987       /* And, if it was a member function, it really was defined in
3988          the scope of the class.  */
3989       && (!DECL_FUNCTION_MEMBER_P (decl)
3990           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3991     /* We already checked these parameters when the template was
3992        declared, so there's no need to do it again now.  This function
3993        was defined in class scope, but we're processing it's body now
3994        that the class is complete.  */
3995     return true;
3996
3997   /* Core issue 226 (C++0x only): the following only applies to class
3998      templates.  */
3999   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4000     {
4001       /* [temp.param]
4002
4003          If a template-parameter has a default template-argument, all
4004          subsequent template-parameters shall have a default
4005          template-argument supplied.  */
4006       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4007         {
4008           tree inner_parms = TREE_VALUE (parm_level);
4009           int ntparms = TREE_VEC_LENGTH (inner_parms);
4010           int seen_def_arg_p = 0;
4011           int i;
4012
4013           for (i = 0; i < ntparms; ++i)
4014             {
4015               tree parm = TREE_VEC_ELT (inner_parms, i);
4016
4017               if (parm == error_mark_node)
4018                 continue;
4019
4020               if (TREE_PURPOSE (parm))
4021                 seen_def_arg_p = 1;
4022               else if (seen_def_arg_p
4023                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4024                 {
4025                   error ("no default argument for %qD", TREE_VALUE (parm));
4026                   /* For better subsequent error-recovery, we indicate that
4027                      there should have been a default argument.  */
4028                   TREE_PURPOSE (parm) = error_mark_node;
4029                   no_errors = false;
4030                 }
4031               else if (is_primary
4032                        && !is_partial
4033                        && !is_friend_decl
4034                        /* Don't complain about an enclosing partial
4035                           specialization.  */
4036                        && parm_level == parms
4037                        && TREE_CODE (decl) == TYPE_DECL
4038                        && i < ntparms - 1
4039                        && template_parameter_pack_p (TREE_VALUE (parm)))
4040                 {
4041                   /* A primary class template can only have one
4042                      parameter pack, at the end of the template
4043                      parameter list.  */
4044
4045                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4046                     error ("parameter pack %qE must be at the end of the"
4047                            " template parameter list", TREE_VALUE (parm));
4048                   else
4049                     error ("parameter pack %qT must be at the end of the"
4050                            " template parameter list", 
4051                            TREE_TYPE (TREE_VALUE (parm)));
4052
4053                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4054                     = error_mark_node;
4055                   no_errors = false;
4056                 }
4057             }
4058         }
4059     }
4060
4061   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4062       || is_partial 
4063       || !is_primary
4064       || is_friend_decl)
4065     /* For an ordinary class template, default template arguments are
4066        allowed at the innermost level, e.g.:
4067          template <class T = int>
4068          struct S {};
4069        but, in a partial specialization, they're not allowed even
4070        there, as we have in [temp.class.spec]:
4071
4072          The template parameter list of a specialization shall not
4073          contain default template argument values.
4074
4075        So, for a partial specialization, or for a function template
4076        (in C++98/C++03), we look at all of them.  */
4077     ;
4078   else
4079     /* But, for a primary class template that is not a partial
4080        specialization we look at all template parameters except the
4081        innermost ones.  */
4082     parms = TREE_CHAIN (parms);
4083
4084   /* Figure out what error message to issue.  */
4085   if (is_friend_decl == 2)
4086     msg = "default template arguments may not be used in function template friend re-declaration";
4087   else if (is_friend_decl)
4088     msg = "default template arguments may not be used in function template friend declarations";
4089   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4090     msg = ("default template arguments may not be used in function templates "
4091            "without -std=c++0x or -std=gnu++0x");
4092   else if (is_partial)
4093     msg = "default template arguments may not be used in partial specializations";
4094   else
4095     msg = "default argument for template parameter for class enclosing %qD";
4096
4097   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4098     /* If we're inside a class definition, there's no need to
4099        examine the parameters to the class itself.  On the one
4100        hand, they will be checked when the class is defined, and,
4101        on the other, default arguments are valid in things like:
4102          template <class T = double>
4103          struct S { template <class U> void f(U); };
4104        Here the default argument for `S' has no bearing on the
4105        declaration of `f'.  */
4106     last_level_to_check = template_class_depth (current_class_type) + 1;
4107   else
4108     /* Check everything.  */
4109     last_level_to_check = 0;
4110
4111   for (parm_level = parms;
4112        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4113        parm_level = TREE_CHAIN (parm_level))
4114     {
4115       tree inner_parms = TREE_VALUE (parm_level);
4116       int i;
4117       int ntparms;
4118
4119       ntparms = TREE_VEC_LENGTH (inner_parms);
4120       for (i = 0; i < ntparms; ++i)
4121         {
4122           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4123             continue;
4124
4125           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4126             {
4127               if (msg)
4128                 {
4129                   no_errors = false;
4130                   if (is_friend_decl == 2)
4131                     return no_errors;
4132
4133                   error (msg, decl);
4134                   msg = 0;
4135                 }
4136
4137               /* Clear out the default argument so that we are not
4138                  confused later.  */
4139               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4140             }
4141         }
4142
4143       /* At this point, if we're still interested in issuing messages,
4144          they must apply to classes surrounding the object declared.  */
4145       if (msg)
4146         msg = "default argument for template parameter for class enclosing %qD";
4147     }
4148
4149   return no_errors;
4150 }
4151
4152 /* Worker for push_template_decl_real, called via
4153    for_each_template_parm.  DATA is really an int, indicating the
4154    level of the parameters we are interested in.  If T is a template
4155    parameter of that level, return nonzero.  */
4156
4157 static int
4158 template_parm_this_level_p (tree t, void* data)
4159 {
4160   int this_level = *(int *)data;
4161   int level;
4162
4163   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4164     level = TEMPLATE_PARM_LEVEL (t);
4165   else
4166     level = TEMPLATE_TYPE_LEVEL (t);
4167   return level == this_level;
4168 }
4169
4170 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4171    parameters given by current_template_args, or reuses a
4172    previously existing one, if appropriate.  Returns the DECL, or an
4173    equivalent one, if it is replaced via a call to duplicate_decls.
4174
4175    If IS_FRIEND is true, DECL is a friend declaration.  */
4176
4177 tree
4178 push_template_decl_real (tree decl, bool is_friend)
4179 {
4180   tree tmpl;
4181   tree args;
4182   tree info;
4183   tree ctx;
4184   int primary;
4185   int is_partial;
4186   int new_template_p = 0;
4187   /* True if the template is a member template, in the sense of
4188      [temp.mem].  */
4189   bool member_template_p = false;
4190
4191   if (decl == error_mark_node || !current_template_parms)
4192     return error_mark_node;
4193
4194   /* See if this is a partial specialization.  */
4195   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4196                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4197                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4198
4199   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4200     is_friend = true;
4201
4202   if (is_friend)
4203     /* For a friend, we want the context of the friend function, not
4204        the type of which it is a friend.  */
4205     ctx = DECL_CONTEXT (decl);
4206   else if (CP_DECL_CONTEXT (decl)
4207            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4208     /* In the case of a virtual function, we want the class in which
4209        it is defined.  */
4210     ctx = CP_DECL_CONTEXT (decl);
4211   else
4212     /* Otherwise, if we're currently defining some class, the DECL
4213        is assumed to be a member of the class.  */
4214     ctx = current_scope ();
4215
4216   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4217     ctx = NULL_TREE;
4218
4219   if (!DECL_CONTEXT (decl))
4220     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4221
4222   /* See if this is a primary template.  */
4223   if (is_friend && ctx)
4224     /* A friend template that specifies a class context, i.e.
4225          template <typename T> friend void A<T>::f();
4226        is not primary.  */
4227     primary = 0;
4228   else
4229     primary = template_parm_scope_p ();
4230
4231   if (primary)
4232     {
4233       if (DECL_CLASS_SCOPE_P (decl))
4234         member_template_p = true;
4235       if (TREE_CODE (decl) == TYPE_DECL
4236           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4237         {
4238           error ("template class without a name");
4239           return error_mark_node;
4240         }
4241       else if (TREE_CODE (decl) == FUNCTION_DECL)
4242         {
4243           if (DECL_DESTRUCTOR_P (decl))
4244             {
4245               /* [temp.mem]
4246
4247                  A destructor shall not be a member template.  */
4248               error ("destructor %qD declared as member template", decl);
4249               return error_mark_node;
4250             }
4251           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4252               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4253                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4254                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4255                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4256                       == void_list_node)))
4257             {
4258               /* [basic.stc.dynamic.allocation]
4259
4260                  An allocation function can be a function
4261                  template. ... Template allocation functions shall
4262                  have two or more parameters.  */
4263               error ("invalid template declaration of %qD", decl);
4264               return error_mark_node;
4265             }
4266         }
4267       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4268                && CLASS_TYPE_P (TREE_TYPE (decl)))
4269         /* OK */;
4270       else
4271         {
4272           error ("template declaration of %q#D", decl);
4273           return error_mark_node;
4274         }
4275     }
4276
4277   /* Check to see that the rules regarding the use of default
4278      arguments are not being violated.  */
4279   check_default_tmpl_args (decl, current_template_parms,
4280                            primary, is_partial, /*is_friend_decl=*/0);
4281
4282   /* Ensure that there are no parameter packs in the type of this
4283      declaration that have not been expanded.  */
4284   if (TREE_CODE (decl) == FUNCTION_DECL)
4285     {
4286       /* Check each of the arguments individually to see if there are
4287          any bare parameter packs.  */
4288       tree type = TREE_TYPE (decl);
4289       tree arg = DECL_ARGUMENTS (decl);
4290       tree argtype = TYPE_ARG_TYPES (type);
4291
4292       while (arg && argtype)
4293         {
4294           if (!FUNCTION_PARAMETER_PACK_P (arg)
4295               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4296             {
4297             /* This is a PARM_DECL that contains unexpanded parameter
4298                packs. We have already complained about this in the
4299                check_for_bare_parameter_packs call, so just replace
4300                these types with ERROR_MARK_NODE.  */
4301               TREE_TYPE (arg) = error_mark_node;
4302               TREE_VALUE (argtype) = error_mark_node;
4303             }
4304
4305           arg = TREE_CHAIN (arg);
4306           argtype = TREE_CHAIN (argtype);
4307         }
4308
4309       /* Check for bare parameter packs in the return type and the
4310          exception specifiers.  */
4311       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4312         /* Errors were already issued, set return type to int
4313            as the frontend doesn't expect error_mark_node as
4314            the return type.  */
4315         TREE_TYPE (type) = integer_type_node;
4316       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4317         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4318     }
4319   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4320     {
4321       TREE_TYPE (decl) = error_mark_node;
4322       return error_mark_node;
4323     }
4324
4325   if (is_partial)
4326     return process_partial_specialization (decl);
4327
4328   args = current_template_args ();
4329
4330   if (!ctx
4331       || TREE_CODE (ctx) == FUNCTION_DECL
4332       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4333       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4334     {
4335       if (DECL_LANG_SPECIFIC (decl)
4336           && DECL_TEMPLATE_INFO (decl)
4337           && DECL_TI_TEMPLATE (decl))
4338         tmpl = DECL_TI_TEMPLATE (decl);
4339       /* If DECL is a TYPE_DECL for a class-template, then there won't
4340          be DECL_LANG_SPECIFIC.  The information equivalent to
4341          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4342       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4343                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4344                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4345         {
4346           /* Since a template declaration already existed for this
4347              class-type, we must be redeclaring it here.  Make sure
4348              that the redeclaration is valid.  */
4349           redeclare_class_template (TREE_TYPE (decl),
4350                                     current_template_parms);
4351           /* We don't need to create a new TEMPLATE_DECL; just use the
4352              one we already had.  */
4353           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4354         }
4355       else
4356         {
4357           tmpl = build_template_decl (decl, current_template_parms,
4358                                       member_template_p);
4359           new_template_p = 1;
4360
4361           if (DECL_LANG_SPECIFIC (decl)
4362               && DECL_TEMPLATE_SPECIALIZATION (decl))
4363             {
4364               /* A specialization of a member template of a template
4365                  class.  */
4366               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4367               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4368               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4369             }
4370         }
4371     }
4372   else
4373     {
4374       tree a, t, current, parms;
4375       int i;
4376       tree tinfo = get_template_info (decl);
4377
4378       if (!tinfo)
4379         {
4380           error ("template definition of non-template %q#D", decl);
4381           return error_mark_node;
4382         }
4383
4384       tmpl = TI_TEMPLATE (tinfo);
4385
4386       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4387           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4388           && DECL_TEMPLATE_SPECIALIZATION (decl)
4389           && DECL_MEMBER_TEMPLATE_P (tmpl))
4390         {
4391           tree new_tmpl;
4392
4393           /* The declaration is a specialization of a member
4394              template, declared outside the class.  Therefore, the
4395              innermost template arguments will be NULL, so we
4396              replace them with the arguments determined by the
4397              earlier call to check_explicit_specialization.  */
4398           args = DECL_TI_ARGS (decl);
4399
4400           new_tmpl
4401             = build_template_decl (decl, current_template_parms,
4402                                    member_template_p);
4403           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4404           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4405           DECL_TI_TEMPLATE (decl) = new_tmpl;
4406           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4407           DECL_TEMPLATE_INFO (new_tmpl)
4408             = build_template_info (tmpl, args);
4409
4410           register_specialization (new_tmpl,
4411                                    most_general_template (tmpl),
4412                                    args,
4413                                    is_friend, 0);
4414           return decl;
4415         }
4416
4417       /* Make sure the template headers we got make sense.  */
4418
4419       parms = DECL_TEMPLATE_PARMS (tmpl);
4420       i = TMPL_PARMS_DEPTH (parms);
4421       if (TMPL_ARGS_DEPTH (args) != i)
4422         {
4423           error ("expected %d levels of template parms for %q#D, got %d",
4424                  i, decl, TMPL_ARGS_DEPTH (args));
4425         }
4426       else
4427         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4428           {
4429             a = TMPL_ARGS_LEVEL (args, i);
4430             t = INNERMOST_TEMPLATE_PARMS (parms);
4431
4432             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4433               {
4434                 if (current == decl)
4435                   error ("got %d template parameters for %q#D",
4436                          TREE_VEC_LENGTH (a), decl);
4437                 else
4438                   error ("got %d template parameters for %q#T",
4439                          TREE_VEC_LENGTH (a), current);
4440                 error ("  but %d required", TREE_VEC_LENGTH (t));
4441                 return error_mark_node;
4442               }
4443
4444             if (current == decl)
4445               current = ctx;
4446             else
4447               current = (TYPE_P (current)
4448                          ? TYPE_CONTEXT (current)
4449                          : DECL_CONTEXT (current));
4450           }
4451
4452       /* Check that the parms are used in the appropriate qualifying scopes
4453          in the declarator.  */
4454       if (!comp_template_args
4455           (TI_ARGS (tinfo),
4456            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4457         {
4458           error ("\
4459 template arguments to %qD do not match original template %qD",
4460                  decl, DECL_TEMPLATE_RESULT (tmpl));
4461           if (!uses_template_parms (TI_ARGS (tinfo)))
4462             inform (input_location, "use template<> for an explicit specialization");
4463           /* Avoid crash in import_export_decl.  */
4464           DECL_INTERFACE_KNOWN (decl) = 1;
4465           return error_mark_node;
4466         }
4467     }
4468
4469   DECL_TEMPLATE_RESULT (tmpl) = decl;
4470   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4471
4472   /* Push template declarations for global functions and types.  Note
4473      that we do not try to push a global template friend declared in a
4474      template class; such a thing may well depend on the template
4475      parameters of the class.  */
4476   if (new_template_p && !ctx
4477       && !(is_friend && template_class_depth (current_class_type) > 0))
4478     {
4479       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4480       if (tmpl == error_mark_node)
4481         return error_mark_node;
4482
4483       /* Hide template friend classes that haven't been declared yet.  */
4484       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4485         {
4486           DECL_ANTICIPATED (tmpl) = 1;
4487           DECL_FRIEND_P (tmpl) = 1;
4488         }
4489     }
4490
4491   if (primary)
4492     {
4493       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4494       int i;
4495
4496       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4497       if (DECL_CONV_FN_P (tmpl))
4498         {
4499           int depth = TMPL_PARMS_DEPTH (parms);
4500
4501           /* It is a conversion operator. See if the type converted to
4502              depends on innermost template operands.  */
4503
4504           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4505                                          depth))
4506             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4507         }
4508
4509       /* Give template template parms a DECL_CONTEXT of the template
4510          for which they are a parameter.  */
4511       parms = INNERMOST_TEMPLATE_PARMS (parms);
4512       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4513         {
4514           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4515           if (TREE_CODE (parm) == TEMPLATE_DECL)
4516             DECL_CONTEXT (parm) = tmpl;
4517
4518           if (TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM)
4519             DECL_CONTEXT (TYPE_NAME (TREE_TYPE (parm))) = tmpl;
4520         }
4521     }
4522
4523   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4524      back to its most general template.  If TMPL is a specialization,
4525      ARGS may only have the innermost set of arguments.  Add the missing
4526      argument levels if necessary.  */
4527   if (DECL_TEMPLATE_INFO (tmpl))
4528     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4529
4530   info = build_template_info (tmpl, args);
4531
4532   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4533     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4534   else if (DECL_LANG_SPECIFIC (decl))
4535     DECL_TEMPLATE_INFO (decl) = info;
4536
4537   return DECL_TEMPLATE_RESULT (tmpl);
4538 }
4539
4540 tree
4541 push_template_decl (tree decl)
4542 {
4543   return push_template_decl_real (decl, false);
4544 }
4545
4546 /* Called when a class template TYPE is redeclared with the indicated
4547    template PARMS, e.g.:
4548
4549      template <class T> struct S;
4550      template <class T> struct S {};  */
4551
4552 bool
4553 redeclare_class_template (tree type, tree parms)
4554 {
4555   tree tmpl;
4556   tree tmpl_parms;
4557   int i;
4558
4559   if (!TYPE_TEMPLATE_INFO (type))
4560     {
4561       error ("%qT is not a template type", type);
4562       return false;
4563     }
4564
4565   tmpl = TYPE_TI_TEMPLATE (type);
4566   if (!PRIMARY_TEMPLATE_P (tmpl))
4567     /* The type is nested in some template class.  Nothing to worry
4568        about here; there are no new template parameters for the nested
4569        type.  */
4570     return true;
4571
4572   if (!parms)
4573     {
4574       error ("template specifiers not specified in declaration of %qD",
4575              tmpl);
4576       return false;
4577     }
4578
4579   parms = INNERMOST_TEMPLATE_PARMS (parms);
4580   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4581
4582   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4583     {
4584       error ("redeclared with %d template parameter(s)", 
4585              TREE_VEC_LENGTH (parms));
4586       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4587              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4588       return false;
4589     }
4590
4591   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4592     {
4593       tree tmpl_parm;
4594       tree parm;
4595       tree tmpl_default;
4596       tree parm_default;
4597
4598       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4599           || TREE_VEC_ELT (parms, i) == error_mark_node)
4600         continue;
4601
4602       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4603       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4604       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4605       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4606
4607       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4608          TEMPLATE_DECL.  */
4609       if (tmpl_parm != error_mark_node
4610           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4611               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4612                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4613               || (TREE_CODE (tmpl_parm) != PARM_DECL
4614                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4615                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4616               || (TREE_CODE (tmpl_parm) == PARM_DECL
4617                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4618                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4619         {
4620           error ("template parameter %q+#D", tmpl_parm);
4621           error ("redeclared here as %q#D", parm);
4622           return false;
4623         }
4624
4625       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4626         {
4627           /* We have in [temp.param]:
4628
4629              A template-parameter may not be given default arguments
4630              by two different declarations in the same scope.  */
4631           error_at (input_location, "redefinition of default argument for %q#D", parm);
4632           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4633                   "original definition appeared here");
4634           return false;
4635         }
4636
4637       if (parm_default != NULL_TREE)
4638         /* Update the previous template parameters (which are the ones
4639            that will really count) with the new default value.  */
4640         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4641       else if (tmpl_default != NULL_TREE)
4642         /* Update the new parameters, too; they'll be used as the
4643            parameters for any members.  */
4644         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4645     }
4646
4647     return true;
4648 }
4649
4650 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4651    (possibly simplified) expression.  */
4652
4653 tree
4654 fold_non_dependent_expr (tree expr)
4655 {
4656   if (expr == NULL_TREE)
4657     return NULL_TREE;
4658
4659   /* If we're in a template, but EXPR isn't value dependent, simplify
4660      it.  We're supposed to treat:
4661
4662        template <typename T> void f(T[1 + 1]);
4663        template <typename T> void f(T[2]);
4664
4665      as two declarations of the same function, for example.  */
4666   if (processing_template_decl
4667       && !type_dependent_expression_p (expr)
4668       && !value_dependent_expression_p (expr))
4669     {
4670       HOST_WIDE_INT saved_processing_template_decl;
4671
4672       saved_processing_template_decl = processing_template_decl;
4673       processing_template_decl = 0;
4674       expr = tsubst_copy_and_build (expr,
4675                                     /*args=*/NULL_TREE,
4676                                     tf_error,
4677                                     /*in_decl=*/NULL_TREE,
4678                                     /*function_p=*/false,
4679                                     /*integral_constant_expression_p=*/true);
4680       processing_template_decl = saved_processing_template_decl;
4681     }
4682   return expr;
4683 }
4684
4685 /* EXPR is an expression which is used in a constant-expression context.
4686    For instance, it could be a VAR_DECL with a constant initializer.
4687    Extract the innermost constant expression.
4688
4689    This is basically a more powerful version of
4690    integral_constant_value, which can be used also in templates where
4691    initializers can maintain a syntactic rather than semantic form
4692    (even if they are non-dependent, for access-checking purposes).  */
4693
4694 static tree
4695 fold_decl_constant_value (tree expr)
4696 {
4697   tree const_expr = expr;
4698   do
4699     {
4700       expr = fold_non_dependent_expr (const_expr);
4701       const_expr = integral_constant_value (expr);
4702     }
4703   while (expr != const_expr);
4704
4705   return expr;
4706 }
4707
4708 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4709    must be a function or a pointer-to-function type, as specified
4710    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4711    and check that the resulting function has external linkage.  */
4712
4713 static tree
4714 convert_nontype_argument_function (tree type, tree expr)
4715 {
4716   tree fns = expr;
4717   tree fn, fn_no_ptr;
4718
4719   fn = instantiate_type (type, fns, tf_none);
4720   if (fn == error_mark_node)
4721     return error_mark_node;
4722
4723   fn_no_ptr = fn;
4724   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4725     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4726   if (TREE_CODE (fn_no_ptr) == BASELINK)
4727     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4728  
4729   /* [temp.arg.nontype]/1
4730
4731      A template-argument for a non-type, non-template template-parameter
4732      shall be one of:
4733      [...]
4734      -- the address of an object or function with external linkage.  */
4735   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4736     {
4737       error ("%qE is not a valid template argument for type %qT "
4738              "because function %qD has not external linkage",
4739              expr, type, fn_no_ptr);
4740       return NULL_TREE;
4741     }
4742
4743   return fn;
4744 }
4745
4746 /* Subroutine of convert_nontype_argument.
4747    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4748    Emit an error otherwise.  */
4749
4750 static bool
4751 check_valid_ptrmem_cst_expr (tree type, tree expr)
4752 {
4753   STRIP_NOPS (expr);
4754   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4755     return true;
4756   error ("%qE is not a valid template argument for type %qT",
4757          expr, type);
4758   error ("it must be a pointer-to-member of the form `&X::Y'");
4759   return false;
4760 }
4761
4762 /* Attempt to convert the non-type template parameter EXPR to the
4763    indicated TYPE.  If the conversion is successful, return the
4764    converted value.  If the conversion is unsuccessful, return
4765    NULL_TREE if we issued an error message, or error_mark_node if we
4766    did not.  We issue error messages for out-and-out bad template
4767    parameters, but not simply because the conversion failed, since we
4768    might be just trying to do argument deduction.  Both TYPE and EXPR
4769    must be non-dependent.
4770
4771    The conversion follows the special rules described in
4772    [temp.arg.nontype], and it is much more strict than an implicit
4773    conversion.
4774
4775    This function is called twice for each template argument (see
4776    lookup_template_class for a more accurate description of this
4777    problem). This means that we need to handle expressions which
4778    are not valid in a C++ source, but can be created from the
4779    first call (for instance, casts to perform conversions). These
4780    hacks can go away after we fix the double coercion problem.  */
4781
4782 static tree
4783 convert_nontype_argument (tree type, tree expr)
4784 {
4785   tree expr_type;
4786
4787   /* Detect immediately string literals as invalid non-type argument.
4788      This special-case is not needed for correctness (we would easily
4789      catch this later), but only to provide better diagnostic for this
4790      common user mistake. As suggested by DR 100, we do not mention
4791      linkage issues in the diagnostic as this is not the point.  */
4792   if (TREE_CODE (expr) == STRING_CST)
4793     {
4794       error ("%qE is not a valid template argument for type %qT "
4795              "because string literals can never be used in this context",
4796              expr, type);
4797       return NULL_TREE;
4798     }
4799
4800   /* If we are in a template, EXPR may be non-dependent, but still
4801      have a syntactic, rather than semantic, form.  For example, EXPR
4802      might be a SCOPE_REF, rather than the VAR_DECL to which the
4803      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4804      so that access checking can be performed when the template is
4805      instantiated -- but here we need the resolved form so that we can
4806      convert the argument.  */
4807   expr = fold_non_dependent_expr (expr);
4808   if (error_operand_p (expr))
4809     return error_mark_node;
4810   expr_type = TREE_TYPE (expr);
4811
4812   /* HACK: Due to double coercion, we can get a
4813      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4814      which is the tree that we built on the first call (see
4815      below when coercing to reference to object or to reference to
4816      function). We just strip everything and get to the arg.
4817      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4818      for examples.  */
4819   if (TREE_CODE (expr) == NOP_EXPR)
4820     {
4821       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4822         {
4823           /* ??? Maybe we could use convert_from_reference here, but we
4824              would need to relax its constraints because the NOP_EXPR
4825              could actually change the type to something more cv-qualified,
4826              and this is not folded by convert_from_reference.  */
4827           tree addr = TREE_OPERAND (expr, 0);
4828           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4829           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4830           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4831           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4832                       (TREE_TYPE (expr_type),
4833                        TREE_TYPE (TREE_TYPE (addr))));
4834
4835           expr = TREE_OPERAND (addr, 0);
4836           expr_type = TREE_TYPE (expr);
4837         }
4838
4839       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4840          parameter is a pointer to object, through decay and
4841          qualification conversion. Let's strip everything.  */
4842       else if (TYPE_PTROBV_P (type))
4843         {
4844           STRIP_NOPS (expr);
4845           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4846           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4847           /* Skip the ADDR_EXPR only if it is part of the decay for
4848              an array. Otherwise, it is part of the original argument
4849              in the source code.  */
4850           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4851             expr = TREE_OPERAND (expr, 0);
4852           expr_type = TREE_TYPE (expr);
4853         }
4854     }
4855
4856   /* [temp.arg.nontype]/5, bullet 1
4857
4858      For a non-type template-parameter of integral or enumeration type,
4859      integral promotions (_conv.prom_) and integral conversions
4860      (_conv.integral_) are applied.  */
4861   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4862     {
4863       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4864         return error_mark_node;
4865
4866       expr = fold_decl_constant_value (expr);
4867       /* Notice that there are constant expressions like '4 % 0' which
4868          do not fold into integer constants.  */
4869       if (TREE_CODE (expr) != INTEGER_CST)
4870         {
4871           error ("%qE is not a valid template argument for type %qT "
4872                  "because it is a non-constant expression", expr, type);
4873           return NULL_TREE;
4874         }
4875
4876       /* At this point, an implicit conversion does what we want,
4877          because we already know that the expression is of integral
4878          type.  */
4879       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4880       if (expr == error_mark_node)
4881         return error_mark_node;
4882
4883       /* Conversion was allowed: fold it to a bare integer constant.  */
4884       expr = fold (expr);
4885     }
4886   /* [temp.arg.nontype]/5, bullet 2
4887
4888      For a non-type template-parameter of type pointer to object,
4889      qualification conversions (_conv.qual_) and the array-to-pointer
4890      conversion (_conv.array_) are applied.  */
4891   else if (TYPE_PTROBV_P (type))
4892     {
4893       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4894
4895          A template-argument for a non-type, non-template template-parameter
4896          shall be one of: [...]
4897
4898          -- the name of a non-type template-parameter;
4899          -- the address of an object or function with external linkage, [...]
4900             expressed as "& id-expression" where the & is optional if the name
4901             refers to a function or array, or if the corresponding
4902             template-parameter is a reference.
4903
4904         Here, we do not care about functions, as they are invalid anyway
4905         for a parameter of type pointer-to-object.  */
4906
4907       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4908         /* Non-type template parameters are OK.  */
4909         ;
4910       else if (TREE_CODE (expr) != ADDR_EXPR
4911                && TREE_CODE (expr_type) != ARRAY_TYPE)
4912         {
4913           if (TREE_CODE (expr) == VAR_DECL)
4914             {
4915               error ("%qD is not a valid template argument "
4916                      "because %qD is a variable, not the address of "
4917                      "a variable",
4918                      expr, expr);
4919               return NULL_TREE;
4920             }
4921           /* Other values, like integer constants, might be valid
4922              non-type arguments of some other type.  */
4923           return error_mark_node;
4924         }
4925       else
4926         {
4927           tree decl;
4928
4929           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4930                   ? TREE_OPERAND (expr, 0) : expr);
4931           if (TREE_CODE (decl) != VAR_DECL)
4932             {
4933               error ("%qE is not a valid template argument of type %qT "
4934                      "because %qE is not a variable",
4935                      expr, type, decl);
4936               return NULL_TREE;
4937             }
4938           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4939             {
4940               error ("%qE is not a valid template argument of type %qT "
4941                      "because %qD does not have external linkage",
4942                      expr, type, decl);
4943               return NULL_TREE;
4944             }
4945         }
4946
4947       expr = decay_conversion (expr);
4948       if (expr == error_mark_node)
4949         return error_mark_node;
4950
4951       expr = perform_qualification_conversions (type, expr);
4952       if (expr == error_mark_node)
4953         return error_mark_node;
4954     }
4955   /* [temp.arg.nontype]/5, bullet 3
4956
4957      For a non-type template-parameter of type reference to object, no
4958      conversions apply. The type referred to by the reference may be more
4959      cv-qualified than the (otherwise identical) type of the
4960      template-argument. The template-parameter is bound directly to the
4961      template-argument, which must be an lvalue.  */
4962   else if (TYPE_REF_OBJ_P (type))
4963     {
4964       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4965                                                       expr_type))
4966         return error_mark_node;
4967
4968       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4969         {
4970           error ("%qE is not a valid template argument for type %qT "
4971                  "because of conflicts in cv-qualification", expr, type);
4972           return NULL_TREE;
4973         }
4974
4975       if (!real_lvalue_p (expr))
4976         {
4977           error ("%qE is not a valid template argument for type %qT "
4978                  "because it is not an lvalue", expr, type);
4979           return NULL_TREE;
4980         }
4981
4982       /* [temp.arg.nontype]/1
4983
4984          A template-argument for a non-type, non-template template-parameter
4985          shall be one of: [...]
4986
4987          -- the address of an object or function with external linkage.  */
4988       if (TREE_CODE (expr) == INDIRECT_REF
4989           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
4990         {
4991           expr = TREE_OPERAND (expr, 0);
4992           if (DECL_P (expr))
4993             {
4994               error ("%q#D is not a valid template argument for type %qT "
4995                      "because a reference variable does not have a constant "
4996                      "address", expr, type);
4997               return NULL_TREE;
4998             }
4999         }
5000
5001       if (!DECL_P (expr))
5002         {
5003           error ("%qE is not a valid template argument for type %qT "
5004                  "because it is not an object with external linkage",
5005                  expr, type);
5006           return NULL_TREE;
5007         }
5008
5009       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5010         {
5011           error ("%qE is not a valid template argument for type %qT "
5012                  "because object %qD has not external linkage",
5013                  expr, type, expr);
5014           return NULL_TREE;
5015         }
5016
5017       expr = build_nop (type, build_address (expr));
5018     }
5019   /* [temp.arg.nontype]/5, bullet 4
5020
5021      For a non-type template-parameter of type pointer to function, only
5022      the function-to-pointer conversion (_conv.func_) is applied. If the
5023      template-argument represents a set of overloaded functions (or a
5024      pointer to such), the matching function is selected from the set
5025      (_over.over_).  */
5026   else if (TYPE_PTRFN_P (type))
5027     {
5028       /* If the argument is a template-id, we might not have enough
5029          context information to decay the pointer.  */
5030       if (!type_unknown_p (expr_type))
5031         {
5032           expr = decay_conversion (expr);
5033           if (expr == error_mark_node)
5034             return error_mark_node;
5035         }
5036
5037       expr = convert_nontype_argument_function (type, expr);
5038       if (!expr || expr == error_mark_node)
5039         return expr;
5040
5041       if (TREE_CODE (expr) != ADDR_EXPR)
5042         {
5043           error ("%qE is not a valid template argument for type %qT", expr, type);
5044           error ("it must be the address of a function with external linkage");
5045           return NULL_TREE;
5046         }
5047     }
5048   /* [temp.arg.nontype]/5, bullet 5
5049
5050      For a non-type template-parameter of type reference to function, no
5051      conversions apply. If the template-argument represents a set of
5052      overloaded functions, the matching function is selected from the set
5053      (_over.over_).  */
5054   else if (TYPE_REFFN_P (type))
5055     {
5056       if (TREE_CODE (expr) == ADDR_EXPR)
5057         {
5058           error ("%qE is not a valid template argument for type %qT "
5059                  "because it is a pointer", expr, type);
5060           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5061           return NULL_TREE;
5062         }
5063
5064       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5065       if (!expr || expr == error_mark_node)
5066         return expr;
5067
5068       expr = build_nop (type, build_address (expr));
5069     }
5070   /* [temp.arg.nontype]/5, bullet 6
5071
5072      For a non-type template-parameter of type pointer to member function,
5073      no conversions apply. If the template-argument represents a set of
5074      overloaded member functions, the matching member function is selected
5075      from the set (_over.over_).  */
5076   else if (TYPE_PTRMEMFUNC_P (type))
5077     {
5078       expr = instantiate_type (type, expr, tf_none);
5079       if (expr == error_mark_node)
5080         return error_mark_node;
5081
5082       /* [temp.arg.nontype] bullet 1 says the pointer to member
5083          expression must be a pointer-to-member constant.  */
5084       if (!check_valid_ptrmem_cst_expr (type, expr))
5085         return error_mark_node;
5086
5087       /* There is no way to disable standard conversions in
5088          resolve_address_of_overloaded_function (called by
5089          instantiate_type). It is possible that the call succeeded by
5090          converting &B::I to &D::I (where B is a base of D), so we need
5091          to reject this conversion here.
5092
5093          Actually, even if there was a way to disable standard conversions,
5094          it would still be better to reject them here so that we can
5095          provide a superior diagnostic.  */
5096       if (!same_type_p (TREE_TYPE (expr), type))
5097         {
5098           /* Make sure we are just one standard conversion off.  */
5099           gcc_assert (can_convert (type, TREE_TYPE (expr)));
5100           error ("%qE is not a valid template argument for type %qT "
5101                  "because it is of type %qT", expr, type,
5102                  TREE_TYPE (expr));
5103           inform (input_location, "standard conversions are not allowed in this context");
5104           return NULL_TREE;
5105         }
5106     }
5107   /* [temp.arg.nontype]/5, bullet 7
5108
5109      For a non-type template-parameter of type pointer to data member,
5110      qualification conversions (_conv.qual_) are applied.  */
5111   else if (TYPE_PTRMEM_P (type))
5112     {
5113       /* [temp.arg.nontype] bullet 1 says the pointer to member
5114          expression must be a pointer-to-member constant.  */
5115       if (!check_valid_ptrmem_cst_expr (type, expr))
5116         return error_mark_node;
5117
5118       expr = perform_qualification_conversions (type, expr);
5119       if (expr == error_mark_node)
5120         return expr;
5121     }
5122   /* A template non-type parameter must be one of the above.  */
5123   else
5124     gcc_unreachable ();
5125
5126   /* Sanity check: did we actually convert the argument to the
5127      right type?  */
5128   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5129   return expr;
5130 }
5131
5132 /* Subroutine of coerce_template_template_parms, which returns 1 if
5133    PARM_PARM and ARG_PARM match using the rule for the template
5134    parameters of template template parameters. Both PARM and ARG are
5135    template parameters; the rest of the arguments are the same as for
5136    coerce_template_template_parms.
5137  */
5138 static int
5139 coerce_template_template_parm (tree parm,
5140                               tree arg,
5141                               tsubst_flags_t complain,
5142                               tree in_decl,
5143                               tree outer_args)
5144 {
5145   if (arg == NULL_TREE || arg == error_mark_node
5146       || parm == NULL_TREE || parm == error_mark_node)
5147     return 0;
5148   
5149   if (TREE_CODE (arg) != TREE_CODE (parm))
5150     return 0;
5151   
5152   switch (TREE_CODE (parm))
5153     {
5154     case TEMPLATE_DECL:
5155       /* We encounter instantiations of templates like
5156          template <template <template <class> class> class TT>
5157          class C;  */
5158       {
5159         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5160         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5161         
5162         if (!coerce_template_template_parms
5163             (parmparm, argparm, complain, in_decl, outer_args))
5164           return 0;
5165       }
5166       /* Fall through.  */
5167       
5168     case TYPE_DECL:
5169       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5170           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5171         /* Argument is a parameter pack but parameter is not.  */
5172         return 0;
5173       break;
5174       
5175     case PARM_DECL:
5176       /* The tsubst call is used to handle cases such as
5177          
5178            template <int> class C {};
5179            template <class T, template <T> class TT> class D {};
5180            D<int, C> d;
5181
5182          i.e. the parameter list of TT depends on earlier parameters.  */
5183       if (!uses_template_parms (TREE_TYPE (arg))
5184           && !same_type_p
5185                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5186                  TREE_TYPE (arg)))
5187         return 0;
5188       
5189       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5190           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5191         /* Argument is a parameter pack but parameter is not.  */
5192         return 0;
5193       
5194       break;
5195
5196     default:
5197       gcc_unreachable ();
5198     }
5199
5200   return 1;
5201 }
5202
5203
5204 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5205    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5206    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5207    or PARM_DECL.
5208
5209    Consider the example:
5210      template <class T> class A;
5211      template<template <class U> class TT> class B;
5212
5213    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5214    the parameters to A, and OUTER_ARGS contains A.  */
5215
5216 static int
5217 coerce_template_template_parms (tree parm_parms,
5218                                 tree arg_parms,
5219                                 tsubst_flags_t complain,
5220                                 tree in_decl,
5221                                 tree outer_args)
5222 {
5223   int nparms, nargs, i;
5224   tree parm, arg;
5225   int variadic_p = 0;
5226
5227   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5228   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5229
5230   nparms = TREE_VEC_LENGTH (parm_parms);
5231   nargs = TREE_VEC_LENGTH (arg_parms);
5232
5233   /* Determine whether we have a parameter pack at the end of the
5234      template template parameter's template parameter list.  */
5235   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5236     {
5237       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5238       
5239       if (parm == error_mark_node)
5240         return 0;
5241
5242       switch (TREE_CODE (parm))
5243         {
5244         case TEMPLATE_DECL:
5245         case TYPE_DECL:
5246           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5247             variadic_p = 1;
5248           break;
5249           
5250         case PARM_DECL:
5251           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5252             variadic_p = 1;
5253           break;
5254           
5255         default:
5256           gcc_unreachable ();
5257         }
5258     }
5259  
5260   if (nargs != nparms
5261       && !(variadic_p && nargs >= nparms - 1))
5262     return 0;
5263
5264   /* Check all of the template parameters except the parameter pack at
5265      the end (if any).  */
5266   for (i = 0; i < nparms - variadic_p; ++i)
5267     {
5268       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5269           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5270         continue;
5271
5272       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5273       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5274
5275       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5276                                           outer_args))
5277         return 0;
5278
5279     }
5280
5281   if (variadic_p)
5282     {
5283       /* Check each of the template parameters in the template
5284          argument against the template parameter pack at the end of
5285          the template template parameter.  */
5286       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5287         return 0;
5288
5289       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5290
5291       for (; i < nargs; ++i)
5292         {
5293           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5294             continue;
5295  
5296           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5297  
5298           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5299                                               outer_args))
5300             return 0;
5301         }
5302     }
5303
5304   return 1;
5305 }
5306
5307 /* Verifies that the deduced template arguments (in TARGS) for the
5308    template template parameters (in TPARMS) represent valid bindings,
5309    by comparing the template parameter list of each template argument
5310    to the template parameter list of its corresponding template
5311    template parameter, in accordance with DR150. This
5312    routine can only be called after all template arguments have been
5313    deduced. It will return TRUE if all of the template template
5314    parameter bindings are okay, FALSE otherwise.  */
5315 bool 
5316 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5317 {
5318   int i, ntparms = TREE_VEC_LENGTH (tparms);
5319   bool ret = true;
5320
5321   /* We're dealing with template parms in this process.  */
5322   ++processing_template_decl;
5323
5324   targs = INNERMOST_TEMPLATE_ARGS (targs);
5325
5326   for (i = 0; i < ntparms; ++i)
5327     {
5328       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5329       tree targ = TREE_VEC_ELT (targs, i);
5330
5331       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5332         {
5333           tree packed_args = NULL_TREE;
5334           int idx, len = 1;
5335
5336           if (ARGUMENT_PACK_P (targ))
5337             {
5338               /* Look inside the argument pack.  */
5339               packed_args = ARGUMENT_PACK_ARGS (targ);
5340               len = TREE_VEC_LENGTH (packed_args);
5341             }
5342
5343           for (idx = 0; idx < len; ++idx)
5344             {
5345               tree targ_parms = NULL_TREE;
5346
5347               if (packed_args)
5348                 /* Extract the next argument from the argument
5349                    pack.  */
5350                 targ = TREE_VEC_ELT (packed_args, idx);
5351
5352               if (PACK_EXPANSION_P (targ))
5353                 /* Look at the pattern of the pack expansion.  */
5354                 targ = PACK_EXPANSION_PATTERN (targ);
5355
5356               /* Extract the template parameters from the template
5357                  argument.  */
5358               if (TREE_CODE (targ) == TEMPLATE_DECL)
5359                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5360               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5361                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5362
5363               /* Verify that we can coerce the template template
5364                  parameters from the template argument to the template
5365                  parameter.  This requires an exact match.  */
5366               if (targ_parms
5367                   && !coerce_template_template_parms
5368                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5369                         targ_parms,
5370                         tf_none,
5371                         tparm,
5372                         targs))
5373                 {
5374                   ret = false;
5375                   goto out;
5376                 }
5377             }
5378         }
5379     }
5380
5381  out:
5382
5383   --processing_template_decl;
5384   return ret;
5385 }
5386
5387 /* Convert the indicated template ARG as necessary to match the
5388    indicated template PARM.  Returns the converted ARG, or
5389    error_mark_node if the conversion was unsuccessful.  Error and
5390    warning messages are issued under control of COMPLAIN.  This
5391    conversion is for the Ith parameter in the parameter list.  ARGS is
5392    the full set of template arguments deduced so far.  */
5393
5394 static tree
5395 convert_template_argument (tree parm,
5396                            tree arg,
5397                            tree args,
5398                            tsubst_flags_t complain,
5399                            int i,
5400                            tree in_decl)
5401 {
5402   tree orig_arg;
5403   tree val;
5404   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5405
5406   if (TREE_CODE (arg) == TREE_LIST
5407       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5408     {
5409       /* The template argument was the name of some
5410          member function.  That's usually
5411          invalid, but static members are OK.  In any
5412          case, grab the underlying fields/functions
5413          and issue an error later if required.  */
5414       orig_arg = TREE_VALUE (arg);
5415       TREE_TYPE (arg) = unknown_type_node;
5416     }
5417
5418   orig_arg = arg;
5419
5420   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5421   requires_type = (TREE_CODE (parm) == TYPE_DECL
5422                    || requires_tmpl_type);
5423
5424   /* When determining whether an argument pack expansion is a template,
5425      look at the pattern.  */
5426   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5427     arg = PACK_EXPANSION_PATTERN (arg);
5428
5429   /* Deal with an injected-class-name used as a template template arg.  */
5430   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5431     {
5432       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5433       if (TREE_CODE (t) == TEMPLATE_DECL)
5434         {
5435           if (complain & tf_warning_or_error)
5436             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5437                      " used as template template argument", TYPE_NAME (arg));
5438           else if (flag_pedantic_errors)
5439             t = arg;
5440
5441           arg = t;
5442         }
5443     }
5444
5445   is_tmpl_type = 
5446     ((TREE_CODE (arg) == TEMPLATE_DECL
5447       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5448      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5449      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5450
5451   if (is_tmpl_type
5452       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5453           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5454     arg = TYPE_STUB_DECL (arg);
5455
5456   is_type = TYPE_P (arg) || is_tmpl_type;
5457
5458   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5459       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5460     {
5461       permerror (input_location, "to refer to a type member of a template parameter, "
5462                  "use %<typename %E%>", orig_arg);
5463
5464       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5465                                      TREE_OPERAND (arg, 1),
5466                                      typename_type,
5467                                      complain & tf_error);
5468       arg = orig_arg;
5469       is_type = 1;
5470     }
5471   if (is_type != requires_type)
5472     {
5473       if (in_decl)
5474         {
5475           if (complain & tf_error)
5476             {
5477               error ("type/value mismatch at argument %d in template "
5478                      "parameter list for %qD",
5479                      i + 1, in_decl);
5480               if (is_type)
5481                 error ("  expected a constant of type %qT, got %qT",
5482                        TREE_TYPE (parm),
5483                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5484               else if (requires_tmpl_type)
5485                 error ("  expected a class template, got %qE", orig_arg);
5486               else
5487                 error ("  expected a type, got %qE", orig_arg);
5488             }
5489         }
5490       return error_mark_node;
5491     }
5492   if (is_tmpl_type ^ requires_tmpl_type)
5493     {
5494       if (in_decl && (complain & tf_error))
5495         {
5496           error ("type/value mismatch at argument %d in template "
5497                  "parameter list for %qD",
5498                  i + 1, in_decl);
5499           if (is_tmpl_type)
5500             error ("  expected a type, got %qT", DECL_NAME (arg));
5501           else
5502             error ("  expected a class template, got %qT", orig_arg);
5503         }
5504       return error_mark_node;
5505     }
5506
5507   if (is_type)
5508     {
5509       if (requires_tmpl_type)
5510         {
5511           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5512             /* The number of argument required is not known yet.
5513                Just accept it for now.  */
5514             val = TREE_TYPE (arg);
5515           else
5516             {
5517               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5518               tree argparm;
5519
5520               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5521
5522               if (coerce_template_template_parms (parmparm, argparm,
5523                                                   complain, in_decl,
5524                                                   args))
5525                 {
5526                   val = arg;
5527
5528                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5529                      TEMPLATE_DECL.  */
5530                   if (val != error_mark_node)
5531                     {
5532                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5533                         val = TREE_TYPE (val);
5534                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5535                         val = make_pack_expansion (val);
5536                     }
5537                 }
5538               else
5539                 {
5540                   if (in_decl && (complain & tf_error))
5541                     {
5542                       error ("type/value mismatch at argument %d in "
5543                              "template parameter list for %qD",
5544                              i + 1, in_decl);
5545                       error ("  expected a template of type %qD, got %qT",
5546                              parm, orig_arg);
5547                     }
5548
5549                   val = error_mark_node;
5550                 }
5551             }
5552         }
5553       else
5554         val = orig_arg;
5555       /* We only form one instance of each template specialization.
5556          Therefore, if we use a non-canonical variant (i.e., a
5557          typedef), any future messages referring to the type will use
5558          the typedef, which is confusing if those future uses do not
5559          themselves also use the typedef.  */
5560       if (TYPE_P (val))
5561         val = strip_typedefs (val);
5562     }
5563   else
5564     {
5565       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5566
5567       if (invalid_nontype_parm_type_p (t, complain))
5568         return error_mark_node;
5569
5570       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5571         {
5572           if (same_type_p (t, TREE_TYPE (orig_arg)))
5573             val = orig_arg;
5574           else
5575             {
5576               /* Not sure if this is reachable, but it doesn't hurt
5577                  to be robust.  */
5578               error ("type mismatch in nontype parameter pack");
5579               val = error_mark_node;
5580             }
5581         }
5582       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5583         /* We used to call digest_init here.  However, digest_init
5584            will report errors, which we don't want when complain
5585            is zero.  More importantly, digest_init will try too
5586            hard to convert things: for example, `0' should not be
5587            converted to pointer type at this point according to
5588            the standard.  Accepting this is not merely an
5589            extension, since deciding whether or not these
5590            conversions can occur is part of determining which
5591            function template to call, or whether a given explicit
5592            argument specification is valid.  */
5593         val = convert_nontype_argument (t, orig_arg);
5594       else
5595         val = orig_arg;
5596
5597       if (val == NULL_TREE)
5598         val = error_mark_node;
5599       else if (val == error_mark_node && (complain & tf_error))
5600         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5601
5602       if (TREE_CODE (val) == SCOPE_REF)
5603         {
5604           /* Strip typedefs from the SCOPE_REF.  */
5605           tree type = strip_typedefs (TREE_TYPE (val));
5606           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5607           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5608                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5609         }
5610     }
5611
5612   return val;
5613 }
5614
5615 /* Coerces the remaining template arguments in INNER_ARGS (from
5616    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5617    Returns the coerced argument pack. PARM_IDX is the position of this
5618    parameter in the template parameter list. ARGS is the original
5619    template argument list.  */
5620 static tree
5621 coerce_template_parameter_pack (tree parms,
5622                                 int parm_idx,
5623                                 tree args,
5624                                 tree inner_args,
5625                                 int arg_idx,
5626                                 tree new_args,
5627                                 int* lost,
5628                                 tree in_decl,
5629                                 tsubst_flags_t complain)
5630 {
5631   tree parm = TREE_VEC_ELT (parms, parm_idx);
5632   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5633   tree packed_args;
5634   tree argument_pack;
5635   tree packed_types = NULL_TREE;
5636
5637   if (arg_idx > nargs)
5638     arg_idx = nargs;
5639
5640   packed_args = make_tree_vec (nargs - arg_idx);
5641
5642   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5643       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5644     {
5645       /* When the template parameter is a non-type template
5646          parameter pack whose type uses parameter packs, we need
5647          to look at each of the template arguments
5648          separately. Build a vector of the types for these
5649          non-type template parameters in PACKED_TYPES.  */
5650       tree expansion 
5651         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5652       packed_types = tsubst_pack_expansion (expansion, args,
5653                                             complain, in_decl);
5654
5655       if (packed_types == error_mark_node)
5656         return error_mark_node;
5657
5658       /* Check that we have the right number of arguments.  */
5659       if (arg_idx < nargs
5660           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5661           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5662         {
5663           int needed_parms 
5664             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5665           error ("wrong number of template arguments (%d, should be %d)",
5666                  nargs, needed_parms);
5667           return error_mark_node;
5668         }
5669
5670       /* If we aren't able to check the actual arguments now
5671          (because they haven't been expanded yet), we can at least
5672          verify that all of the types used for the non-type
5673          template parameter pack are, in fact, valid for non-type
5674          template parameters.  */
5675       if (arg_idx < nargs 
5676           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5677         {
5678           int j, len = TREE_VEC_LENGTH (packed_types);
5679           for (j = 0; j < len; ++j)
5680             {
5681               tree t = TREE_VEC_ELT (packed_types, j);
5682               if (invalid_nontype_parm_type_p (t, complain))
5683                 return error_mark_node;
5684             }
5685         }
5686     }
5687
5688   /* Convert the remaining arguments, which will be a part of the
5689      parameter pack "parm".  */
5690   for (; arg_idx < nargs; ++arg_idx)
5691     {
5692       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5693       tree actual_parm = TREE_VALUE (parm);
5694
5695       if (packed_types && !PACK_EXPANSION_P (arg))
5696         {
5697           /* When we have a vector of types (corresponding to the
5698              non-type template parameter pack that uses parameter
5699              packs in its type, as mention above), and the
5700              argument is not an expansion (which expands to a
5701              currently unknown number of arguments), clone the
5702              parm and give it the next type in PACKED_TYPES.  */
5703           actual_parm = copy_node (actual_parm);
5704           TREE_TYPE (actual_parm) = 
5705             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5706         }
5707
5708       if (arg != error_mark_node)
5709         arg = convert_template_argument (actual_parm, 
5710                                          arg, new_args, complain, parm_idx,
5711                                          in_decl);
5712       if (arg == error_mark_node)
5713         (*lost)++;
5714       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5715     }
5716
5717   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5718       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5719     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5720   else
5721     {
5722       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5723       TREE_TYPE (argument_pack) 
5724         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5725       TREE_CONSTANT (argument_pack) = 1;
5726     }
5727
5728   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5729   return argument_pack;
5730 }
5731
5732 /* Convert all template arguments to their appropriate types, and
5733    return a vector containing the innermost resulting template
5734    arguments.  If any error occurs, return error_mark_node. Error and
5735    warning messages are issued under control of COMPLAIN.
5736
5737    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5738    for arguments not specified in ARGS.  Otherwise, if
5739    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5740    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5741    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5742    ARGS.  */
5743
5744 static tree
5745 coerce_template_parms (tree parms,
5746                        tree args,
5747                        tree in_decl,
5748                        tsubst_flags_t complain,
5749                        bool require_all_args,
5750                        bool use_default_args)
5751 {
5752   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5753   tree inner_args;
5754   tree new_args;
5755   tree new_inner_args;
5756   int saved_unevaluated_operand;
5757   int saved_inhibit_evaluation_warnings;
5758
5759   /* When used as a boolean value, indicates whether this is a
5760      variadic template parameter list. Since it's an int, we can also
5761      subtract it from nparms to get the number of non-variadic
5762      parameters.  */
5763   int variadic_p = 0;
5764
5765   nparms = TREE_VEC_LENGTH (parms);
5766
5767   /* Determine if there are any parameter packs.  */
5768   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5769     {
5770       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5771       if (template_parameter_pack_p (tparm))
5772         ++variadic_p;
5773     }
5774
5775   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5776   /* If there are 0 or 1 parameter packs, we need to expand any argument
5777      packs so that we can deduce a parameter pack from some non-packed args
5778      followed by an argument pack, as in variadic85.C.  If there are more
5779      than that, we need to leave argument packs intact so the arguments are
5780      assigned to the right parameter packs.  This should only happen when
5781      dealing with a nested class inside a partial specialization of a class
5782      template, as in variadic92.C.  */
5783   if (variadic_p <= 1)
5784     inner_args = expand_template_argument_pack (inner_args);
5785
5786   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5787   if ((nargs > nparms && !variadic_p)
5788       || (nargs < nparms - variadic_p
5789           && require_all_args
5790           && (!use_default_args
5791               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5792                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5793     {
5794       if (complain & tf_error)
5795         {
5796           const char *or_more = "";
5797           if (variadic_p)
5798             {
5799               or_more = " or more";
5800               --nparms;
5801             }
5802
5803           error ("wrong number of template arguments (%d, should be %d%s)",
5804                  nargs, nparms, or_more);
5805
5806           if (in_decl)
5807             error ("provided for %q+D", in_decl);
5808         }
5809
5810       return error_mark_node;
5811     }
5812
5813   /* We need to evaluate the template arguments, even though this
5814      template-id may be nested within a "sizeof".  */
5815   saved_unevaluated_operand = cp_unevaluated_operand;
5816   cp_unevaluated_operand = 0;
5817   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5818   c_inhibit_evaluation_warnings = 0;
5819   new_inner_args = make_tree_vec (nparms);
5820   new_args = add_outermost_template_args (args, new_inner_args);
5821   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5822     {
5823       tree arg;
5824       tree parm;
5825
5826       /* Get the Ith template parameter.  */
5827       parm = TREE_VEC_ELT (parms, parm_idx);
5828  
5829       if (parm == error_mark_node)
5830       {
5831         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5832         continue;
5833       }
5834
5835       /* Calculate the next argument.  */
5836       if (arg_idx < nargs)
5837         arg = TREE_VEC_ELT (inner_args, arg_idx);
5838       else
5839         arg = NULL_TREE;
5840
5841       if (template_parameter_pack_p (TREE_VALUE (parm))
5842           && !(arg && ARGUMENT_PACK_P (arg)))
5843         {
5844           /* All remaining arguments will be placed in the
5845              template parameter pack PARM.  */
5846           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5847                                                 inner_args, arg_idx,
5848                                                 new_args, &lost,
5849                                                 in_decl, complain);
5850
5851           /* Store this argument.  */
5852           if (arg == error_mark_node)
5853             lost++;
5854           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5855
5856           /* We are done with all of the arguments.  */
5857           arg_idx = nargs;
5858           
5859           continue;
5860         }
5861       else if (arg)
5862         {
5863           if (PACK_EXPANSION_P (arg))
5864             {
5865               if (complain & tf_error)
5866                 {
5867                   /* FIXME this restriction was removed by N2555; see
5868                      bug 35722.  */
5869                   /* If ARG is a pack expansion, but PARM is not a
5870                      template parameter pack (if it were, we would have
5871                      handled it above), we're trying to expand into a
5872                      fixed-length argument list.  */
5873                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5874                     sorry ("cannot expand %<%E%> into a fixed-length "
5875                            "argument list", arg);
5876                   else
5877                     sorry ("cannot expand %<%T%> into a fixed-length "
5878                            "argument list", arg);
5879                 }
5880               return error_mark_node;
5881             }
5882         }
5883       else if (require_all_args)
5884         /* There must be a default arg in this case.  */
5885         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5886                                    complain, in_decl);
5887       else
5888         break;
5889
5890       if (arg == error_mark_node)
5891         {
5892           if (complain & tf_error)
5893             error ("template argument %d is invalid", arg_idx + 1);
5894         }
5895       else if (!arg)
5896         /* This only occurs if there was an error in the template
5897            parameter list itself (which we would already have
5898            reported) that we are trying to recover from, e.g., a class
5899            template with a parameter list such as
5900            template<typename..., typename>.  */
5901         return error_mark_node;
5902       else
5903         arg = convert_template_argument (TREE_VALUE (parm),
5904                                          arg, new_args, complain, 
5905                                          parm_idx, in_decl);
5906
5907       if (arg == error_mark_node)
5908         lost++;
5909       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5910     }
5911   cp_unevaluated_operand = saved_unevaluated_operand;
5912   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5913
5914   if (lost)
5915     return error_mark_node;
5916
5917   return new_inner_args;
5918 }
5919
5920 /* Returns 1 if template args OT and NT are equivalent.  */
5921
5922 static int
5923 template_args_equal (tree ot, tree nt)
5924 {
5925   if (nt == ot)
5926     return 1;
5927
5928   if (TREE_CODE (nt) == TREE_VEC)
5929     /* For member templates */
5930     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5931   else if (PACK_EXPANSION_P (ot))
5932     return PACK_EXPANSION_P (nt) 
5933       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5934                               PACK_EXPANSION_PATTERN (nt));
5935   else if (ARGUMENT_PACK_P (ot))
5936     {
5937       int i, len;
5938       tree opack, npack;
5939
5940       if (!ARGUMENT_PACK_P (nt))
5941         return 0;
5942
5943       opack = ARGUMENT_PACK_ARGS (ot);
5944       npack = ARGUMENT_PACK_ARGS (nt);
5945       len = TREE_VEC_LENGTH (opack);
5946       if (TREE_VEC_LENGTH (npack) != len)
5947         return 0;
5948       for (i = 0; i < len; ++i)
5949         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5950                                   TREE_VEC_ELT (npack, i)))
5951           return 0;
5952       return 1;
5953     }
5954   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
5955     {
5956       /* We get here probably because we are in the middle of substituting
5957          into the pattern of a pack expansion. In that case the
5958          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
5959          interested in. So we want to use the initial pack argument for
5960          the comparison.  */
5961       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
5962       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
5963         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
5964       return template_args_equal (ot, nt);
5965     }
5966   else if (TYPE_P (nt))
5967     return TYPE_P (ot) && same_type_p (ot, nt);
5968   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5969     return 0;
5970   else
5971     return cp_tree_equal (ot, nt);
5972 }
5973
5974 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5975    of template arguments.  Returns 0 otherwise.  */
5976
5977 int
5978 comp_template_args (tree oldargs, tree newargs)
5979 {
5980   int i;
5981
5982   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5983     return 0;
5984
5985   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5986     {
5987       tree nt = TREE_VEC_ELT (newargs, i);
5988       tree ot = TREE_VEC_ELT (oldargs, i);
5989
5990       if (! template_args_equal (ot, nt))
5991         return 0;
5992     }
5993   return 1;
5994 }
5995
5996 static void
5997 add_pending_template (tree d)
5998 {
5999   tree ti = (TYPE_P (d)
6000              ? CLASSTYPE_TEMPLATE_INFO (d)
6001              : DECL_TEMPLATE_INFO (d));
6002   struct pending_template *pt;
6003   int level;
6004
6005   if (TI_PENDING_TEMPLATE_FLAG (ti))
6006     return;
6007
6008   /* We are called both from instantiate_decl, where we've already had a
6009      tinst_level pushed, and instantiate_template, where we haven't.
6010      Compensate.  */
6011   level = !current_tinst_level || current_tinst_level->decl != d;
6012
6013   if (level)
6014     push_tinst_level (d);
6015
6016   pt = GGC_NEW (struct pending_template);
6017   pt->next = NULL;
6018   pt->tinst = current_tinst_level;
6019   if (last_pending_template)
6020     last_pending_template->next = pt;
6021   else
6022     pending_templates = pt;
6023
6024   last_pending_template = pt;
6025
6026   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6027
6028   if (level)
6029     pop_tinst_level ();
6030 }
6031
6032
6033 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6034    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6035    documentation for TEMPLATE_ID_EXPR.  */
6036
6037 tree
6038 lookup_template_function (tree fns, tree arglist)
6039 {
6040   tree type;
6041
6042   if (fns == error_mark_node || arglist == error_mark_node)
6043     return error_mark_node;
6044
6045   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6046   gcc_assert (fns && (is_overloaded_fn (fns)
6047                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6048
6049   if (BASELINK_P (fns))
6050     {
6051       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6052                                          unknown_type_node,
6053                                          BASELINK_FUNCTIONS (fns),
6054                                          arglist);
6055       return fns;
6056     }
6057
6058   type = TREE_TYPE (fns);
6059   if (TREE_CODE (fns) == OVERLOAD || !type)
6060     type = unknown_type_node;
6061
6062   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6063 }
6064
6065 /* Within the scope of a template class S<T>, the name S gets bound
6066    (in build_self_reference) to a TYPE_DECL for the class, not a
6067    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6068    or one of its enclosing classes, and that type is a template,
6069    return the associated TEMPLATE_DECL.  Otherwise, the original
6070    DECL is returned.
6071
6072    Also handle the case when DECL is a TREE_LIST of ambiguous
6073    injected-class-names from different bases.  */
6074
6075 tree
6076 maybe_get_template_decl_from_type_decl (tree decl)
6077 {
6078   if (decl == NULL_TREE)
6079     return decl;
6080
6081   /* DR 176: A lookup that finds an injected-class-name (10.2
6082      [class.member.lookup]) can result in an ambiguity in certain cases
6083      (for example, if it is found in more than one base class). If all of
6084      the injected-class-names that are found refer to specializations of
6085      the same class template, and if the name is followed by a
6086      template-argument-list, the reference refers to the class template
6087      itself and not a specialization thereof, and is not ambiguous.  */
6088   if (TREE_CODE (decl) == TREE_LIST)
6089     {
6090       tree t, tmpl = NULL_TREE;
6091       for (t = decl; t; t = TREE_CHAIN (t))
6092         {
6093           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6094           if (!tmpl)
6095             tmpl = elt;
6096           else if (tmpl != elt)
6097             break;
6098         }
6099       if (tmpl && t == NULL_TREE)
6100         return tmpl;
6101       else
6102         return decl;
6103     }
6104
6105   return (decl != NULL_TREE
6106           && DECL_SELF_REFERENCE_P (decl)
6107           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6108     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6109 }
6110
6111 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6112    parameters, find the desired type.
6113
6114    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6115
6116    IN_DECL, if non-NULL, is the template declaration we are trying to
6117    instantiate.
6118
6119    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6120    the class we are looking up.
6121
6122    Issue error and warning messages under control of COMPLAIN.
6123
6124    If the template class is really a local class in a template
6125    function, then the FUNCTION_CONTEXT is the function in which it is
6126    being instantiated.
6127
6128    ??? Note that this function is currently called *twice* for each
6129    template-id: the first time from the parser, while creating the
6130    incomplete type (finish_template_type), and the second type during the
6131    real instantiation (instantiate_template_class). This is surely something
6132    that we want to avoid. It also causes some problems with argument
6133    coercion (see convert_nontype_argument for more information on this).  */
6134
6135 tree
6136 lookup_template_class (tree d1,
6137                        tree arglist,
6138                        tree in_decl,
6139                        tree context,
6140                        int entering_scope,
6141                        tsubst_flags_t complain)
6142 {
6143   tree templ = NULL_TREE, parmlist;
6144   tree t;
6145   spec_entry **slot;
6146   spec_entry *entry;
6147   spec_entry elt;
6148   hashval_t hash;
6149
6150   timevar_push (TV_NAME_LOOKUP);
6151
6152   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6153     {
6154       tree value = innermost_non_namespace_value (d1);
6155       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6156         templ = value;
6157       else
6158         {
6159           if (context)
6160             push_decl_namespace (context);
6161           templ = lookup_name (d1);
6162           templ = maybe_get_template_decl_from_type_decl (templ);
6163           if (context)
6164             pop_decl_namespace ();
6165         }
6166       if (templ)
6167         context = DECL_CONTEXT (templ);
6168     }
6169   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6170     {
6171       tree type = TREE_TYPE (d1);
6172
6173       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6174          an implicit typename for the second A.  Deal with it.  */
6175       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6176         type = TREE_TYPE (type);
6177
6178       if (CLASSTYPE_TEMPLATE_INFO (type))
6179         {
6180           templ = CLASSTYPE_TI_TEMPLATE (type);
6181           d1 = DECL_NAME (templ);
6182         }
6183     }
6184   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6185            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6186     {
6187       templ = TYPE_TI_TEMPLATE (d1);
6188       d1 = DECL_NAME (templ);
6189     }
6190   else if (TREE_CODE (d1) == TEMPLATE_DECL
6191            && DECL_TEMPLATE_RESULT (d1)
6192            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6193     {
6194       templ = d1;
6195       d1 = DECL_NAME (templ);
6196       context = DECL_CONTEXT (templ);
6197     }
6198
6199   /* Issue an error message if we didn't find a template.  */
6200   if (! templ)
6201     {
6202       if (complain & tf_error)
6203         error ("%qT is not a template", d1);
6204       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6205     }
6206
6207   if (TREE_CODE (templ) != TEMPLATE_DECL
6208          /* Make sure it's a user visible template, if it was named by
6209             the user.  */
6210       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6211           && !PRIMARY_TEMPLATE_P (templ)))
6212     {
6213       if (complain & tf_error)
6214         {
6215           error ("non-template type %qT used as a template", d1);
6216           if (in_decl)
6217             error ("for template declaration %q+D", in_decl);
6218         }
6219       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6220     }
6221
6222   complain &= ~tf_user;
6223
6224   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6225     {
6226       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6227          template arguments */
6228
6229       tree parm;
6230       tree arglist2;
6231       tree outer;
6232
6233       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6234
6235       /* Consider an example where a template template parameter declared as
6236
6237            template <class T, class U = std::allocator<T> > class TT
6238
6239          The template parameter level of T and U are one level larger than
6240          of TT.  To proper process the default argument of U, say when an
6241          instantiation `TT<int>' is seen, we need to build the full
6242          arguments containing {int} as the innermost level.  Outer levels,
6243          available when not appearing as default template argument, can be
6244          obtained from the arguments of the enclosing template.
6245
6246          Suppose that TT is later substituted with std::vector.  The above
6247          instantiation is `TT<int, std::allocator<T> >' with TT at
6248          level 1, and T at level 2, while the template arguments at level 1
6249          becomes {std::vector} and the inner level 2 is {int}.  */
6250
6251       outer = DECL_CONTEXT (templ);
6252       if (outer)
6253         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6254       else if (current_template_parms)
6255         /* This is an argument of the current template, so we haven't set
6256            DECL_CONTEXT yet.  */
6257         outer = current_template_args ();
6258
6259       if (outer)
6260         arglist = add_to_template_args (outer, arglist);
6261
6262       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6263                                         complain,
6264                                         /*require_all_args=*/true,
6265                                         /*use_default_args=*/true);
6266       if (arglist2 == error_mark_node
6267           || (!uses_template_parms (arglist2)
6268               && check_instantiated_args (templ, arglist2, complain)))
6269         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6270
6271       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6272       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6273     }
6274   else
6275     {
6276       tree template_type = TREE_TYPE (templ);
6277       tree gen_tmpl;
6278       tree type_decl;
6279       tree found = NULL_TREE;
6280       int arg_depth;
6281       int parm_depth;
6282       int is_partial_instantiation;
6283
6284       gen_tmpl = most_general_template (templ);
6285       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6286       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6287       arg_depth = TMPL_ARGS_DEPTH (arglist);
6288
6289       if (arg_depth == 1 && parm_depth > 1)
6290         {
6291           /* We've been given an incomplete set of template arguments.
6292              For example, given:
6293
6294                template <class T> struct S1 {
6295                  template <class U> struct S2 {};
6296                  template <class U> struct S2<U*> {};
6297                 };
6298
6299              we will be called with an ARGLIST of `U*', but the
6300              TEMPLATE will be `template <class T> template
6301              <class U> struct S1<T>::S2'.  We must fill in the missing
6302              arguments.  */
6303           arglist
6304             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6305                                            arglist);
6306           arg_depth = TMPL_ARGS_DEPTH (arglist);
6307         }
6308
6309       /* Now we should have enough arguments.  */
6310       gcc_assert (parm_depth == arg_depth);
6311
6312       /* From here on, we're only interested in the most general
6313          template.  */
6314
6315       /* Calculate the BOUND_ARGS.  These will be the args that are
6316          actually tsubst'd into the definition to create the
6317          instantiation.  */
6318       if (parm_depth > 1)
6319         {
6320           /* We have multiple levels of arguments to coerce, at once.  */
6321           int i;
6322           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6323
6324           tree bound_args = make_tree_vec (parm_depth);
6325
6326           for (i = saved_depth,
6327                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6328                i > 0 && t != NULL_TREE;
6329                --i, t = TREE_CHAIN (t))
6330             {
6331               tree a = coerce_template_parms (TREE_VALUE (t),
6332                                               arglist, gen_tmpl,
6333                                               complain,
6334                                               /*require_all_args=*/true,
6335                                               /*use_default_args=*/true);
6336
6337               /* Don't process further if one of the levels fails.  */
6338               if (a == error_mark_node)
6339                 {
6340                   /* Restore the ARGLIST to its full size.  */
6341                   TREE_VEC_LENGTH (arglist) = saved_depth;
6342                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6343                 }
6344
6345               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6346
6347               /* We temporarily reduce the length of the ARGLIST so
6348                  that coerce_template_parms will see only the arguments
6349                  corresponding to the template parameters it is
6350                  examining.  */
6351               TREE_VEC_LENGTH (arglist)--;
6352             }
6353
6354           /* Restore the ARGLIST to its full size.  */
6355           TREE_VEC_LENGTH (arglist) = saved_depth;
6356
6357           arglist = bound_args;
6358         }
6359       else
6360         arglist
6361           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6362                                    INNERMOST_TEMPLATE_ARGS (arglist),
6363                                    gen_tmpl,
6364                                    complain,
6365                                    /*require_all_args=*/true,
6366                                    /*use_default_args=*/true);
6367
6368       if (arglist == error_mark_node)
6369         /* We were unable to bind the arguments.  */
6370         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6371
6372       /* In the scope of a template class, explicit references to the
6373          template class refer to the type of the template, not any
6374          instantiation of it.  For example, in:
6375
6376            template <class T> class C { void f(C<T>); }
6377
6378          the `C<T>' is just the same as `C'.  Outside of the
6379          class, however, such a reference is an instantiation.  */
6380       if ((entering_scope
6381            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6382            || currently_open_class (template_type))
6383           /* comp_template_args is expensive, check it last.  */
6384           && comp_template_args (TYPE_TI_ARGS (template_type),
6385                                  arglist))
6386         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6387
6388       /* If we already have this specialization, return it.  */
6389       elt.tmpl = gen_tmpl;
6390       elt.args = arglist;
6391       hash = hash_specialization (&elt);
6392       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6393                                                   &elt, hash);
6394
6395       if (entry)
6396         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6397
6398       /* This type is a "partial instantiation" if any of the template
6399          arguments still involve template parameters.  Note that we set
6400          IS_PARTIAL_INSTANTIATION for partial specializations as
6401          well.  */
6402       is_partial_instantiation = uses_template_parms (arglist);
6403
6404       /* If the deduced arguments are invalid, then the binding
6405          failed.  */
6406       if (!is_partial_instantiation
6407           && check_instantiated_args (gen_tmpl,
6408                                       INNERMOST_TEMPLATE_ARGS (arglist),
6409                                       complain))
6410         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6411
6412       if (!is_partial_instantiation
6413           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6414           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6415           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6416         {
6417           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6418                                       DECL_NAME (gen_tmpl),
6419                                       /*tag_scope=*/ts_global);
6420           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6421         }
6422
6423       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6424                         complain, in_decl);
6425       if (!context)
6426         context = global_namespace;
6427
6428       /* Create the type.  */
6429       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6430         {
6431           if (!is_partial_instantiation)
6432             {
6433               set_current_access_from_decl (TYPE_NAME (template_type));
6434               t = start_enum (TYPE_IDENTIFIER (template_type),
6435                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6436                                       arglist, complain, in_decl),
6437                               SCOPED_ENUM_P (template_type));
6438             }
6439           else
6440             {
6441               /* We don't want to call start_enum for this type, since
6442                  the values for the enumeration constants may involve
6443                  template parameters.  And, no one should be interested
6444                  in the enumeration constants for such a type.  */
6445               t = cxx_make_type (ENUMERAL_TYPE);
6446               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6447             }
6448         }
6449       else
6450         {
6451           t = make_class_type (TREE_CODE (template_type));
6452           CLASSTYPE_DECLARED_CLASS (t)
6453             = CLASSTYPE_DECLARED_CLASS (template_type);
6454           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6455           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6456
6457           /* A local class.  Make sure the decl gets registered properly.  */
6458           if (context == current_function_decl)
6459             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6460
6461           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6462             /* This instantiation is another name for the primary
6463                template type. Set the TYPE_CANONICAL field
6464                appropriately. */
6465             TYPE_CANONICAL (t) = template_type;
6466           else if (any_template_arguments_need_structural_equality_p (arglist))
6467             /* Some of the template arguments require structural
6468                equality testing, so this template class requires
6469                structural equality testing. */
6470             SET_TYPE_STRUCTURAL_EQUALITY (t);
6471         }
6472
6473       /* If we called start_enum or pushtag above, this information
6474          will already be set up.  */
6475       if (!TYPE_NAME (t))
6476         {
6477           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6478
6479           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6480           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6481           DECL_SOURCE_LOCATION (type_decl)
6482             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6483         }
6484       else
6485         type_decl = TYPE_NAME (t);
6486
6487       TREE_PRIVATE (type_decl)
6488         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6489       TREE_PROTECTED (type_decl)
6490         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6491       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6492         {
6493           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6494           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6495         }
6496
6497       /* Set up the template information.  We have to figure out which
6498          template is the immediate parent if this is a full
6499          instantiation.  */
6500       if (parm_depth == 1 || is_partial_instantiation
6501           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6502         /* This case is easy; there are no member templates involved.  */
6503         found = gen_tmpl;
6504       else
6505         {
6506           /* This is a full instantiation of a member template.  Find
6507              the partial instantiation of which this is an instance.  */
6508
6509           /* Temporarily reduce by one the number of levels in the ARGLIST
6510              so as to avoid comparing the last set of arguments.  */
6511           TREE_VEC_LENGTH (arglist)--;
6512           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6513           TREE_VEC_LENGTH (arglist)++;
6514           found = CLASSTYPE_TI_TEMPLATE (found);
6515         }
6516
6517       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6518
6519       elt.spec = t;
6520       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6521                                                        &elt, hash, INSERT);
6522       *slot = GGC_NEW (spec_entry);
6523       **slot = elt;
6524
6525       /* Note this use of the partial instantiation so we can check it
6526          later in maybe_process_partial_specialization.  */
6527       DECL_TEMPLATE_INSTANTIATIONS (templ)
6528         = tree_cons (arglist, t,
6529                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6530
6531       if (TREE_CODE (t) == ENUMERAL_TYPE
6532           && !is_partial_instantiation)
6533         /* Now that the type has been registered on the instantiations
6534            list, we set up the enumerators.  Because the enumeration
6535            constants may involve the enumeration type itself, we make
6536            sure to register the type first, and then create the
6537            constants.  That way, doing tsubst_expr for the enumeration
6538            constants won't result in recursive calls here; we'll find
6539            the instantiation and exit above.  */
6540         tsubst_enum (template_type, t, arglist);
6541
6542       if (is_partial_instantiation)
6543         /* If the type makes use of template parameters, the
6544            code that generates debugging information will crash.  */
6545         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6546
6547       /* Possibly limit visibility based on template args.  */
6548       TREE_PUBLIC (type_decl) = 1;
6549       determine_visibility (type_decl);
6550
6551       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6552     }
6553   timevar_pop (TV_NAME_LOOKUP);
6554 }
6555 \f
6556 struct pair_fn_data
6557 {
6558   tree_fn_t fn;
6559   void *data;
6560   /* True when we should also visit template parameters that occur in
6561      non-deduced contexts.  */
6562   bool include_nondeduced_p;
6563   struct pointer_set_t *visited;
6564 };
6565
6566 /* Called from for_each_template_parm via walk_tree.  */
6567
6568 static tree
6569 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6570 {
6571   tree t = *tp;
6572   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6573   tree_fn_t fn = pfd->fn;
6574   void *data = pfd->data;
6575
6576   if (TYPE_P (t)
6577       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6578       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6579                                  pfd->include_nondeduced_p))
6580     return error_mark_node;
6581
6582   switch (TREE_CODE (t))
6583     {
6584     case RECORD_TYPE:
6585       if (TYPE_PTRMEMFUNC_P (t))
6586         break;
6587       /* Fall through.  */
6588
6589     case UNION_TYPE:
6590     case ENUMERAL_TYPE:
6591       if (!TYPE_TEMPLATE_INFO (t))
6592         *walk_subtrees = 0;
6593       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6594                                        fn, data, pfd->visited, 
6595                                        pfd->include_nondeduced_p))
6596         return error_mark_node;
6597       break;
6598
6599     case INTEGER_TYPE:
6600       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6601                                   fn, data, pfd->visited, 
6602                                   pfd->include_nondeduced_p)
6603           || for_each_template_parm (TYPE_MAX_VALUE (t),
6604                                      fn, data, pfd->visited,
6605                                      pfd->include_nondeduced_p))
6606         return error_mark_node;
6607       break;
6608
6609     case METHOD_TYPE:
6610       /* Since we're not going to walk subtrees, we have to do this
6611          explicitly here.  */
6612       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6613                                   pfd->visited, pfd->include_nondeduced_p))
6614         return error_mark_node;
6615       /* Fall through.  */
6616
6617     case FUNCTION_TYPE:
6618       /* Check the return type.  */
6619       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6620                                   pfd->include_nondeduced_p))
6621         return error_mark_node;
6622
6623       /* Check the parameter types.  Since default arguments are not
6624          instantiated until they are needed, the TYPE_ARG_TYPES may
6625          contain expressions that involve template parameters.  But,
6626          no-one should be looking at them yet.  And, once they're
6627          instantiated, they don't contain template parameters, so
6628          there's no point in looking at them then, either.  */
6629       {
6630         tree parm;
6631
6632         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6633           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6634                                       pfd->visited, pfd->include_nondeduced_p))
6635             return error_mark_node;
6636
6637         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6638            want walk_tree walking into them itself.  */
6639         *walk_subtrees = 0;
6640       }
6641       break;
6642
6643     case TYPEOF_TYPE:
6644       if (pfd->include_nondeduced_p
6645           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6646                                      pfd->visited, 
6647                                      pfd->include_nondeduced_p))
6648         return error_mark_node;
6649       break;
6650
6651     case FUNCTION_DECL:
6652     case VAR_DECL:
6653       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6654           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6655                                      pfd->visited, pfd->include_nondeduced_p))
6656         return error_mark_node;
6657       /* Fall through.  */
6658
6659     case PARM_DECL:
6660     case CONST_DECL:
6661       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6662           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6663                                      pfd->visited, pfd->include_nondeduced_p))
6664         return error_mark_node;
6665       if (DECL_CONTEXT (t)
6666           && pfd->include_nondeduced_p
6667           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6668                                      pfd->visited, pfd->include_nondeduced_p))
6669         return error_mark_node;
6670       break;
6671
6672     case BOUND_TEMPLATE_TEMPLATE_PARM:
6673       /* Record template parameters such as `T' inside `TT<T>'.  */
6674       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6675                                   pfd->include_nondeduced_p))
6676         return error_mark_node;
6677       /* Fall through.  */
6678
6679     case TEMPLATE_TEMPLATE_PARM:
6680     case TEMPLATE_TYPE_PARM:
6681     case TEMPLATE_PARM_INDEX:
6682       if (fn && (*fn)(t, data))
6683         return error_mark_node;
6684       else if (!fn)
6685         return error_mark_node;
6686       break;
6687
6688     case TEMPLATE_DECL:
6689       /* A template template parameter is encountered.  */
6690       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6691           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6692                                      pfd->include_nondeduced_p))
6693         return error_mark_node;
6694
6695       /* Already substituted template template parameter */
6696       *walk_subtrees = 0;
6697       break;
6698
6699     case TYPENAME_TYPE:
6700       if (!fn
6701           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6702                                      data, pfd->visited, 
6703                                      pfd->include_nondeduced_p))
6704         return error_mark_node;
6705       break;
6706
6707     case CONSTRUCTOR:
6708       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6709           && pfd->include_nondeduced_p
6710           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6711                                      (TREE_TYPE (t)), fn, data,
6712                                      pfd->visited, pfd->include_nondeduced_p))
6713         return error_mark_node;
6714       break;
6715
6716     case INDIRECT_REF:
6717     case COMPONENT_REF:
6718       /* If there's no type, then this thing must be some expression
6719          involving template parameters.  */
6720       if (!fn && !TREE_TYPE (t))
6721         return error_mark_node;
6722       break;
6723
6724     case MODOP_EXPR:
6725     case CAST_EXPR:
6726     case REINTERPRET_CAST_EXPR:
6727     case CONST_CAST_EXPR:
6728     case STATIC_CAST_EXPR:
6729     case DYNAMIC_CAST_EXPR:
6730     case ARROW_EXPR:
6731     case DOTSTAR_EXPR:
6732     case TYPEID_EXPR:
6733     case PSEUDO_DTOR_EXPR:
6734       if (!fn)
6735         return error_mark_node;
6736       break;
6737
6738     default:
6739       break;
6740     }
6741
6742   /* We didn't find any template parameters we liked.  */
6743   return NULL_TREE;
6744 }
6745
6746 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6747    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6748    call FN with the parameter and the DATA.
6749    If FN returns nonzero, the iteration is terminated, and
6750    for_each_template_parm returns 1.  Otherwise, the iteration
6751    continues.  If FN never returns a nonzero value, the value
6752    returned by for_each_template_parm is 0.  If FN is NULL, it is
6753    considered to be the function which always returns 1.
6754
6755    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6756    parameters that occur in non-deduced contexts.  When false, only
6757    visits those template parameters that can be deduced.  */
6758
6759 static int
6760 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6761                         struct pointer_set_t *visited,
6762                         bool include_nondeduced_p)
6763 {
6764   struct pair_fn_data pfd;
6765   int result;
6766
6767   /* Set up.  */
6768   pfd.fn = fn;
6769   pfd.data = data;
6770   pfd.include_nondeduced_p = include_nondeduced_p;
6771
6772   /* Walk the tree.  (Conceptually, we would like to walk without
6773      duplicates, but for_each_template_parm_r recursively calls
6774      for_each_template_parm, so we would need to reorganize a fair
6775      bit to use walk_tree_without_duplicates, so we keep our own
6776      visited list.)  */
6777   if (visited)
6778     pfd.visited = visited;
6779   else
6780     pfd.visited = pointer_set_create ();
6781   result = cp_walk_tree (&t,
6782                          for_each_template_parm_r,
6783                          &pfd,
6784                          pfd.visited) != NULL_TREE;
6785
6786   /* Clean up.  */
6787   if (!visited)
6788     {
6789       pointer_set_destroy (pfd.visited);
6790       pfd.visited = 0;
6791     }
6792
6793   return result;
6794 }
6795
6796 /* Returns true if T depends on any template parameter.  */
6797
6798 int
6799 uses_template_parms (tree t)
6800 {
6801   bool dependent_p;
6802   int saved_processing_template_decl;
6803
6804   saved_processing_template_decl = processing_template_decl;
6805   if (!saved_processing_template_decl)
6806     processing_template_decl = 1;
6807   if (TYPE_P (t))
6808     dependent_p = dependent_type_p (t);
6809   else if (TREE_CODE (t) == TREE_VEC)
6810     dependent_p = any_dependent_template_arguments_p (t);
6811   else if (TREE_CODE (t) == TREE_LIST)
6812     dependent_p = (uses_template_parms (TREE_VALUE (t))
6813                    || uses_template_parms (TREE_CHAIN (t)));
6814   else if (TREE_CODE (t) == TYPE_DECL)
6815     dependent_p = dependent_type_p (TREE_TYPE (t));
6816   else if (DECL_P (t)
6817            || EXPR_P (t)
6818            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6819            || TREE_CODE (t) == OVERLOAD
6820            || TREE_CODE (t) == BASELINK
6821            || TREE_CODE (t) == IDENTIFIER_NODE
6822            || TREE_CODE (t) == TRAIT_EXPR
6823            || TREE_CODE (t) == CONSTRUCTOR
6824            || CONSTANT_CLASS_P (t))
6825     dependent_p = (type_dependent_expression_p (t)
6826                    || value_dependent_expression_p (t));
6827   else
6828     {
6829       gcc_assert (t == error_mark_node);
6830       dependent_p = false;
6831     }
6832
6833   processing_template_decl = saved_processing_template_decl;
6834
6835   return dependent_p;
6836 }
6837
6838 /* Returns true if T depends on any template parameter with level LEVEL.  */
6839
6840 int
6841 uses_template_parms_level (tree t, int level)
6842 {
6843   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6844                                  /*include_nondeduced_p=*/true);
6845 }
6846
6847 static int tinst_depth;
6848 extern int max_tinst_depth;
6849 #ifdef GATHER_STATISTICS
6850 int depth_reached;
6851 #endif
6852 static int tinst_level_tick;
6853 static int last_template_error_tick;
6854
6855 /* We're starting to instantiate D; record the template instantiation context
6856    for diagnostics and to restore it later.  */
6857
6858 static int
6859 push_tinst_level (tree d)
6860 {
6861   struct tinst_level *new_level;
6862
6863   if (tinst_depth >= max_tinst_depth)
6864     {
6865       /* If the instantiation in question still has unbound template parms,
6866          we don't really care if we can't instantiate it, so just return.
6867          This happens with base instantiation for implicit `typename'.  */
6868       if (uses_template_parms (d))
6869         return 0;
6870
6871       last_template_error_tick = tinst_level_tick;
6872       error ("template instantiation depth exceeds maximum of %d (use "
6873              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6874              max_tinst_depth, d);
6875
6876       print_instantiation_context ();
6877
6878       return 0;
6879     }
6880
6881   new_level = GGC_NEW (struct tinst_level);
6882   new_level->decl = d;
6883   new_level->locus = input_location;
6884   new_level->in_system_header_p = in_system_header;
6885   new_level->next = current_tinst_level;
6886   current_tinst_level = new_level;
6887
6888   ++tinst_depth;
6889 #ifdef GATHER_STATISTICS
6890   if (tinst_depth > depth_reached)
6891     depth_reached = tinst_depth;
6892 #endif
6893
6894   ++tinst_level_tick;
6895   return 1;
6896 }
6897
6898 /* We're done instantiating this template; return to the instantiation
6899    context.  */
6900
6901 static void
6902 pop_tinst_level (void)
6903 {
6904   /* Restore the filename and line number stashed away when we started
6905      this instantiation.  */
6906   input_location = current_tinst_level->locus;
6907   current_tinst_level = current_tinst_level->next;
6908   --tinst_depth;
6909   ++tinst_level_tick;
6910 }
6911
6912 /* We're instantiating a deferred template; restore the template
6913    instantiation context in which the instantiation was requested, which
6914    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6915
6916 static tree
6917 reopen_tinst_level (struct tinst_level *level)
6918 {
6919   struct tinst_level *t;
6920
6921   tinst_depth = 0;
6922   for (t = level; t; t = t->next)
6923     ++tinst_depth;
6924
6925   current_tinst_level = level;
6926   pop_tinst_level ();
6927   return level->decl;
6928 }
6929
6930 /* Returns the TINST_LEVEL which gives the original instantiation
6931    context.  */
6932
6933 struct tinst_level *
6934 outermost_tinst_level (void)
6935 {
6936   struct tinst_level *level = current_tinst_level;
6937   if (level)
6938     while (level->next)
6939       level = level->next;
6940   return level;
6941 }
6942
6943 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6944
6945 bool
6946 parameter_of_template_p (tree parm, tree templ)
6947 {
6948   tree parms;
6949   int i;
6950
6951   if (!parm || !templ)
6952     return false;
6953
6954   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6955   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6956
6957   parms = DECL_TEMPLATE_PARMS (templ);
6958   parms = INNERMOST_TEMPLATE_PARMS (parms);
6959
6960   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6961     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6962       return true;
6963
6964   return false;
6965 }
6966
6967 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6968    vector of template arguments, as for tsubst.
6969
6970    Returns an appropriate tsubst'd friend declaration.  */
6971
6972 static tree
6973 tsubst_friend_function (tree decl, tree args)
6974 {
6975   tree new_friend;
6976
6977   if (TREE_CODE (decl) == FUNCTION_DECL
6978       && DECL_TEMPLATE_INSTANTIATION (decl)
6979       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6980     /* This was a friend declared with an explicit template
6981        argument list, e.g.:
6982
6983        friend void f<>(T);
6984
6985        to indicate that f was a template instantiation, not a new
6986        function declaration.  Now, we have to figure out what
6987        instantiation of what template.  */
6988     {
6989       tree template_id, arglist, fns;
6990       tree new_args;
6991       tree tmpl;
6992       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6993
6994       /* Friend functions are looked up in the containing namespace scope.
6995          We must enter that scope, to avoid finding member functions of the
6996          current class with same name.  */
6997       push_nested_namespace (ns);
6998       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6999                          tf_warning_or_error, NULL_TREE,
7000                          /*integral_constant_expression_p=*/false);
7001       pop_nested_namespace (ns);
7002       arglist = tsubst (DECL_TI_ARGS (decl), args,
7003                         tf_warning_or_error, NULL_TREE);
7004       template_id = lookup_template_function (fns, arglist);
7005
7006       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7007       tmpl = determine_specialization (template_id, new_friend,
7008                                        &new_args,
7009                                        /*need_member_template=*/0,
7010                                        TREE_VEC_LENGTH (args),
7011                                        tsk_none);
7012       return instantiate_template (tmpl, new_args, tf_error);
7013     }
7014
7015   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7016
7017   /* The NEW_FRIEND will look like an instantiation, to the
7018      compiler, but is not an instantiation from the point of view of
7019      the language.  For example, we might have had:
7020
7021      template <class T> struct S {
7022        template <class U> friend void f(T, U);
7023      };
7024
7025      Then, in S<int>, template <class U> void f(int, U) is not an
7026      instantiation of anything.  */
7027   if (new_friend == error_mark_node)
7028     return error_mark_node;
7029
7030   DECL_USE_TEMPLATE (new_friend) = 0;
7031   if (TREE_CODE (decl) == TEMPLATE_DECL)
7032     {
7033       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7034       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7035         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7036     }
7037
7038   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7039      is not a template instantiation and should not be mangled like
7040      one.  Therefore, we forget the mangling here; we'll recompute it
7041      later if we need it.  */
7042   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7043     {
7044       SET_DECL_RTL (new_friend, NULL_RTX);
7045       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7046     }
7047
7048   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7049     {
7050       tree old_decl;
7051       tree new_friend_template_info;
7052       tree new_friend_result_template_info;
7053       tree ns;
7054       int  new_friend_is_defn;
7055
7056       /* We must save some information from NEW_FRIEND before calling
7057          duplicate decls since that function will free NEW_FRIEND if
7058          possible.  */
7059       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7060       new_friend_is_defn =
7061             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7062                            (template_for_substitution (new_friend)))
7063              != NULL_TREE);
7064       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7065         {
7066           /* This declaration is a `primary' template.  */
7067           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7068
7069           new_friend_result_template_info
7070             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7071         }
7072       else
7073         new_friend_result_template_info = NULL_TREE;
7074
7075       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7076       if (new_friend_is_defn)
7077         DECL_INITIAL (new_friend) = error_mark_node;
7078
7079       /* Inside pushdecl_namespace_level, we will push into the
7080          current namespace. However, the friend function should go
7081          into the namespace of the template.  */
7082       ns = decl_namespace_context (new_friend);
7083       push_nested_namespace (ns);
7084       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7085       pop_nested_namespace (ns);
7086
7087       if (old_decl == error_mark_node)
7088         return error_mark_node;
7089
7090       if (old_decl != new_friend)
7091         {
7092           /* This new friend declaration matched an existing
7093              declaration.  For example, given:
7094
7095                template <class T> void f(T);
7096                template <class U> class C {
7097                  template <class T> friend void f(T) {}
7098                };
7099
7100              the friend declaration actually provides the definition
7101              of `f', once C has been instantiated for some type.  So,
7102              old_decl will be the out-of-class template declaration,
7103              while new_friend is the in-class definition.
7104
7105              But, if `f' was called before this point, the
7106              instantiation of `f' will have DECL_TI_ARGS corresponding
7107              to `T' but not to `U', references to which might appear
7108              in the definition of `f'.  Previously, the most general
7109              template for an instantiation of `f' was the out-of-class
7110              version; now it is the in-class version.  Therefore, we
7111              run through all specialization of `f', adding to their
7112              DECL_TI_ARGS appropriately.  In particular, they need a
7113              new set of outer arguments, corresponding to the
7114              arguments for this class instantiation.
7115
7116              The same situation can arise with something like this:
7117
7118                friend void f(int);
7119                template <class T> class C {
7120                  friend void f(T) {}
7121                };
7122
7123              when `C<int>' is instantiated.  Now, `f(int)' is defined
7124              in the class.  */
7125
7126           if (!new_friend_is_defn)
7127             /* On the other hand, if the in-class declaration does
7128                *not* provide a definition, then we don't want to alter
7129                existing definitions.  We can just leave everything
7130                alone.  */
7131             ;
7132           else
7133             {
7134               tree new_template = TI_TEMPLATE (new_friend_template_info);
7135               tree new_args = TI_ARGS (new_friend_template_info);
7136
7137               /* Overwrite whatever template info was there before, if
7138                  any, with the new template information pertaining to
7139                  the declaration.  */
7140               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7141
7142               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7143                 /* We should have called reregister_specialization in
7144                    duplicate_decls.  */
7145                 gcc_assert (retrieve_specialization (new_template,
7146                                                      new_args, 0)
7147                             == old_decl);
7148               else
7149                 {
7150                   tree t;
7151
7152                   /* Indicate that the old function template is a partial
7153                      instantiation.  */
7154                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7155                     = new_friend_result_template_info;
7156
7157                   gcc_assert (new_template
7158                               == most_general_template (new_template));
7159                   gcc_assert (new_template != old_decl);
7160
7161                   /* Reassign any specializations already in the hash table
7162                      to the new more general template, and add the
7163                      additional template args.  */
7164                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7165                        t != NULL_TREE;
7166                        t = TREE_CHAIN (t))
7167                     {
7168                       tree spec = TREE_VALUE (t);
7169                       spec_entry elt;
7170
7171                       elt.tmpl = old_decl;
7172                       elt.args = DECL_TI_ARGS (spec);
7173                       elt.spec = NULL_TREE;
7174
7175                       htab_remove_elt (decl_specializations, &elt);
7176
7177                       DECL_TI_ARGS (spec)
7178                         = add_outermost_template_args (new_args,
7179                                                        DECL_TI_ARGS (spec));
7180
7181                       register_specialization
7182                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7183
7184                     }
7185                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7186                 }
7187             }
7188
7189           /* The information from NEW_FRIEND has been merged into OLD_DECL
7190              by duplicate_decls.  */
7191           new_friend = old_decl;
7192         }
7193     }
7194   else
7195     {
7196       tree context = DECL_CONTEXT (new_friend);
7197       bool dependent_p;
7198
7199       /* In the code
7200            template <class T> class C {
7201              template <class U> friend void C1<U>::f (); // case 1
7202              friend void C2<T>::f ();                    // case 2
7203            };
7204          we only need to make sure CONTEXT is a complete type for
7205          case 2.  To distinguish between the two cases, we note that
7206          CONTEXT of case 1 remains dependent type after tsubst while
7207          this isn't true for case 2.  */
7208       ++processing_template_decl;
7209       dependent_p = dependent_type_p (context);
7210       --processing_template_decl;
7211
7212       if (!dependent_p
7213           && !complete_type_or_else (context, NULL_TREE))
7214         return error_mark_node;
7215
7216       if (COMPLETE_TYPE_P (context))
7217         {
7218           /* Check to see that the declaration is really present, and,
7219              possibly obtain an improved declaration.  */
7220           tree fn = check_classfn (context,
7221                                    new_friend, NULL_TREE);
7222
7223           if (fn)
7224             new_friend = fn;
7225         }
7226     }
7227
7228   return new_friend;
7229 }
7230
7231 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7232    template arguments, as for tsubst.
7233
7234    Returns an appropriate tsubst'd friend type or error_mark_node on
7235    failure.  */
7236
7237 static tree
7238 tsubst_friend_class (tree friend_tmpl, tree args)
7239 {
7240   tree friend_type;
7241   tree tmpl;
7242   tree context;
7243
7244   context = DECL_CONTEXT (friend_tmpl);
7245
7246   if (context)
7247     {
7248       if (TREE_CODE (context) == NAMESPACE_DECL)
7249         push_nested_namespace (context);
7250       else
7251         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7252     }
7253
7254   /* Look for a class template declaration.  We look for hidden names
7255      because two friend declarations of the same template are the
7256      same.  For example, in:
7257
7258        struct A { 
7259          template <typename> friend class F;
7260        };
7261        template <typename> struct B { 
7262          template <typename> friend class F;
7263        };
7264
7265      both F templates are the same.  */
7266   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7267                            /*block_p=*/true, 0, 
7268                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7269
7270   /* But, if we don't find one, it might be because we're in a
7271      situation like this:
7272
7273        template <class T>
7274        struct S {
7275          template <class U>
7276          friend struct S;
7277        };
7278
7279      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7280      for `S<int>', not the TEMPLATE_DECL.  */
7281   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7282     {
7283       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7284       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7285     }
7286
7287   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7288     {
7289       /* The friend template has already been declared.  Just
7290          check to see that the declarations match, and install any new
7291          default parameters.  We must tsubst the default parameters,
7292          of course.  We only need the innermost template parameters
7293          because that is all that redeclare_class_template will look
7294          at.  */
7295       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7296           > TMPL_ARGS_DEPTH (args))
7297         {
7298           tree parms;
7299           location_t saved_input_location;
7300           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7301                                          args, tf_warning_or_error);
7302
7303           saved_input_location = input_location;
7304           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7305           redeclare_class_template (TREE_TYPE (tmpl), parms);
7306           input_location = saved_input_location;
7307           
7308         }
7309
7310       friend_type = TREE_TYPE (tmpl);
7311     }
7312   else
7313     {
7314       /* The friend template has not already been declared.  In this
7315          case, the instantiation of the template class will cause the
7316          injection of this template into the global scope.  */
7317       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7318       if (tmpl == error_mark_node)
7319         return error_mark_node;
7320
7321       /* The new TMPL is not an instantiation of anything, so we
7322          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7323          the new type because that is supposed to be the corresponding
7324          template decl, i.e., TMPL.  */
7325       DECL_USE_TEMPLATE (tmpl) = 0;
7326       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7327       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7328       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7329         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7330
7331       /* Inject this template into the global scope.  */
7332       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7333     }
7334
7335   if (context)
7336     {
7337       if (TREE_CODE (context) == NAMESPACE_DECL)
7338         pop_nested_namespace (context);
7339       else
7340         pop_nested_class ();
7341     }
7342
7343   return friend_type;
7344 }
7345
7346 /* Returns zero if TYPE cannot be completed later due to circularity.
7347    Otherwise returns one.  */
7348
7349 static int
7350 can_complete_type_without_circularity (tree type)
7351 {
7352   if (type == NULL_TREE || type == error_mark_node)
7353     return 0;
7354   else if (COMPLETE_TYPE_P (type))
7355     return 1;
7356   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7357     return can_complete_type_without_circularity (TREE_TYPE (type));
7358   else if (CLASS_TYPE_P (type)
7359            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7360     return 0;
7361   else
7362     return 1;
7363 }
7364
7365 /* Apply any attributes which had to be deferred until instantiation
7366    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7367    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7368
7369 static void
7370 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7371                                 tree args, tsubst_flags_t complain, tree in_decl)
7372 {
7373   tree last_dep = NULL_TREE;
7374   tree t;
7375   tree *p;
7376
7377   for (t = attributes; t; t = TREE_CHAIN (t))
7378     if (ATTR_IS_DEPENDENT (t))
7379       {
7380         last_dep = t;
7381         attributes = copy_list (attributes);
7382         break;
7383       }
7384
7385   if (DECL_P (*decl_p))
7386     {
7387       if (TREE_TYPE (*decl_p) == error_mark_node)
7388         return;
7389       p = &DECL_ATTRIBUTES (*decl_p);
7390     }
7391   else
7392     p = &TYPE_ATTRIBUTES (*decl_p);
7393
7394   if (last_dep)
7395     {
7396       tree late_attrs = NULL_TREE;
7397       tree *q = &late_attrs;
7398
7399       for (*p = attributes; *p; )
7400         {
7401           t = *p;
7402           if (ATTR_IS_DEPENDENT (t))
7403             {
7404               *p = TREE_CHAIN (t);
7405               TREE_CHAIN (t) = NULL_TREE;
7406               /* If the first attribute argument is an identifier, don't
7407                  pass it through tsubst.  Attributes like mode, format,
7408                  cleanup and several target specific attributes expect it
7409                  unmodified.  */
7410               if (TREE_VALUE (t)
7411                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7412                   && TREE_VALUE (TREE_VALUE (t))
7413                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7414                       == IDENTIFIER_NODE))
7415                 {
7416                   tree chain
7417                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7418                                    in_decl,
7419                                    /*integral_constant_expression_p=*/false);
7420                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7421                     TREE_VALUE (t)
7422                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7423                                    chain);
7424                 }
7425               else
7426                 TREE_VALUE (t)
7427                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7428                                  /*integral_constant_expression_p=*/false);
7429               *q = t;
7430               q = &TREE_CHAIN (t);
7431             }
7432           else
7433             p = &TREE_CHAIN (t);
7434         }
7435
7436       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7437     }
7438 }
7439
7440 /* Perform (or defer) access check for typedefs that were referenced
7441    from within the template TMPL code.
7442    This is a subroutine of instantiate_template and instantiate_class_template.
7443    TMPL is the template to consider and TARGS is the list of arguments of
7444    that template.  */
7445
7446 static void
7447 perform_typedefs_access_check (tree tmpl, tree targs)
7448 {
7449   location_t saved_location;
7450   int i;
7451   qualified_typedef_usage_t *iter;
7452
7453   if (!tmpl
7454       || (!CLASS_TYPE_P (tmpl)
7455           && TREE_CODE (tmpl) != FUNCTION_DECL))
7456     return;
7457
7458   saved_location = input_location;
7459   for (i = 0;
7460        VEC_iterate (qualified_typedef_usage_t,
7461                     get_types_needing_access_check (tmpl),
7462                     i, iter);
7463         ++i)
7464     {
7465       tree type_decl = iter->typedef_decl;
7466       tree type_scope = iter->context;
7467
7468       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7469         continue;
7470
7471       if (uses_template_parms (type_decl))
7472         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7473       if (uses_template_parms (type_scope))
7474         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7475
7476       /* Make access check error messages point to the location
7477          of the use of the typedef.  */
7478       input_location = iter->locus;
7479       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7480                                      type_decl, type_decl);
7481     }
7482     input_location = saved_location;
7483 }
7484
7485 tree
7486 instantiate_class_template (tree type)
7487 {
7488   tree templ, args, pattern, t, member;
7489   tree typedecl;
7490   tree pbinfo;
7491   tree base_list;
7492   unsigned int saved_maximum_field_alignment;
7493
7494   if (type == error_mark_node)
7495     return error_mark_node;
7496
7497   if (TYPE_BEING_DEFINED (type)
7498       || COMPLETE_TYPE_P (type)
7499       || uses_template_parms (type))
7500     return type;
7501
7502   /* Figure out which template is being instantiated.  */
7503   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7504   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7505
7506   /* Determine what specialization of the original template to
7507      instantiate.  */
7508   t = most_specialized_class (type, templ);
7509   if (t == error_mark_node)
7510     {
7511       TYPE_BEING_DEFINED (type) = 1;
7512       return error_mark_node;
7513     }
7514   else if (t)
7515     {
7516       /* This TYPE is actually an instantiation of a partial
7517          specialization.  We replace the innermost set of ARGS with
7518          the arguments appropriate for substitution.  For example,
7519          given:
7520
7521            template <class T> struct S {};
7522            template <class T> struct S<T*> {};
7523
7524          and supposing that we are instantiating S<int*>, ARGS will
7525          presently be {int*} -- but we need {int}.  */
7526       pattern = TREE_TYPE (t);
7527       args = TREE_PURPOSE (t);
7528     }
7529   else
7530     {
7531       pattern = TREE_TYPE (templ);
7532       args = CLASSTYPE_TI_ARGS (type);
7533     }
7534
7535   /* If the template we're instantiating is incomplete, then clearly
7536      there's nothing we can do.  */
7537   if (!COMPLETE_TYPE_P (pattern))
7538     return type;
7539
7540   /* If we've recursively instantiated too many templates, stop.  */
7541   if (! push_tinst_level (type))
7542     return type;
7543
7544   /* Now we're really doing the instantiation.  Mark the type as in
7545      the process of being defined.  */
7546   TYPE_BEING_DEFINED (type) = 1;
7547
7548   /* We may be in the middle of deferred access check.  Disable
7549      it now.  */
7550   push_deferring_access_checks (dk_no_deferred);
7551
7552   push_to_top_level ();
7553   /* Use #pragma pack from the template context.  */
7554   saved_maximum_field_alignment = maximum_field_alignment;
7555   maximum_field_alignment = TYPE_PRECISION (pattern);
7556
7557   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7558
7559   /* Set the input location to the most specialized template definition.
7560      This is needed if tsubsting causes an error.  */
7561   typedecl = TYPE_MAIN_DECL (pattern);
7562   input_location = DECL_SOURCE_LOCATION (typedecl);
7563
7564   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7565   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7566   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7567   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7568   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7569   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7570   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7571   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7572   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7573   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7574   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7575   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7576   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7577   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7578   if (ANON_AGGR_TYPE_P (pattern))
7579     SET_ANON_AGGR_TYPE_P (type);
7580   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7581     {
7582       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7583       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7584     }
7585
7586   pbinfo = TYPE_BINFO (pattern);
7587
7588   /* We should never instantiate a nested class before its enclosing
7589      class; we need to look up the nested class by name before we can
7590      instantiate it, and that lookup should instantiate the enclosing
7591      class.  */
7592   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7593               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7594               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7595
7596   base_list = NULL_TREE;
7597   if (BINFO_N_BASE_BINFOS (pbinfo))
7598     {
7599       tree pbase_binfo;
7600       tree context = TYPE_CONTEXT (type);
7601       tree pushed_scope;
7602       int i;
7603
7604       /* We must enter the scope containing the type, as that is where
7605          the accessibility of types named in dependent bases are
7606          looked up from.  */
7607       pushed_scope = push_scope (context ? context : global_namespace);
7608
7609       /* Substitute into each of the bases to determine the actual
7610          basetypes.  */
7611       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7612         {
7613           tree base;
7614           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7615           tree expanded_bases = NULL_TREE;
7616           int idx, len = 1;
7617
7618           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7619             {
7620               expanded_bases = 
7621                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7622                                        args, tf_error, NULL_TREE);
7623               if (expanded_bases == error_mark_node)
7624                 continue;
7625
7626               len = TREE_VEC_LENGTH (expanded_bases);
7627             }
7628
7629           for (idx = 0; idx < len; idx++)
7630             {
7631               if (expanded_bases)
7632                 /* Extract the already-expanded base class.  */
7633                 base = TREE_VEC_ELT (expanded_bases, idx);
7634               else
7635                 /* Substitute to figure out the base class.  */
7636                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7637                                NULL_TREE);
7638
7639               if (base == error_mark_node)
7640                 continue;
7641
7642               base_list = tree_cons (access, base, base_list);
7643               if (BINFO_VIRTUAL_P (pbase_binfo))
7644                 TREE_TYPE (base_list) = integer_type_node;
7645             }
7646         }
7647
7648       /* The list is now in reverse order; correct that.  */
7649       base_list = nreverse (base_list);
7650
7651       if (pushed_scope)
7652         pop_scope (pushed_scope);
7653     }
7654   /* Now call xref_basetypes to set up all the base-class
7655      information.  */
7656   xref_basetypes (type, base_list);
7657
7658   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7659                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7660                                   args, tf_error, NULL_TREE);
7661
7662   /* Now that our base classes are set up, enter the scope of the
7663      class, so that name lookups into base classes, etc. will work
7664      correctly.  This is precisely analogous to what we do in
7665      begin_class_definition when defining an ordinary non-template
7666      class, except we also need to push the enclosing classes.  */
7667   push_nested_class (type);
7668
7669   /* Now members are processed in the order of declaration.  */
7670   for (member = CLASSTYPE_DECL_LIST (pattern);
7671        member; member = TREE_CHAIN (member))
7672     {
7673       tree t = TREE_VALUE (member);
7674
7675       if (TREE_PURPOSE (member))
7676         {
7677           if (TYPE_P (t))
7678             {
7679               /* Build new CLASSTYPE_NESTED_UTDS.  */
7680
7681               tree newtag;
7682               bool class_template_p;
7683
7684               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7685                                   && TYPE_LANG_SPECIFIC (t)
7686                                   && CLASSTYPE_IS_TEMPLATE (t));
7687               /* If the member is a class template, then -- even after
7688                  substitution -- there may be dependent types in the
7689                  template argument list for the class.  We increment
7690                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7691                  that function will assume that no types are dependent
7692                  when outside of a template.  */
7693               if (class_template_p)
7694                 ++processing_template_decl;
7695               newtag = tsubst (t, args, tf_error, NULL_TREE);
7696               if (class_template_p)
7697                 --processing_template_decl;
7698               if (newtag == error_mark_node)
7699                 continue;
7700
7701               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7702                 {
7703                   tree name = TYPE_IDENTIFIER (t);
7704
7705                   if (class_template_p)
7706                     /* Unfortunately, lookup_template_class sets
7707                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7708                        instantiation (i.e., for the type of a member
7709                        template class nested within a template class.)
7710                        This behavior is required for
7711                        maybe_process_partial_specialization to work
7712                        correctly, but is not accurate in this case;
7713                        the TAG is not an instantiation of anything.
7714                        (The corresponding TEMPLATE_DECL is an
7715                        instantiation, but the TYPE is not.) */
7716                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7717
7718                   /* Now, we call pushtag to put this NEWTAG into the scope of
7719                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7720                      pushtag calling push_template_decl.  We don't have to do
7721                      this for enums because it will already have been done in
7722                      tsubst_enum.  */
7723                   if (name)
7724                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7725                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7726                 }
7727             }
7728           else if (TREE_CODE (t) == FUNCTION_DECL
7729                    || DECL_FUNCTION_TEMPLATE_P (t))
7730             {
7731               /* Build new TYPE_METHODS.  */
7732               tree r;
7733
7734               if (TREE_CODE (t) == TEMPLATE_DECL)
7735                 ++processing_template_decl;
7736               r = tsubst (t, args, tf_error, NULL_TREE);
7737               if (TREE_CODE (t) == TEMPLATE_DECL)
7738                 --processing_template_decl;
7739               set_current_access_from_decl (r);
7740               finish_member_declaration (r);
7741             }
7742           else
7743             {
7744               /* Build new TYPE_FIELDS.  */
7745               if (TREE_CODE (t) == STATIC_ASSERT)
7746                 {
7747                   tree condition = 
7748                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7749                                  tf_warning_or_error, NULL_TREE,
7750                                  /*integral_constant_expression_p=*/true);
7751                   finish_static_assert (condition,
7752                                         STATIC_ASSERT_MESSAGE (t), 
7753                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7754                                         /*member_p=*/true);
7755                 }
7756               else if (TREE_CODE (t) != CONST_DECL)
7757                 {
7758                   tree r;
7759
7760                   /* The file and line for this declaration, to
7761                      assist in error message reporting.  Since we
7762                      called push_tinst_level above, we don't need to
7763                      restore these.  */
7764                   input_location = DECL_SOURCE_LOCATION (t);
7765
7766                   if (TREE_CODE (t) == TEMPLATE_DECL)
7767                     ++processing_template_decl;
7768                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7769                   if (TREE_CODE (t) == TEMPLATE_DECL)
7770                     --processing_template_decl;
7771                   if (TREE_CODE (r) == VAR_DECL)
7772                     {
7773                       /* In [temp.inst]:
7774
7775                            [t]he initialization (and any associated
7776                            side-effects) of a static data member does
7777                            not occur unless the static data member is
7778                            itself used in a way that requires the
7779                            definition of the static data member to
7780                            exist.
7781
7782                          Therefore, we do not substitute into the
7783                          initialized for the static data member here.  */
7784                       finish_static_data_member_decl
7785                         (r,
7786                          /*init=*/NULL_TREE,
7787                          /*init_const_expr_p=*/false,
7788                          /*asmspec_tree=*/NULL_TREE,
7789                          /*flags=*/0);
7790                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7791                         check_static_variable_definition (r, TREE_TYPE (r));
7792                     }
7793                   else if (TREE_CODE (r) == FIELD_DECL)
7794                     {
7795                       /* Determine whether R has a valid type and can be
7796                          completed later.  If R is invalid, then it is
7797                          replaced by error_mark_node so that it will not be
7798                          added to TYPE_FIELDS.  */
7799                       tree rtype = TREE_TYPE (r);
7800                       if (can_complete_type_without_circularity (rtype))
7801                         complete_type (rtype);
7802
7803                       if (!COMPLETE_TYPE_P (rtype))
7804                         {
7805                           cxx_incomplete_type_error (r, rtype);
7806                           r = error_mark_node;
7807                         }
7808                     }
7809
7810                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7811                      such a thing will already have been added to the field
7812                      list by tsubst_enum in finish_member_declaration in the
7813                      CLASSTYPE_NESTED_UTDS case above.  */
7814                   if (!(TREE_CODE (r) == TYPE_DECL
7815                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7816                         && DECL_ARTIFICIAL (r)))
7817                     {
7818                       set_current_access_from_decl (r);
7819                       finish_member_declaration (r);
7820                     }
7821                 }
7822             }
7823         }
7824       else
7825         {
7826           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7827             {
7828               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7829
7830               tree friend_type = t;
7831               bool adjust_processing_template_decl = false;
7832
7833               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7834                 {
7835                   /* template <class T> friend class C;  */
7836                   friend_type = tsubst_friend_class (friend_type, args);
7837                   adjust_processing_template_decl = true;
7838                 }
7839               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7840                 {
7841                   /* template <class T> friend class C::D;  */
7842                   friend_type = tsubst (friend_type, args,
7843                                         tf_warning_or_error, NULL_TREE);
7844                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7845                     friend_type = TREE_TYPE (friend_type);
7846                   adjust_processing_template_decl = true;
7847                 }
7848               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7849                 {
7850                   /* This could be either
7851
7852                        friend class T::C;
7853
7854                      when dependent_type_p is false or
7855
7856                        template <class U> friend class T::C;
7857
7858                      otherwise.  */
7859                   friend_type = tsubst (friend_type, args,
7860                                         tf_warning_or_error, NULL_TREE);
7861                   /* Bump processing_template_decl for correct
7862                      dependent_type_p calculation.  */
7863                   ++processing_template_decl;
7864                   if (dependent_type_p (friend_type))
7865                     adjust_processing_template_decl = true;
7866                   --processing_template_decl;
7867                 }
7868               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7869                        && hidden_name_p (TYPE_NAME (friend_type)))
7870                 {
7871                   /* friend class C;
7872
7873                      where C hasn't been declared yet.  Let's lookup name
7874                      from namespace scope directly, bypassing any name that
7875                      come from dependent base class.  */
7876                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7877
7878                   /* The call to xref_tag_from_type does injection for friend
7879                      classes.  */
7880                   push_nested_namespace (ns);
7881                   friend_type =
7882                     xref_tag_from_type (friend_type, NULL_TREE,
7883                                         /*tag_scope=*/ts_current);
7884                   pop_nested_namespace (ns);
7885                 }
7886               else if (uses_template_parms (friend_type))
7887                 /* friend class C<T>;  */
7888                 friend_type = tsubst (friend_type, args,
7889                                       tf_warning_or_error, NULL_TREE);
7890               /* Otherwise it's
7891
7892                    friend class C;
7893
7894                  where C is already declared or
7895
7896                    friend class C<int>;
7897
7898                  We don't have to do anything in these cases.  */
7899
7900               if (adjust_processing_template_decl)
7901                 /* Trick make_friend_class into realizing that the friend
7902                    we're adding is a template, not an ordinary class.  It's
7903                    important that we use make_friend_class since it will
7904                    perform some error-checking and output cross-reference
7905                    information.  */
7906                 ++processing_template_decl;
7907
7908               if (friend_type != error_mark_node)
7909                 make_friend_class (type, friend_type, /*complain=*/false);
7910
7911               if (adjust_processing_template_decl)
7912                 --processing_template_decl;
7913             }
7914           else
7915             {
7916               /* Build new DECL_FRIENDLIST.  */
7917               tree r;
7918
7919               /* The file and line for this declaration, to
7920                  assist in error message reporting.  Since we
7921                  called push_tinst_level above, we don't need to
7922                  restore these.  */
7923               input_location = DECL_SOURCE_LOCATION (t);
7924
7925               if (TREE_CODE (t) == TEMPLATE_DECL)
7926                 {
7927                   ++processing_template_decl;
7928                   push_deferring_access_checks (dk_no_check);
7929                 }
7930
7931               r = tsubst_friend_function (t, args);
7932               add_friend (type, r, /*complain=*/false);
7933               if (TREE_CODE (t) == TEMPLATE_DECL)
7934                 {
7935                   pop_deferring_access_checks ();
7936                   --processing_template_decl;
7937                 }
7938             }
7939         }
7940     }
7941
7942   /* Set the file and line number information to whatever is given for
7943      the class itself.  This puts error messages involving generated
7944      implicit functions at a predictable point, and the same point
7945      that would be used for non-template classes.  */
7946   input_location = DECL_SOURCE_LOCATION (typedecl);
7947
7948   unreverse_member_declarations (type);
7949   finish_struct_1 (type);
7950   TYPE_BEING_DEFINED (type) = 0;
7951
7952   /* Now that the class is complete, instantiate default arguments for
7953      any member functions.  We don't do this earlier because the
7954      default arguments may reference members of the class.  */
7955   if (!PRIMARY_TEMPLATE_P (templ))
7956     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7957       if (TREE_CODE (t) == FUNCTION_DECL
7958           /* Implicitly generated member functions will not have template
7959              information; they are not instantiations, but instead are
7960              created "fresh" for each instantiation.  */
7961           && DECL_TEMPLATE_INFO (t))
7962         tsubst_default_arguments (t);
7963
7964   /* Some typedefs referenced from within the template code need to be access
7965      checked at template instantiation time, i.e now. These types were
7966      added to the template at parsing time. Let's get those and perform
7967      the access checks then.  */
7968   perform_typedefs_access_check (pattern, args);
7969   perform_deferred_access_checks ();
7970   pop_nested_class ();
7971   maximum_field_alignment = saved_maximum_field_alignment;
7972   pop_from_top_level ();
7973   pop_deferring_access_checks ();
7974   pop_tinst_level ();
7975
7976   /* The vtable for a template class can be emitted in any translation
7977      unit in which the class is instantiated.  When there is no key
7978      method, however, finish_struct_1 will already have added TYPE to
7979      the keyed_classes list.  */
7980   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7981     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7982
7983   return type;
7984 }
7985
7986 static tree
7987 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7988 {
7989   tree r;
7990
7991   if (!t)
7992     r = t;
7993   else if (TYPE_P (t))
7994     r = tsubst (t, args, complain, in_decl);
7995   else
7996     {
7997       r = tsubst_expr (t, args, complain, in_decl,
7998                        /*integral_constant_expression_p=*/true);
7999       r = fold_non_dependent_expr (r);
8000     }
8001   return r;
8002 }
8003
8004 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8005    NONTYPE_ARGUMENT_PACK.  */
8006
8007 static tree
8008 make_fnparm_pack (tree spec_parm)
8009 {
8010   /* Collect all of the extra "packed" parameters into an
8011      argument pack.  */
8012   tree parmvec;
8013   tree parmtypevec;
8014   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8015   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8016   int i, len = list_length (spec_parm);
8017
8018   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8019   parmvec = make_tree_vec (len);
8020   parmtypevec = make_tree_vec (len);
8021   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8022     {
8023       TREE_VEC_ELT (parmvec, i) = spec_parm;
8024       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8025     }
8026
8027   /* Build the argument packs.  */
8028   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8029   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8030   TREE_TYPE (argpack) = argtypepack;
8031
8032   return argpack;
8033 }        
8034
8035 /* Substitute ARGS into T, which is an pack expansion
8036    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8037    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8038    (if only a partial substitution could be performed) or
8039    ERROR_MARK_NODE if there was an error.  */
8040 tree
8041 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8042                        tree in_decl)
8043 {
8044   tree pattern;
8045   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8046   int i, len = -1;
8047   tree result;
8048   int incomplete = 0;
8049   bool very_local_specializations = false;
8050
8051   gcc_assert (PACK_EXPANSION_P (t));
8052   pattern = PACK_EXPANSION_PATTERN (t);
8053
8054   /* Determine the argument packs that will instantiate the parameter
8055      packs used in the expansion expression. While we're at it,
8056      compute the number of arguments to be expanded and make sure it
8057      is consistent.  */
8058   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8059        pack = TREE_CHAIN (pack))
8060     {
8061       tree parm_pack = TREE_VALUE (pack);
8062       tree arg_pack = NULL_TREE;
8063       tree orig_arg = NULL_TREE;
8064
8065       if (TREE_CODE (parm_pack) == PARM_DECL)
8066         {
8067           arg_pack = retrieve_local_specialization (parm_pack);
8068           if (arg_pack == NULL_TREE)
8069             {
8070               /* This can happen for a parameter name used later in a function
8071                  declaration (such as in a late-specified return type).  Just
8072                  make a dummy decl, since it's only used for its type.  */
8073               gcc_assert (cp_unevaluated_operand != 0);
8074               arg_pack = tsubst_decl (parm_pack, args, complain);
8075               arg_pack = make_fnparm_pack (arg_pack);
8076             }
8077         }
8078       else
8079         {
8080           int level, idx, levels;
8081           template_parm_level_and_index (parm_pack, &level, &idx);
8082
8083           levels = TMPL_ARGS_DEPTH (args);
8084           if (level <= levels)
8085             arg_pack = TMPL_ARG (args, level, idx);
8086         }
8087
8088       orig_arg = arg_pack;
8089       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8090         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8091       
8092       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8093         /* This can only happen if we forget to expand an argument
8094            pack somewhere else. Just return an error, silently.  */
8095         {
8096           result = make_tree_vec (1);
8097           TREE_VEC_ELT (result, 0) = error_mark_node;
8098           return result;
8099         }
8100
8101       if (arg_pack
8102           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8103           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8104         {
8105           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8106           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8107           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8108               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8109             /* The argument pack that the parameter maps to is just an
8110                expansion of the parameter itself, such as one would
8111                find in the implicit typedef of a class inside the
8112                class itself.  Consider this parameter "unsubstituted",
8113                so that we will maintain the outer pack expansion.  */
8114             arg_pack = NULL_TREE;
8115         }
8116           
8117       if (arg_pack)
8118         {
8119           int my_len = 
8120             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8121
8122           /* It's all-or-nothing with incomplete argument packs.  */
8123           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8124             return error_mark_node;
8125           
8126           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8127             incomplete = 1;
8128
8129           if (len < 0)
8130             len = my_len;
8131           else if (len != my_len)
8132             {
8133               if (incomplete)
8134                 /* We got explicit args for some packs but not others;
8135                    do nothing now and try again after deduction.  */
8136                 return t;
8137               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8138                 error ("mismatched argument pack lengths while expanding "
8139                        "%<%T%>",
8140                        pattern);
8141               else
8142                 error ("mismatched argument pack lengths while expanding "
8143                        "%<%E%>",
8144                        pattern);
8145               return error_mark_node;
8146             }
8147
8148           /* Keep track of the parameter packs and their corresponding
8149              argument packs.  */
8150           packs = tree_cons (parm_pack, arg_pack, packs);
8151           TREE_TYPE (packs) = orig_arg;
8152         }
8153       else
8154         /* We can't substitute for this parameter pack.  */
8155         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8156                                          TREE_VALUE (pack),
8157                                          unsubstituted_packs);
8158     }
8159
8160   /* We cannot expand this expansion expression, because we don't have
8161      all of the argument packs we need. Substitute into the pattern
8162      and return a PACK_EXPANSION_*. The caller will need to deal with
8163      that.  */
8164   if (unsubstituted_packs)
8165     {
8166       tree new_pat;
8167       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8168         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8169                                /*integral_constant_expression_p=*/false);
8170       else
8171         new_pat = tsubst (pattern, args, complain, in_decl);
8172       return make_pack_expansion (new_pat);
8173     }
8174
8175   /* We could not find any argument packs that work.  */
8176   if (len < 0)
8177     return error_mark_node;
8178
8179   if (!local_specializations)
8180     {
8181       /* We're in a late-specified return type, so we don't have a local
8182          specializations table.  Create one for doing this expansion.  */
8183       very_local_specializations = true;
8184       local_specializations = htab_create (37,
8185                                            hash_local_specialization,
8186                                            eq_local_specializations,
8187                                            NULL);
8188     }
8189
8190   /* For each argument in each argument pack, substitute into the
8191      pattern.  */
8192   result = make_tree_vec (len + incomplete);
8193   for (i = 0; i < len + incomplete; ++i)
8194     {
8195       /* For parameter pack, change the substitution of the parameter
8196          pack to the ith argument in its argument pack, then expand
8197          the pattern.  */
8198       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8199         {
8200           tree parm = TREE_PURPOSE (pack);
8201
8202           if (TREE_CODE (parm) == PARM_DECL)
8203             {
8204               /* Select the Ith argument from the pack.  */
8205               tree arg = make_node (ARGUMENT_PACK_SELECT);
8206               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8207               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8208               mark_used (parm);
8209               register_local_specialization (arg, parm);
8210             }
8211           else
8212             {
8213               tree value = parm;
8214               int idx, level;
8215               template_parm_level_and_index (parm, &level, &idx);
8216               
8217               if (i < len) 
8218                 {
8219                   /* Select the Ith argument from the pack. */
8220                   value = make_node (ARGUMENT_PACK_SELECT);
8221                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8222                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8223                 }
8224
8225               /* Update the corresponding argument.  */
8226               TMPL_ARG (args, level, idx) = value;
8227             }
8228         }
8229
8230       /* Substitute into the PATTERN with the altered arguments.  */
8231       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8232         TREE_VEC_ELT (result, i) = 
8233           tsubst_expr (pattern, args, complain, in_decl,
8234                        /*integral_constant_expression_p=*/false);
8235       else
8236         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8237
8238       if (i == len)
8239         /* When we have incomplete argument packs, the last "expanded"
8240            result is itself a pack expansion, which allows us
8241            to deduce more arguments.  */
8242         TREE_VEC_ELT (result, i) = 
8243           make_pack_expansion (TREE_VEC_ELT (result, i));
8244
8245       if (TREE_VEC_ELT (result, i) == error_mark_node)
8246         {
8247           result = error_mark_node;
8248           break;
8249         }
8250     }
8251
8252   /* Update ARGS to restore the substitution from parameter packs to
8253      their argument packs.  */
8254   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8255     {
8256       tree parm = TREE_PURPOSE (pack);
8257
8258       if (TREE_CODE (parm) == PARM_DECL)
8259         register_local_specialization (TREE_TYPE (pack), parm);
8260       else
8261         {
8262           int idx, level;
8263           template_parm_level_and_index (parm, &level, &idx);
8264           
8265           /* Update the corresponding argument.  */
8266           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8267             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8268               TREE_TYPE (pack);
8269           else
8270             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8271         }
8272     }
8273
8274   if (very_local_specializations)
8275     {
8276       htab_delete (local_specializations);
8277       local_specializations = NULL;
8278     }
8279   
8280   return result;
8281 }
8282
8283 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8284    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8285    parameter packs; all parms generated from a function parameter pack will
8286    have the same DECL_PARM_INDEX.  */
8287
8288 tree
8289 get_pattern_parm (tree parm, tree tmpl)
8290 {
8291   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8292   tree patparm;
8293
8294   if (DECL_ARTIFICIAL (parm))
8295     {
8296       for (patparm = DECL_ARGUMENTS (pattern);
8297            patparm; patparm = TREE_CHAIN (patparm))
8298         if (DECL_ARTIFICIAL (patparm)
8299             && DECL_NAME (parm) == DECL_NAME (patparm))
8300           break;
8301     }
8302   else
8303     {
8304       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8305       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8306       gcc_assert (DECL_PARM_INDEX (patparm)
8307                   == DECL_PARM_INDEX (parm));
8308     }
8309
8310   return patparm;
8311 }
8312
8313 /* Substitute ARGS into the vector or list of template arguments T.  */
8314
8315 static tree
8316 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8317 {
8318   tree orig_t = t;
8319   int len = TREE_VEC_LENGTH (t);
8320   int need_new = 0, i, expanded_len_adjust = 0, out;
8321   tree *elts = (tree *) alloca (len * sizeof (tree));
8322
8323   for (i = 0; i < len; i++)
8324     {
8325       tree orig_arg = TREE_VEC_ELT (t, i);
8326       tree new_arg;
8327
8328       if (TREE_CODE (orig_arg) == TREE_VEC)
8329         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8330       else if (PACK_EXPANSION_P (orig_arg))
8331         {
8332           /* Substitute into an expansion expression.  */
8333           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8334
8335           if (TREE_CODE (new_arg) == TREE_VEC)
8336             /* Add to the expanded length adjustment the number of
8337                expanded arguments. We subtract one from this
8338                measurement, because the argument pack expression
8339                itself is already counted as 1 in
8340                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8341                the argument pack is empty.  */
8342             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8343         }
8344       else if (ARGUMENT_PACK_P (orig_arg))
8345         {
8346           /* Substitute into each of the arguments.  */
8347           new_arg = TYPE_P (orig_arg)
8348             ? cxx_make_type (TREE_CODE (orig_arg))
8349             : make_node (TREE_CODE (orig_arg));
8350           
8351           SET_ARGUMENT_PACK_ARGS (
8352             new_arg,
8353             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8354                                   args, complain, in_decl));
8355
8356           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8357             new_arg = error_mark_node;
8358
8359           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8360             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8361                                           complain, in_decl);
8362             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8363
8364             if (TREE_TYPE (new_arg) == error_mark_node)
8365               new_arg = error_mark_node;
8366           }
8367         }
8368       else
8369         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8370
8371       if (new_arg == error_mark_node)
8372         return error_mark_node;
8373
8374       elts[i] = new_arg;
8375       if (new_arg != orig_arg)
8376         need_new = 1;
8377     }
8378
8379   if (!need_new)
8380     return t;
8381
8382   /* Make space for the expanded arguments coming from template
8383      argument packs.  */
8384   t = make_tree_vec (len + expanded_len_adjust);
8385   for (i = 0, out = 0; i < len; i++)
8386     {
8387       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8388            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8389           && TREE_CODE (elts[i]) == TREE_VEC)
8390         {
8391           int idx;
8392
8393           /* Now expand the template argument pack "in place".  */
8394           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8395             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8396         }
8397       else
8398         {
8399           TREE_VEC_ELT (t, out) = elts[i];
8400           out++;
8401         }
8402     }
8403
8404   return t;
8405 }
8406
8407 /* Return the result of substituting ARGS into the template parameters
8408    given by PARMS.  If there are m levels of ARGS and m + n levels of
8409    PARMS, then the result will contain n levels of PARMS.  For
8410    example, if PARMS is `template <class T> template <class U>
8411    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8412    result will be `template <int*, double, class V>'.  */
8413
8414 static tree
8415 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8416 {
8417   tree r = NULL_TREE;
8418   tree* new_parms;
8419
8420   /* When substituting into a template, we must set
8421      PROCESSING_TEMPLATE_DECL as the template parameters may be
8422      dependent if they are based on one-another, and the dependency
8423      predicates are short-circuit outside of templates.  */
8424   ++processing_template_decl;
8425
8426   for (new_parms = &r;
8427        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8428        new_parms = &(TREE_CHAIN (*new_parms)),
8429          parms = TREE_CHAIN (parms))
8430     {
8431       tree new_vec =
8432         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8433       int i;
8434
8435       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8436         {
8437           tree tuple;
8438           tree default_value;
8439           tree parm_decl;
8440
8441           if (parms == error_mark_node)
8442             continue;
8443
8444           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8445
8446           if (tuple == error_mark_node)
8447             continue;
8448
8449           default_value = TREE_PURPOSE (tuple);
8450           parm_decl = TREE_VALUE (tuple);
8451
8452           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8453           if (TREE_CODE (parm_decl) == PARM_DECL
8454               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8455             parm_decl = error_mark_node;
8456           default_value = tsubst_template_arg (default_value, args,
8457                                                complain, NULL_TREE);
8458
8459           tuple = build_tree_list (default_value, parm_decl);
8460           TREE_VEC_ELT (new_vec, i) = tuple;
8461         }
8462
8463       *new_parms =
8464         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8465                              - TMPL_ARGS_DEPTH (args)),
8466                    new_vec, NULL_TREE);
8467     }
8468
8469   --processing_template_decl;
8470
8471   return r;
8472 }
8473
8474 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8475    type T.  If T is not an aggregate or enumeration type, it is
8476    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8477    ENTERING_SCOPE is nonzero, T is the context for a template which
8478    we are presently tsubst'ing.  Return the substituted value.  */
8479
8480 static tree
8481 tsubst_aggr_type (tree t,
8482                   tree args,
8483                   tsubst_flags_t complain,
8484                   tree in_decl,
8485                   int entering_scope)
8486 {
8487   if (t == NULL_TREE)
8488     return NULL_TREE;
8489
8490   switch (TREE_CODE (t))
8491     {
8492     case RECORD_TYPE:
8493       if (TYPE_PTRMEMFUNC_P (t))
8494         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8495
8496       /* Else fall through.  */
8497     case ENUMERAL_TYPE:
8498     case UNION_TYPE:
8499       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8500         {
8501           tree argvec;
8502           tree context;
8503           tree r;
8504           int saved_unevaluated_operand;
8505           int saved_inhibit_evaluation_warnings;
8506
8507           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8508           saved_unevaluated_operand = cp_unevaluated_operand;
8509           cp_unevaluated_operand = 0;
8510           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8511           c_inhibit_evaluation_warnings = 0;
8512
8513           /* First, determine the context for the type we are looking
8514              up.  */
8515           context = TYPE_CONTEXT (t);
8516           if (context)
8517             {
8518               context = tsubst_aggr_type (context, args, complain,
8519                                           in_decl, /*entering_scope=*/1);
8520               /* If context is a nested class inside a class template,
8521                  it may still need to be instantiated (c++/33959).  */
8522               if (TYPE_P (context))
8523                 context = complete_type (context);
8524             }
8525
8526           /* Then, figure out what arguments are appropriate for the
8527              type we are trying to find.  For example, given:
8528
8529                template <class T> struct S;
8530                template <class T, class U> void f(T, U) { S<U> su; }
8531
8532              and supposing that we are instantiating f<int, double>,
8533              then our ARGS will be {int, double}, but, when looking up
8534              S we only want {double}.  */
8535           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8536                                          complain, in_decl);
8537           if (argvec == error_mark_node)
8538             r = error_mark_node;
8539           else
8540             {
8541               r = lookup_template_class (t, argvec, in_decl, context,
8542                                          entering_scope, complain);
8543               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8544             }
8545
8546           cp_unevaluated_operand = saved_unevaluated_operand;
8547           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8548
8549           return r;
8550         }
8551       else
8552         /* This is not a template type, so there's nothing to do.  */
8553         return t;
8554
8555     default:
8556       return tsubst (t, args, complain, in_decl);
8557     }
8558 }
8559
8560 /* Substitute into the default argument ARG (a default argument for
8561    FN), which has the indicated TYPE.  */
8562
8563 tree
8564 tsubst_default_argument (tree fn, tree type, tree arg)
8565 {
8566   tree saved_class_ptr = NULL_TREE;
8567   tree saved_class_ref = NULL_TREE;
8568
8569   /* This default argument came from a template.  Instantiate the
8570      default argument here, not in tsubst.  In the case of
8571      something like:
8572
8573        template <class T>
8574        struct S {
8575          static T t();
8576          void f(T = t());
8577        };
8578
8579      we must be careful to do name lookup in the scope of S<T>,
8580      rather than in the current class.  */
8581   push_access_scope (fn);
8582   /* The "this" pointer is not valid in a default argument.  */
8583   if (cfun)
8584     {
8585       saved_class_ptr = current_class_ptr;
8586       cp_function_chain->x_current_class_ptr = NULL_TREE;
8587       saved_class_ref = current_class_ref;
8588       cp_function_chain->x_current_class_ref = NULL_TREE;
8589     }
8590
8591   push_deferring_access_checks(dk_no_deferred);
8592   /* The default argument expression may cause implicitly defined
8593      member functions to be synthesized, which will result in garbage
8594      collection.  We must treat this situation as if we were within
8595      the body of function so as to avoid collecting live data on the
8596      stack.  */
8597   ++function_depth;
8598   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8599                      tf_warning_or_error, NULL_TREE,
8600                      /*integral_constant_expression_p=*/false);
8601   --function_depth;
8602   pop_deferring_access_checks();
8603
8604   /* Restore the "this" pointer.  */
8605   if (cfun)
8606     {
8607       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8608       cp_function_chain->x_current_class_ref = saved_class_ref;
8609     }
8610
8611   /* Make sure the default argument is reasonable.  */
8612   arg = check_default_argument (type, arg);
8613
8614   pop_access_scope (fn);
8615
8616   return arg;
8617 }
8618
8619 /* Substitute into all the default arguments for FN.  */
8620
8621 static void
8622 tsubst_default_arguments (tree fn)
8623 {
8624   tree arg;
8625   tree tmpl_args;
8626
8627   tmpl_args = DECL_TI_ARGS (fn);
8628
8629   /* If this function is not yet instantiated, we certainly don't need
8630      its default arguments.  */
8631   if (uses_template_parms (tmpl_args))
8632     return;
8633
8634   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8635        arg;
8636        arg = TREE_CHAIN (arg))
8637     if (TREE_PURPOSE (arg))
8638       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8639                                                     TREE_VALUE (arg),
8640                                                     TREE_PURPOSE (arg));
8641 }
8642
8643 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8644    result of the substitution.  Issue error and warning messages under
8645    control of COMPLAIN.  */
8646
8647 static tree
8648 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8649 {
8650 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8651   location_t saved_loc;
8652   tree r = NULL_TREE;
8653   tree in_decl = t;
8654   hashval_t hash = 0;
8655
8656   /* Set the filename and linenumber to improve error-reporting.  */
8657   saved_loc = input_location;
8658   input_location = DECL_SOURCE_LOCATION (t);
8659
8660   switch (TREE_CODE (t))
8661     {
8662     case TEMPLATE_DECL:
8663       {
8664         /* We can get here when processing a member function template,
8665            member class template, or template template parameter.  */
8666         tree decl = DECL_TEMPLATE_RESULT (t);
8667         tree spec;
8668         tree tmpl_args;
8669         tree full_args;
8670
8671         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8672           {
8673             /* Template template parameter is treated here.  */
8674             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8675             if (new_type == error_mark_node)
8676               RETURN (error_mark_node);
8677
8678             r = copy_decl (t);
8679             TREE_CHAIN (r) = NULL_TREE;
8680             TREE_TYPE (r) = new_type;
8681             DECL_TEMPLATE_RESULT (r)
8682               = build_decl (DECL_SOURCE_LOCATION (decl),
8683                             TYPE_DECL, DECL_NAME (decl), new_type);
8684             DECL_TEMPLATE_PARMS (r)
8685               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8686                                        complain);
8687             TYPE_NAME (new_type) = r;
8688             break;
8689           }
8690
8691         /* We might already have an instance of this template.
8692            The ARGS are for the surrounding class type, so the
8693            full args contain the tsubst'd args for the context,
8694            plus the innermost args from the template decl.  */
8695         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8696           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8697           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8698         /* Because this is a template, the arguments will still be
8699            dependent, even after substitution.  If
8700            PROCESSING_TEMPLATE_DECL is not set, the dependency
8701            predicates will short-circuit.  */
8702         ++processing_template_decl;
8703         full_args = tsubst_template_args (tmpl_args, args,
8704                                           complain, in_decl);
8705         --processing_template_decl;
8706         if (full_args == error_mark_node)
8707           RETURN (error_mark_node);
8708
8709         /* If this is a default template template argument,
8710            tsubst might not have changed anything.  */
8711         if (full_args == tmpl_args)
8712           RETURN (t);
8713
8714         hash = hash_tmpl_and_args (t, full_args);
8715         spec = retrieve_specialization (t, full_args, hash);
8716         if (spec != NULL_TREE)
8717           {
8718             r = spec;
8719             break;
8720           }
8721
8722         /* Make a new template decl.  It will be similar to the
8723            original, but will record the current template arguments.
8724            We also create a new function declaration, which is just
8725            like the old one, but points to this new template, rather
8726            than the old one.  */
8727         r = copy_decl (t);
8728         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8729         TREE_CHAIN (r) = NULL_TREE;
8730
8731         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8732
8733         if (TREE_CODE (decl) == TYPE_DECL)
8734           {
8735             tree new_type;
8736             ++processing_template_decl;
8737             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8738             --processing_template_decl;
8739             if (new_type == error_mark_node)
8740               RETURN (error_mark_node);
8741
8742             TREE_TYPE (r) = new_type;
8743             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8744             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8745             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8746             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8747           }
8748         else
8749           {
8750             tree new_decl;
8751             ++processing_template_decl;
8752             new_decl = tsubst (decl, args, complain, in_decl);
8753             --processing_template_decl;
8754             if (new_decl == error_mark_node)
8755               RETURN (error_mark_node);
8756
8757             DECL_TEMPLATE_RESULT (r) = new_decl;
8758             DECL_TI_TEMPLATE (new_decl) = r;
8759             TREE_TYPE (r) = TREE_TYPE (new_decl);
8760             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8761             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8762           }
8763
8764         SET_DECL_IMPLICIT_INSTANTIATION (r);
8765         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8766         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8767
8768         /* The template parameters for this new template are all the
8769            template parameters for the old template, except the
8770            outermost level of parameters.  */
8771         DECL_TEMPLATE_PARMS (r)
8772           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8773                                    complain);
8774
8775         if (PRIMARY_TEMPLATE_P (t))
8776           DECL_PRIMARY_TEMPLATE (r) = r;
8777
8778         if (TREE_CODE (decl) != TYPE_DECL)
8779           /* Record this non-type partial instantiation.  */
8780           register_specialization (r, t,
8781                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8782                                    false, hash);
8783       }
8784       break;
8785
8786     case FUNCTION_DECL:
8787       {
8788         tree ctx;
8789         tree argvec = NULL_TREE;
8790         tree *friends;
8791         tree gen_tmpl;
8792         tree type;
8793         int member;
8794         int args_depth;
8795         int parms_depth;
8796
8797         /* Nobody should be tsubst'ing into non-template functions.  */
8798         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8799
8800         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8801           {
8802             tree spec;
8803             bool dependent_p;
8804
8805             /* If T is not dependent, just return it.  We have to
8806                increment PROCESSING_TEMPLATE_DECL because
8807                value_dependent_expression_p assumes that nothing is
8808                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8809             ++processing_template_decl;
8810             dependent_p = value_dependent_expression_p (t);
8811             --processing_template_decl;
8812             if (!dependent_p)
8813               RETURN (t);
8814
8815             /* Calculate the most general template of which R is a
8816                specialization, and the complete set of arguments used to
8817                specialize R.  */
8818             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8819             argvec = tsubst_template_args (DECL_TI_ARGS
8820                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8821                                            args, complain, in_decl);
8822
8823             /* Check to see if we already have this specialization.  */
8824             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8825             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8826
8827             if (spec)
8828               {
8829                 r = spec;
8830                 break;
8831               }
8832
8833             /* We can see more levels of arguments than parameters if
8834                there was a specialization of a member template, like
8835                this:
8836
8837                  template <class T> struct S { template <class U> void f(); }
8838                  template <> template <class U> void S<int>::f(U);
8839
8840                Here, we'll be substituting into the specialization,
8841                because that's where we can find the code we actually
8842                want to generate, but we'll have enough arguments for
8843                the most general template.
8844
8845                We also deal with the peculiar case:
8846
8847                  template <class T> struct S {
8848                    template <class U> friend void f();
8849                  };
8850                  template <class U> void f() {}
8851                  template S<int>;
8852                  template void f<double>();
8853
8854                Here, the ARGS for the instantiation of will be {int,
8855                double}.  But, we only need as many ARGS as there are
8856                levels of template parameters in CODE_PATTERN.  We are
8857                careful not to get fooled into reducing the ARGS in
8858                situations like:
8859
8860                  template <class T> struct S { template <class U> void f(U); }
8861                  template <class T> template <> void S<T>::f(int) {}
8862
8863                which we can spot because the pattern will be a
8864                specialization in this case.  */
8865             args_depth = TMPL_ARGS_DEPTH (args);
8866             parms_depth =
8867               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8868             if (args_depth > parms_depth
8869                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8870               args = get_innermost_template_args (args, parms_depth);
8871           }
8872         else
8873           {
8874             /* This special case arises when we have something like this:
8875
8876                  template <class T> struct S {
8877                    friend void f<int>(int, double);
8878                  };
8879
8880                Here, the DECL_TI_TEMPLATE for the friend declaration
8881                will be an IDENTIFIER_NODE.  We are being called from
8882                tsubst_friend_function, and we want only to create a
8883                new decl (R) with appropriate types so that we can call
8884                determine_specialization.  */
8885             gen_tmpl = NULL_TREE;
8886           }
8887
8888         if (DECL_CLASS_SCOPE_P (t))
8889           {
8890             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8891               member = 2;
8892             else
8893               member = 1;
8894             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8895                                     complain, t, /*entering_scope=*/1);
8896           }
8897         else
8898           {
8899             member = 0;
8900             ctx = DECL_CONTEXT (t);
8901           }
8902         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8903         if (type == error_mark_node)
8904           RETURN (error_mark_node);
8905
8906         /* We do NOT check for matching decls pushed separately at this
8907            point, as they may not represent instantiations of this
8908            template, and in any case are considered separate under the
8909            discrete model.  */
8910         r = copy_decl (t);
8911         DECL_USE_TEMPLATE (r) = 0;
8912         TREE_TYPE (r) = type;
8913         /* Clear out the mangled name and RTL for the instantiation.  */
8914         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8915         SET_DECL_RTL (r, NULL_RTX);
8916         /* Leave DECL_INITIAL set on deleted instantiations.  */
8917         if (!DECL_DELETED_FN (r))
8918           DECL_INITIAL (r) = NULL_TREE;
8919         DECL_CONTEXT (r) = ctx;
8920
8921         if (member && DECL_CONV_FN_P (r))
8922           /* Type-conversion operator.  Reconstruct the name, in
8923              case it's the name of one of the template's parameters.  */
8924           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8925
8926         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8927                                      complain, t);
8928         DECL_RESULT (r) = NULL_TREE;
8929
8930         TREE_STATIC (r) = 0;
8931         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8932         DECL_EXTERNAL (r) = 1;
8933         /* If this is an instantiation of a function with internal
8934            linkage, we already know what object file linkage will be
8935            assigned to the instantiation.  */
8936         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8937         DECL_DEFER_OUTPUT (r) = 0;
8938         TREE_CHAIN (r) = NULL_TREE;
8939         DECL_PENDING_INLINE_INFO (r) = 0;
8940         DECL_PENDING_INLINE_P (r) = 0;
8941         DECL_SAVED_TREE (r) = NULL_TREE;
8942         DECL_STRUCT_FUNCTION (r) = NULL;
8943         TREE_USED (r) = 0;
8944         /* We'll re-clone as appropriate in instantiate_template.  */
8945         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8946
8947         /* If we aren't complaining now, return on error before we register
8948            the specialization so that we'll complain eventually.  */
8949         if ((complain & tf_error) == 0
8950             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8951             && !grok_op_properties (r, /*complain=*/false))
8952           RETURN (error_mark_node);
8953
8954         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8955            this in the special friend case mentioned above where
8956            GEN_TMPL is NULL.  */
8957         if (gen_tmpl)
8958           {
8959             DECL_TEMPLATE_INFO (r)
8960               = build_template_info (gen_tmpl, argvec);
8961             SET_DECL_IMPLICIT_INSTANTIATION (r);
8962             register_specialization (r, gen_tmpl, argvec, false, hash);
8963
8964             /* We're not supposed to instantiate default arguments
8965                until they are called, for a template.  But, for a
8966                declaration like:
8967
8968                  template <class T> void f ()
8969                  { extern void g(int i = T()); }
8970
8971                we should do the substitution when the template is
8972                instantiated.  We handle the member function case in
8973                instantiate_class_template since the default arguments
8974                might refer to other members of the class.  */
8975             if (!member
8976                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8977                 && !uses_template_parms (argvec))
8978               tsubst_default_arguments (r);
8979           }
8980         else
8981           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8982
8983         /* Copy the list of befriending classes.  */
8984         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8985              *friends;
8986              friends = &TREE_CHAIN (*friends))
8987           {
8988             *friends = copy_node (*friends);
8989             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8990                                             args, complain,
8991                                             in_decl);
8992           }
8993
8994         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8995           {
8996             maybe_retrofit_in_chrg (r);
8997             if (DECL_CONSTRUCTOR_P (r))
8998               grok_ctor_properties (ctx, r);
8999             /* If this is an instantiation of a member template, clone it.
9000                If it isn't, that'll be handled by
9001                clone_constructors_and_destructors.  */
9002             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9003               clone_function_decl (r, /*update_method_vec_p=*/0);
9004           }
9005         else if ((complain & tf_error) != 0
9006                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9007                  && !grok_op_properties (r, /*complain=*/true))
9008           RETURN (error_mark_node);
9009
9010         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9011           SET_DECL_FRIEND_CONTEXT (r,
9012                                    tsubst (DECL_FRIEND_CONTEXT (t),
9013                                             args, complain, in_decl));
9014
9015         /* Possibly limit visibility based on template args.  */
9016         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9017         if (DECL_VISIBILITY_SPECIFIED (t))
9018           {
9019             DECL_VISIBILITY_SPECIFIED (r) = 0;
9020             DECL_ATTRIBUTES (r)
9021               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9022           }
9023         determine_visibility (r);
9024         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9025             && !processing_template_decl)
9026           defaulted_late_check (r);
9027
9028         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9029                                         args, complain, in_decl);
9030       }
9031       break;
9032
9033     case PARM_DECL:
9034       {
9035         tree type = NULL_TREE;
9036         int i, len = 1;
9037         tree expanded_types = NULL_TREE;
9038         tree prev_r = NULL_TREE;
9039         tree first_r = NULL_TREE;
9040
9041         if (FUNCTION_PARAMETER_PACK_P (t))
9042           {
9043             /* If there is a local specialization that isn't a
9044                parameter pack, it means that we're doing a "simple"
9045                substitution from inside tsubst_pack_expansion. Just
9046                return the local specialization (which will be a single
9047                parm).  */
9048             tree spec = retrieve_local_specialization (t);
9049             if (spec 
9050                 && TREE_CODE (spec) == PARM_DECL
9051                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9052               RETURN (spec);
9053
9054             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9055                the parameters in this function parameter pack.  */
9056             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9057                                                     complain, in_decl);
9058             if (TREE_CODE (expanded_types) == TREE_VEC)
9059               {
9060                 len = TREE_VEC_LENGTH (expanded_types);
9061
9062                 /* Zero-length parameter packs are boring. Just substitute
9063                    into the chain.  */
9064                 if (len == 0)
9065                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9066                                   TREE_CHAIN (t)));
9067               }
9068             else
9069               {
9070                 /* All we did was update the type. Make a note of that.  */
9071                 type = expanded_types;
9072                 expanded_types = NULL_TREE;
9073               }
9074           }
9075
9076         /* Loop through all of the parameter's we'll build. When T is
9077            a function parameter pack, LEN is the number of expanded
9078            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9079         r = NULL_TREE;
9080         for (i = 0; i < len; ++i)
9081           {
9082             prev_r = r;
9083             r = copy_node (t);
9084             if (DECL_TEMPLATE_PARM_P (t))
9085               SET_DECL_TEMPLATE_PARM_P (r);
9086
9087             /* An argument of a function parameter pack is not a parameter
9088                pack.  */
9089             FUNCTION_PARAMETER_PACK_P (r) = false;
9090
9091             if (expanded_types)
9092               /* We're on the Ith parameter of the function parameter
9093                  pack.  */
9094               {
9095                 /* Get the Ith type.  */
9096                 type = TREE_VEC_ELT (expanded_types, i);
9097
9098                 if (DECL_NAME (r))
9099                   /* Rename the parameter to include the index.  */
9100                   DECL_NAME (r) =
9101                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9102               }
9103             else if (!type)
9104               /* We're dealing with a normal parameter.  */
9105               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9106
9107             type = type_decays_to (type);
9108             TREE_TYPE (r) = type;
9109             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9110
9111             if (DECL_INITIAL (r))
9112               {
9113                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9114                   DECL_INITIAL (r) = TREE_TYPE (r);
9115                 else
9116                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9117                                              complain, in_decl);
9118               }
9119
9120             DECL_CONTEXT (r) = NULL_TREE;
9121
9122             if (!DECL_TEMPLATE_PARM_P (r))
9123               DECL_ARG_TYPE (r) = type_passed_as (type);
9124
9125             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9126                                             args, complain, in_decl);
9127
9128             /* Keep track of the first new parameter we
9129                generate. That's what will be returned to the
9130                caller.  */
9131             if (!first_r)
9132               first_r = r;
9133
9134             /* Build a proper chain of parameters when substituting
9135                into a function parameter pack.  */
9136             if (prev_r)
9137               TREE_CHAIN (prev_r) = r;
9138           }
9139
9140         if (TREE_CHAIN (t))
9141           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9142                                    complain, TREE_CHAIN (t));
9143
9144         /* FIRST_R contains the start of the chain we've built.  */
9145         r = first_r;
9146       }
9147       break;
9148
9149     case FIELD_DECL:
9150       {
9151         tree type;
9152
9153         r = copy_decl (t);
9154         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9155         if (type == error_mark_node)
9156           RETURN (error_mark_node);
9157         TREE_TYPE (r) = type;
9158         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9159
9160         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9161         DECL_INITIAL (r)
9162           = tsubst_expr (DECL_INITIAL (t), args,
9163                          complain, in_decl,
9164                          /*integral_constant_expression_p=*/true);
9165         /* We don't have to set DECL_CONTEXT here; it is set by
9166            finish_member_declaration.  */
9167         TREE_CHAIN (r) = NULL_TREE;
9168         if (VOID_TYPE_P (type))
9169           error ("instantiation of %q+D as type %qT", r, type);
9170
9171         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9172                                         args, complain, in_decl);
9173       }
9174       break;
9175
9176     case USING_DECL:
9177       /* We reach here only for member using decls.  */
9178       if (DECL_DEPENDENT_P (t))
9179         {
9180           r = do_class_using_decl
9181             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9182              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9183           if (!r)
9184             r = error_mark_node;
9185           else
9186             {
9187               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9188               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9189             }
9190         }
9191       else
9192         {
9193           r = copy_node (t);
9194           TREE_CHAIN (r) = NULL_TREE;
9195         }
9196       break;
9197
9198     case TYPE_DECL:
9199     case VAR_DECL:
9200       {
9201         tree argvec = NULL_TREE;
9202         tree gen_tmpl = NULL_TREE;
9203         tree spec;
9204         tree tmpl = NULL_TREE;
9205         tree ctx;
9206         tree type = NULL_TREE;
9207         bool local_p;
9208
9209         if (TREE_CODE (t) == TYPE_DECL
9210             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9211           {
9212             /* If this is the canonical decl, we don't have to
9213                mess with instantiations, and often we can't (for
9214                typename, template type parms and such).  Note that
9215                TYPE_NAME is not correct for the above test if
9216                we've copied the type for a typedef.  */
9217             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9218             if (type == error_mark_node)
9219               RETURN (error_mark_node);
9220             r = TYPE_NAME (type);
9221             break;
9222           }
9223
9224         /* Check to see if we already have the specialization we
9225            need.  */
9226         spec = NULL_TREE;
9227         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9228           {
9229             /* T is a static data member or namespace-scope entity.
9230                We have to substitute into namespace-scope variables
9231                (even though such entities are never templates) because
9232                of cases like:
9233                
9234                  template <class T> void f() { extern T t; }
9235
9236                where the entity referenced is not known until
9237                instantiation time.  */
9238             local_p = false;
9239             ctx = DECL_CONTEXT (t);
9240             if (DECL_CLASS_SCOPE_P (t))
9241               {
9242                 ctx = tsubst_aggr_type (ctx, args,
9243                                         complain,
9244                                         in_decl, /*entering_scope=*/1);
9245                 /* If CTX is unchanged, then T is in fact the
9246                    specialization we want.  That situation occurs when
9247                    referencing a static data member within in its own
9248                    class.  We can use pointer equality, rather than
9249                    same_type_p, because DECL_CONTEXT is always
9250                    canonical.  */
9251                 if (ctx == DECL_CONTEXT (t))
9252                   spec = t;
9253               }
9254
9255             if (!spec)
9256               {
9257                 tmpl = DECL_TI_TEMPLATE (t);
9258                 gen_tmpl = most_general_template (tmpl);
9259                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9260                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9261                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9262               }
9263           }
9264         else
9265           {
9266             /* A local variable.  */
9267             local_p = true;
9268             /* Subsequent calls to pushdecl will fill this in.  */
9269             ctx = NULL_TREE;
9270             spec = retrieve_local_specialization (t);
9271           }
9272         /* If we already have the specialization we need, there is
9273            nothing more to do.  */ 
9274         if (spec)
9275           {
9276             r = spec;
9277             break;
9278           }
9279
9280         /* Create a new node for the specialization we need.  */
9281         r = copy_decl (t);
9282         if (type == NULL_TREE)
9283           {
9284             if (is_typedef_decl (t))
9285               type = DECL_ORIGINAL_TYPE (t);
9286             else
9287               type = TREE_TYPE (t);
9288             type = tsubst (type, args, complain, in_decl);
9289           }
9290         if (TREE_CODE (r) == VAR_DECL)
9291           {
9292             /* Even if the original location is out of scope, the
9293                newly substituted one is not.  */
9294             DECL_DEAD_FOR_LOCAL (r) = 0;
9295             DECL_INITIALIZED_P (r) = 0;
9296             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9297             if (type == error_mark_node)
9298               RETURN (error_mark_node);
9299             if (TREE_CODE (type) == FUNCTION_TYPE)
9300               {
9301                 /* It may seem that this case cannot occur, since:
9302
9303                      typedef void f();
9304                      void g() { f x; }
9305
9306                    declares a function, not a variable.  However:
9307       
9308                      typedef void f();
9309                      template <typename T> void g() { T t; }
9310                      template void g<f>();
9311
9312                    is an attempt to declare a variable with function
9313                    type.  */
9314                 error ("variable %qD has function type",
9315                        /* R is not yet sufficiently initialized, so we
9316                           just use its name.  */
9317                        DECL_NAME (r));
9318                 RETURN (error_mark_node);
9319               }
9320             type = complete_type (type);
9321             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9322               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9323             type = check_var_type (DECL_NAME (r), type);
9324
9325             if (DECL_HAS_VALUE_EXPR_P (t))
9326               {
9327                 tree ve = DECL_VALUE_EXPR (t);
9328                 ve = tsubst_expr (ve, args, complain, in_decl,
9329                                   /*constant_expression_p=*/false);
9330                 SET_DECL_VALUE_EXPR (r, ve);
9331               }
9332           }
9333         else if (DECL_SELF_REFERENCE_P (t))
9334           SET_DECL_SELF_REFERENCE_P (r);
9335         TREE_TYPE (r) = type;
9336         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9337         DECL_CONTEXT (r) = ctx;
9338         /* Clear out the mangled name and RTL for the instantiation.  */
9339         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9340         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9341           SET_DECL_RTL (r, NULL_RTX);
9342         /* The initializer must not be expanded until it is required;
9343            see [temp.inst].  */
9344         DECL_INITIAL (r) = NULL_TREE;
9345         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9346           SET_DECL_RTL (r, NULL_RTX);
9347         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9348         if (TREE_CODE (r) == VAR_DECL)
9349           {
9350             /* Possibly limit visibility based on template args.  */
9351             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9352             if (DECL_VISIBILITY_SPECIFIED (t))
9353               {
9354                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9355                 DECL_ATTRIBUTES (r)
9356                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9357               }
9358             determine_visibility (r);
9359           }
9360
9361         if (!local_p)
9362           {
9363             /* A static data member declaration is always marked
9364                external when it is declared in-class, even if an
9365                initializer is present.  We mimic the non-template
9366                processing here.  */
9367             DECL_EXTERNAL (r) = 1;
9368
9369             register_specialization (r, gen_tmpl, argvec, false, hash);
9370             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9371             SET_DECL_IMPLICIT_INSTANTIATION (r);
9372           }
9373         else if (cp_unevaluated_operand)
9374           {
9375             /* We're substituting this var in a decltype outside of its
9376                scope, such as for a lambda return type.  Don't add it to
9377                local_specializations, do perform auto deduction.  */
9378             tree auto_node = type_uses_auto (type);
9379             tree init
9380               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9381                              /*constant_expression_p=*/false);
9382
9383             if (auto_node && init && describable_type (init))
9384               {
9385                 type = do_auto_deduction (type, init, auto_node);
9386                 TREE_TYPE (r) = type;
9387               }
9388           }
9389         else
9390           register_local_specialization (r, t);
9391
9392         TREE_CHAIN (r) = NULL_TREE;
9393
9394         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9395                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9396                                         args, complain, in_decl);
9397
9398         /* Preserve a typedef that names a type.  */
9399         if (is_typedef_decl (r))
9400           {
9401             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9402             set_underlying_type (r);
9403           }
9404
9405         layout_decl (r, 0);
9406       }
9407       break;
9408
9409     default:
9410       gcc_unreachable ();
9411     }
9412 #undef RETURN
9413
9414  out:
9415   /* Restore the file and line information.  */
9416   input_location = saved_loc;
9417
9418   return r;
9419 }
9420
9421 /* Substitute into the ARG_TYPES of a function type.  */
9422
9423 static tree
9424 tsubst_arg_types (tree arg_types,
9425                   tree args,
9426                   tsubst_flags_t complain,
9427                   tree in_decl)
9428 {
9429   tree remaining_arg_types;
9430   tree type = NULL_TREE;
9431   int i = 1;
9432   tree expanded_args = NULL_TREE;
9433   tree default_arg;
9434
9435   if (!arg_types || arg_types == void_list_node)
9436     return arg_types;
9437
9438   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9439                                           args, complain, in_decl);
9440   if (remaining_arg_types == error_mark_node)
9441     return error_mark_node;
9442
9443   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9444     {
9445       /* For a pack expansion, perform substitution on the
9446          entire expression. Later on, we'll handle the arguments
9447          one-by-one.  */
9448       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9449                                             args, complain, in_decl);
9450
9451       if (TREE_CODE (expanded_args) == TREE_VEC)
9452         /* So that we'll spin through the parameters, one by one.  */
9453         i = TREE_VEC_LENGTH (expanded_args);
9454       else
9455         {
9456           /* We only partially substituted into the parameter
9457              pack. Our type is TYPE_PACK_EXPANSION.  */
9458           type = expanded_args;
9459           expanded_args = NULL_TREE;
9460         }
9461     }
9462
9463   while (i > 0) {
9464     --i;
9465     
9466     if (expanded_args)
9467       type = TREE_VEC_ELT (expanded_args, i);
9468     else if (!type)
9469       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9470
9471     if (type == error_mark_node)
9472       return error_mark_node;
9473     if (VOID_TYPE_P (type))
9474       {
9475         if (complain & tf_error)
9476           {
9477             error ("invalid parameter type %qT", type);
9478             if (in_decl)
9479               error ("in declaration %q+D", in_decl);
9480           }
9481         return error_mark_node;
9482     }
9483     
9484     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9485        top-level qualifiers as required.  */
9486     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9487
9488     /* We do not substitute into default arguments here.  The standard
9489        mandates that they be instantiated only when needed, which is
9490        done in build_over_call.  */
9491     default_arg = TREE_PURPOSE (arg_types);
9492
9493     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9494       {
9495         /* We've instantiated a template before its default arguments
9496            have been parsed.  This can happen for a nested template
9497            class, and is not an error unless we require the default
9498            argument in a call of this function.  */
9499         remaining_arg_types = 
9500           tree_cons (default_arg, type, remaining_arg_types);
9501         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9502                        remaining_arg_types);
9503       }
9504     else
9505       remaining_arg_types = 
9506         hash_tree_cons (default_arg, type, remaining_arg_types);
9507   }
9508         
9509   return remaining_arg_types;
9510 }
9511
9512 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9513    *not* handle the exception-specification for FNTYPE, because the
9514    initial substitution of explicitly provided template parameters
9515    during argument deduction forbids substitution into the
9516    exception-specification:
9517
9518      [temp.deduct]
9519
9520      All references in the function type of the function template to  the
9521      corresponding template parameters are replaced by the specified tem-
9522      plate argument values.  If a substitution in a template parameter or
9523      in  the function type of the function template results in an invalid
9524      type, type deduction fails.  [Note: The equivalent  substitution  in
9525      exception specifications is done only when the function is instanti-
9526      ated, at which point a program is  ill-formed  if  the  substitution
9527      results in an invalid type.]  */
9528
9529 static tree
9530 tsubst_function_type (tree t,
9531                       tree args,
9532                       tsubst_flags_t complain,
9533                       tree in_decl)
9534 {
9535   tree return_type;
9536   tree arg_types;
9537   tree fntype;
9538
9539   /* The TYPE_CONTEXT is not used for function/method types.  */
9540   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9541
9542   /* Substitute the return type.  */
9543   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9544   if (return_type == error_mark_node)
9545     return error_mark_node;
9546   /* The standard does not presently indicate that creation of a
9547      function type with an invalid return type is a deduction failure.
9548      However, that is clearly analogous to creating an array of "void"
9549      or a reference to a reference.  This is core issue #486.  */
9550   if (TREE_CODE (return_type) == ARRAY_TYPE
9551       || TREE_CODE (return_type) == FUNCTION_TYPE)
9552     {
9553       if (complain & tf_error)
9554         {
9555           if (TREE_CODE (return_type) == ARRAY_TYPE)
9556             error ("function returning an array");
9557           else
9558             error ("function returning a function");
9559         }
9560       return error_mark_node;
9561     }
9562
9563   /* Substitute the argument types.  */
9564   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9565                                 complain, in_decl);
9566   if (arg_types == error_mark_node)
9567     return error_mark_node;
9568
9569   /* Construct a new type node and return it.  */
9570   if (TREE_CODE (t) == FUNCTION_TYPE)
9571     fntype = build_function_type (return_type, arg_types);
9572   else
9573     {
9574       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9575       if (! MAYBE_CLASS_TYPE_P (r))
9576         {
9577           /* [temp.deduct]
9578
9579              Type deduction may fail for any of the following
9580              reasons:
9581
9582              -- Attempting to create "pointer to member of T" when T
9583              is not a class type.  */
9584           if (complain & tf_error)
9585             error ("creating pointer to member function of non-class type %qT",
9586                       r);
9587           return error_mark_node;
9588         }
9589
9590       fntype = build_method_type_directly (r, return_type,
9591                                            TREE_CHAIN (arg_types));
9592     }
9593   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9594   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9595
9596   return fntype;
9597 }
9598
9599 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9600    ARGS into that specification, and return the substituted
9601    specification.  If there is no specification, return NULL_TREE.  */
9602
9603 static tree
9604 tsubst_exception_specification (tree fntype,
9605                                 tree args,
9606                                 tsubst_flags_t complain,
9607                                 tree in_decl)
9608 {
9609   tree specs;
9610   tree new_specs;
9611
9612   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9613   new_specs = NULL_TREE;
9614   if (specs)
9615     {
9616       if (! TREE_VALUE (specs))
9617         new_specs = specs;
9618       else
9619         while (specs)
9620           {
9621             tree spec;
9622             int i, len = 1;
9623             tree expanded_specs = NULL_TREE;
9624
9625             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9626               {
9627                 /* Expand the pack expansion type.  */
9628                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9629                                                        args, complain,
9630                                                        in_decl);
9631
9632                 if (expanded_specs == error_mark_node)
9633                   return error_mark_node;
9634                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9635                   len = TREE_VEC_LENGTH (expanded_specs);
9636                 else
9637                   {
9638                     /* We're substituting into a member template, so
9639                        we got a TYPE_PACK_EXPANSION back.  Add that
9640                        expansion and move on.  */
9641                     gcc_assert (TREE_CODE (expanded_specs) 
9642                                 == TYPE_PACK_EXPANSION);
9643                     new_specs = add_exception_specifier (new_specs,
9644                                                          expanded_specs,
9645                                                          complain);
9646                     specs = TREE_CHAIN (specs);
9647                     continue;
9648                   }
9649               }
9650
9651             for (i = 0; i < len; ++i)
9652               {
9653                 if (expanded_specs)
9654                   spec = TREE_VEC_ELT (expanded_specs, i);
9655                 else
9656                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9657                 if (spec == error_mark_node)
9658                   return spec;
9659                 new_specs = add_exception_specifier (new_specs, spec, 
9660                                                      complain);
9661               }
9662
9663             specs = TREE_CHAIN (specs);
9664           }
9665     }
9666   return new_specs;
9667 }
9668
9669 /* Take the tree structure T and replace template parameters used
9670    therein with the argument vector ARGS.  IN_DECL is an associated
9671    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9672    Issue error and warning messages under control of COMPLAIN.  Note
9673    that we must be relatively non-tolerant of extensions here, in
9674    order to preserve conformance; if we allow substitutions that
9675    should not be allowed, we may allow argument deductions that should
9676    not succeed, and therefore report ambiguous overload situations
9677    where there are none.  In theory, we could allow the substitution,
9678    but indicate that it should have failed, and allow our caller to
9679    make sure that the right thing happens, but we don't try to do this
9680    yet.
9681
9682    This function is used for dealing with types, decls and the like;
9683    for expressions, use tsubst_expr or tsubst_copy.  */
9684
9685 tree
9686 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9687 {
9688   tree type, r;
9689
9690   if (t == NULL_TREE || t == error_mark_node
9691       || t == integer_type_node
9692       || t == void_type_node
9693       || t == char_type_node
9694       || t == unknown_type_node
9695       || TREE_CODE (t) == NAMESPACE_DECL)
9696     return t;
9697
9698   if (DECL_P (t))
9699     return tsubst_decl (t, args, complain);
9700
9701   if (args == NULL_TREE)
9702     return t;
9703
9704   if (TREE_CODE (t) == IDENTIFIER_NODE)
9705     type = IDENTIFIER_TYPE_VALUE (t);
9706   else
9707     type = TREE_TYPE (t);
9708
9709   gcc_assert (type != unknown_type_node);
9710
9711   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9712      such as attribute aligned.  */
9713   if (TYPE_P (t)
9714       && TYPE_NAME (t)
9715       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9716     {
9717       tree decl = TYPE_NAME (t);
9718       
9719       if (DECL_CLASS_SCOPE_P (decl)
9720           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9721           && uses_template_parms (DECL_CONTEXT (decl)))
9722         {
9723           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9724           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9725           r = retrieve_specialization (tmpl, gen_args, 0);
9726         }
9727       else if (DECL_FUNCTION_SCOPE_P (decl)
9728                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9729                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9730         r = retrieve_local_specialization (decl);
9731       else
9732         /* The typedef is from a non-template context.  */
9733         return t;
9734
9735       if (r)
9736         {
9737           r = TREE_TYPE (r);
9738           r = cp_build_qualified_type_real
9739             (r, cp_type_quals (t) | cp_type_quals (r),
9740              complain | tf_ignore_bad_quals);
9741           return r;
9742         }
9743       /* Else we must be instantiating the typedef, so fall through.  */
9744     }
9745
9746   if (type
9747       && TREE_CODE (t) != TYPENAME_TYPE
9748       && TREE_CODE (t) != IDENTIFIER_NODE
9749       && TREE_CODE (t) != FUNCTION_TYPE
9750       && TREE_CODE (t) != METHOD_TYPE)
9751     type = tsubst (type, args, complain, in_decl);
9752   if (type == error_mark_node)
9753     return error_mark_node;
9754
9755   switch (TREE_CODE (t))
9756     {
9757     case RECORD_TYPE:
9758     case UNION_TYPE:
9759     case ENUMERAL_TYPE:
9760       return tsubst_aggr_type (t, args, complain, in_decl,
9761                                /*entering_scope=*/0);
9762
9763     case ERROR_MARK:
9764     case IDENTIFIER_NODE:
9765     case VOID_TYPE:
9766     case REAL_TYPE:
9767     case COMPLEX_TYPE:
9768     case VECTOR_TYPE:
9769     case BOOLEAN_TYPE:
9770     case INTEGER_CST:
9771     case REAL_CST:
9772     case STRING_CST:
9773       return t;
9774
9775     case INTEGER_TYPE:
9776       if (t == integer_type_node)
9777         return t;
9778
9779       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9780           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9781         return t;
9782
9783       {
9784         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9785
9786         max = tsubst_expr (omax, args, complain, in_decl,
9787                            /*integral_constant_expression_p=*/false);
9788
9789         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9790            needed.  */
9791         if (TREE_CODE (max) == NOP_EXPR
9792             && TREE_SIDE_EFFECTS (omax)
9793             && !TREE_TYPE (max))
9794           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9795
9796         max = fold_decl_constant_value (max);
9797
9798         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9799            with TREE_SIDE_EFFECTS that indicates this is not an integral
9800            constant expression.  */
9801         if (processing_template_decl
9802             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9803           {
9804             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9805             TREE_SIDE_EFFECTS (max) = 1;
9806           }
9807
9808         if (TREE_CODE (max) != INTEGER_CST
9809             && !at_function_scope_p ()
9810             && !TREE_SIDE_EFFECTS (max)
9811             && !value_dependent_expression_p (max))
9812           {
9813             if (complain & tf_error)
9814               error ("array bound is not an integer constant");
9815             return error_mark_node;
9816           }
9817
9818         /* [temp.deduct]
9819
9820            Type deduction may fail for any of the following
9821            reasons:
9822
9823              Attempting to create an array with a size that is
9824              zero or negative.  */
9825         if (integer_zerop (max) && !(complain & tf_error))
9826           /* We must fail if performing argument deduction (as
9827              indicated by the state of complain), so that
9828              another substitution can be found.  */
9829           return error_mark_node;
9830         else if (TREE_CODE (max) == INTEGER_CST
9831                  && INT_CST_LT (max, integer_zero_node))
9832           {
9833             if (complain & tf_error)
9834               error ("creating array with negative size (%qE)", max);
9835
9836             return error_mark_node;
9837           }
9838
9839         return compute_array_index_type (NULL_TREE, max);
9840       }
9841
9842     case TEMPLATE_TYPE_PARM:
9843     case TEMPLATE_TEMPLATE_PARM:
9844     case BOUND_TEMPLATE_TEMPLATE_PARM:
9845     case TEMPLATE_PARM_INDEX:
9846       {
9847         int idx;
9848         int level;
9849         int levels;
9850         tree arg = NULL_TREE;
9851
9852         r = NULL_TREE;
9853
9854         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9855         template_parm_level_and_index (t, &level, &idx); 
9856
9857         levels = TMPL_ARGS_DEPTH (args);
9858         if (level <= levels)
9859           {
9860             arg = TMPL_ARG (args, level, idx);
9861
9862             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9863               /* See through ARGUMENT_PACK_SELECT arguments. */
9864               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9865           }
9866
9867         if (arg == error_mark_node)
9868           return error_mark_node;
9869         else if (arg != NULL_TREE)
9870           {
9871             if (ARGUMENT_PACK_P (arg))
9872               /* If ARG is an argument pack, we don't actually want to
9873                  perform a substitution here, because substitutions
9874                  for argument packs are only done
9875                  element-by-element. We can get to this point when
9876                  substituting the type of a non-type template
9877                  parameter pack, when that type actually contains
9878                  template parameter packs from an outer template, e.g.,
9879
9880                  template<typename... Types> struct A {
9881                    template<Types... Values> struct B { };
9882                  };  */
9883               return t;
9884
9885             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9886               {
9887                 int quals;
9888                 gcc_assert (TYPE_P (arg));
9889
9890                 /* cv-quals from the template are discarded when
9891                    substituting in a function or reference type.  */
9892                 if (TREE_CODE (arg) == FUNCTION_TYPE
9893                     || TREE_CODE (arg) == METHOD_TYPE
9894                     || TREE_CODE (arg) == REFERENCE_TYPE)
9895                   quals = cp_type_quals (arg);
9896                 else
9897                   quals = cp_type_quals (arg) | cp_type_quals (t);
9898                   
9899                 return cp_build_qualified_type_real
9900                   (arg, quals, complain | tf_ignore_bad_quals);
9901               }
9902             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9903               {
9904                 /* We are processing a type constructed from a
9905                    template template parameter.  */
9906                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9907                                       args, complain, in_decl);
9908                 if (argvec == error_mark_node)
9909                   return error_mark_node;
9910
9911                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9912                    are resolving nested-types in the signature of a
9913                    member function templates.  Otherwise ARG is a
9914                    TEMPLATE_DECL and is the real template to be
9915                    instantiated.  */
9916                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9917                   arg = TYPE_NAME (arg);
9918
9919                 r = lookup_template_class (arg,
9920                                            argvec, in_decl,
9921                                            DECL_CONTEXT (arg),
9922                                             /*entering_scope=*/0,
9923                                            complain);
9924                 return cp_build_qualified_type_real
9925                   (r, TYPE_QUALS (t), complain);
9926               }
9927             else
9928               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9929               return arg;
9930           }
9931
9932         if (level == 1)
9933           /* This can happen during the attempted tsubst'ing in
9934              unify.  This means that we don't yet have any information
9935              about the template parameter in question.  */
9936           return t;
9937
9938         /* If we get here, we must have been looking at a parm for a
9939            more deeply nested template.  Make a new version of this
9940            template parameter, but with a lower level.  */
9941         switch (TREE_CODE (t))
9942           {
9943           case TEMPLATE_TYPE_PARM:
9944           case TEMPLATE_TEMPLATE_PARM:
9945           case BOUND_TEMPLATE_TEMPLATE_PARM:
9946             if (cp_type_quals (t))
9947               {
9948                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9949                 r = cp_build_qualified_type_real
9950                   (r, cp_type_quals (t),
9951                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9952                                ? tf_ignore_bad_quals : 0));
9953               }
9954             else
9955               {
9956                 r = copy_type (t);
9957                 TEMPLATE_TYPE_PARM_INDEX (r)
9958                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9959                                                 r, levels, args, complain);
9960                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9961                 TYPE_MAIN_VARIANT (r) = r;
9962                 TYPE_POINTER_TO (r) = NULL_TREE;
9963                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9964
9965                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9966                   /* We have reduced the level of the template
9967                      template parameter, but not the levels of its
9968                      template parameters, so canonical_type_parameter
9969                      will not be able to find the canonical template
9970                      template parameter for this level. Thus, we
9971                      require structural equality checking to compare
9972                      TEMPLATE_TEMPLATE_PARMs. */
9973                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9974                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9975                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9976                 else
9977                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9978
9979                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9980                   {
9981                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9982                                           complain, in_decl);
9983                     if (argvec == error_mark_node)
9984                       return error_mark_node;
9985
9986                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9987                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
9988                   }
9989               }
9990             break;
9991
9992           case TEMPLATE_PARM_INDEX:
9993             r = reduce_template_parm_level (t, type, levels, args, complain);
9994             break;
9995
9996           default:
9997             gcc_unreachable ();
9998           }
9999
10000         return r;
10001       }
10002
10003     case TREE_LIST:
10004       {
10005         tree purpose, value, chain;
10006
10007         if (t == void_list_node)
10008           return t;
10009
10010         purpose = TREE_PURPOSE (t);
10011         if (purpose)
10012           {
10013             purpose = tsubst (purpose, args, complain, in_decl);
10014             if (purpose == error_mark_node)
10015               return error_mark_node;
10016           }
10017         value = TREE_VALUE (t);
10018         if (value)
10019           {
10020             value = tsubst (value, args, complain, in_decl);
10021             if (value == error_mark_node)
10022               return error_mark_node;
10023           }
10024         chain = TREE_CHAIN (t);
10025         if (chain && chain != void_type_node)
10026           {
10027             chain = tsubst (chain, args, complain, in_decl);
10028             if (chain == error_mark_node)
10029               return error_mark_node;
10030           }
10031         if (purpose == TREE_PURPOSE (t)
10032             && value == TREE_VALUE (t)
10033             && chain == TREE_CHAIN (t))
10034           return t;
10035         return hash_tree_cons (purpose, value, chain);
10036       }
10037
10038     case TREE_BINFO:
10039       /* We should never be tsubsting a binfo.  */
10040       gcc_unreachable ();
10041
10042     case TREE_VEC:
10043       /* A vector of template arguments.  */
10044       gcc_assert (!type);
10045       return tsubst_template_args (t, args, complain, in_decl);
10046
10047     case POINTER_TYPE:
10048     case REFERENCE_TYPE:
10049       {
10050         enum tree_code code;
10051
10052         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10053           return t;
10054
10055         code = TREE_CODE (t);
10056
10057
10058         /* [temp.deduct]
10059
10060            Type deduction may fail for any of the following
10061            reasons:
10062
10063            -- Attempting to create a pointer to reference type.
10064            -- Attempting to create a reference to a reference type or
10065               a reference to void.
10066
10067           Core issue 106 says that creating a reference to a reference
10068           during instantiation is no longer a cause for failure. We
10069           only enforce this check in strict C++98 mode.  */
10070         if ((TREE_CODE (type) == REFERENCE_TYPE
10071              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10072             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10073           {
10074             static location_t last_loc;
10075
10076             /* We keep track of the last time we issued this error
10077                message to avoid spewing a ton of messages during a
10078                single bad template instantiation.  */
10079             if (complain & tf_error
10080                 && last_loc != input_location)
10081               {
10082                 if (TREE_CODE (type) == VOID_TYPE)
10083                   error ("forming reference to void");
10084                else if (code == POINTER_TYPE)
10085                  error ("forming pointer to reference type %qT", type);
10086                else
10087                   error ("forming reference to reference type %qT", type);
10088                 last_loc = input_location;
10089               }
10090
10091             return error_mark_node;
10092           }
10093         else if (code == POINTER_TYPE)
10094           {
10095             r = build_pointer_type (type);
10096             if (TREE_CODE (type) == METHOD_TYPE)
10097               r = build_ptrmemfunc_type (r);
10098           }
10099         else if (TREE_CODE (type) == REFERENCE_TYPE)
10100           /* In C++0x, during template argument substitution, when there is an
10101              attempt to create a reference to a reference type, reference
10102              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10103
10104              "If a template-argument for a template-parameter T names a type
10105              that is a reference to a type A, an attempt to create the type
10106              'lvalue reference to cv T' creates the type 'lvalue reference to
10107              A,' while an attempt to create the type type rvalue reference to
10108              cv T' creates the type T"
10109           */
10110           r = cp_build_reference_type
10111               (TREE_TYPE (type),
10112                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10113         else
10114           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10115         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10116
10117         if (r != error_mark_node)
10118           /* Will this ever be needed for TYPE_..._TO values?  */
10119           layout_type (r);
10120
10121         return r;
10122       }
10123     case OFFSET_TYPE:
10124       {
10125         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10126         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10127           {
10128             /* [temp.deduct]
10129
10130                Type deduction may fail for any of the following
10131                reasons:
10132
10133                -- Attempting to create "pointer to member of T" when T
10134                   is not a class type.  */
10135             if (complain & tf_error)
10136               error ("creating pointer to member of non-class type %qT", r);
10137             return error_mark_node;
10138           }
10139         if (TREE_CODE (type) == REFERENCE_TYPE)
10140           {
10141             if (complain & tf_error)
10142               error ("creating pointer to member reference type %qT", type);
10143             return error_mark_node;
10144           }
10145         if (TREE_CODE (type) == VOID_TYPE)
10146           {
10147             if (complain & tf_error)
10148               error ("creating pointer to member of type void");
10149             return error_mark_node;
10150           }
10151         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10152         if (TREE_CODE (type) == FUNCTION_TYPE)
10153           {
10154             /* The type of the implicit object parameter gets its
10155                cv-qualifiers from the FUNCTION_TYPE. */
10156             tree memptr;
10157             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10158             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10159             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10160                                                  complain);
10161           }
10162         else
10163           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10164                                                TYPE_QUALS (t),
10165                                                complain);
10166       }
10167     case FUNCTION_TYPE:
10168     case METHOD_TYPE:
10169       {
10170         tree fntype;
10171         tree specs;
10172         fntype = tsubst_function_type (t, args, complain, in_decl);
10173         if (fntype == error_mark_node)
10174           return error_mark_node;
10175
10176         /* Substitute the exception specification.  */
10177         specs = tsubst_exception_specification (t, args, complain,
10178                                                 in_decl);
10179         if (specs == error_mark_node)
10180           return error_mark_node;
10181         if (specs)
10182           fntype = build_exception_variant (fntype, specs);
10183         return fntype;
10184       }
10185     case ARRAY_TYPE:
10186       {
10187         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10188         if (domain == error_mark_node)
10189           return error_mark_node;
10190
10191         /* As an optimization, we avoid regenerating the array type if
10192            it will obviously be the same as T.  */
10193         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10194           return t;
10195
10196         /* These checks should match the ones in grokdeclarator.
10197
10198            [temp.deduct]
10199
10200            The deduction may fail for any of the following reasons:
10201
10202            -- Attempting to create an array with an element type that
10203               is void, a function type, or a reference type, or [DR337]
10204               an abstract class type.  */
10205         if (TREE_CODE (type) == VOID_TYPE
10206             || TREE_CODE (type) == FUNCTION_TYPE
10207             || TREE_CODE (type) == REFERENCE_TYPE)
10208           {
10209             if (complain & tf_error)
10210               error ("creating array of %qT", type);
10211             return error_mark_node;
10212           }
10213         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10214           {
10215             if (complain & tf_error)
10216               error ("creating array of %qT, which is an abstract class type",
10217                      type);
10218             return error_mark_node;
10219           }
10220
10221         r = build_cplus_array_type (type, domain);
10222
10223         if (TYPE_USER_ALIGN (t))
10224           {
10225             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10226             TYPE_USER_ALIGN (r) = 1;
10227           }
10228
10229         return r;
10230       }
10231
10232     case PLUS_EXPR:
10233     case MINUS_EXPR:
10234       {
10235         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10236         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10237
10238         if (e1 == error_mark_node || e2 == error_mark_node)
10239           return error_mark_node;
10240
10241         return fold_build2_loc (input_location,
10242                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10243       }
10244
10245     case NEGATE_EXPR:
10246     case NOP_EXPR:
10247       {
10248         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10249         if (e == error_mark_node)
10250           return error_mark_node;
10251
10252         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10253       }
10254
10255     case TYPENAME_TYPE:
10256       {
10257         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10258                                      in_decl, /*entering_scope=*/1);
10259         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10260                               complain, in_decl);
10261
10262         if (ctx == error_mark_node || f == error_mark_node)
10263           return error_mark_node;
10264
10265         if (!MAYBE_CLASS_TYPE_P (ctx))
10266           {
10267             if (complain & tf_error)
10268               error ("%qT is not a class, struct, or union type", ctx);
10269             return error_mark_node;
10270           }
10271         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10272           {
10273             /* Normally, make_typename_type does not require that the CTX
10274                have complete type in order to allow things like:
10275
10276                  template <class T> struct S { typename S<T>::X Y; };
10277
10278                But, such constructs have already been resolved by this
10279                point, so here CTX really should have complete type, unless
10280                it's a partial instantiation.  */
10281             if (!(complain & tf_no_class_instantiations))
10282               ctx = complete_type (ctx);
10283             if (!COMPLETE_TYPE_P (ctx))
10284               {
10285                 if (complain & tf_error)
10286                   cxx_incomplete_type_error (NULL_TREE, ctx);
10287                 return error_mark_node;
10288               }
10289           }
10290
10291         f = make_typename_type (ctx, f, typename_type,
10292                                 (complain & tf_error) | tf_keep_type_decl);
10293         if (f == error_mark_node)
10294           return f;
10295         if (TREE_CODE (f) == TYPE_DECL)
10296           {
10297             complain |= tf_ignore_bad_quals;
10298             f = TREE_TYPE (f);
10299           }
10300
10301         if (TREE_CODE (f) != TYPENAME_TYPE)
10302           {
10303             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10304               error ("%qT resolves to %qT, which is not an enumeration type",
10305                      t, f);
10306             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10307               error ("%qT resolves to %qT, which is is not a class type",
10308                      t, f);
10309           }
10310
10311         return cp_build_qualified_type_real
10312           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10313       }
10314
10315     case UNBOUND_CLASS_TEMPLATE:
10316       {
10317         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10318                                      in_decl, /*entering_scope=*/1);
10319         tree name = TYPE_IDENTIFIER (t);
10320         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10321
10322         if (ctx == error_mark_node || name == error_mark_node)
10323           return error_mark_node;
10324
10325         if (parm_list)
10326           parm_list = tsubst_template_parms (parm_list, args, complain);
10327         return make_unbound_class_template (ctx, name, parm_list, complain);
10328       }
10329
10330     case INDIRECT_REF:
10331     case ADDR_EXPR:
10332     case CALL_EXPR:
10333       gcc_unreachable ();
10334
10335     case ARRAY_REF:
10336       {
10337         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10338         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10339                                /*integral_constant_expression_p=*/false);
10340         if (e1 == error_mark_node || e2 == error_mark_node)
10341           return error_mark_node;
10342
10343         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10344       }
10345
10346     case SCOPE_REF:
10347       {
10348         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10349         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10350         if (e1 == error_mark_node || e2 == error_mark_node)
10351           return error_mark_node;
10352
10353         return build_qualified_name (/*type=*/NULL_TREE,
10354                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10355       }
10356
10357     case TYPEOF_TYPE:
10358       {
10359         tree type;
10360
10361         ++cp_unevaluated_operand;
10362         ++c_inhibit_evaluation_warnings;
10363
10364         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10365                             complain, in_decl,
10366                             /*integral_constant_expression_p=*/false);
10367
10368         --cp_unevaluated_operand;
10369         --c_inhibit_evaluation_warnings;
10370
10371         type = finish_typeof (type);
10372         return cp_build_qualified_type_real (type,
10373                                              cp_type_quals (t)
10374                                              | cp_type_quals (type),
10375                                              complain);
10376       }
10377
10378     case DECLTYPE_TYPE:
10379       {
10380         tree type;
10381
10382         ++cp_unevaluated_operand;
10383         ++c_inhibit_evaluation_warnings;
10384
10385         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10386                             complain, in_decl,
10387                             /*integral_constant_expression_p=*/false);
10388
10389         --cp_unevaluated_operand;
10390         --c_inhibit_evaluation_warnings;
10391
10392         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10393           type = lambda_capture_field_type (type);
10394         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10395           type = lambda_return_type (type);
10396         else
10397           type = finish_decltype_type
10398             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10399         return cp_build_qualified_type_real (type,
10400                                              cp_type_quals (t)
10401                                              | cp_type_quals (type),
10402                                              complain);
10403       }
10404
10405     case TYPE_ARGUMENT_PACK:
10406     case NONTYPE_ARGUMENT_PACK:
10407       {
10408         tree r = TYPE_P (t)
10409           ? cxx_make_type (TREE_CODE (t))
10410           : make_node (TREE_CODE (t));
10411         tree packed_out = 
10412           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10413                                 args,
10414                                 complain,
10415                                 in_decl);
10416         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10417
10418         /* For template nontype argument packs, also substitute into
10419            the type.  */
10420         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10421           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10422
10423         return r;
10424       }
10425       break;
10426
10427     default:
10428       sorry ("use of %qs in template",
10429              tree_code_name [(int) TREE_CODE (t)]);
10430       return error_mark_node;
10431     }
10432 }
10433
10434 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10435    type of the expression on the left-hand side of the "." or "->"
10436    operator.  */
10437
10438 static tree
10439 tsubst_baselink (tree baselink, tree object_type,
10440                  tree args, tsubst_flags_t complain, tree in_decl)
10441 {
10442     tree name;
10443     tree qualifying_scope;
10444     tree fns;
10445     tree optype;
10446     tree template_args = 0;
10447     bool template_id_p = false;
10448
10449     /* A baselink indicates a function from a base class.  Both the
10450        BASELINK_ACCESS_BINFO and the base class referenced may
10451        indicate bases of the template class, rather than the
10452        instantiated class.  In addition, lookups that were not
10453        ambiguous before may be ambiguous now.  Therefore, we perform
10454        the lookup again.  */
10455     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10456     qualifying_scope = tsubst (qualifying_scope, args,
10457                                complain, in_decl);
10458     fns = BASELINK_FUNCTIONS (baselink);
10459     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10460     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10461       {
10462         template_id_p = true;
10463         template_args = TREE_OPERAND (fns, 1);
10464         fns = TREE_OPERAND (fns, 0);
10465         if (template_args)
10466           template_args = tsubst_template_args (template_args, args,
10467                                                 complain, in_decl);
10468       }
10469     name = DECL_NAME (get_first_fn (fns));
10470     if (IDENTIFIER_TYPENAME_P (name))
10471       name = mangle_conv_op_name_for_type (optype);
10472     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10473
10474     /* If lookup found a single function, mark it as used at this
10475        point.  (If it lookup found multiple functions the one selected
10476        later by overload resolution will be marked as used at that
10477        point.)  */
10478     if (BASELINK_P (baselink))
10479       fns = BASELINK_FUNCTIONS (baselink);
10480     if (!template_id_p && !really_overloaded_fn (fns))
10481       mark_used (OVL_CURRENT (fns));
10482
10483     /* Add back the template arguments, if present.  */
10484     if (BASELINK_P (baselink) && template_id_p)
10485       BASELINK_FUNCTIONS (baselink)
10486         = build_nt (TEMPLATE_ID_EXPR,
10487                     BASELINK_FUNCTIONS (baselink),
10488                     template_args);
10489     /* Update the conversion operator type.  */
10490     BASELINK_OPTYPE (baselink) = optype;
10491
10492     if (!object_type)
10493       object_type = current_class_type;
10494     return adjust_result_of_qualified_name_lookup (baselink,
10495                                                    qualifying_scope,
10496                                                    object_type);
10497 }
10498
10499 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10500    true if the qualified-id will be a postfix-expression in-and-of
10501    itself; false if more of the postfix-expression follows the
10502    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10503    of "&".  */
10504
10505 static tree
10506 tsubst_qualified_id (tree qualified_id, tree args,
10507                      tsubst_flags_t complain, tree in_decl,
10508                      bool done, bool address_p)
10509 {
10510   tree expr;
10511   tree scope;
10512   tree name;
10513   bool is_template;
10514   tree template_args;
10515
10516   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10517
10518   /* Figure out what name to look up.  */
10519   name = TREE_OPERAND (qualified_id, 1);
10520   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10521     {
10522       is_template = true;
10523       template_args = TREE_OPERAND (name, 1);
10524       if (template_args)
10525         template_args = tsubst_template_args (template_args, args,
10526                                               complain, in_decl);
10527       name = TREE_OPERAND (name, 0);
10528     }
10529   else
10530     {
10531       is_template = false;
10532       template_args = NULL_TREE;
10533     }
10534
10535   /* Substitute into the qualifying scope.  When there are no ARGS, we
10536      are just trying to simplify a non-dependent expression.  In that
10537      case the qualifying scope may be dependent, and, in any case,
10538      substituting will not help.  */
10539   scope = TREE_OPERAND (qualified_id, 0);
10540   if (args)
10541     {
10542       scope = tsubst (scope, args, complain, in_decl);
10543       expr = tsubst_copy (name, args, complain, in_decl);
10544     }
10545   else
10546     expr = name;
10547
10548   if (dependent_type_p (scope))
10549     {
10550       tree type = NULL_TREE;
10551       if (DECL_P (expr) && !dependent_scope_p (scope))
10552         type = TREE_TYPE (expr);
10553       return build_qualified_name (type, scope, expr,
10554                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10555     }
10556
10557   if (!BASELINK_P (name) && !DECL_P (expr))
10558     {
10559       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10560         {
10561           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10562           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10563             {
10564               error ("qualifying type %qT does not match destructor name ~%qT",
10565                      scope, TREE_OPERAND (expr, 0));
10566               expr = error_mark_node;
10567             }
10568           else
10569             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10570                                           /*is_type_p=*/0, false);
10571         }
10572       else
10573         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10574       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10575                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10576         {
10577           if (complain & tf_error)
10578             {
10579               error ("dependent-name %qE is parsed as a non-type, but "
10580                      "instantiation yields a type", qualified_id);
10581               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10582             }
10583           return error_mark_node;
10584         }
10585     }
10586
10587   if (DECL_P (expr))
10588     {
10589       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10590                                            scope);
10591       /* Remember that there was a reference to this entity.  */
10592       mark_used (expr);
10593     }
10594
10595   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10596     {
10597       if (complain & tf_error)
10598         qualified_name_lookup_error (scope,
10599                                      TREE_OPERAND (qualified_id, 1),
10600                                      expr, input_location);
10601       return error_mark_node;
10602     }
10603
10604   if (is_template)
10605     expr = lookup_template_function (expr, template_args);
10606
10607   if (expr == error_mark_node && complain & tf_error)
10608     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10609                                  expr, input_location);
10610   else if (TYPE_P (scope))
10611     {
10612       expr = (adjust_result_of_qualified_name_lookup
10613               (expr, scope, current_class_type));
10614       expr = (finish_qualified_id_expr
10615               (scope, expr, done, address_p,
10616                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10617                /*template_arg_p=*/false));
10618     }
10619
10620   /* Expressions do not generally have reference type.  */
10621   if (TREE_CODE (expr) != SCOPE_REF
10622       /* However, if we're about to form a pointer-to-member, we just
10623          want the referenced member referenced.  */
10624       && TREE_CODE (expr) != OFFSET_REF)
10625     expr = convert_from_reference (expr);
10626
10627   return expr;
10628 }
10629
10630 /* Like tsubst, but deals with expressions.  This function just replaces
10631    template parms; to finish processing the resultant expression, use
10632    tsubst_expr.  */
10633
10634 static tree
10635 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10636 {
10637   enum tree_code code;
10638   tree r;
10639
10640   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10641     return t;
10642
10643   code = TREE_CODE (t);
10644
10645   switch (code)
10646     {
10647     case PARM_DECL:
10648       r = retrieve_local_specialization (t);
10649
10650       if (r == NULL)
10651         {
10652           tree c;
10653           /* This can happen for a parameter name used later in a function
10654              declaration (such as in a late-specified return type).  Just
10655              make a dummy decl, since it's only used for its type.  */
10656           gcc_assert (cp_unevaluated_operand != 0);
10657           /* We copy T because want to tsubst the PARM_DECL only,
10658              not the following PARM_DECLs that are chained to T.  */
10659           c = copy_node (t);
10660           r = tsubst_decl (c, args, complain);
10661           /* Give it the template pattern as its context; its true context
10662              hasn't been instantiated yet and this is good enough for
10663              mangling.  */
10664           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10665         }
10666       
10667       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10668         r = ARGUMENT_PACK_SELECT_ARG (r);
10669       mark_used (r);
10670       return r;
10671
10672     case CONST_DECL:
10673       {
10674         tree enum_type;
10675         tree v;
10676
10677         if (DECL_TEMPLATE_PARM_P (t))
10678           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10679         /* There is no need to substitute into namespace-scope
10680            enumerators.  */
10681         if (DECL_NAMESPACE_SCOPE_P (t))
10682           return t;
10683         /* If ARGS is NULL, then T is known to be non-dependent.  */
10684         if (args == NULL_TREE)
10685           return integral_constant_value (t);
10686
10687         /* Unfortunately, we cannot just call lookup_name here.
10688            Consider:
10689
10690              template <int I> int f() {
10691              enum E { a = I };
10692              struct S { void g() { E e = a; } };
10693              };
10694
10695            When we instantiate f<7>::S::g(), say, lookup_name is not
10696            clever enough to find f<7>::a.  */
10697         enum_type
10698           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10699                               /*entering_scope=*/0);
10700
10701         for (v = TYPE_VALUES (enum_type);
10702              v != NULL_TREE;
10703              v = TREE_CHAIN (v))
10704           if (TREE_PURPOSE (v) == DECL_NAME (t))
10705             return TREE_VALUE (v);
10706
10707           /* We didn't find the name.  That should never happen; if
10708              name-lookup found it during preliminary parsing, we
10709              should find it again here during instantiation.  */
10710         gcc_unreachable ();
10711       }
10712       return t;
10713
10714     case FIELD_DECL:
10715       if (DECL_CONTEXT (t))
10716         {
10717           tree ctx;
10718
10719           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10720                                   /*entering_scope=*/1);
10721           if (ctx != DECL_CONTEXT (t))
10722             {
10723               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10724               if (!r)
10725                 {
10726                   if (complain & tf_error)
10727                     error ("using invalid field %qD", t);
10728                   return error_mark_node;
10729                 }
10730               return r;
10731             }
10732         }
10733
10734       return t;
10735
10736     case VAR_DECL:
10737     case FUNCTION_DECL:
10738       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10739           || local_variable_p (t))
10740         t = tsubst (t, args, complain, in_decl);
10741       mark_used (t);
10742       return t;
10743
10744     case BASELINK:
10745       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10746
10747     case TEMPLATE_DECL:
10748       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10749         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10750                        args, complain, in_decl);
10751       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10752         return tsubst (t, args, complain, in_decl);
10753       else if (DECL_CLASS_SCOPE_P (t)
10754                && uses_template_parms (DECL_CONTEXT (t)))
10755         {
10756           /* Template template argument like the following example need
10757              special treatment:
10758
10759                template <template <class> class TT> struct C {};
10760                template <class T> struct D {
10761                  template <class U> struct E {};
10762                  C<E> c;                                // #1
10763                };
10764                D<int> d;                                // #2
10765
10766              We are processing the template argument `E' in #1 for
10767              the template instantiation #2.  Originally, `E' is a
10768              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10769              have to substitute this with one having context `D<int>'.  */
10770
10771           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10772           return lookup_field (context, DECL_NAME(t), 0, false);
10773         }
10774       else
10775         /* Ordinary template template argument.  */
10776         return t;
10777
10778     case CAST_EXPR:
10779     case REINTERPRET_CAST_EXPR:
10780     case CONST_CAST_EXPR:
10781     case STATIC_CAST_EXPR:
10782     case DYNAMIC_CAST_EXPR:
10783     case NOP_EXPR:
10784       return build1
10785         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10786          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10787
10788     case SIZEOF_EXPR:
10789       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10790         {
10791           /* We only want to compute the number of arguments.  */
10792           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10793                                                 complain, in_decl);
10794           int len = 0;
10795
10796           if (TREE_CODE (expanded) == TREE_VEC)
10797             len = TREE_VEC_LENGTH (expanded);
10798
10799           if (expanded == error_mark_node)
10800             return error_mark_node;
10801           else if (PACK_EXPANSION_P (expanded)
10802                    || (TREE_CODE (expanded) == TREE_VEC
10803                        && len > 0
10804                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10805             {
10806               if (TREE_CODE (expanded) == TREE_VEC)
10807                 expanded = TREE_VEC_ELT (expanded, len - 1);
10808
10809               if (TYPE_P (expanded))
10810                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10811                                                    complain & tf_error);
10812               else
10813                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10814                                                    complain & tf_error);
10815             }
10816           else
10817             return build_int_cst (size_type_node, len);
10818         }
10819       /* Fall through */
10820
10821     case INDIRECT_REF:
10822     case NEGATE_EXPR:
10823     case TRUTH_NOT_EXPR:
10824     case BIT_NOT_EXPR:
10825     case ADDR_EXPR:
10826     case UNARY_PLUS_EXPR:      /* Unary + */
10827     case ALIGNOF_EXPR:
10828     case ARROW_EXPR:
10829     case THROW_EXPR:
10830     case TYPEID_EXPR:
10831     case REALPART_EXPR:
10832     case IMAGPART_EXPR:
10833       return build1
10834         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10835          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10836
10837     case COMPONENT_REF:
10838       {
10839         tree object;
10840         tree name;
10841
10842         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10843         name = TREE_OPERAND (t, 1);
10844         if (TREE_CODE (name) == BIT_NOT_EXPR)
10845           {
10846             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10847                                 complain, in_decl);
10848             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10849           }
10850         else if (TREE_CODE (name) == SCOPE_REF
10851                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10852           {
10853             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10854                                      complain, in_decl);
10855             name = TREE_OPERAND (name, 1);
10856             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10857                                 complain, in_decl);
10858             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10859             name = build_qualified_name (/*type=*/NULL_TREE,
10860                                          base, name,
10861                                          /*template_p=*/false);
10862           }
10863         else if (TREE_CODE (name) == BASELINK)
10864           name = tsubst_baselink (name,
10865                                   non_reference (TREE_TYPE (object)),
10866                                   args, complain,
10867                                   in_decl);
10868         else
10869           name = tsubst_copy (name, args, complain, in_decl);
10870         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10871       }
10872
10873     case PLUS_EXPR:
10874     case MINUS_EXPR:
10875     case MULT_EXPR:
10876     case TRUNC_DIV_EXPR:
10877     case CEIL_DIV_EXPR:
10878     case FLOOR_DIV_EXPR:
10879     case ROUND_DIV_EXPR:
10880     case EXACT_DIV_EXPR:
10881     case BIT_AND_EXPR:
10882     case BIT_IOR_EXPR:
10883     case BIT_XOR_EXPR:
10884     case TRUNC_MOD_EXPR:
10885     case FLOOR_MOD_EXPR:
10886     case TRUTH_ANDIF_EXPR:
10887     case TRUTH_ORIF_EXPR:
10888     case TRUTH_AND_EXPR:
10889     case TRUTH_OR_EXPR:
10890     case RSHIFT_EXPR:
10891     case LSHIFT_EXPR:
10892     case RROTATE_EXPR:
10893     case LROTATE_EXPR:
10894     case EQ_EXPR:
10895     case NE_EXPR:
10896     case MAX_EXPR:
10897     case MIN_EXPR:
10898     case LE_EXPR:
10899     case GE_EXPR:
10900     case LT_EXPR:
10901     case GT_EXPR:
10902     case COMPOUND_EXPR:
10903     case DOTSTAR_EXPR:
10904     case MEMBER_REF:
10905     case PREDECREMENT_EXPR:
10906     case PREINCREMENT_EXPR:
10907     case POSTDECREMENT_EXPR:
10908     case POSTINCREMENT_EXPR:
10909       return build_nt
10910         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10911          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10912
10913     case SCOPE_REF:
10914       return build_qualified_name (/*type=*/NULL_TREE,
10915                                    tsubst_copy (TREE_OPERAND (t, 0),
10916                                                 args, complain, in_decl),
10917                                    tsubst_copy (TREE_OPERAND (t, 1),
10918                                                 args, complain, in_decl),
10919                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10920
10921     case ARRAY_REF:
10922       return build_nt
10923         (ARRAY_REF,
10924          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10925          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10926          NULL_TREE, NULL_TREE);
10927
10928     case CALL_EXPR:
10929       {
10930         int n = VL_EXP_OPERAND_LENGTH (t);
10931         tree result = build_vl_exp (CALL_EXPR, n);
10932         int i;
10933         for (i = 0; i < n; i++)
10934           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10935                                              complain, in_decl);
10936         return result;
10937       }
10938
10939     case COND_EXPR:
10940     case MODOP_EXPR:
10941     case PSEUDO_DTOR_EXPR:
10942       {
10943         r = build_nt
10944           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10945            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10946            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10947         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10948         return r;
10949       }
10950
10951     case NEW_EXPR:
10952       {
10953         r = build_nt
10954         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10955          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10956          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10957         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10958         return r;
10959       }
10960
10961     case DELETE_EXPR:
10962       {
10963         r = build_nt
10964         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10965          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10966         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10967         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10968         return r;
10969       }
10970
10971     case TEMPLATE_ID_EXPR:
10972       {
10973         /* Substituted template arguments */
10974         tree fn = TREE_OPERAND (t, 0);
10975         tree targs = TREE_OPERAND (t, 1);
10976
10977         fn = tsubst_copy (fn, args, complain, in_decl);
10978         if (targs)
10979           targs = tsubst_template_args (targs, args, complain, in_decl);
10980
10981         return lookup_template_function (fn, targs);
10982       }
10983
10984     case TREE_LIST:
10985       {
10986         tree purpose, value, chain;
10987
10988         if (t == void_list_node)
10989           return t;
10990
10991         purpose = TREE_PURPOSE (t);
10992         if (purpose)
10993           purpose = tsubst_copy (purpose, args, complain, in_decl);
10994         value = TREE_VALUE (t);
10995         if (value)
10996           value = tsubst_copy (value, args, complain, in_decl);
10997         chain = TREE_CHAIN (t);
10998         if (chain && chain != void_type_node)
10999           chain = tsubst_copy (chain, args, complain, in_decl);
11000         if (purpose == TREE_PURPOSE (t)
11001             && value == TREE_VALUE (t)
11002             && chain == TREE_CHAIN (t))
11003           return t;
11004         return tree_cons (purpose, value, chain);
11005       }
11006
11007     case RECORD_TYPE:
11008     case UNION_TYPE:
11009     case ENUMERAL_TYPE:
11010     case INTEGER_TYPE:
11011     case TEMPLATE_TYPE_PARM:
11012     case TEMPLATE_TEMPLATE_PARM:
11013     case BOUND_TEMPLATE_TEMPLATE_PARM:
11014     case TEMPLATE_PARM_INDEX:
11015     case POINTER_TYPE:
11016     case REFERENCE_TYPE:
11017     case OFFSET_TYPE:
11018     case FUNCTION_TYPE:
11019     case METHOD_TYPE:
11020     case ARRAY_TYPE:
11021     case TYPENAME_TYPE:
11022     case UNBOUND_CLASS_TEMPLATE:
11023     case TYPEOF_TYPE:
11024     case DECLTYPE_TYPE:
11025     case TYPE_DECL:
11026       return tsubst (t, args, complain, in_decl);
11027
11028     case IDENTIFIER_NODE:
11029       if (IDENTIFIER_TYPENAME_P (t))
11030         {
11031           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11032           return mangle_conv_op_name_for_type (new_type);
11033         }
11034       else
11035         return t;
11036
11037     case CONSTRUCTOR:
11038       /* This is handled by tsubst_copy_and_build.  */
11039       gcc_unreachable ();
11040
11041     case VA_ARG_EXPR:
11042       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11043                                           in_decl),
11044                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11045
11046     case CLEANUP_POINT_EXPR:
11047       /* We shouldn't have built any of these during initial template
11048          generation.  Instead, they should be built during instantiation
11049          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11050       gcc_unreachable ();
11051
11052     case OFFSET_REF:
11053       mark_used (TREE_OPERAND (t, 1));
11054       return t;
11055
11056     case EXPR_PACK_EXPANSION:
11057       error ("invalid use of pack expansion expression");
11058       return error_mark_node;
11059
11060     case NONTYPE_ARGUMENT_PACK:
11061       error ("use %<...%> to expand argument pack");
11062       return error_mark_node;
11063
11064     default:
11065       return t;
11066     }
11067 }
11068
11069 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11070
11071 static tree
11072 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11073                     tree in_decl)
11074 {
11075   tree new_clauses = NULL, nc, oc;
11076
11077   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11078     {
11079       nc = copy_node (oc);
11080       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11081       new_clauses = nc;
11082
11083       switch (OMP_CLAUSE_CODE (nc))
11084         {
11085         case OMP_CLAUSE_LASTPRIVATE:
11086           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11087             {
11088               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11089               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11090                            in_decl, /*integral_constant_expression_p=*/false);
11091               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11092                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11093             }
11094           /* FALLTHRU */
11095         case OMP_CLAUSE_PRIVATE:
11096         case OMP_CLAUSE_SHARED:
11097         case OMP_CLAUSE_FIRSTPRIVATE:
11098         case OMP_CLAUSE_REDUCTION:
11099         case OMP_CLAUSE_COPYIN:
11100         case OMP_CLAUSE_COPYPRIVATE:
11101         case OMP_CLAUSE_IF:
11102         case OMP_CLAUSE_NUM_THREADS:
11103         case OMP_CLAUSE_SCHEDULE:
11104         case OMP_CLAUSE_COLLAPSE:
11105           OMP_CLAUSE_OPERAND (nc, 0)
11106             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11107                            in_decl, /*integral_constant_expression_p=*/false);
11108           break;
11109         case OMP_CLAUSE_NOWAIT:
11110         case OMP_CLAUSE_ORDERED:
11111         case OMP_CLAUSE_DEFAULT:
11112         case OMP_CLAUSE_UNTIED:
11113           break;
11114         default:
11115           gcc_unreachable ();
11116         }
11117     }
11118
11119   return finish_omp_clauses (nreverse (new_clauses));
11120 }
11121
11122 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11123
11124 static tree
11125 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11126                           tree in_decl)
11127 {
11128 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11129
11130   tree purpose, value, chain;
11131
11132   if (t == NULL)
11133     return t;
11134
11135   if (TREE_CODE (t) != TREE_LIST)
11136     return tsubst_copy_and_build (t, args, complain, in_decl,
11137                                   /*function_p=*/false,
11138                                   /*integral_constant_expression_p=*/false);
11139
11140   if (t == void_list_node)
11141     return t;
11142
11143   purpose = TREE_PURPOSE (t);
11144   if (purpose)
11145     purpose = RECUR (purpose);
11146   value = TREE_VALUE (t);
11147   if (value && TREE_CODE (value) != LABEL_DECL)
11148     value = RECUR (value);
11149   chain = TREE_CHAIN (t);
11150   if (chain && chain != void_type_node)
11151     chain = RECUR (chain);
11152   return tree_cons (purpose, value, chain);
11153 #undef RECUR
11154 }
11155
11156 /* Substitute one OMP_FOR iterator.  */
11157
11158 static void
11159 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11160                          tree condv, tree incrv, tree *clauses,
11161                          tree args, tsubst_flags_t complain, tree in_decl,
11162                          bool integral_constant_expression_p)
11163 {
11164 #define RECUR(NODE)                             \
11165   tsubst_expr ((NODE), args, complain, in_decl, \
11166                integral_constant_expression_p)
11167   tree decl, init, cond, incr, auto_node;
11168
11169   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11170   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11171   decl = RECUR (TREE_OPERAND (init, 0));
11172   init = TREE_OPERAND (init, 1);
11173   auto_node = type_uses_auto (TREE_TYPE (decl));
11174   if (auto_node && init)
11175     {
11176       tree init_expr = init;
11177       if (TREE_CODE (init_expr) == DECL_EXPR)
11178         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11179       init_expr = RECUR (init_expr);
11180       TREE_TYPE (decl)
11181         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11182     }
11183   gcc_assert (!type_dependent_expression_p (decl));
11184
11185   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11186     {
11187       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11188       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11189       if (TREE_CODE (incr) == MODIFY_EXPR)
11190         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11191                                     RECUR (TREE_OPERAND (incr, 1)),
11192                                     complain);
11193       else
11194         incr = RECUR (incr);
11195       TREE_VEC_ELT (declv, i) = decl;
11196       TREE_VEC_ELT (initv, i) = init;
11197       TREE_VEC_ELT (condv, i) = cond;
11198       TREE_VEC_ELT (incrv, i) = incr;
11199       return;
11200     }
11201
11202   if (init && TREE_CODE (init) != DECL_EXPR)
11203     {
11204       tree c;
11205       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11206         {
11207           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11208                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11209               && OMP_CLAUSE_DECL (c) == decl)
11210             break;
11211           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11212                    && OMP_CLAUSE_DECL (c) == decl)
11213             error ("iteration variable %qD should not be firstprivate", decl);
11214           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11215                    && OMP_CLAUSE_DECL (c) == decl)
11216             error ("iteration variable %qD should not be reduction", decl);
11217         }
11218       if (c == NULL)
11219         {
11220           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11221           OMP_CLAUSE_DECL (c) = decl;
11222           c = finish_omp_clauses (c);
11223           if (c)
11224             {
11225               OMP_CLAUSE_CHAIN (c) = *clauses;
11226               *clauses = c;
11227             }
11228         }
11229     }
11230   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11231   if (COMPARISON_CLASS_P (cond))
11232     cond = build2 (TREE_CODE (cond), boolean_type_node,
11233                    RECUR (TREE_OPERAND (cond, 0)),
11234                    RECUR (TREE_OPERAND (cond, 1)));
11235   else
11236     cond = RECUR (cond);
11237   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11238   switch (TREE_CODE (incr))
11239     {
11240     case PREINCREMENT_EXPR:
11241     case PREDECREMENT_EXPR:
11242     case POSTINCREMENT_EXPR:
11243     case POSTDECREMENT_EXPR:
11244       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11245                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11246       break;
11247     case MODIFY_EXPR:
11248       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11249           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11250         {
11251           tree rhs = TREE_OPERAND (incr, 1);
11252           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11253                          RECUR (TREE_OPERAND (incr, 0)),
11254                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11255                                  RECUR (TREE_OPERAND (rhs, 0)),
11256                                  RECUR (TREE_OPERAND (rhs, 1))));
11257         }
11258       else
11259         incr = RECUR (incr);
11260       break;
11261     case MODOP_EXPR:
11262       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11263           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11264         {
11265           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11266           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11267                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11268                                  TREE_TYPE (decl), lhs,
11269                                  RECUR (TREE_OPERAND (incr, 2))));
11270         }
11271       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11272                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11273                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11274         {
11275           tree rhs = TREE_OPERAND (incr, 2);
11276           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11277                          RECUR (TREE_OPERAND (incr, 0)),
11278                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11279                                  RECUR (TREE_OPERAND (rhs, 0)),
11280                                  RECUR (TREE_OPERAND (rhs, 1))));
11281         }
11282       else
11283         incr = RECUR (incr);
11284       break;
11285     default:
11286       incr = RECUR (incr);
11287       break;
11288     }
11289
11290   TREE_VEC_ELT (declv, i) = decl;
11291   TREE_VEC_ELT (initv, i) = init;
11292   TREE_VEC_ELT (condv, i) = cond;
11293   TREE_VEC_ELT (incrv, i) = incr;
11294 #undef RECUR
11295 }
11296
11297 /* Like tsubst_copy for expressions, etc. but also does semantic
11298    processing.  */
11299
11300 static tree
11301 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11302              bool integral_constant_expression_p)
11303 {
11304 #define RECUR(NODE)                             \
11305   tsubst_expr ((NODE), args, complain, in_decl, \
11306                integral_constant_expression_p)
11307
11308   tree stmt, tmp;
11309
11310   if (t == NULL_TREE || t == error_mark_node)
11311     return t;
11312
11313   if (EXPR_HAS_LOCATION (t))
11314     input_location = EXPR_LOCATION (t);
11315   if (STATEMENT_CODE_P (TREE_CODE (t)))
11316     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11317
11318   switch (TREE_CODE (t))
11319     {
11320     case STATEMENT_LIST:
11321       {
11322         tree_stmt_iterator i;
11323         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11324           RECUR (tsi_stmt (i));
11325         break;
11326       }
11327
11328     case CTOR_INITIALIZER:
11329       finish_mem_initializers (tsubst_initializer_list
11330                                (TREE_OPERAND (t, 0), args));
11331       break;
11332
11333     case RETURN_EXPR:
11334       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11335       break;
11336
11337     case EXPR_STMT:
11338       tmp = RECUR (EXPR_STMT_EXPR (t));
11339       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11340         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11341       else
11342         finish_expr_stmt (tmp);
11343       break;
11344
11345     case USING_STMT:
11346       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11347       break;
11348
11349     case DECL_EXPR:
11350       {
11351         tree decl;
11352         tree init;
11353
11354         decl = DECL_EXPR_DECL (t);
11355         if (TREE_CODE (decl) == LABEL_DECL)
11356           finish_label_decl (DECL_NAME (decl));
11357         else if (TREE_CODE (decl) == USING_DECL)
11358           {
11359             tree scope = USING_DECL_SCOPE (decl);
11360             tree name = DECL_NAME (decl);
11361             tree decl;
11362
11363             scope = RECUR (scope);
11364             decl = lookup_qualified_name (scope, name,
11365                                           /*is_type_p=*/false,
11366                                           /*complain=*/false);
11367             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11368               qualified_name_lookup_error (scope, name, decl, input_location);
11369             else
11370               do_local_using_decl (decl, scope, name);
11371           }
11372         else
11373           {
11374             init = DECL_INITIAL (decl);
11375             decl = tsubst (decl, args, complain, in_decl);
11376             if (decl != error_mark_node)
11377               {
11378                 /* By marking the declaration as instantiated, we avoid
11379                    trying to instantiate it.  Since instantiate_decl can't
11380                    handle local variables, and since we've already done
11381                    all that needs to be done, that's the right thing to
11382                    do.  */
11383                 if (TREE_CODE (decl) == VAR_DECL)
11384                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11385                 if (TREE_CODE (decl) == VAR_DECL
11386                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11387                   /* Anonymous aggregates are a special case.  */
11388                   finish_anon_union (decl);
11389                 else
11390                   {
11391                     maybe_push_decl (decl);
11392                     if (TREE_CODE (decl) == VAR_DECL
11393                         && DECL_PRETTY_FUNCTION_P (decl))
11394                       {
11395                         /* For __PRETTY_FUNCTION__ we have to adjust the
11396                            initializer.  */
11397                         const char *const name
11398                           = cxx_printable_name (current_function_decl, 2);
11399                         init = cp_fname_init (name, &TREE_TYPE (decl));
11400                       }
11401                     else
11402                       {
11403                         tree t = RECUR (init);
11404
11405                         if (init && !t)
11406                           /* If we had an initializer but it
11407                              instantiated to nothing,
11408                              value-initialize the object.  This will
11409                              only occur when the initializer was a
11410                              pack expansion where the parameter packs
11411                              used in that expansion were of length
11412                              zero.  */
11413                           init = build_value_init (TREE_TYPE (decl));
11414                         else
11415                           init = t;
11416                       }
11417
11418                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11419                   }
11420               }
11421           }
11422
11423         /* A DECL_EXPR can also be used as an expression, in the condition
11424            clause of an if/for/while construct.  */
11425         return decl;
11426       }
11427
11428     case FOR_STMT:
11429       stmt = begin_for_stmt ();
11430                           RECUR (FOR_INIT_STMT (t));
11431       finish_for_init_stmt (stmt);
11432       tmp = RECUR (FOR_COND (t));
11433       finish_for_cond (tmp, stmt);
11434       tmp = RECUR (FOR_EXPR (t));
11435       finish_for_expr (tmp, stmt);
11436       RECUR (FOR_BODY (t));
11437       finish_for_stmt (stmt);
11438       break;
11439
11440     case WHILE_STMT:
11441       stmt = begin_while_stmt ();
11442       tmp = RECUR (WHILE_COND (t));
11443       finish_while_stmt_cond (tmp, stmt);
11444       RECUR (WHILE_BODY (t));
11445       finish_while_stmt (stmt);
11446       break;
11447
11448     case DO_STMT:
11449       stmt = begin_do_stmt ();
11450       RECUR (DO_BODY (t));
11451       finish_do_body (stmt);
11452       tmp = RECUR (DO_COND (t));
11453       finish_do_stmt (tmp, stmt);
11454       break;
11455
11456     case IF_STMT:
11457       stmt = begin_if_stmt ();
11458       tmp = RECUR (IF_COND (t));
11459       finish_if_stmt_cond (tmp, stmt);
11460       RECUR (THEN_CLAUSE (t));
11461       finish_then_clause (stmt);
11462
11463       if (ELSE_CLAUSE (t))
11464         {
11465           begin_else_clause (stmt);
11466           RECUR (ELSE_CLAUSE (t));
11467           finish_else_clause (stmt);
11468         }
11469
11470       finish_if_stmt (stmt);
11471       break;
11472
11473     case BIND_EXPR:
11474       if (BIND_EXPR_BODY_BLOCK (t))
11475         stmt = begin_function_body ();
11476       else
11477         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11478                                     ? BCS_TRY_BLOCK : 0);
11479
11480       RECUR (BIND_EXPR_BODY (t));
11481
11482       if (BIND_EXPR_BODY_BLOCK (t))
11483         finish_function_body (stmt);
11484       else
11485         finish_compound_stmt (stmt);
11486       break;
11487
11488     case BREAK_STMT:
11489       finish_break_stmt ();
11490       break;
11491
11492     case CONTINUE_STMT:
11493       finish_continue_stmt ();
11494       break;
11495
11496     case SWITCH_STMT:
11497       stmt = begin_switch_stmt ();
11498       tmp = RECUR (SWITCH_STMT_COND (t));
11499       finish_switch_cond (tmp, stmt);
11500       RECUR (SWITCH_STMT_BODY (t));
11501       finish_switch_stmt (stmt);
11502       break;
11503
11504     case CASE_LABEL_EXPR:
11505       finish_case_label (EXPR_LOCATION (t),
11506                          RECUR (CASE_LOW (t)),
11507                          RECUR (CASE_HIGH (t)));
11508       break;
11509
11510     case LABEL_EXPR:
11511       {
11512         tree decl = LABEL_EXPR_LABEL (t);
11513         tree label;
11514
11515         label = finish_label_stmt (DECL_NAME (decl));
11516         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11517           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11518       }
11519       break;
11520
11521     case GOTO_EXPR:
11522       tmp = GOTO_DESTINATION (t);
11523       if (TREE_CODE (tmp) != LABEL_DECL)
11524         /* Computed goto's must be tsubst'd into.  On the other hand,
11525            non-computed gotos must not be; the identifier in question
11526            will have no binding.  */
11527         tmp = RECUR (tmp);
11528       else
11529         tmp = DECL_NAME (tmp);
11530       finish_goto_stmt (tmp);
11531       break;
11532
11533     case ASM_EXPR:
11534       tmp = finish_asm_stmt
11535         (ASM_VOLATILE_P (t),
11536          RECUR (ASM_STRING (t)),
11537          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11538          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11539          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11540          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11541       {
11542         tree asm_expr = tmp;
11543         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11544           asm_expr = TREE_OPERAND (asm_expr, 0);
11545         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11546       }
11547       break;
11548
11549     case TRY_BLOCK:
11550       if (CLEANUP_P (t))
11551         {
11552           stmt = begin_try_block ();
11553           RECUR (TRY_STMTS (t));
11554           finish_cleanup_try_block (stmt);
11555           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11556         }
11557       else
11558         {
11559           tree compound_stmt = NULL_TREE;
11560
11561           if (FN_TRY_BLOCK_P (t))
11562             stmt = begin_function_try_block (&compound_stmt);
11563           else
11564             stmt = begin_try_block ();
11565
11566           RECUR (TRY_STMTS (t));
11567
11568           if (FN_TRY_BLOCK_P (t))
11569             finish_function_try_block (stmt);
11570           else
11571             finish_try_block (stmt);
11572
11573           RECUR (TRY_HANDLERS (t));
11574           if (FN_TRY_BLOCK_P (t))
11575             finish_function_handler_sequence (stmt, compound_stmt);
11576           else
11577             finish_handler_sequence (stmt);
11578         }
11579       break;
11580
11581     case HANDLER:
11582       {
11583         tree decl = HANDLER_PARMS (t);
11584
11585         if (decl)
11586           {
11587             decl = tsubst (decl, args, complain, in_decl);
11588             /* Prevent instantiate_decl from trying to instantiate
11589                this variable.  We've already done all that needs to be
11590                done.  */
11591             if (decl != error_mark_node)
11592               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11593           }
11594         stmt = begin_handler ();
11595         finish_handler_parms (decl, stmt);
11596         RECUR (HANDLER_BODY (t));
11597         finish_handler (stmt);
11598       }
11599       break;
11600
11601     case TAG_DEFN:
11602       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11603       break;
11604
11605     case STATIC_ASSERT:
11606       {
11607         tree condition = 
11608           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11609                        args,
11610                        complain, in_decl,
11611                        /*integral_constant_expression_p=*/true);
11612         finish_static_assert (condition,
11613                               STATIC_ASSERT_MESSAGE (t),
11614                               STATIC_ASSERT_SOURCE_LOCATION (t),
11615                               /*member_p=*/false);
11616       }
11617       break;
11618
11619     case OMP_PARALLEL:
11620       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11621                                 args, complain, in_decl);
11622       stmt = begin_omp_parallel ();
11623       RECUR (OMP_PARALLEL_BODY (t));
11624       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11625         = OMP_PARALLEL_COMBINED (t);
11626       break;
11627
11628     case OMP_TASK:
11629       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11630                                 args, complain, in_decl);
11631       stmt = begin_omp_task ();
11632       RECUR (OMP_TASK_BODY (t));
11633       finish_omp_task (tmp, stmt);
11634       break;
11635
11636     case OMP_FOR:
11637       {
11638         tree clauses, body, pre_body;
11639         tree declv, initv, condv, incrv;
11640         int i;
11641
11642         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11643                                       args, complain, in_decl);
11644         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11645         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11646         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11647         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11648
11649         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11650           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11651                                    &clauses, args, complain, in_decl,
11652                                    integral_constant_expression_p);
11653
11654         stmt = begin_omp_structured_block ();
11655
11656         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11657           if (TREE_VEC_ELT (initv, i) == NULL
11658               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11659             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11660           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11661             {
11662               tree init = RECUR (TREE_VEC_ELT (initv, i));
11663               gcc_assert (init == TREE_VEC_ELT (declv, i));
11664               TREE_VEC_ELT (initv, i) = NULL_TREE;
11665             }
11666           else
11667             {
11668               tree decl_expr = TREE_VEC_ELT (initv, i);
11669               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11670               gcc_assert (init != NULL);
11671               TREE_VEC_ELT (initv, i) = RECUR (init);
11672               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11673               RECUR (decl_expr);
11674               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11675             }
11676
11677         pre_body = push_stmt_list ();
11678         RECUR (OMP_FOR_PRE_BODY (t));
11679         pre_body = pop_stmt_list (pre_body);
11680
11681         body = push_stmt_list ();
11682         RECUR (OMP_FOR_BODY (t));
11683         body = pop_stmt_list (body);
11684
11685         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11686                             body, pre_body, clauses);
11687
11688         add_stmt (finish_omp_structured_block (stmt));
11689       }
11690       break;
11691
11692     case OMP_SECTIONS:
11693     case OMP_SINGLE:
11694       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11695       stmt = push_stmt_list ();
11696       RECUR (OMP_BODY (t));
11697       stmt = pop_stmt_list (stmt);
11698
11699       t = copy_node (t);
11700       OMP_BODY (t) = stmt;
11701       OMP_CLAUSES (t) = tmp;
11702       add_stmt (t);
11703       break;
11704
11705     case OMP_SECTION:
11706     case OMP_CRITICAL:
11707     case OMP_MASTER:
11708     case OMP_ORDERED:
11709       stmt = push_stmt_list ();
11710       RECUR (OMP_BODY (t));
11711       stmt = pop_stmt_list (stmt);
11712
11713       t = copy_node (t);
11714       OMP_BODY (t) = stmt;
11715       add_stmt (t);
11716       break;
11717
11718     case OMP_ATOMIC:
11719       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11720       {
11721         tree op1 = TREE_OPERAND (t, 1);
11722         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11723         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11724         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11725       }
11726       break;
11727
11728     case EXPR_PACK_EXPANSION:
11729       error ("invalid use of pack expansion expression");
11730       return error_mark_node;
11731
11732     case NONTYPE_ARGUMENT_PACK:
11733       error ("use %<...%> to expand argument pack");
11734       return error_mark_node;
11735
11736     default:
11737       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11738
11739       return tsubst_copy_and_build (t, args, complain, in_decl,
11740                                     /*function_p=*/false,
11741                                     integral_constant_expression_p);
11742     }
11743
11744   return NULL_TREE;
11745 #undef RECUR
11746 }
11747
11748 /* T is a postfix-expression that is not being used in a function
11749    call.  Return the substituted version of T.  */
11750
11751 static tree
11752 tsubst_non_call_postfix_expression (tree t, tree args,
11753                                     tsubst_flags_t complain,
11754                                     tree in_decl)
11755 {
11756   if (TREE_CODE (t) == SCOPE_REF)
11757     t = tsubst_qualified_id (t, args, complain, in_decl,
11758                              /*done=*/false, /*address_p=*/false);
11759   else
11760     t = tsubst_copy_and_build (t, args, complain, in_decl,
11761                                /*function_p=*/false,
11762                                /*integral_constant_expression_p=*/false);
11763
11764   return t;
11765 }
11766
11767 /* Like tsubst but deals with expressions and performs semantic
11768    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11769
11770 tree
11771 tsubst_copy_and_build (tree t,
11772                        tree args,
11773                        tsubst_flags_t complain,
11774                        tree in_decl,
11775                        bool function_p,
11776                        bool integral_constant_expression_p)
11777 {
11778 #define RECUR(NODE)                                             \
11779   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11780                          /*function_p=*/false,                  \
11781                          integral_constant_expression_p)
11782
11783   tree op1;
11784
11785   if (t == NULL_TREE || t == error_mark_node)
11786     return t;
11787
11788   switch (TREE_CODE (t))
11789     {
11790     case USING_DECL:
11791       t = DECL_NAME (t);
11792       /* Fall through.  */
11793     case IDENTIFIER_NODE:
11794       {
11795         tree decl;
11796         cp_id_kind idk;
11797         bool non_integral_constant_expression_p;
11798         const char *error_msg;
11799
11800         if (IDENTIFIER_TYPENAME_P (t))
11801           {
11802             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11803             t = mangle_conv_op_name_for_type (new_type);
11804           }
11805
11806         /* Look up the name.  */
11807         decl = lookup_name (t);
11808
11809         /* By convention, expressions use ERROR_MARK_NODE to indicate
11810            failure, not NULL_TREE.  */
11811         if (decl == NULL_TREE)
11812           decl = error_mark_node;
11813
11814         decl = finish_id_expression (t, decl, NULL_TREE,
11815                                      &idk,
11816                                      integral_constant_expression_p,
11817                                      /*allow_non_integral_constant_expression_p=*/false,
11818                                      &non_integral_constant_expression_p,
11819                                      /*template_p=*/false,
11820                                      /*done=*/true,
11821                                      /*address_p=*/false,
11822                                      /*template_arg_p=*/false,
11823                                      &error_msg,
11824                                      input_location);
11825         if (error_msg)
11826           error (error_msg);
11827         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11828           decl = unqualified_name_lookup_error (decl);
11829         return decl;
11830       }
11831
11832     case TEMPLATE_ID_EXPR:
11833       {
11834         tree object;
11835         tree templ = RECUR (TREE_OPERAND (t, 0));
11836         tree targs = TREE_OPERAND (t, 1);
11837
11838         if (targs)
11839           targs = tsubst_template_args (targs, args, complain, in_decl);
11840
11841         if (TREE_CODE (templ) == COMPONENT_REF)
11842           {
11843             object = TREE_OPERAND (templ, 0);
11844             templ = TREE_OPERAND (templ, 1);
11845           }
11846         else
11847           object = NULL_TREE;
11848         templ = lookup_template_function (templ, targs);
11849
11850         if (object)
11851           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11852                          object, templ, NULL_TREE);
11853         else
11854           return baselink_for_fns (templ);
11855       }
11856
11857     case INDIRECT_REF:
11858       {
11859         tree r = RECUR (TREE_OPERAND (t, 0));
11860
11861         if (REFERENCE_REF_P (t))
11862           {
11863             /* A type conversion to reference type will be enclosed in
11864                such an indirect ref, but the substitution of the cast
11865                will have also added such an indirect ref.  */
11866             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11867               r = convert_from_reference (r);
11868           }
11869         else
11870           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
11871         return r;
11872       }
11873
11874     case NOP_EXPR:
11875       return build_nop
11876         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11877          RECUR (TREE_OPERAND (t, 0)));
11878
11879     case CAST_EXPR:
11880     case REINTERPRET_CAST_EXPR:
11881     case CONST_CAST_EXPR:
11882     case DYNAMIC_CAST_EXPR:
11883     case STATIC_CAST_EXPR:
11884       {
11885         tree type;
11886         tree op;
11887
11888         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11889         if (integral_constant_expression_p
11890             && !cast_valid_in_integral_constant_expression_p (type))
11891           {
11892             if (complain & tf_error)
11893               error ("a cast to a type other than an integral or "
11894                      "enumeration type cannot appear in a constant-expression");
11895             return error_mark_node; 
11896           }
11897
11898         op = RECUR (TREE_OPERAND (t, 0));
11899
11900         switch (TREE_CODE (t))
11901           {
11902           case CAST_EXPR:
11903             return build_functional_cast (type, op, complain);
11904           case REINTERPRET_CAST_EXPR:
11905             return build_reinterpret_cast (type, op, complain);
11906           case CONST_CAST_EXPR:
11907             return build_const_cast (type, op, complain);
11908           case DYNAMIC_CAST_EXPR:
11909             return build_dynamic_cast (type, op, complain);
11910           case STATIC_CAST_EXPR:
11911             return build_static_cast (type, op, complain);
11912           default:
11913             gcc_unreachable ();
11914           }
11915       }
11916
11917     case POSTDECREMENT_EXPR:
11918     case POSTINCREMENT_EXPR:
11919       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11920                                                 args, complain, in_decl);
11921       return build_x_unary_op (TREE_CODE (t), op1, complain);
11922
11923     case PREDECREMENT_EXPR:
11924     case PREINCREMENT_EXPR:
11925     case NEGATE_EXPR:
11926     case BIT_NOT_EXPR:
11927     case ABS_EXPR:
11928     case TRUTH_NOT_EXPR:
11929     case UNARY_PLUS_EXPR:  /* Unary + */
11930     case REALPART_EXPR:
11931     case IMAGPART_EXPR:
11932       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11933                                complain);
11934
11935     case ADDR_EXPR:
11936       op1 = TREE_OPERAND (t, 0);
11937       if (TREE_CODE (op1) == SCOPE_REF)
11938         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11939                                    /*done=*/true, /*address_p=*/true);
11940       else
11941         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11942                                                   in_decl);
11943       if (TREE_CODE (op1) == LABEL_DECL)
11944         return finish_label_address_expr (DECL_NAME (op1),
11945                                           EXPR_LOCATION (op1));
11946       return build_x_unary_op (ADDR_EXPR, op1, complain);
11947
11948     case PLUS_EXPR:
11949     case MINUS_EXPR:
11950     case MULT_EXPR:
11951     case TRUNC_DIV_EXPR:
11952     case CEIL_DIV_EXPR:
11953     case FLOOR_DIV_EXPR:
11954     case ROUND_DIV_EXPR:
11955     case EXACT_DIV_EXPR:
11956     case BIT_AND_EXPR:
11957     case BIT_IOR_EXPR:
11958     case BIT_XOR_EXPR:
11959     case TRUNC_MOD_EXPR:
11960     case FLOOR_MOD_EXPR:
11961     case TRUTH_ANDIF_EXPR:
11962     case TRUTH_ORIF_EXPR:
11963     case TRUTH_AND_EXPR:
11964     case TRUTH_OR_EXPR:
11965     case RSHIFT_EXPR:
11966     case LSHIFT_EXPR:
11967     case RROTATE_EXPR:
11968     case LROTATE_EXPR:
11969     case EQ_EXPR:
11970     case NE_EXPR:
11971     case MAX_EXPR:
11972     case MIN_EXPR:
11973     case LE_EXPR:
11974     case GE_EXPR:
11975     case LT_EXPR:
11976     case GT_EXPR:
11977     case MEMBER_REF:
11978     case DOTSTAR_EXPR:
11979       return build_x_binary_op
11980         (TREE_CODE (t),
11981          RECUR (TREE_OPERAND (t, 0)),
11982          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11983           ? ERROR_MARK
11984           : TREE_CODE (TREE_OPERAND (t, 0))),
11985          RECUR (TREE_OPERAND (t, 1)),
11986          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11987           ? ERROR_MARK
11988           : TREE_CODE (TREE_OPERAND (t, 1))),
11989          /*overloaded_p=*/NULL,
11990          complain);
11991
11992     case SCOPE_REF:
11993       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11994                                   /*address_p=*/false);
11995     case ARRAY_REF:
11996       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11997                                                 args, complain, in_decl);
11998       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11999
12000     case SIZEOF_EXPR:
12001       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12002         return tsubst_copy (t, args, complain, in_decl);
12003       /* Fall through */
12004       
12005     case ALIGNOF_EXPR:
12006       op1 = TREE_OPERAND (t, 0);
12007       if (!args)
12008         {
12009           /* When there are no ARGS, we are trying to evaluate a
12010              non-dependent expression from the parser.  Trying to do
12011              the substitutions may not work.  */
12012           if (!TYPE_P (op1))
12013             op1 = TREE_TYPE (op1);
12014         }
12015       else
12016         {
12017           ++cp_unevaluated_operand;
12018           ++c_inhibit_evaluation_warnings;
12019           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12020                                        /*function_p=*/false,
12021                                        /*integral_constant_expression_p=*/false);
12022           --cp_unevaluated_operand;
12023           --c_inhibit_evaluation_warnings;
12024         }
12025       if (TYPE_P (op1))
12026         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12027                                            complain & tf_error);
12028       else
12029         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12030                                            complain & tf_error);
12031
12032     case MODOP_EXPR:
12033       {
12034         tree r = build_x_modify_expr
12035           (RECUR (TREE_OPERAND (t, 0)),
12036            TREE_CODE (TREE_OPERAND (t, 1)),
12037            RECUR (TREE_OPERAND (t, 2)),
12038            complain);
12039         /* TREE_NO_WARNING must be set if either the expression was
12040            parenthesized or it uses an operator such as >>= rather
12041            than plain assignment.  In the former case, it was already
12042            set and must be copied.  In the latter case,
12043            build_x_modify_expr sets it and it must not be reset
12044            here.  */
12045         if (TREE_NO_WARNING (t))
12046           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12047         return r;
12048       }
12049
12050     case ARROW_EXPR:
12051       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12052                                                 args, complain, in_decl);
12053       /* Remember that there was a reference to this entity.  */
12054       if (DECL_P (op1))
12055         mark_used (op1);
12056       return build_x_arrow (op1);
12057
12058     case NEW_EXPR:
12059       {
12060         tree placement = RECUR (TREE_OPERAND (t, 0));
12061         tree init = RECUR (TREE_OPERAND (t, 3));
12062         VEC(tree,gc) *placement_vec;
12063         VEC(tree,gc) *init_vec;
12064         tree ret;
12065
12066         if (placement == NULL_TREE)
12067           placement_vec = NULL;
12068         else
12069           {
12070             placement_vec = make_tree_vector ();
12071             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12072               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12073           }
12074
12075         /* If there was an initializer in the original tree, but it
12076            instantiated to an empty list, then we should pass a
12077            non-NULL empty vector to tell build_new that it was an
12078            empty initializer() rather than no initializer.  This can
12079            only happen when the initializer is a pack expansion whose
12080            parameter packs are of length zero.  */
12081         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12082           init_vec = NULL;
12083         else
12084           {
12085             init_vec = make_tree_vector ();
12086             if (init == void_zero_node)
12087               gcc_assert (init_vec != NULL);
12088             else
12089               {
12090                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12091                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12092               }
12093           }
12094
12095         ret = build_new (&placement_vec,
12096                          RECUR (TREE_OPERAND (t, 1)),
12097                          RECUR (TREE_OPERAND (t, 2)),
12098                          &init_vec,
12099                          NEW_EXPR_USE_GLOBAL (t),
12100                          complain);
12101
12102         if (placement_vec != NULL)
12103           release_tree_vector (placement_vec);
12104         if (init_vec != NULL)
12105           release_tree_vector (init_vec);
12106
12107         return ret;
12108       }
12109
12110     case DELETE_EXPR:
12111      return delete_sanity
12112        (RECUR (TREE_OPERAND (t, 0)),
12113         RECUR (TREE_OPERAND (t, 1)),
12114         DELETE_EXPR_USE_VEC (t),
12115         DELETE_EXPR_USE_GLOBAL (t));
12116
12117     case COMPOUND_EXPR:
12118       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12119                                     RECUR (TREE_OPERAND (t, 1)),
12120                                     complain);
12121
12122     case CALL_EXPR:
12123       {
12124         tree function;
12125         VEC(tree,gc) *call_args;
12126         unsigned int nargs, i;
12127         bool qualified_p;
12128         bool koenig_p;
12129         tree ret;
12130
12131         function = CALL_EXPR_FN (t);
12132         /* When we parsed the expression,  we determined whether or
12133            not Koenig lookup should be performed.  */
12134         koenig_p = KOENIG_LOOKUP_P (t);
12135         if (TREE_CODE (function) == SCOPE_REF)
12136           {
12137             qualified_p = true;
12138             function = tsubst_qualified_id (function, args, complain, in_decl,
12139                                             /*done=*/false,
12140                                             /*address_p=*/false);
12141           }
12142         else
12143           {
12144             if (TREE_CODE (function) == COMPONENT_REF)
12145               {
12146                 tree op = TREE_OPERAND (function, 1);
12147
12148                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12149                                || (BASELINK_P (op)
12150                                    && BASELINK_QUALIFIED_P (op)));
12151               }
12152             else
12153               qualified_p = false;
12154
12155             function = tsubst_copy_and_build (function, args, complain,
12156                                               in_decl,
12157                                               !qualified_p,
12158                                               integral_constant_expression_p);
12159
12160             if (BASELINK_P (function))
12161               qualified_p = true;
12162           }
12163
12164         nargs = call_expr_nargs (t);
12165         call_args = make_tree_vector ();
12166         for (i = 0; i < nargs; ++i)
12167           {
12168             tree arg = CALL_EXPR_ARG (t, i);
12169
12170             if (!PACK_EXPANSION_P (arg))
12171               VEC_safe_push (tree, gc, call_args,
12172                              RECUR (CALL_EXPR_ARG (t, i)));
12173             else
12174               {
12175                 /* Expand the pack expansion and push each entry onto
12176                    CALL_ARGS.  */
12177                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12178                 if (TREE_CODE (arg) == TREE_VEC)
12179                   {
12180                     unsigned int len, j;
12181
12182                     len = TREE_VEC_LENGTH (arg);
12183                     for (j = 0; j < len; ++j)
12184                       {
12185                         tree value = TREE_VEC_ELT (arg, j);
12186                         if (value != NULL_TREE)
12187                           value = convert_from_reference (value);
12188                         VEC_safe_push (tree, gc, call_args, value);
12189                       }
12190                   }
12191                 else
12192                   {
12193                     /* A partial substitution.  Add one entry.  */
12194                     VEC_safe_push (tree, gc, call_args, arg);
12195                   }
12196               }
12197           }
12198
12199         /* We do not perform argument-dependent lookup if normal
12200            lookup finds a non-function, in accordance with the
12201            expected resolution of DR 218.  */
12202         if (koenig_p
12203             && ((is_overloaded_fn (function)
12204                  /* If lookup found a member function, the Koenig lookup is
12205                     not appropriate, even if an unqualified-name was used
12206                     to denote the function.  */
12207                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12208                 || TREE_CODE (function) == IDENTIFIER_NODE)
12209             /* Only do this when substitution turns a dependent call
12210                into a non-dependent call.  */
12211             && type_dependent_expression_p_push (t)
12212             && !any_type_dependent_arguments_p (call_args))
12213           function = perform_koenig_lookup (function, call_args);
12214
12215         if (TREE_CODE (function) == IDENTIFIER_NODE)
12216           {
12217             unqualified_name_lookup_error (function);
12218             release_tree_vector (call_args);
12219             return error_mark_node;
12220           }
12221
12222         /* Remember that there was a reference to this entity.  */
12223         if (DECL_P (function))
12224           mark_used (function);
12225
12226         if (TREE_CODE (function) == OFFSET_REF)
12227           ret = build_offset_ref_call_from_tree (function, &call_args);
12228         else if (TREE_CODE (function) == COMPONENT_REF)
12229           {
12230             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12231               ret = finish_call_expr (function, &call_args,
12232                                        /*disallow_virtual=*/false,
12233                                        /*koenig_p=*/false,
12234                                        complain);
12235             else
12236               ret = (build_new_method_call
12237                       (TREE_OPERAND (function, 0),
12238                        TREE_OPERAND (function, 1),
12239                        &call_args, NULL_TREE,
12240                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12241                        /*fn_p=*/NULL,
12242                        complain));
12243           }
12244         else
12245           ret = finish_call_expr (function, &call_args,
12246                                   /*disallow_virtual=*/qualified_p,
12247                                   koenig_p,
12248                                   complain);
12249
12250         release_tree_vector (call_args);
12251
12252         return ret;
12253       }
12254
12255     case COND_EXPR:
12256       return build_x_conditional_expr
12257         (RECUR (TREE_OPERAND (t, 0)),
12258          RECUR (TREE_OPERAND (t, 1)),
12259          RECUR (TREE_OPERAND (t, 2)),
12260          complain);
12261
12262     case PSEUDO_DTOR_EXPR:
12263       return finish_pseudo_destructor_expr
12264         (RECUR (TREE_OPERAND (t, 0)),
12265          RECUR (TREE_OPERAND (t, 1)),
12266          RECUR (TREE_OPERAND (t, 2)));
12267
12268     case TREE_LIST:
12269       {
12270         tree purpose, value, chain;
12271
12272         if (t == void_list_node)
12273           return t;
12274
12275         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12276             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12277           {
12278             /* We have pack expansions, so expand those and
12279                create a new list out of it.  */
12280             tree purposevec = NULL_TREE;
12281             tree valuevec = NULL_TREE;
12282             tree chain;
12283             int i, len = -1;
12284
12285             /* Expand the argument expressions.  */
12286             if (TREE_PURPOSE (t))
12287               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12288                                                  complain, in_decl);
12289             if (TREE_VALUE (t))
12290               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12291                                                complain, in_decl);
12292
12293             /* Build the rest of the list.  */
12294             chain = TREE_CHAIN (t);
12295             if (chain && chain != void_type_node)
12296               chain = RECUR (chain);
12297
12298             /* Determine the number of arguments.  */
12299             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12300               {
12301                 len = TREE_VEC_LENGTH (purposevec);
12302                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12303               }
12304             else if (TREE_CODE (valuevec) == TREE_VEC)
12305               len = TREE_VEC_LENGTH (valuevec);
12306             else
12307               {
12308                 /* Since we only performed a partial substitution into
12309                    the argument pack, we only return a single list
12310                    node.  */
12311                 if (purposevec == TREE_PURPOSE (t)
12312                     && valuevec == TREE_VALUE (t)
12313                     && chain == TREE_CHAIN (t))
12314                   return t;
12315
12316                 return tree_cons (purposevec, valuevec, chain);
12317               }
12318             
12319             /* Convert the argument vectors into a TREE_LIST */
12320             i = len;
12321             while (i > 0)
12322               {
12323                 /* Grab the Ith values.  */
12324                 i--;
12325                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12326                                      : NULL_TREE;
12327                 value 
12328                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12329                              : NULL_TREE;
12330
12331                 /* Build the list (backwards).  */
12332                 chain = tree_cons (purpose, value, chain);
12333               }
12334
12335             return chain;
12336           }
12337
12338         purpose = TREE_PURPOSE (t);
12339         if (purpose)
12340           purpose = RECUR (purpose);
12341         value = TREE_VALUE (t);
12342         if (value)
12343           value = RECUR (value);
12344         chain = TREE_CHAIN (t);
12345         if (chain && chain != void_type_node)
12346           chain = RECUR (chain);
12347         if (purpose == TREE_PURPOSE (t)
12348             && value == TREE_VALUE (t)
12349             && chain == TREE_CHAIN (t))
12350           return t;
12351         return tree_cons (purpose, value, chain);
12352       }
12353
12354     case COMPONENT_REF:
12355       {
12356         tree object;
12357         tree object_type;
12358         tree member;
12359
12360         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12361                                                      args, complain, in_decl);
12362         /* Remember that there was a reference to this entity.  */
12363         if (DECL_P (object))
12364           mark_used (object);
12365         object_type = TREE_TYPE (object);
12366
12367         member = TREE_OPERAND (t, 1);
12368         if (BASELINK_P (member))
12369           member = tsubst_baselink (member,
12370                                     non_reference (TREE_TYPE (object)),
12371                                     args, complain, in_decl);
12372         else
12373           member = tsubst_copy (member, args, complain, in_decl);
12374         if (member == error_mark_node)
12375           return error_mark_node;
12376
12377         if (object_type && !CLASS_TYPE_P (object_type))
12378           {
12379             if (SCALAR_TYPE_P (object_type))
12380               {
12381                 tree s = NULL_TREE;
12382                 tree dtor = member;
12383
12384                 if (TREE_CODE (dtor) == SCOPE_REF)
12385                   {
12386                     s = TREE_OPERAND (dtor, 0);
12387                     dtor = TREE_OPERAND (dtor, 1);
12388                   }
12389                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12390                   {
12391                     dtor = TREE_OPERAND (dtor, 0);
12392                     if (TYPE_P (dtor))
12393                       return finish_pseudo_destructor_expr (object, s, dtor);
12394                   }
12395               }
12396           }
12397         else if (TREE_CODE (member) == SCOPE_REF
12398                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12399           {
12400             tree tmpl;
12401             tree args;
12402
12403             /* Lookup the template functions now that we know what the
12404                scope is.  */
12405             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12406             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12407             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12408                                             /*is_type_p=*/false,
12409                                             /*complain=*/false);
12410             if (BASELINK_P (member))
12411               {
12412                 BASELINK_FUNCTIONS (member)
12413                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12414                               args);
12415                 member = (adjust_result_of_qualified_name_lookup
12416                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12417                            object_type));
12418               }
12419             else
12420               {
12421                 qualified_name_lookup_error (object_type, tmpl, member,
12422                                              input_location);
12423                 return error_mark_node;
12424               }
12425           }
12426         else if (TREE_CODE (member) == SCOPE_REF
12427                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12428                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12429           {
12430             if (complain & tf_error)
12431               {
12432                 if (TYPE_P (TREE_OPERAND (member, 0)))
12433                   error ("%qT is not a class or namespace",
12434                          TREE_OPERAND (member, 0));
12435                 else
12436                   error ("%qD is not a class or namespace",
12437                          TREE_OPERAND (member, 0));
12438               }
12439             return error_mark_node;
12440           }
12441         else if (TREE_CODE (member) == FIELD_DECL)
12442           return finish_non_static_data_member (member, object, NULL_TREE);
12443
12444         return finish_class_member_access_expr (object, member,
12445                                                 /*template_p=*/false,
12446                                                 complain);
12447       }
12448
12449     case THROW_EXPR:
12450       return build_throw
12451         (RECUR (TREE_OPERAND (t, 0)));
12452
12453     case CONSTRUCTOR:
12454       {
12455         VEC(constructor_elt,gc) *n;
12456         constructor_elt *ce;
12457         unsigned HOST_WIDE_INT idx;
12458         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12459         bool process_index_p;
12460         int newlen;
12461         bool need_copy_p = false;
12462         tree r;
12463
12464         if (type == error_mark_node)
12465           return error_mark_node;
12466
12467         /* digest_init will do the wrong thing if we let it.  */
12468         if (type && TYPE_PTRMEMFUNC_P (type))
12469           return t;
12470
12471         /* We do not want to process the index of aggregate
12472            initializers as they are identifier nodes which will be
12473            looked up by digest_init.  */
12474         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12475
12476         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12477         newlen = VEC_length (constructor_elt, n);
12478         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12479           {
12480             if (ce->index && process_index_p)
12481               ce->index = RECUR (ce->index);
12482
12483             if (PACK_EXPANSION_P (ce->value))
12484               {
12485                 /* Substitute into the pack expansion.  */
12486                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12487                                                   in_decl);
12488
12489                 if (ce->value == error_mark_node)
12490                   ;
12491                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12492                   /* Just move the argument into place.  */
12493                   ce->value = TREE_VEC_ELT (ce->value, 0);
12494                 else
12495                   {
12496                     /* Update the length of the final CONSTRUCTOR
12497                        arguments vector, and note that we will need to
12498                        copy.*/
12499                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12500                     need_copy_p = true;
12501                   }
12502               }
12503             else
12504               ce->value = RECUR (ce->value);
12505           }
12506
12507         if (need_copy_p)
12508           {
12509             VEC(constructor_elt,gc) *old_n = n;
12510
12511             n = VEC_alloc (constructor_elt, gc, newlen);
12512             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12513                  idx++)
12514               {
12515                 if (TREE_CODE (ce->value) == TREE_VEC)
12516                   {
12517                     int i, len = TREE_VEC_LENGTH (ce->value);
12518                     for (i = 0; i < len; ++i)
12519                       CONSTRUCTOR_APPEND_ELT (n, 0,
12520                                               TREE_VEC_ELT (ce->value, i));
12521                   }
12522                 else
12523                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12524               }
12525           }
12526
12527         r = build_constructor (init_list_type_node, n);
12528         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12529
12530         if (TREE_HAS_CONSTRUCTOR (t))
12531           return finish_compound_literal (type, r);
12532
12533         return r;
12534       }
12535
12536     case TYPEID_EXPR:
12537       {
12538         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12539         if (TYPE_P (operand_0))
12540           return get_typeid (operand_0);
12541         return build_typeid (operand_0);
12542       }
12543
12544     case VAR_DECL:
12545       if (!args)
12546         return t;
12547       /* Fall through */
12548
12549     case PARM_DECL:
12550       {
12551         tree r = tsubst_copy (t, args, complain, in_decl);
12552
12553         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12554           /* If the original type was a reference, we'll be wrapped in
12555              the appropriate INDIRECT_REF.  */
12556           r = convert_from_reference (r);
12557         return r;
12558       }
12559
12560     case VA_ARG_EXPR:
12561       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12562                              tsubst_copy (TREE_TYPE (t), args, complain,
12563                                           in_decl));
12564
12565     case OFFSETOF_EXPR:
12566       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12567
12568     case TRAIT_EXPR:
12569       {
12570         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12571                                   complain, in_decl);
12572
12573         tree type2 = TRAIT_EXPR_TYPE2 (t);
12574         if (type2)
12575           type2 = tsubst_copy (type2, args, complain, in_decl);
12576         
12577         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12578       }
12579
12580     case STMT_EXPR:
12581       {
12582         tree old_stmt_expr = cur_stmt_expr;
12583         tree stmt_expr = begin_stmt_expr ();
12584
12585         cur_stmt_expr = stmt_expr;
12586         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12587                      integral_constant_expression_p);
12588         stmt_expr = finish_stmt_expr (stmt_expr, false);
12589         cur_stmt_expr = old_stmt_expr;
12590
12591         /* If the resulting list of expression statement is empty,
12592            fold it further into void_zero_node.  */
12593         if (empty_expr_stmt_p (stmt_expr))
12594           stmt_expr = void_zero_node;
12595
12596         return stmt_expr;
12597       }
12598
12599     case CONST_DECL:
12600       t = tsubst_copy (t, args, complain, in_decl);
12601       /* As in finish_id_expression, we resolve enumeration constants
12602          to their underlying values.  */
12603       if (TREE_CODE (t) == CONST_DECL)
12604         {
12605           used_types_insert (TREE_TYPE (t));
12606           return DECL_INITIAL (t);
12607         }
12608       return t;
12609
12610     case LAMBDA_EXPR:
12611       {
12612         tree r = build_lambda_expr ();
12613
12614         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12615         TREE_TYPE (r) = type;
12616         CLASSTYPE_LAMBDA_EXPR (type) = r;
12617
12618         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12619           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12620         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12621         LAMBDA_EXPR_DISCRIMINATOR (r)
12622           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12623         LAMBDA_EXPR_CAPTURE_LIST (r)
12624           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12625         LAMBDA_EXPR_THIS_CAPTURE (r)
12626           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12627         LAMBDA_EXPR_EXTRA_SCOPE (r)
12628           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12629
12630         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12631         determine_visibility (TYPE_NAME (type));
12632         /* Now that we know visibility, instantiate the type so we have a
12633            declaration of the op() for later calls to lambda_function.  */
12634         complete_type (type);
12635
12636         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12637         if (type)
12638           apply_lambda_return_type (r, type);
12639
12640         return build_lambda_object (r);
12641       }
12642
12643     default:
12644       /* Handle Objective-C++ constructs, if appropriate.  */
12645       {
12646         tree subst
12647           = objcp_tsubst_copy_and_build (t, args, complain,
12648                                          in_decl, /*function_p=*/false);
12649         if (subst)
12650           return subst;
12651       }
12652       return tsubst_copy (t, args, complain, in_decl);
12653     }
12654
12655 #undef RECUR
12656 }
12657
12658 /* Verify that the instantiated ARGS are valid. For type arguments,
12659    make sure that the type's linkage is ok. For non-type arguments,
12660    make sure they are constants if they are integral or enumerations.
12661    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12662
12663 static bool
12664 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12665 {
12666   if (ARGUMENT_PACK_P (t))
12667     {
12668       tree vec = ARGUMENT_PACK_ARGS (t);
12669       int len = TREE_VEC_LENGTH (vec);
12670       bool result = false;
12671       int i;
12672
12673       for (i = 0; i < len; ++i)
12674         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12675           result = true;
12676       return result;
12677     }
12678   else if (TYPE_P (t))
12679     {
12680       /* [basic.link]: A name with no linkage (notably, the name
12681          of a class or enumeration declared in a local scope)
12682          shall not be used to declare an entity with linkage.
12683          This implies that names with no linkage cannot be used as
12684          template arguments
12685
12686          DR 757 relaxes this restriction for C++0x.  */
12687       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12688                  : no_linkage_check (t, /*relaxed_p=*/false));
12689
12690       if (nt)
12691         {
12692           /* DR 488 makes use of a type with no linkage cause
12693              type deduction to fail.  */
12694           if (complain & tf_error)
12695             {
12696               if (TYPE_ANONYMOUS_P (nt))
12697                 error ("%qT is/uses anonymous type", t);
12698               else
12699                 error ("template argument for %qD uses local type %qT",
12700                        tmpl, t);
12701             }
12702           return true;
12703         }
12704       /* In order to avoid all sorts of complications, we do not
12705          allow variably-modified types as template arguments.  */
12706       else if (variably_modified_type_p (t, NULL_TREE))
12707         {
12708           if (complain & tf_error)
12709             error ("%qT is a variably modified type", t);
12710           return true;
12711         }
12712     }
12713   /* A non-type argument of integral or enumerated type must be a
12714      constant.  */
12715   else if (TREE_TYPE (t)
12716            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12717            && !TREE_CONSTANT (t))
12718     {
12719       if (complain & tf_error)
12720         error ("integral expression %qE is not constant", t);
12721       return true;
12722     }
12723   return false;
12724 }
12725
12726 static bool
12727 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12728 {
12729   int ix, len = DECL_NTPARMS (tmpl);
12730   bool result = false;
12731
12732   for (ix = 0; ix != len; ix++)
12733     {
12734       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12735         result = true;
12736     }
12737   if (result && (complain & tf_error))
12738     error ("  trying to instantiate %qD", tmpl);
12739   return result;
12740 }
12741
12742 /* Instantiate the indicated variable or function template TMPL with
12743    the template arguments in TARG_PTR.  */
12744
12745 tree
12746 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12747 {
12748   tree targ_ptr = orig_args;
12749   tree fndecl;
12750   tree gen_tmpl;
12751   tree spec;
12752   HOST_WIDE_INT saved_processing_template_decl;
12753
12754   if (tmpl == error_mark_node)
12755     return error_mark_node;
12756
12757   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12758
12759   /* If this function is a clone, handle it specially.  */
12760   if (DECL_CLONED_FUNCTION_P (tmpl))
12761     {
12762       tree spec;
12763       tree clone;
12764
12765       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12766          DECL_CLONED_FUNCTION.  */
12767       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12768                                    targ_ptr, complain);
12769       if (spec == error_mark_node)
12770         return error_mark_node;
12771
12772       /* Look for the clone.  */
12773       FOR_EACH_CLONE (clone, spec)
12774         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12775           return clone;
12776       /* We should always have found the clone by now.  */
12777       gcc_unreachable ();
12778       return NULL_TREE;
12779     }
12780
12781   /* Check to see if we already have this specialization.  */
12782   gen_tmpl = most_general_template (tmpl);
12783   if (tmpl != gen_tmpl)
12784     /* The TMPL is a partial instantiation.  To get a full set of
12785        arguments we must add the arguments used to perform the
12786        partial instantiation.  */
12787     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12788                                             targ_ptr);
12789
12790   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12791      but it doesn't seem to be on the hot path.  */
12792   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12793
12794   gcc_assert (tmpl == gen_tmpl
12795               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12796                   == spec)
12797               || fndecl == NULL_TREE);
12798
12799   if (spec != NULL_TREE)
12800     return spec;
12801
12802   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12803                                complain))
12804     return error_mark_node;
12805
12806   /* We are building a FUNCTION_DECL, during which the access of its
12807      parameters and return types have to be checked.  However this
12808      FUNCTION_DECL which is the desired context for access checking
12809      is not built yet.  We solve this chicken-and-egg problem by
12810      deferring all checks until we have the FUNCTION_DECL.  */
12811   push_deferring_access_checks (dk_deferred);
12812
12813   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12814      (because, for example, we have encountered a non-dependent
12815      function call in the body of a template function and must now
12816      determine which of several overloaded functions will be called),
12817      within the instantiation itself we are not processing a
12818      template.  */  
12819   saved_processing_template_decl = processing_template_decl;
12820   processing_template_decl = 0;
12821   /* Substitute template parameters to obtain the specialization.  */
12822   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12823                    targ_ptr, complain, gen_tmpl);
12824   processing_template_decl = saved_processing_template_decl;
12825   if (fndecl == error_mark_node)
12826     return error_mark_node;
12827
12828   /* Now we know the specialization, compute access previously
12829      deferred.  */
12830   push_access_scope (fndecl);
12831
12832   /* Some typedefs referenced from within the template code need to be access
12833      checked at template instantiation time, i.e now. These types were
12834      added to the template at parsing time. Let's get those and perfom
12835      the acces checks then.  */
12836   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12837   perform_deferred_access_checks ();
12838   pop_access_scope (fndecl);
12839   pop_deferring_access_checks ();
12840
12841   /* The DECL_TI_TEMPLATE should always be the immediate parent
12842      template, not the most general template.  */
12843   DECL_TI_TEMPLATE (fndecl) = tmpl;
12844
12845   /* If we've just instantiated the main entry point for a function,
12846      instantiate all the alternate entry points as well.  We do this
12847      by cloning the instantiation of the main entry point, not by
12848      instantiating the template clones.  */
12849   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12850     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12851
12852   return fndecl;
12853 }
12854
12855 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12856    NARGS elements of the arguments that are being used when calling
12857    it.  TARGS is a vector into which the deduced template arguments
12858    are placed.
12859
12860    Return zero for success, 2 for an incomplete match that doesn't resolve
12861    all the types, and 1 for complete failure.  An error message will be
12862    printed only for an incomplete match.
12863
12864    If FN is a conversion operator, or we are trying to produce a specific
12865    specialization, RETURN_TYPE is the return type desired.
12866
12867    The EXPLICIT_TARGS are explicit template arguments provided via a
12868    template-id.
12869
12870    The parameter STRICT is one of:
12871
12872    DEDUCE_CALL:
12873      We are deducing arguments for a function call, as in
12874      [temp.deduct.call].
12875
12876    DEDUCE_CONV:
12877      We are deducing arguments for a conversion function, as in
12878      [temp.deduct.conv].
12879
12880    DEDUCE_EXACT:
12881      We are deducing arguments when doing an explicit instantiation
12882      as in [temp.explicit], when determining an explicit specialization
12883      as in [temp.expl.spec], or when taking the address of a function
12884      template, as in [temp.deduct.funcaddr].  */
12885
12886 int
12887 fn_type_unification (tree fn,
12888                      tree explicit_targs,
12889                      tree targs,
12890                      const tree *args,
12891                      unsigned int nargs,
12892                      tree return_type,
12893                      unification_kind_t strict,
12894                      int flags)
12895 {
12896   tree parms;
12897   tree fntype;
12898   int result;
12899   bool incomplete_argument_packs_p = false;
12900
12901   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12902
12903   fntype = TREE_TYPE (fn);
12904   if (explicit_targs)
12905     {
12906       /* [temp.deduct]
12907
12908          The specified template arguments must match the template
12909          parameters in kind (i.e., type, nontype, template), and there
12910          must not be more arguments than there are parameters;
12911          otherwise type deduction fails.
12912
12913          Nontype arguments must match the types of the corresponding
12914          nontype template parameters, or must be convertible to the
12915          types of the corresponding nontype parameters as specified in
12916          _temp.arg.nontype_, otherwise type deduction fails.
12917
12918          All references in the function type of the function template
12919          to the corresponding template parameters are replaced by the
12920          specified template argument values.  If a substitution in a
12921          template parameter or in the function type of the function
12922          template results in an invalid type, type deduction fails.  */
12923       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12924       int i, len = TREE_VEC_LENGTH (tparms);
12925       tree converted_args;
12926       bool incomplete = false;
12927
12928       if (explicit_targs == error_mark_node)
12929         return 1;
12930
12931       converted_args
12932         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12933                                   /*require_all_args=*/false,
12934                                   /*use_default_args=*/false));
12935       if (converted_args == error_mark_node)
12936         return 1;
12937
12938       /* Substitute the explicit args into the function type.  This is
12939          necessary so that, for instance, explicitly declared function
12940          arguments can match null pointed constants.  If we were given
12941          an incomplete set of explicit args, we must not do semantic
12942          processing during substitution as we could create partial
12943          instantiations.  */
12944       for (i = 0; i < len; i++)
12945         {
12946           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12947           bool parameter_pack = false;
12948
12949           /* Dig out the actual parm.  */
12950           if (TREE_CODE (parm) == TYPE_DECL
12951               || TREE_CODE (parm) == TEMPLATE_DECL)
12952             {
12953               parm = TREE_TYPE (parm);
12954               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12955             }
12956           else if (TREE_CODE (parm) == PARM_DECL)
12957             {
12958               parm = DECL_INITIAL (parm);
12959               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12960             }
12961
12962           if (parameter_pack)
12963             {
12964               int level, idx;
12965               tree targ;
12966               template_parm_level_and_index (parm, &level, &idx);
12967
12968               /* Mark the argument pack as "incomplete". We could
12969                  still deduce more arguments during unification.  */
12970               targ = TMPL_ARG (converted_args, level, idx);
12971               if (targ)
12972                 {
12973                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12974                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12975                     = ARGUMENT_PACK_ARGS (targ);
12976                 }
12977
12978               /* We have some incomplete argument packs.  */
12979               incomplete_argument_packs_p = true;
12980             }
12981         }
12982
12983       if (incomplete_argument_packs_p)
12984         /* Any substitution is guaranteed to be incomplete if there
12985            are incomplete argument packs, because we can still deduce
12986            more arguments.  */
12987         incomplete = 1;
12988       else
12989         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12990
12991       processing_template_decl += incomplete;
12992       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12993       processing_template_decl -= incomplete;
12994
12995       if (fntype == error_mark_node)
12996         return 1;
12997
12998       /* Place the explicitly specified arguments in TARGS.  */
12999       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13000         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13001     }
13002
13003   /* Never do unification on the 'this' parameter.  */
13004   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13005
13006   if (return_type)
13007     {
13008       tree *new_args;
13009
13010       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13011       new_args = XALLOCAVEC (tree, nargs + 1);
13012       new_args[0] = return_type;
13013       memcpy (new_args + 1, args, nargs * sizeof (tree));
13014       args = new_args;
13015       ++nargs;
13016     }
13017
13018   /* We allow incomplete unification without an error message here
13019      because the standard doesn't seem to explicitly prohibit it.  Our
13020      callers must be ready to deal with unification failures in any
13021      event.  */
13022   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13023                                   targs, parms, args, nargs, /*subr=*/0,
13024                                   strict, flags);
13025
13026   if (result == 0 && incomplete_argument_packs_p)
13027     {
13028       int i, len = NUM_TMPL_ARGS (targs);
13029
13030       /* Clear the "incomplete" flags on all argument packs.  */
13031       for (i = 0; i < len; i++)
13032         {
13033           tree arg = TREE_VEC_ELT (targs, i);
13034           if (ARGUMENT_PACK_P (arg))
13035             {
13036               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13037               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13038             }
13039         }
13040     }
13041
13042   /* Now that we have bindings for all of the template arguments,
13043      ensure that the arguments deduced for the template template
13044      parameters have compatible template parameter lists.  We cannot
13045      check this property before we have deduced all template
13046      arguments, because the template parameter types of a template
13047      template parameter might depend on prior template parameters
13048      deduced after the template template parameter.  The following
13049      ill-formed example illustrates this issue:
13050
13051        template<typename T, template<T> class C> void f(C<5>, T);
13052
13053        template<int N> struct X {};
13054
13055        void g() {
13056          f(X<5>(), 5l); // error: template argument deduction fails
13057        }
13058
13059      The template parameter list of 'C' depends on the template type
13060      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13061      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13062      time that we deduce 'C'.  */
13063   if (result == 0
13064       && !template_template_parm_bindings_ok_p 
13065            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13066     return 1;
13067
13068   if (result == 0)
13069     /* All is well so far.  Now, check:
13070
13071        [temp.deduct]
13072
13073        When all template arguments have been deduced, all uses of
13074        template parameters in nondeduced contexts are replaced with
13075        the corresponding deduced argument values.  If the
13076        substitution results in an invalid type, as described above,
13077        type deduction fails.  */
13078     {
13079       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13080       if (substed == error_mark_node)
13081         return 1;
13082
13083       /* If we're looking for an exact match, check that what we got
13084          is indeed an exact match.  It might not be if some template
13085          parameters are used in non-deduced contexts.  */
13086       if (strict == DEDUCE_EXACT)
13087         {
13088           unsigned int i;
13089
13090           tree sarg
13091             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13092           if (return_type)
13093             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13094           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13095             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13096               return 1;
13097         }
13098     }
13099
13100   return result;
13101 }
13102
13103 /* Adjust types before performing type deduction, as described in
13104    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13105    sections are symmetric.  PARM is the type of a function parameter
13106    or the return type of the conversion function.  ARG is the type of
13107    the argument passed to the call, or the type of the value
13108    initialized with the result of the conversion function.
13109    ARG_EXPR is the original argument expression, which may be null.  */
13110
13111 static int
13112 maybe_adjust_types_for_deduction (unification_kind_t strict,
13113                                   tree* parm,
13114                                   tree* arg,
13115                                   tree arg_expr)
13116 {
13117   int result = 0;
13118
13119   switch (strict)
13120     {
13121     case DEDUCE_CALL:
13122       break;
13123
13124     case DEDUCE_CONV:
13125       {
13126         /* Swap PARM and ARG throughout the remainder of this
13127            function; the handling is precisely symmetric since PARM
13128            will initialize ARG rather than vice versa.  */
13129         tree* temp = parm;
13130         parm = arg;
13131         arg = temp;
13132         break;
13133       }
13134
13135     case DEDUCE_EXACT:
13136       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13137          too, but here handle it by stripping the reference from PARM
13138          rather than by adding it to ARG.  */
13139       if (TREE_CODE (*parm) == REFERENCE_TYPE
13140           && TYPE_REF_IS_RVALUE (*parm)
13141           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13142           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13143           && TREE_CODE (*arg) == REFERENCE_TYPE
13144           && !TYPE_REF_IS_RVALUE (*arg))
13145         *parm = TREE_TYPE (*parm);
13146       /* Nothing else to do in this case.  */
13147       return 0;
13148
13149     default:
13150       gcc_unreachable ();
13151     }
13152
13153   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13154     {
13155       /* [temp.deduct.call]
13156
13157          If P is not a reference type:
13158
13159          --If A is an array type, the pointer type produced by the
13160          array-to-pointer standard conversion (_conv.array_) is
13161          used in place of A for type deduction; otherwise,
13162
13163          --If A is a function type, the pointer type produced by
13164          the function-to-pointer standard conversion
13165          (_conv.func_) is used in place of A for type deduction;
13166          otherwise,
13167
13168          --If A is a cv-qualified type, the top level
13169          cv-qualifiers of A's type are ignored for type
13170          deduction.  */
13171       if (TREE_CODE (*arg) == ARRAY_TYPE)
13172         *arg = build_pointer_type (TREE_TYPE (*arg));
13173       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13174         *arg = build_pointer_type (*arg);
13175       else
13176         *arg = TYPE_MAIN_VARIANT (*arg);
13177     }
13178
13179   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13180      of the form T&&, where T is a template parameter, and the argument
13181      is an lvalue, T is deduced as A& */
13182   if (TREE_CODE (*parm) == REFERENCE_TYPE
13183       && TYPE_REF_IS_RVALUE (*parm)
13184       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13185       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13186       && arg_expr && real_lvalue_p (arg_expr))
13187     *arg = build_reference_type (*arg);
13188
13189   /* [temp.deduct.call]
13190
13191      If P is a cv-qualified type, the top level cv-qualifiers
13192      of P's type are ignored for type deduction.  If P is a
13193      reference type, the type referred to by P is used for
13194      type deduction.  */
13195   *parm = TYPE_MAIN_VARIANT (*parm);
13196   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13197     {
13198       *parm = TREE_TYPE (*parm);
13199       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13200     }
13201
13202   /* DR 322. For conversion deduction, remove a reference type on parm
13203      too (which has been swapped into ARG).  */
13204   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13205     *arg = TREE_TYPE (*arg);
13206
13207   return result;
13208 }
13209
13210 /* Most parms like fn_type_unification.
13211
13212    If SUBR is 1, we're being called recursively (to unify the
13213    arguments of a function or method parameter of a function
13214    template). */
13215
13216 static int
13217 type_unification_real (tree tparms,
13218                        tree targs,
13219                        tree xparms,
13220                        const tree *xargs,
13221                        unsigned int xnargs,
13222                        int subr,
13223                        unification_kind_t strict,
13224                        int flags)
13225 {
13226   tree parm, arg, arg_expr;
13227   int i;
13228   int ntparms = TREE_VEC_LENGTH (tparms);
13229   int sub_strict;
13230   int saw_undeduced = 0;
13231   tree parms;
13232   const tree *args;
13233   unsigned int nargs;
13234   unsigned int ia;
13235
13236   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13237   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13238   gcc_assert (ntparms > 0);
13239
13240   switch (strict)
13241     {
13242     case DEDUCE_CALL:
13243       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13244                     | UNIFY_ALLOW_DERIVED);
13245       break;
13246
13247     case DEDUCE_CONV:
13248       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13249       break;
13250
13251     case DEDUCE_EXACT:
13252       sub_strict = UNIFY_ALLOW_NONE;
13253       break;
13254
13255     default:
13256       gcc_unreachable ();
13257     }
13258
13259  again:
13260   parms = xparms;
13261   args = xargs;
13262   nargs = xnargs;
13263
13264   ia = 0;
13265   while (parms && parms != void_list_node
13266          && ia < nargs)
13267     {
13268       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13269         break;
13270
13271       parm = TREE_VALUE (parms);
13272       parms = TREE_CHAIN (parms);
13273       arg = args[ia];
13274       ++ia;
13275       arg_expr = NULL;
13276
13277       if (arg == error_mark_node)
13278         return 1;
13279       if (arg == unknown_type_node)
13280         /* We can't deduce anything from this, but we might get all the
13281            template args from other function args.  */
13282         continue;
13283
13284       /* Conversions will be performed on a function argument that
13285          corresponds with a function parameter that contains only
13286          non-deducible template parameters and explicitly specified
13287          template parameters.  */
13288       if (!uses_template_parms (parm))
13289         {
13290           tree type;
13291
13292           if (!TYPE_P (arg))
13293             type = TREE_TYPE (arg);
13294           else
13295             type = arg;
13296
13297           if (same_type_p (parm, type))
13298             continue;
13299           if (strict != DEDUCE_EXACT
13300               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13301                                   flags))
13302             continue;
13303
13304           return 1;
13305         }
13306
13307       if (!TYPE_P (arg))
13308         {
13309           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13310           if (type_unknown_p (arg))
13311             {
13312               /* [temp.deduct.type] 
13313
13314                  A template-argument can be deduced from a pointer to
13315                  function or pointer to member function argument if
13316                  the set of overloaded functions does not contain
13317                  function templates and at most one of a set of
13318                  overloaded functions provides a unique match.  */
13319               if (resolve_overloaded_unification
13320                   (tparms, targs, parm, arg, strict, sub_strict))
13321                 continue;
13322
13323               return 1;
13324             }
13325           arg_expr = arg;
13326           arg = unlowered_expr_type (arg);
13327           if (arg == error_mark_node)
13328             return 1;
13329         }
13330
13331       {
13332         int arg_strict = sub_strict;
13333
13334         if (!subr)
13335           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13336                                                           arg_expr);
13337
13338         if (arg == init_list_type_node && arg_expr)
13339           arg = arg_expr;
13340         if (unify (tparms, targs, parm, arg, arg_strict))
13341           return 1;
13342       }
13343     }
13344
13345
13346   if (parms 
13347       && parms != void_list_node
13348       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13349     {
13350       /* Unify the remaining arguments with the pack expansion type.  */
13351       tree argvec;
13352       tree parmvec = make_tree_vec (1);
13353
13354       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13355       argvec = make_tree_vec (nargs - ia);
13356       for (i = 0; ia < nargs; ++ia, ++i)
13357         TREE_VEC_ELT (argvec, i) = args[ia];
13358
13359       /* Copy the parameter into parmvec.  */
13360       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13361       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13362                                 /*call_args_p=*/true, /*subr=*/subr))
13363         return 1;
13364
13365       /* Advance to the end of the list of parameters.  */
13366       parms = TREE_CHAIN (parms);
13367     }
13368
13369   /* Fail if we've reached the end of the parm list, and more args
13370      are present, and the parm list isn't variadic.  */
13371   if (ia < nargs && parms == void_list_node)
13372     return 1;
13373   /* Fail if parms are left and they don't have default values.  */
13374   if (parms && parms != void_list_node
13375       && TREE_PURPOSE (parms) == NULL_TREE)
13376     return 1;
13377
13378   if (!subr)
13379     for (i = 0; i < ntparms; i++)
13380       if (!TREE_VEC_ELT (targs, i))
13381         {
13382           tree tparm;
13383
13384           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13385             continue;
13386
13387           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13388
13389           /* If this is an undeduced nontype parameter that depends on
13390              a type parameter, try another pass; its type may have been
13391              deduced from a later argument than the one from which
13392              this parameter can be deduced.  */
13393           if (TREE_CODE (tparm) == PARM_DECL
13394               && uses_template_parms (TREE_TYPE (tparm))
13395               && !saw_undeduced++)
13396             goto again;
13397
13398           /* Core issue #226 (C++0x) [temp.deduct]:
13399
13400                If a template argument has not been deduced, its
13401                default template argument, if any, is used. 
13402
13403              When we are in C++98 mode, TREE_PURPOSE will either
13404              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13405              to explicitly check cxx_dialect here.  */
13406           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13407             {
13408               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13409               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13410               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13411               arg = convert_template_argument (parm, arg, targs, tf_none,
13412                                                i, NULL_TREE);
13413               if (arg == error_mark_node)
13414                 return 1;
13415               else
13416                 {
13417                   TREE_VEC_ELT (targs, i) = arg;
13418                   continue;
13419                 }
13420             }
13421
13422           /* If the type parameter is a parameter pack, then it will
13423              be deduced to an empty parameter pack.  */
13424           if (template_parameter_pack_p (tparm))
13425             {
13426               tree arg;
13427
13428               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13429                 {
13430                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13431                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13432                   TREE_CONSTANT (arg) = 1;
13433                 }
13434               else
13435                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13436
13437               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13438
13439               TREE_VEC_ELT (targs, i) = arg;
13440               continue;
13441             }
13442
13443           return 2;
13444         }
13445
13446   return 0;
13447 }
13448
13449 /* Subroutine of type_unification_real.  Args are like the variables
13450    at the call site.  ARG is an overloaded function (or template-id);
13451    we try deducing template args from each of the overloads, and if
13452    only one succeeds, we go with that.  Modifies TARGS and returns
13453    true on success.  */
13454
13455 static bool
13456 resolve_overloaded_unification (tree tparms,
13457                                 tree targs,
13458                                 tree parm,
13459                                 tree arg,
13460                                 unification_kind_t strict,
13461                                 int sub_strict)
13462 {
13463   tree tempargs = copy_node (targs);
13464   int good = 0;
13465   tree goodfn = NULL_TREE;
13466   bool addr_p;
13467
13468   if (TREE_CODE (arg) == ADDR_EXPR)
13469     {
13470       arg = TREE_OPERAND (arg, 0);
13471       addr_p = true;
13472     }
13473   else
13474     addr_p = false;
13475
13476   if (TREE_CODE (arg) == COMPONENT_REF)
13477     /* Handle `&x' where `x' is some static or non-static member
13478        function name.  */
13479     arg = TREE_OPERAND (arg, 1);
13480
13481   if (TREE_CODE (arg) == OFFSET_REF)
13482     arg = TREE_OPERAND (arg, 1);
13483
13484   /* Strip baselink information.  */
13485   if (BASELINK_P (arg))
13486     arg = BASELINK_FUNCTIONS (arg);
13487
13488   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13489     {
13490       /* If we got some explicit template args, we need to plug them into
13491          the affected templates before we try to unify, in case the
13492          explicit args will completely resolve the templates in question.  */
13493
13494       tree expl_subargs = TREE_OPERAND (arg, 1);
13495       arg = TREE_OPERAND (arg, 0);
13496
13497       for (; arg; arg = OVL_NEXT (arg))
13498         {
13499           tree fn = OVL_CURRENT (arg);
13500           tree subargs, elem;
13501
13502           if (TREE_CODE (fn) != TEMPLATE_DECL)
13503             continue;
13504
13505           ++processing_template_decl;
13506           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13507                                   expl_subargs, /*check_ret=*/false);
13508           if (subargs)
13509             {
13510               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13511               if (try_one_overload (tparms, targs, tempargs, parm,
13512                                     elem, strict, sub_strict, addr_p)
13513                   && (!goodfn || !decls_match (goodfn, elem)))
13514                 {
13515                   goodfn = elem;
13516                   ++good;
13517                 }
13518             }
13519           --processing_template_decl;
13520         }
13521     }
13522   else if (TREE_CODE (arg) != OVERLOAD
13523            && TREE_CODE (arg) != FUNCTION_DECL)
13524     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13525        -- but the deduction does not succeed because the expression is
13526        not just the function on its own.  */
13527     return false;
13528   else
13529     for (; arg; arg = OVL_NEXT (arg))
13530       if (try_one_overload (tparms, targs, tempargs, parm,
13531                             TREE_TYPE (OVL_CURRENT (arg)),
13532                             strict, sub_strict, addr_p)
13533           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13534         {
13535           goodfn = OVL_CURRENT (arg);
13536           ++good;
13537         }
13538
13539   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13540      to function or pointer to member function argument if the set of
13541      overloaded functions does not contain function templates and at most
13542      one of a set of overloaded functions provides a unique match.
13543
13544      So if we found multiple possibilities, we return success but don't
13545      deduce anything.  */
13546
13547   if (good == 1)
13548     {
13549       int i = TREE_VEC_LENGTH (targs);
13550       for (; i--; )
13551         if (TREE_VEC_ELT (tempargs, i))
13552           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13553     }
13554   if (good)
13555     return true;
13556
13557   return false;
13558 }
13559
13560 /* Core DR 115: In contexts where deduction is done and fails, or in
13561    contexts where deduction is not done, if a template argument list is
13562    specified and it, along with any default template arguments, identifies
13563    a single function template specialization, then the template-id is an
13564    lvalue for the function template specialization.  */
13565
13566 tree
13567 resolve_nondeduced_context (tree orig_expr)
13568 {
13569   tree expr, offset, baselink;
13570   bool addr;
13571
13572   if (!type_unknown_p (orig_expr))
13573     return orig_expr;
13574
13575   expr = orig_expr;
13576   addr = false;
13577   offset = NULL_TREE;
13578   baselink = NULL_TREE;
13579
13580   if (TREE_CODE (expr) == ADDR_EXPR)
13581     {
13582       expr = TREE_OPERAND (expr, 0);
13583       addr = true;
13584     }
13585   if (TREE_CODE (expr) == OFFSET_REF)
13586     {
13587       offset = expr;
13588       expr = TREE_OPERAND (expr, 1);
13589     }
13590   if (TREE_CODE (expr) == BASELINK)
13591     {
13592       baselink = expr;
13593       expr = BASELINK_FUNCTIONS (expr);
13594     }
13595
13596   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13597     {
13598       int good = 0;
13599       tree goodfn = NULL_TREE;
13600
13601       /* If we got some explicit template args, we need to plug them into
13602          the affected templates before we try to unify, in case the
13603          explicit args will completely resolve the templates in question.  */
13604
13605       tree expl_subargs = TREE_OPERAND (expr, 1);
13606       tree arg = TREE_OPERAND (expr, 0);
13607       tree badfn = NULL_TREE;
13608       tree badargs = NULL_TREE;
13609
13610       for (; arg; arg = OVL_NEXT (arg))
13611         {
13612           tree fn = OVL_CURRENT (arg);
13613           tree subargs, elem;
13614
13615           if (TREE_CODE (fn) != TEMPLATE_DECL)
13616             continue;
13617
13618           ++processing_template_decl;
13619           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13620                                   expl_subargs, /*check_ret=*/false);
13621           if (subargs && !any_dependent_template_arguments_p (subargs))
13622             {
13623               elem = instantiate_template (fn, subargs, tf_none);
13624               if (elem == error_mark_node)
13625                 {
13626                   badfn = fn;
13627                   badargs = subargs;
13628                 }
13629               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13630                 {
13631                   goodfn = elem;
13632                   ++good;
13633                 }
13634             }
13635           --processing_template_decl;
13636         }
13637       if (good == 1)
13638         {
13639           expr = goodfn;
13640           if (baselink)
13641             expr = build_baselink (BASELINK_BINFO (baselink),
13642                                    BASELINK_ACCESS_BINFO (baselink),
13643                                    expr, BASELINK_OPTYPE (baselink));
13644           if (offset)
13645             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13646                            TREE_OPERAND (offset, 0), expr);
13647           if (addr)
13648             expr = build_address (expr);
13649           return expr;
13650         }
13651       else if (good == 0 && badargs)
13652         /* There were no good options and at least one bad one, so let the
13653            user know what the problem is.  */
13654         instantiate_template (badfn, badargs, tf_warning_or_error);
13655     }
13656   return orig_expr;
13657 }
13658
13659 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13660    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13661    different overloads deduce different arguments for a given parm.
13662    ADDR_P is true if the expression for which deduction is being
13663    performed was of the form "& fn" rather than simply "fn".
13664
13665    Returns 1 on success.  */
13666
13667 static int
13668 try_one_overload (tree tparms,
13669                   tree orig_targs,
13670                   tree targs,
13671                   tree parm,
13672                   tree arg,
13673                   unification_kind_t strict,
13674                   int sub_strict,
13675                   bool addr_p)
13676 {
13677   int nargs;
13678   tree tempargs;
13679   int i;
13680
13681   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13682      to function or pointer to member function argument if the set of
13683      overloaded functions does not contain function templates and at most
13684      one of a set of overloaded functions provides a unique match.
13685
13686      So if this is a template, just return success.  */
13687
13688   if (uses_template_parms (arg))
13689     return 1;
13690
13691   if (TREE_CODE (arg) == METHOD_TYPE)
13692     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13693   else if (addr_p)
13694     arg = build_pointer_type (arg);
13695
13696   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13697
13698   /* We don't copy orig_targs for this because if we have already deduced
13699      some template args from previous args, unify would complain when we
13700      try to deduce a template parameter for the same argument, even though
13701      there isn't really a conflict.  */
13702   nargs = TREE_VEC_LENGTH (targs);
13703   tempargs = make_tree_vec (nargs);
13704
13705   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13706     return 0;
13707
13708   /* First make sure we didn't deduce anything that conflicts with
13709      explicitly specified args.  */
13710   for (i = nargs; i--; )
13711     {
13712       tree elt = TREE_VEC_ELT (tempargs, i);
13713       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13714
13715       if (!elt)
13716         /*NOP*/;
13717       else if (uses_template_parms (elt))
13718         /* Since we're unifying against ourselves, we will fill in
13719            template args used in the function parm list with our own
13720            template parms.  Discard them.  */
13721         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13722       else if (oldelt && !template_args_equal (oldelt, elt))
13723         return 0;
13724     }
13725
13726   for (i = nargs; i--; )
13727     {
13728       tree elt = TREE_VEC_ELT (tempargs, i);
13729
13730       if (elt)
13731         TREE_VEC_ELT (targs, i) = elt;
13732     }
13733
13734   return 1;
13735 }
13736
13737 /* PARM is a template class (perhaps with unbound template
13738    parameters).  ARG is a fully instantiated type.  If ARG can be
13739    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13740    TARGS are as for unify.  */
13741
13742 static tree
13743 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13744 {
13745   tree copy_of_targs;
13746
13747   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13748       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13749           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13750     return NULL_TREE;
13751
13752   /* We need to make a new template argument vector for the call to
13753      unify.  If we used TARGS, we'd clutter it up with the result of
13754      the attempted unification, even if this class didn't work out.
13755      We also don't want to commit ourselves to all the unifications
13756      we've already done, since unification is supposed to be done on
13757      an argument-by-argument basis.  In other words, consider the
13758      following pathological case:
13759
13760        template <int I, int J, int K>
13761        struct S {};
13762
13763        template <int I, int J>
13764        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13765
13766        template <int I, int J, int K>
13767        void f(S<I, J, K>, S<I, I, I>);
13768
13769        void g() {
13770          S<0, 0, 0> s0;
13771          S<0, 1, 2> s2;
13772
13773          f(s0, s2);
13774        }
13775
13776      Now, by the time we consider the unification involving `s2', we
13777      already know that we must have `f<0, 0, 0>'.  But, even though
13778      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13779      because there are two ways to unify base classes of S<0, 1, 2>
13780      with S<I, I, I>.  If we kept the already deduced knowledge, we
13781      would reject the possibility I=1.  */
13782   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13783
13784   /* If unification failed, we're done.  */
13785   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13786              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13787     return NULL_TREE;
13788
13789   return arg;
13790 }
13791
13792 /* Given a template type PARM and a class type ARG, find the unique
13793    base type in ARG that is an instance of PARM.  We do not examine
13794    ARG itself; only its base-classes.  If there is not exactly one
13795    appropriate base class, return NULL_TREE.  PARM may be the type of
13796    a partial specialization, as well as a plain template type.  Used
13797    by unify.  */
13798
13799 static tree
13800 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13801 {
13802   tree rval = NULL_TREE;
13803   tree binfo;
13804
13805   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13806
13807   binfo = TYPE_BINFO (complete_type (arg));
13808   if (!binfo)
13809     /* The type could not be completed.  */
13810     return NULL_TREE;
13811
13812   /* Walk in inheritance graph order.  The search order is not
13813      important, and this avoids multiple walks of virtual bases.  */
13814   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13815     {
13816       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13817
13818       if (r)
13819         {
13820           /* If there is more than one satisfactory baseclass, then:
13821
13822                [temp.deduct.call]
13823
13824               If they yield more than one possible deduced A, the type
13825               deduction fails.
13826
13827              applies.  */
13828           if (rval && !same_type_p (r, rval))
13829             return NULL_TREE;
13830
13831           rval = r;
13832         }
13833     }
13834
13835   return rval;
13836 }
13837
13838 /* Returns the level of DECL, which declares a template parameter.  */
13839
13840 static int
13841 template_decl_level (tree decl)
13842 {
13843   switch (TREE_CODE (decl))
13844     {
13845     case TYPE_DECL:
13846     case TEMPLATE_DECL:
13847       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13848
13849     case PARM_DECL:
13850       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13851
13852     default:
13853       gcc_unreachable ();
13854     }
13855   return 0;
13856 }
13857
13858 /* Decide whether ARG can be unified with PARM, considering only the
13859    cv-qualifiers of each type, given STRICT as documented for unify.
13860    Returns nonzero iff the unification is OK on that basis.  */
13861
13862 static int
13863 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13864 {
13865   int arg_quals = cp_type_quals (arg);
13866   int parm_quals = cp_type_quals (parm);
13867
13868   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13869       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13870     {
13871       /*  Although a CVR qualifier is ignored when being applied to a
13872           substituted template parameter ([8.3.2]/1 for example), that
13873           does not apply during deduction [14.8.2.4]/1, (even though
13874           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13875           this).  Except when we're allowing additional CV qualifiers
13876           at the outer level [14.8.2.1]/3,1st bullet.  */
13877       if ((TREE_CODE (arg) == REFERENCE_TYPE
13878            || TREE_CODE (arg) == FUNCTION_TYPE
13879            || TREE_CODE (arg) == METHOD_TYPE)
13880           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13881         return 0;
13882
13883       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13884           && (parm_quals & TYPE_QUAL_RESTRICT))
13885         return 0;
13886     }
13887
13888   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13889       && (arg_quals & parm_quals) != parm_quals)
13890     return 0;
13891
13892   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13893       && (parm_quals & arg_quals) != arg_quals)
13894     return 0;
13895
13896   return 1;
13897 }
13898
13899 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13900 void 
13901 template_parm_level_and_index (tree parm, int* level, int* index)
13902 {
13903   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13904       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13905       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13906     {
13907       *index = TEMPLATE_TYPE_IDX (parm);
13908       *level = TEMPLATE_TYPE_LEVEL (parm);
13909     }
13910   else
13911     {
13912       *index = TEMPLATE_PARM_IDX (parm);
13913       *level = TEMPLATE_PARM_LEVEL (parm);
13914     }
13915 }
13916
13917 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13918    expansion at the end of PACKED_PARMS. Returns 0 if the type
13919    deduction succeeds, 1 otherwise. STRICT is the same as in
13920    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13921    call argument list. We'll need to adjust the arguments to make them
13922    types. SUBR tells us if this is from a recursive call to
13923    type_unification_real.  */
13924 int
13925 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13926                       tree packed_args, int strict, bool call_args_p,
13927                       bool subr)
13928 {
13929   tree parm 
13930     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13931   tree pattern = PACK_EXPANSION_PATTERN (parm);
13932   tree pack, packs = NULL_TREE;
13933   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13934   int len = TREE_VEC_LENGTH (packed_args);
13935
13936   /* Determine the parameter packs we will be deducing from the
13937      pattern, and record their current deductions.  */
13938   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13939        pack; pack = TREE_CHAIN (pack))
13940     {
13941       tree parm_pack = TREE_VALUE (pack);
13942       int idx, level;
13943
13944       /* Determine the index and level of this parameter pack.  */
13945       template_parm_level_and_index (parm_pack, &level, &idx);
13946
13947       /* Keep track of the parameter packs and their corresponding
13948          argument packs.  */
13949       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13950       TREE_TYPE (packs) = make_tree_vec (len - start);
13951     }
13952   
13953   /* Loop through all of the arguments that have not yet been
13954      unified and unify each with the pattern.  */
13955   for (i = start; i < len; i++)
13956     {
13957       tree parm = pattern;
13958
13959       /* For each parameter pack, clear out the deduced value so that
13960          we can deduce it again.  */
13961       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13962         {
13963           int idx, level;
13964           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13965
13966           TMPL_ARG (targs, level, idx) = NULL_TREE;
13967         }
13968
13969       /* Unify the pattern with the current argument.  */
13970       {
13971         tree arg = TREE_VEC_ELT (packed_args, i);
13972         tree arg_expr = NULL_TREE;
13973         int arg_strict = strict;
13974         bool skip_arg_p = false;
13975
13976         if (call_args_p)
13977           {
13978             int sub_strict;
13979
13980             /* This mirrors what we do in type_unification_real.  */
13981             switch (strict)
13982               {
13983               case DEDUCE_CALL:
13984                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13985                               | UNIFY_ALLOW_MORE_CV_QUAL
13986                               | UNIFY_ALLOW_DERIVED);
13987                 break;
13988                 
13989               case DEDUCE_CONV:
13990                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13991                 break;
13992                 
13993               case DEDUCE_EXACT:
13994                 sub_strict = UNIFY_ALLOW_NONE;
13995                 break;
13996                 
13997               default:
13998                 gcc_unreachable ();
13999               }
14000
14001             if (!TYPE_P (arg))
14002               {
14003                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14004                 if (type_unknown_p (arg))
14005                   {
14006                     /* [temp.deduct.type] A template-argument can be
14007                        deduced from a pointer to function or pointer
14008                        to member function argument if the set of
14009                        overloaded functions does not contain function
14010                        templates and at most one of a set of
14011                        overloaded functions provides a unique
14012                        match.  */
14013
14014                     if (resolve_overloaded_unification
14015                         (tparms, targs, parm, arg,
14016                          (unification_kind_t) strict,
14017                          sub_strict)
14018                         != 0)
14019                       return 1;
14020                     skip_arg_p = true;
14021                   }
14022
14023                 if (!skip_arg_p)
14024                   {
14025                     arg_expr = arg;
14026                     arg = unlowered_expr_type (arg);
14027                     if (arg == error_mark_node)
14028                       return 1;
14029                   }
14030               }
14031       
14032             arg_strict = sub_strict;
14033
14034             if (!subr)
14035               arg_strict |= 
14036                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14037                                                   &parm, &arg, arg_expr);
14038           }
14039
14040         if (!skip_arg_p)
14041           {
14042             if (unify (tparms, targs, parm, arg, arg_strict))
14043               return 1;
14044           }
14045       }
14046
14047       /* For each parameter pack, collect the deduced value.  */
14048       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14049         {
14050           int idx, level;
14051           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14052
14053           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14054             TMPL_ARG (targs, level, idx);
14055         }
14056     }
14057
14058   /* Verify that the results of unification with the parameter packs
14059      produce results consistent with what we've seen before, and make
14060      the deduced argument packs available.  */
14061   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14062     {
14063       tree old_pack = TREE_VALUE (pack);
14064       tree new_args = TREE_TYPE (pack);
14065       int i, len = TREE_VEC_LENGTH (new_args);
14066       bool nondeduced_p = false;
14067
14068       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14069          actually deduce anything.  */
14070       for (i = 0; i < len && !nondeduced_p; ++i)
14071         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14072           nondeduced_p = true;
14073       if (nondeduced_p)
14074         continue;
14075
14076       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14077         {
14078           /* Prepend the explicit arguments onto NEW_ARGS.  */
14079           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14080           tree old_args = new_args;
14081           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14082           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14083
14084           /* Copy the explicit arguments.  */
14085           new_args = make_tree_vec (len);
14086           for (i = 0; i < explicit_len; i++)
14087             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14088
14089           /* Copy the deduced arguments.  */
14090           for (; i < len; i++)
14091             TREE_VEC_ELT (new_args, i) =
14092               TREE_VEC_ELT (old_args, i - explicit_len);
14093         }
14094
14095       if (!old_pack)
14096         {
14097           tree result;
14098           int idx, level;
14099           
14100           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14101
14102           /* Build the deduced *_ARGUMENT_PACK.  */
14103           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14104             {
14105               result = make_node (NONTYPE_ARGUMENT_PACK);
14106               TREE_TYPE (result) = 
14107                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14108               TREE_CONSTANT (result) = 1;
14109             }
14110           else
14111             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14112
14113           SET_ARGUMENT_PACK_ARGS (result, new_args);
14114
14115           /* Note the deduced argument packs for this parameter
14116              pack.  */
14117           TMPL_ARG (targs, level, idx) = result;
14118         }
14119       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14120                && (ARGUMENT_PACK_ARGS (old_pack) 
14121                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14122         {
14123           /* We only had the explicitly-provided arguments before, but
14124              now we have a complete set of arguments.  */
14125           int idx, level;
14126           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14127           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14128
14129           /* Keep the original deduced argument pack.  */
14130           TMPL_ARG (targs, level, idx) = old_pack;
14131
14132           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14133           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14134           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14135         }
14136       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14137                                     new_args))
14138         /* Inconsistent unification of this parameter pack.  */
14139         return 1;
14140       else
14141         {
14142           int idx, level;
14143           
14144           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14145
14146           /* Keep the original deduced argument pack.  */
14147           TMPL_ARG (targs, level, idx) = old_pack;
14148         }
14149     }
14150
14151   return 0;
14152 }
14153
14154 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14155    set of template parameters to a template.  TARGS is the bindings
14156    for those template parameters, as determined thus far; TARGS may
14157    include template arguments for outer levels of template parameters
14158    as well.  PARM is a parameter to a template function, or a
14159    subcomponent of that parameter; ARG is the corresponding argument.
14160    This function attempts to match PARM with ARG in a manner
14161    consistent with the existing assignments in TARGS.  If more values
14162    are deduced, then TARGS is updated.
14163
14164    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14165    parameter STRICT is a bitwise or of the following flags:
14166
14167      UNIFY_ALLOW_NONE:
14168        Require an exact match between PARM and ARG.
14169      UNIFY_ALLOW_MORE_CV_QUAL:
14170        Allow the deduced ARG to be more cv-qualified (by qualification
14171        conversion) than ARG.
14172      UNIFY_ALLOW_LESS_CV_QUAL:
14173        Allow the deduced ARG to be less cv-qualified than ARG.
14174      UNIFY_ALLOW_DERIVED:
14175        Allow the deduced ARG to be a template base class of ARG,
14176        or a pointer to a template base class of the type pointed to by
14177        ARG.
14178      UNIFY_ALLOW_INTEGER:
14179        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14180        case for more information.
14181      UNIFY_ALLOW_OUTER_LEVEL:
14182        This is the outermost level of a deduction. Used to determine validity
14183        of qualification conversions. A valid qualification conversion must
14184        have const qualified pointers leading up to the inner type which
14185        requires additional CV quals, except at the outer level, where const
14186        is not required [conv.qual]. It would be normal to set this flag in
14187        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14188      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14189        This is the outermost level of a deduction, and PARM can be more CV
14190        qualified at this point.
14191      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14192        This is the outermost level of a deduction, and PARM can be less CV
14193        qualified at this point.  */
14194
14195 static int
14196 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14197 {
14198   int idx;
14199   tree targ;
14200   tree tparm;
14201   int strict_in = strict;
14202
14203   /* I don't think this will do the right thing with respect to types.
14204      But the only case I've seen it in so far has been array bounds, where
14205      signedness is the only information lost, and I think that will be
14206      okay.  */
14207   while (TREE_CODE (parm) == NOP_EXPR)
14208     parm = TREE_OPERAND (parm, 0);
14209
14210   if (arg == error_mark_node)
14211     return 1;
14212   if (arg == unknown_type_node
14213       || arg == init_list_type_node)
14214     /* We can't deduce anything from this, but we might get all the
14215        template args from other function args.  */
14216     return 0;
14217
14218   /* If PARM uses template parameters, then we can't bail out here,
14219      even if ARG == PARM, since we won't record unifications for the
14220      template parameters.  We might need them if we're trying to
14221      figure out which of two things is more specialized.  */
14222   if (arg == parm && !uses_template_parms (parm))
14223     return 0;
14224
14225   /* Handle init lists early, so the rest of the function can assume
14226      we're dealing with a type. */
14227   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14228     {
14229       tree elt, elttype;
14230       unsigned i;
14231       tree orig_parm = parm;
14232
14233       /* Replace T with std::initializer_list<T> for deduction.  */
14234       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14235           && flag_deduce_init_list)
14236         parm = listify (parm);
14237
14238       if (!is_std_init_list (parm))
14239         /* We can only deduce from an initializer list argument if the
14240            parameter is std::initializer_list; otherwise this is a
14241            non-deduced context. */
14242         return 0;
14243
14244       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14245
14246       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14247         {
14248           int elt_strict = strict;
14249           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14250             {
14251               tree type = TREE_TYPE (elt);
14252               /* It should only be possible to get here for a call.  */
14253               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14254               elt_strict |= maybe_adjust_types_for_deduction
14255                 (DEDUCE_CALL, &elttype, &type, elt);
14256               elt = type;
14257             }
14258
14259           if (unify (tparms, targs, elttype, elt, elt_strict))
14260             return 1;
14261         }
14262
14263       /* If the std::initializer_list<T> deduction worked, replace the
14264          deduced A with std::initializer_list<A>.  */
14265       if (orig_parm != parm)
14266         {
14267           idx = TEMPLATE_TYPE_IDX (orig_parm);
14268           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14269           targ = listify (targ);
14270           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14271         }
14272       return 0;
14273     }
14274
14275   /* Immediately reject some pairs that won't unify because of
14276      cv-qualification mismatches.  */
14277   if (TREE_CODE (arg) == TREE_CODE (parm)
14278       && TYPE_P (arg)
14279       /* It is the elements of the array which hold the cv quals of an array
14280          type, and the elements might be template type parms. We'll check
14281          when we recurse.  */
14282       && TREE_CODE (arg) != ARRAY_TYPE
14283       /* We check the cv-qualifiers when unifying with template type
14284          parameters below.  We want to allow ARG `const T' to unify with
14285          PARM `T' for example, when computing which of two templates
14286          is more specialized, for example.  */
14287       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14288       && !check_cv_quals_for_unify (strict_in, arg, parm))
14289     return 1;
14290
14291   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14292       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14293     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14294   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14295   strict &= ~UNIFY_ALLOW_DERIVED;
14296   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14297   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14298
14299   switch (TREE_CODE (parm))
14300     {
14301     case TYPENAME_TYPE:
14302     case SCOPE_REF:
14303     case UNBOUND_CLASS_TEMPLATE:
14304       /* In a type which contains a nested-name-specifier, template
14305          argument values cannot be deduced for template parameters used
14306          within the nested-name-specifier.  */
14307       return 0;
14308
14309     case TEMPLATE_TYPE_PARM:
14310     case TEMPLATE_TEMPLATE_PARM:
14311     case BOUND_TEMPLATE_TEMPLATE_PARM:
14312       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14313       if (tparm == error_mark_node)
14314         return 1;
14315
14316       if (TEMPLATE_TYPE_LEVEL (parm)
14317           != template_decl_level (tparm))
14318         /* The PARM is not one we're trying to unify.  Just check
14319            to see if it matches ARG.  */
14320         return (TREE_CODE (arg) == TREE_CODE (parm)
14321                 && same_type_p (parm, arg)) ? 0 : 1;
14322       idx = TEMPLATE_TYPE_IDX (parm);
14323       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14324       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14325
14326       /* Check for mixed types and values.  */
14327       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14328            && TREE_CODE (tparm) != TYPE_DECL)
14329           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14330               && TREE_CODE (tparm) != TEMPLATE_DECL))
14331         return 1;
14332
14333       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14334         {
14335           /* ARG must be constructed from a template class or a template
14336              template parameter.  */
14337           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14338               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14339             return 1;
14340
14341           {
14342             tree parmvec = TYPE_TI_ARGS (parm);
14343             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14344             tree parm_parms 
14345               = DECL_INNERMOST_TEMPLATE_PARMS
14346                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14347             int i, len;
14348             int parm_variadic_p = 0;
14349
14350             /* The resolution to DR150 makes clear that default
14351                arguments for an N-argument may not be used to bind T
14352                to a template template parameter with fewer than N
14353                parameters.  It is not safe to permit the binding of
14354                default arguments as an extension, as that may change
14355                the meaning of a conforming program.  Consider:
14356
14357                   struct Dense { static const unsigned int dim = 1; };
14358
14359                   template <template <typename> class View,
14360                             typename Block>
14361                   void operator+(float, View<Block> const&);
14362
14363                   template <typename Block,
14364                             unsigned int Dim = Block::dim>
14365                   struct Lvalue_proxy { operator float() const; };
14366
14367                   void
14368                   test_1d (void) {
14369                     Lvalue_proxy<Dense> p;
14370                     float b;
14371                     b + p;
14372                   }
14373
14374               Here, if Lvalue_proxy is permitted to bind to View, then
14375               the global operator+ will be used; if they are not, the
14376               Lvalue_proxy will be converted to float.  */
14377             if (coerce_template_parms (parm_parms,
14378                                        argvec,
14379                                        TYPE_TI_TEMPLATE (parm),
14380                                        tf_none,
14381                                        /*require_all_args=*/true,
14382                                        /*use_default_args=*/false)
14383                 == error_mark_node)
14384               return 1;
14385
14386             /* Deduce arguments T, i from TT<T> or TT<i>.
14387                We check each element of PARMVEC and ARGVEC individually
14388                rather than the whole TREE_VEC since they can have
14389                different number of elements.  */
14390
14391             parmvec = expand_template_argument_pack (parmvec);
14392             argvec = expand_template_argument_pack (argvec);
14393
14394             len = TREE_VEC_LENGTH (parmvec);
14395
14396             /* Check if the parameters end in a pack, making them
14397                variadic.  */
14398             if (len > 0
14399                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14400               parm_variadic_p = 1;
14401             
14402             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14403               return 1;
14404
14405              for (i = 0; i < len - parm_variadic_p; ++i)
14406               {
14407                 if (unify (tparms, targs,
14408                            TREE_VEC_ELT (parmvec, i),
14409                            TREE_VEC_ELT (argvec, i),
14410                            UNIFY_ALLOW_NONE))
14411                   return 1;
14412               }
14413
14414             if (parm_variadic_p
14415                 && unify_pack_expansion (tparms, targs,
14416                                          parmvec, argvec,
14417                                          UNIFY_ALLOW_NONE,
14418                                          /*call_args_p=*/false,
14419                                          /*subr=*/false))
14420               return 1;
14421           }
14422           arg = TYPE_TI_TEMPLATE (arg);
14423
14424           /* Fall through to deduce template name.  */
14425         }
14426
14427       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14428           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14429         {
14430           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14431
14432           /* Simple cases: Value already set, does match or doesn't.  */
14433           if (targ != NULL_TREE && template_args_equal (targ, arg))
14434             return 0;
14435           else if (targ)
14436             return 1;
14437         }
14438       else
14439         {
14440           /* If PARM is `const T' and ARG is only `int', we don't have
14441              a match unless we are allowing additional qualification.
14442              If ARG is `const int' and PARM is just `T' that's OK;
14443              that binds `const int' to `T'.  */
14444           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14445                                          arg, parm))
14446             return 1;
14447
14448           /* Consider the case where ARG is `const volatile int' and
14449              PARM is `const T'.  Then, T should be `volatile int'.  */
14450           arg = cp_build_qualified_type_real
14451             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14452           if (arg == error_mark_node)
14453             return 1;
14454
14455           /* Simple cases: Value already set, does match or doesn't.  */
14456           if (targ != NULL_TREE && same_type_p (targ, arg))
14457             return 0;
14458           else if (targ)
14459             return 1;
14460
14461           /* Make sure that ARG is not a variable-sized array.  (Note
14462              that were talking about variable-sized arrays (like
14463              `int[n]'), rather than arrays of unknown size (like
14464              `int[]').)  We'll get very confused by such a type since
14465              the bound of the array will not be computable in an
14466              instantiation.  Besides, such types are not allowed in
14467              ISO C++, so we can do as we please here.  */
14468           if (variably_modified_type_p (arg, NULL_TREE))
14469             return 1;
14470
14471           /* Strip typedefs as in convert_template_argument.  */
14472           arg = strip_typedefs (arg);
14473         }
14474
14475       /* If ARG is a parameter pack or an expansion, we cannot unify
14476          against it unless PARM is also a parameter pack.  */
14477       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14478           && !template_parameter_pack_p (parm))
14479         return 1;
14480
14481       /* If the argument deduction results is a METHOD_TYPE,
14482          then there is a problem.
14483          METHOD_TYPE doesn't map to any real C++ type the result of
14484          the deduction can not be of that type.  */
14485       if (TREE_CODE (arg) == METHOD_TYPE)
14486         return 1;
14487
14488       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14489       return 0;
14490
14491     case TEMPLATE_PARM_INDEX:
14492       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14493       if (tparm == error_mark_node)
14494         return 1;
14495
14496       if (TEMPLATE_PARM_LEVEL (parm)
14497           != template_decl_level (tparm))
14498         /* The PARM is not one we're trying to unify.  Just check
14499            to see if it matches ARG.  */
14500         return !(TREE_CODE (arg) == TREE_CODE (parm)
14501                  && cp_tree_equal (parm, arg));
14502
14503       idx = TEMPLATE_PARM_IDX (parm);
14504       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14505
14506       if (targ)
14507         return !cp_tree_equal (targ, arg);
14508
14509       /* [temp.deduct.type] If, in the declaration of a function template
14510          with a non-type template-parameter, the non-type
14511          template-parameter is used in an expression in the function
14512          parameter-list and, if the corresponding template-argument is
14513          deduced, the template-argument type shall match the type of the
14514          template-parameter exactly, except that a template-argument
14515          deduced from an array bound may be of any integral type.
14516          The non-type parameter might use already deduced type parameters.  */
14517       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14518       if (!TREE_TYPE (arg))
14519         /* Template-parameter dependent expression.  Just accept it for now.
14520            It will later be processed in convert_template_argument.  */
14521         ;
14522       else if (same_type_p (TREE_TYPE (arg), tparm))
14523         /* OK */;
14524       else if ((strict & UNIFY_ALLOW_INTEGER)
14525                && (TREE_CODE (tparm) == INTEGER_TYPE
14526                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14527         /* Convert the ARG to the type of PARM; the deduced non-type
14528            template argument must exactly match the types of the
14529            corresponding parameter.  */
14530         arg = fold (build_nop (tparm, arg));
14531       else if (uses_template_parms (tparm))
14532         /* We haven't deduced the type of this parameter yet.  Try again
14533            later.  */
14534         return 0;
14535       else
14536         return 1;
14537
14538       /* If ARG is a parameter pack or an expansion, we cannot unify
14539          against it unless PARM is also a parameter pack.  */
14540       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14541           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14542         return 1;
14543
14544       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14545       return 0;
14546
14547     case PTRMEM_CST:
14548      {
14549         /* A pointer-to-member constant can be unified only with
14550          another constant.  */
14551       if (TREE_CODE (arg) != PTRMEM_CST)
14552         return 1;
14553
14554       /* Just unify the class member. It would be useless (and possibly
14555          wrong, depending on the strict flags) to unify also
14556          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14557          arg refer to the same variable, even if through different
14558          classes. For instance:
14559
14560          struct A { int x; };
14561          struct B : A { };
14562
14563          Unification of &A::x and &B::x must succeed.  */
14564       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14565                     PTRMEM_CST_MEMBER (arg), strict);
14566      }
14567
14568     case POINTER_TYPE:
14569       {
14570         if (TREE_CODE (arg) != POINTER_TYPE)
14571           return 1;
14572
14573         /* [temp.deduct.call]
14574
14575            A can be another pointer or pointer to member type that can
14576            be converted to the deduced A via a qualification
14577            conversion (_conv.qual_).
14578
14579            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14580            This will allow for additional cv-qualification of the
14581            pointed-to types if appropriate.  */
14582
14583         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14584           /* The derived-to-base conversion only persists through one
14585              level of pointers.  */
14586           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14587
14588         return unify (tparms, targs, TREE_TYPE (parm),
14589                       TREE_TYPE (arg), strict);
14590       }
14591
14592     case REFERENCE_TYPE:
14593       if (TREE_CODE (arg) != REFERENCE_TYPE)
14594         return 1;
14595       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14596                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14597
14598     case ARRAY_TYPE:
14599       if (TREE_CODE (arg) != ARRAY_TYPE)
14600         return 1;
14601       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14602           != (TYPE_DOMAIN (arg) == NULL_TREE))
14603         return 1;
14604       if (TYPE_DOMAIN (parm) != NULL_TREE)
14605         {
14606           tree parm_max;
14607           tree arg_max;
14608           bool parm_cst;
14609           bool arg_cst;
14610
14611           /* Our representation of array types uses "N - 1" as the
14612              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14613              not an integer constant.  We cannot unify arbitrarily
14614              complex expressions, so we eliminate the MINUS_EXPRs
14615              here.  */
14616           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14617           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14618           if (!parm_cst)
14619             {
14620               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14621               parm_max = TREE_OPERAND (parm_max, 0);
14622             }
14623           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14624           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14625           if (!arg_cst)
14626             {
14627               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14628                  trying to unify the type of a variable with the type
14629                  of a template parameter.  For example:
14630
14631                    template <unsigned int N>
14632                    void f (char (&) [N]);
14633                    int g(); 
14634                    void h(int i) {
14635                      char a[g(i)];
14636                      f(a); 
14637                    }
14638
14639                 Here, the type of the ARG will be "int [g(i)]", and
14640                 may be a SAVE_EXPR, etc.  */
14641               if (TREE_CODE (arg_max) != MINUS_EXPR)
14642                 return 1;
14643               arg_max = TREE_OPERAND (arg_max, 0);
14644             }
14645
14646           /* If only one of the bounds used a MINUS_EXPR, compensate
14647              by adding one to the other bound.  */
14648           if (parm_cst && !arg_cst)
14649             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14650                                     integer_type_node,
14651                                     parm_max,
14652                                     integer_one_node);
14653           else if (arg_cst && !parm_cst)
14654             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14655                                    integer_type_node,
14656                                    arg_max,
14657                                    integer_one_node);
14658
14659           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14660             return 1;
14661         }
14662       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14663                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14664
14665     case REAL_TYPE:
14666     case COMPLEX_TYPE:
14667     case VECTOR_TYPE:
14668     case INTEGER_TYPE:
14669     case BOOLEAN_TYPE:
14670     case ENUMERAL_TYPE:
14671     case VOID_TYPE:
14672       if (TREE_CODE (arg) != TREE_CODE (parm))
14673         return 1;
14674
14675       /* We have already checked cv-qualification at the top of the
14676          function.  */
14677       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14678         return 1;
14679
14680       /* As far as unification is concerned, this wins.  Later checks
14681          will invalidate it if necessary.  */
14682       return 0;
14683
14684       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14685       /* Type INTEGER_CST can come from ordinary constant template args.  */
14686     case INTEGER_CST:
14687       while (TREE_CODE (arg) == NOP_EXPR)
14688         arg = TREE_OPERAND (arg, 0);
14689
14690       if (TREE_CODE (arg) != INTEGER_CST)
14691         return 1;
14692       return !tree_int_cst_equal (parm, arg);
14693
14694     case TREE_VEC:
14695       {
14696         int i;
14697         if (TREE_CODE (arg) != TREE_VEC)
14698           return 1;
14699         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14700           return 1;
14701         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14702           if (unify (tparms, targs,
14703                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14704                      UNIFY_ALLOW_NONE))
14705             return 1;
14706         return 0;
14707       }
14708
14709     case RECORD_TYPE:
14710     case UNION_TYPE:
14711       if (TREE_CODE (arg) != TREE_CODE (parm))
14712         return 1;
14713
14714       if (TYPE_PTRMEMFUNC_P (parm))
14715         {
14716           if (!TYPE_PTRMEMFUNC_P (arg))
14717             return 1;
14718
14719           return unify (tparms, targs,
14720                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14721                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14722                         strict);
14723         }
14724
14725       if (CLASSTYPE_TEMPLATE_INFO (parm))
14726         {
14727           tree t = NULL_TREE;
14728
14729           if (strict_in & UNIFY_ALLOW_DERIVED)
14730             {
14731               /* First, we try to unify the PARM and ARG directly.  */
14732               t = try_class_unification (tparms, targs,
14733                                          parm, arg);
14734
14735               if (!t)
14736                 {
14737                   /* Fallback to the special case allowed in
14738                      [temp.deduct.call]:
14739
14740                        If P is a class, and P has the form
14741                        template-id, then A can be a derived class of
14742                        the deduced A.  Likewise, if P is a pointer to
14743                        a class of the form template-id, A can be a
14744                        pointer to a derived class pointed to by the
14745                        deduced A.  */
14746                   t = get_template_base (tparms, targs, parm, arg);
14747
14748                   if (!t)
14749                     return 1;
14750                 }
14751             }
14752           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14753                    && (CLASSTYPE_TI_TEMPLATE (parm)
14754                        == CLASSTYPE_TI_TEMPLATE (arg)))
14755             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14756                Then, we should unify `int' and `U'.  */
14757             t = arg;
14758           else
14759             /* There's no chance of unification succeeding.  */
14760             return 1;
14761
14762           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14763                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14764         }
14765       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14766         return 1;
14767       return 0;
14768
14769     case METHOD_TYPE:
14770     case FUNCTION_TYPE:
14771       {
14772         unsigned int nargs;
14773         tree *args;
14774         tree a;
14775         unsigned int i;
14776
14777         if (TREE_CODE (arg) != TREE_CODE (parm))
14778           return 1;
14779
14780         /* CV qualifications for methods can never be deduced, they must
14781            match exactly.  We need to check them explicitly here,
14782            because type_unification_real treats them as any other
14783            cv-qualified parameter.  */
14784         if (TREE_CODE (parm) == METHOD_TYPE
14785             && (!check_cv_quals_for_unify
14786                 (UNIFY_ALLOW_NONE,
14787                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14788                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14789           return 1;
14790
14791         if (unify (tparms, targs, TREE_TYPE (parm),
14792                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14793           return 1;
14794
14795         nargs = list_length (TYPE_ARG_TYPES (arg));
14796         args = XALLOCAVEC (tree, nargs);
14797         for (a = TYPE_ARG_TYPES (arg), i = 0;
14798              a != NULL_TREE && a != void_list_node;
14799              a = TREE_CHAIN (a), ++i)
14800           args[i] = TREE_VALUE (a);
14801         nargs = i;
14802
14803         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14804                                       args, nargs, 1, DEDUCE_EXACT,
14805                                       LOOKUP_NORMAL);
14806       }
14807
14808     case OFFSET_TYPE:
14809       /* Unify a pointer to member with a pointer to member function, which
14810          deduces the type of the member as a function type. */
14811       if (TYPE_PTRMEMFUNC_P (arg))
14812         {
14813           tree method_type;
14814           tree fntype;
14815           cp_cv_quals cv_quals;
14816
14817           /* Check top-level cv qualifiers */
14818           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14819             return 1;
14820
14821           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14822                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14823             return 1;
14824
14825           /* Determine the type of the function we are unifying against. */
14826           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14827           fntype =
14828             build_function_type (TREE_TYPE (method_type),
14829                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14830
14831           /* Extract the cv-qualifiers of the member function from the
14832              implicit object parameter and place them on the function
14833              type to be restored later. */
14834           cv_quals =
14835             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14836           fntype = build_qualified_type (fntype, cv_quals);
14837           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14838         }
14839
14840       if (TREE_CODE (arg) != OFFSET_TYPE)
14841         return 1;
14842       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14843                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14844         return 1;
14845       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14846                     strict);
14847
14848     case CONST_DECL:
14849       if (DECL_TEMPLATE_PARM_P (parm))
14850         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14851       if (arg != integral_constant_value (parm))
14852         return 1;
14853       return 0;
14854
14855     case FIELD_DECL:
14856     case TEMPLATE_DECL:
14857       /* Matched cases are handled by the ARG == PARM test above.  */
14858       return 1;
14859
14860     case TYPE_ARGUMENT_PACK:
14861     case NONTYPE_ARGUMENT_PACK:
14862       {
14863         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14864         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14865         int i, len = TREE_VEC_LENGTH (packed_parms);
14866         int argslen = TREE_VEC_LENGTH (packed_args);
14867         int parm_variadic_p = 0;
14868
14869         for (i = 0; i < len; ++i)
14870           {
14871             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14872               {
14873                 if (i == len - 1)
14874                   /* We can unify against something with a trailing
14875                      parameter pack.  */
14876                   parm_variadic_p = 1;
14877                 else
14878                   /* Since there is something following the pack
14879                      expansion, we cannot unify this template argument
14880                      list.  */
14881                   return 0;
14882               }
14883           }
14884           
14885
14886         /* If we don't have enough arguments to satisfy the parameters
14887            (not counting the pack expression at the end), or we have
14888            too many arguments for a parameter list that doesn't end in
14889            a pack expression, we can't unify.  */
14890         if (argslen < (len - parm_variadic_p)
14891             || (argslen > len && !parm_variadic_p))
14892           return 1;
14893
14894         /* Unify all of the parameters that precede the (optional)
14895            pack expression.  */
14896         for (i = 0; i < len - parm_variadic_p; ++i)
14897           {
14898             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14899                        TREE_VEC_ELT (packed_args, i), strict))
14900               return 1;
14901           }
14902
14903         if (parm_variadic_p)
14904           return unify_pack_expansion (tparms, targs, 
14905                                        packed_parms, packed_args,
14906                                        strict, /*call_args_p=*/false,
14907                                        /*subr=*/false);
14908         return 0;
14909       }
14910
14911       break;
14912
14913     case TYPEOF_TYPE:
14914     case DECLTYPE_TYPE:
14915       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14916          nodes.  */
14917       return 0;
14918
14919     case ERROR_MARK:
14920       /* Unification fails if we hit an error node.  */
14921       return 1;
14922
14923     default:
14924       gcc_assert (EXPR_P (parm));
14925
14926       /* We must be looking at an expression.  This can happen with
14927          something like:
14928
14929            template <int I>
14930            void foo(S<I>, S<I + 2>);
14931
14932          This is a "nondeduced context":
14933
14934            [deduct.type]
14935
14936            The nondeduced contexts are:
14937
14938            --A type that is a template-id in which one or more of
14939              the template-arguments is an expression that references
14940              a template-parameter.
14941
14942          In these cases, we assume deduction succeeded, but don't
14943          actually infer any unifications.  */
14944
14945       if (!uses_template_parms (parm)
14946           && !template_args_equal (parm, arg))
14947         return 1;
14948       else
14949         return 0;
14950     }
14951 }
14952 \f
14953 /* Note that DECL can be defined in this translation unit, if
14954    required.  */
14955
14956 static void
14957 mark_definable (tree decl)
14958 {
14959   tree clone;
14960   DECL_NOT_REALLY_EXTERN (decl) = 1;
14961   FOR_EACH_CLONE (clone, decl)
14962     DECL_NOT_REALLY_EXTERN (clone) = 1;
14963 }
14964
14965 /* Called if RESULT is explicitly instantiated, or is a member of an
14966    explicitly instantiated class.  */
14967
14968 void
14969 mark_decl_instantiated (tree result, int extern_p)
14970 {
14971   SET_DECL_EXPLICIT_INSTANTIATION (result);
14972
14973   /* If this entity has already been written out, it's too late to
14974      make any modifications.  */
14975   if (TREE_ASM_WRITTEN (result))
14976     return;
14977
14978   if (TREE_CODE (result) != FUNCTION_DECL)
14979     /* The TREE_PUBLIC flag for function declarations will have been
14980        set correctly by tsubst.  */
14981     TREE_PUBLIC (result) = 1;
14982
14983   /* This might have been set by an earlier implicit instantiation.  */
14984   DECL_COMDAT (result) = 0;
14985
14986   if (extern_p)
14987     DECL_NOT_REALLY_EXTERN (result) = 0;
14988   else
14989     {
14990       mark_definable (result);
14991       /* Always make artificials weak.  */
14992       if (DECL_ARTIFICIAL (result) && flag_weak)
14993         comdat_linkage (result);
14994       /* For WIN32 we also want to put explicit instantiations in
14995          linkonce sections.  */
14996       else if (TREE_PUBLIC (result))
14997         maybe_make_one_only (result);
14998     }
14999
15000   /* If EXTERN_P, then this function will not be emitted -- unless
15001      followed by an explicit instantiation, at which point its linkage
15002      will be adjusted.  If !EXTERN_P, then this function will be
15003      emitted here.  In neither circumstance do we want
15004      import_export_decl to adjust the linkage.  */
15005   DECL_INTERFACE_KNOWN (result) = 1;
15006 }
15007
15008 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15009    important template arguments.  If any are missing, we check whether
15010    they're important by using error_mark_node for substituting into any
15011    args that were used for partial ordering (the ones between ARGS and END)
15012    and seeing if it bubbles up.  */
15013
15014 static bool
15015 check_undeduced_parms (tree targs, tree args, tree end)
15016 {
15017   bool found = false;
15018   int i;
15019   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15020     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15021       {
15022         found = true;
15023         TREE_VEC_ELT (targs, i) = error_mark_node;
15024       }
15025   if (found)
15026     {
15027       for (; args != end; args = TREE_CHAIN (args))
15028         {
15029           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15030           if (substed == error_mark_node)
15031             return true;
15032         }
15033     }
15034   return false;
15035 }
15036
15037 /* Given two function templates PAT1 and PAT2, return:
15038
15039    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15040    -1 if PAT2 is more specialized than PAT1.
15041    0 if neither is more specialized.
15042
15043    LEN indicates the number of parameters we should consider
15044    (defaulted parameters should not be considered).
15045
15046    The 1998 std underspecified function template partial ordering, and
15047    DR214 addresses the issue.  We take pairs of arguments, one from
15048    each of the templates, and deduce them against each other.  One of
15049    the templates will be more specialized if all the *other*
15050    template's arguments deduce against its arguments and at least one
15051    of its arguments *does* *not* deduce against the other template's
15052    corresponding argument.  Deduction is done as for class templates.
15053    The arguments used in deduction have reference and top level cv
15054    qualifiers removed.  Iff both arguments were originally reference
15055    types *and* deduction succeeds in both directions, the template
15056    with the more cv-qualified argument wins for that pairing (if
15057    neither is more cv-qualified, they both are equal).  Unlike regular
15058    deduction, after all the arguments have been deduced in this way,
15059    we do *not* verify the deduced template argument values can be
15060    substituted into non-deduced contexts.
15061
15062    The logic can be a bit confusing here, because we look at deduce1 and
15063    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15064    can find template arguments for pat1 to make arg1 look like arg2, that
15065    means that arg2 is at least as specialized as arg1.  */
15066
15067 int
15068 more_specialized_fn (tree pat1, tree pat2, int len)
15069 {
15070   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15071   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15072   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15073   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15074   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15075   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15076   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15077   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15078   tree origs1, origs2;
15079   bool lose1 = false;
15080   bool lose2 = false;
15081
15082   /* Remove the this parameter from non-static member functions.  If
15083      one is a non-static member function and the other is not a static
15084      member function, remove the first parameter from that function
15085      also.  This situation occurs for operator functions where we
15086      locate both a member function (with this pointer) and non-member
15087      operator (with explicit first operand).  */
15088   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15089     {
15090       len--; /* LEN is the number of significant arguments for DECL1 */
15091       args1 = TREE_CHAIN (args1);
15092       if (!DECL_STATIC_FUNCTION_P (decl2))
15093         args2 = TREE_CHAIN (args2);
15094     }
15095   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15096     {
15097       args2 = TREE_CHAIN (args2);
15098       if (!DECL_STATIC_FUNCTION_P (decl1))
15099         {
15100           len--;
15101           args1 = TREE_CHAIN (args1);
15102         }
15103     }
15104
15105   /* If only one is a conversion operator, they are unordered.  */
15106   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15107     return 0;
15108
15109   /* Consider the return type for a conversion function */
15110   if (DECL_CONV_FN_P (decl1))
15111     {
15112       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15113       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15114       len++;
15115     }
15116
15117   processing_template_decl++;
15118
15119   origs1 = args1;
15120   origs2 = args2;
15121
15122   while (len--
15123          /* Stop when an ellipsis is seen.  */
15124          && args1 != NULL_TREE && args2 != NULL_TREE)
15125     {
15126       tree arg1 = TREE_VALUE (args1);
15127       tree arg2 = TREE_VALUE (args2);
15128       int deduce1, deduce2;
15129       int quals1 = -1;
15130       int quals2 = -1;
15131
15132       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15133           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15134         {
15135           /* When both arguments are pack expansions, we need only
15136              unify the patterns themselves.  */
15137           arg1 = PACK_EXPANSION_PATTERN (arg1);
15138           arg2 = PACK_EXPANSION_PATTERN (arg2);
15139
15140           /* This is the last comparison we need to do.  */
15141           len = 0;
15142         }
15143
15144       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15145         {
15146           arg1 = TREE_TYPE (arg1);
15147           quals1 = cp_type_quals (arg1);
15148         }
15149
15150       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15151         {
15152           arg2 = TREE_TYPE (arg2);
15153           quals2 = cp_type_quals (arg2);
15154         }
15155
15156       if ((quals1 < 0) != (quals2 < 0))
15157         {
15158           /* Only of the args is a reference, see if we should apply
15159              array/function pointer decay to it.  This is not part of
15160              DR214, but is, IMHO, consistent with the deduction rules
15161              for the function call itself, and with our earlier
15162              implementation of the underspecified partial ordering
15163              rules.  (nathan).  */
15164           if (quals1 >= 0)
15165             {
15166               switch (TREE_CODE (arg1))
15167                 {
15168                 case ARRAY_TYPE:
15169                   arg1 = TREE_TYPE (arg1);
15170                   /* FALLTHROUGH. */
15171                 case FUNCTION_TYPE:
15172                   arg1 = build_pointer_type (arg1);
15173                   break;
15174
15175                 default:
15176                   break;
15177                 }
15178             }
15179           else
15180             {
15181               switch (TREE_CODE (arg2))
15182                 {
15183                 case ARRAY_TYPE:
15184                   arg2 = TREE_TYPE (arg2);
15185                   /* FALLTHROUGH. */
15186                 case FUNCTION_TYPE:
15187                   arg2 = build_pointer_type (arg2);
15188                   break;
15189
15190                 default:
15191                   break;
15192                 }
15193             }
15194         }
15195
15196       arg1 = TYPE_MAIN_VARIANT (arg1);
15197       arg2 = TYPE_MAIN_VARIANT (arg2);
15198
15199       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15200         {
15201           int i, len2 = list_length (args2);
15202           tree parmvec = make_tree_vec (1);
15203           tree argvec = make_tree_vec (len2);
15204           tree ta = args2;
15205
15206           /* Setup the parameter vector, which contains only ARG1.  */
15207           TREE_VEC_ELT (parmvec, 0) = arg1;
15208
15209           /* Setup the argument vector, which contains the remaining
15210              arguments.  */
15211           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15212             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15213
15214           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15215                                            argvec, UNIFY_ALLOW_NONE, 
15216                                            /*call_args_p=*/false, 
15217                                            /*subr=*/0);
15218
15219           /* We cannot deduce in the other direction, because ARG1 is
15220              a pack expansion but ARG2 is not.  */
15221           deduce2 = 0;
15222         }
15223       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15224         {
15225           int i, len1 = list_length (args1);
15226           tree parmvec = make_tree_vec (1);
15227           tree argvec = make_tree_vec (len1);
15228           tree ta = args1;
15229
15230           /* Setup the parameter vector, which contains only ARG1.  */
15231           TREE_VEC_ELT (parmvec, 0) = arg2;
15232
15233           /* Setup the argument vector, which contains the remaining
15234              arguments.  */
15235           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15236             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15237
15238           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15239                                            argvec, UNIFY_ALLOW_NONE, 
15240                                            /*call_args_p=*/false, 
15241                                            /*subr=*/0);
15242
15243           /* We cannot deduce in the other direction, because ARG2 is
15244              a pack expansion but ARG1 is not.*/
15245           deduce1 = 0;
15246         }
15247
15248       else
15249         {
15250           /* The normal case, where neither argument is a pack
15251              expansion.  */
15252           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15253           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15254         }
15255
15256       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15257          arg2, then arg2 is not as specialized as arg1.  */
15258       if (!deduce1)
15259         lose2 = true;
15260       if (!deduce2)
15261         lose1 = true;
15262
15263       /* "If, for a given type, deduction succeeds in both directions
15264          (i.e., the types are identical after the transformations above)
15265          and if the type from the argument template is more cv-qualified
15266          than the type from the parameter template (as described above)
15267          that type is considered to be more specialized than the other. If
15268          neither type is more cv-qualified than the other then neither type
15269          is more specialized than the other."
15270
15271          We check same_type_p explicitly because deduction can also succeed
15272          in both directions when there is a nondeduced context.  */
15273       if (deduce1 && deduce2
15274           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15275           && same_type_p (arg1, arg2))
15276         {
15277           if ((quals1 & quals2) == quals2)
15278             lose2 = true;
15279           if ((quals1 & quals2) == quals1)
15280             lose1 = true;
15281         }
15282
15283       if (lose1 && lose2)
15284         /* We've failed to deduce something in either direction.
15285            These must be unordered.  */
15286         break;
15287
15288       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15289           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15290         /* We have already processed all of the arguments in our
15291            handing of the pack expansion type.  */
15292         len = 0;
15293
15294       args1 = TREE_CHAIN (args1);
15295       args2 = TREE_CHAIN (args2);
15296     }
15297
15298   /* "In most cases, all template parameters must have values in order for
15299      deduction to succeed, but for partial ordering purposes a template
15300      parameter may remain without a value provided it is not used in the
15301      types being used for partial ordering."
15302
15303      Thus, if we are missing any of the targs1 we need to substitute into
15304      origs1, then pat2 is not as specialized as pat1.  This can happen when
15305      there is a nondeduced context.  */
15306   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15307     lose2 = true;
15308   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15309     lose1 = true;
15310
15311   processing_template_decl--;
15312
15313   /* All things being equal, if the next argument is a pack expansion
15314      for one function but not for the other, prefer the
15315      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15316   if (lose1 == lose2
15317       && args1 && TREE_VALUE (args1)
15318       && args2 && TREE_VALUE (args2))
15319     {
15320       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15321       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15322     }
15323
15324   if (lose1 == lose2)
15325     return 0;
15326   else if (!lose1)
15327     return 1;
15328   else
15329     return -1;
15330 }
15331
15332 /* Determine which of two partial specializations is more specialized.
15333
15334    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15335    to the first partial specialization.  The TREE_VALUE is the
15336    innermost set of template parameters for the partial
15337    specialization.  PAT2 is similar, but for the second template.
15338
15339    Return 1 if the first partial specialization is more specialized;
15340    -1 if the second is more specialized; 0 if neither is more
15341    specialized.
15342
15343    See [temp.class.order] for information about determining which of
15344    two templates is more specialized.  */
15345
15346 static int
15347 more_specialized_class (tree pat1, tree pat2)
15348 {
15349   tree targs;
15350   tree tmpl1, tmpl2;
15351   int winner = 0;
15352   bool any_deductions = false;
15353
15354   tmpl1 = TREE_TYPE (pat1);
15355   tmpl2 = TREE_TYPE (pat2);
15356
15357   /* Just like what happens for functions, if we are ordering between
15358      different class template specializations, we may encounter dependent
15359      types in the arguments, and we need our dependency check functions
15360      to behave correctly.  */
15361   ++processing_template_decl;
15362   targs = get_class_bindings (TREE_VALUE (pat1),
15363                               CLASSTYPE_TI_ARGS (tmpl1),
15364                               CLASSTYPE_TI_ARGS (tmpl2));
15365   if (targs)
15366     {
15367       --winner;
15368       any_deductions = true;
15369     }
15370
15371   targs = get_class_bindings (TREE_VALUE (pat2),
15372                               CLASSTYPE_TI_ARGS (tmpl2),
15373                               CLASSTYPE_TI_ARGS (tmpl1));
15374   if (targs)
15375     {
15376       ++winner;
15377       any_deductions = true;
15378     }
15379   --processing_template_decl;
15380
15381   /* In the case of a tie where at least one of the class templates
15382      has a parameter pack at the end, the template with the most
15383      non-packed parameters wins.  */
15384   if (winner == 0
15385       && any_deductions
15386       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15387           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15388     {
15389       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15390       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15391       int len1 = TREE_VEC_LENGTH (args1);
15392       int len2 = TREE_VEC_LENGTH (args2);
15393
15394       /* We don't count the pack expansion at the end.  */
15395       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15396         --len1;
15397       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15398         --len2;
15399
15400       if (len1 > len2)
15401         return 1;
15402       else if (len1 < len2)
15403         return -1;
15404     }
15405
15406   return winner;
15407 }
15408
15409 /* Return the template arguments that will produce the function signature
15410    DECL from the function template FN, with the explicit template
15411    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15412    also match.  Return NULL_TREE if no satisfactory arguments could be
15413    found.  */
15414
15415 static tree
15416 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15417 {
15418   int ntparms = DECL_NTPARMS (fn);
15419   tree targs = make_tree_vec (ntparms);
15420   tree decl_type;
15421   tree decl_arg_types;
15422   tree *args;
15423   unsigned int nargs, ix;
15424   tree arg;
15425
15426   /* Substitute the explicit template arguments into the type of DECL.
15427      The call to fn_type_unification will handle substitution into the
15428      FN.  */
15429   decl_type = TREE_TYPE (decl);
15430   if (explicit_args && uses_template_parms (decl_type))
15431     {
15432       tree tmpl;
15433       tree converted_args;
15434
15435       if (DECL_TEMPLATE_INFO (decl))
15436         tmpl = DECL_TI_TEMPLATE (decl);
15437       else
15438         /* We can get here for some invalid specializations.  */
15439         return NULL_TREE;
15440
15441       converted_args
15442         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15443                                  explicit_args, NULL_TREE,
15444                                  tf_none,
15445                                  /*require_all_args=*/false,
15446                                  /*use_default_args=*/false);
15447       if (converted_args == error_mark_node)
15448         return NULL_TREE;
15449
15450       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15451       if (decl_type == error_mark_node)
15452         return NULL_TREE;
15453     }
15454
15455   /* Never do unification on the 'this' parameter.  */
15456   decl_arg_types = skip_artificial_parms_for (decl, 
15457                                               TYPE_ARG_TYPES (decl_type));
15458
15459   nargs = list_length (decl_arg_types);
15460   args = XALLOCAVEC (tree, nargs);
15461   for (arg = decl_arg_types, ix = 0;
15462        arg != NULL_TREE && arg != void_list_node;
15463        arg = TREE_CHAIN (arg), ++ix)
15464     args[ix] = TREE_VALUE (arg);
15465
15466   if (fn_type_unification (fn, explicit_args, targs,
15467                            args, ix,
15468                            (check_rettype || DECL_CONV_FN_P (fn)
15469                             ? TREE_TYPE (decl_type) : NULL_TREE),
15470                            DEDUCE_EXACT, LOOKUP_NORMAL))
15471     return NULL_TREE;
15472
15473   return targs;
15474 }
15475
15476 /* Return the innermost template arguments that, when applied to a
15477    template specialization whose innermost template parameters are
15478    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15479    ARGS.
15480
15481    For example, suppose we have:
15482
15483      template <class T, class U> struct S {};
15484      template <class T> struct S<T*, int> {};
15485
15486    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15487    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15488    int}.  The resulting vector will be {double}, indicating that `T'
15489    is bound to `double'.  */
15490
15491 static tree
15492 get_class_bindings (tree tparms, tree spec_args, tree args)
15493 {
15494   int i, ntparms = TREE_VEC_LENGTH (tparms);
15495   tree deduced_args;
15496   tree innermost_deduced_args;
15497
15498   innermost_deduced_args = make_tree_vec (ntparms);
15499   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15500     {
15501       deduced_args = copy_node (args);
15502       SET_TMPL_ARGS_LEVEL (deduced_args,
15503                            TMPL_ARGS_DEPTH (deduced_args),
15504                            innermost_deduced_args);
15505     }
15506   else
15507     deduced_args = innermost_deduced_args;
15508
15509   if (unify (tparms, deduced_args,
15510              INNERMOST_TEMPLATE_ARGS (spec_args),
15511              INNERMOST_TEMPLATE_ARGS (args),
15512              UNIFY_ALLOW_NONE))
15513     return NULL_TREE;
15514
15515   for (i =  0; i < ntparms; ++i)
15516     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15517       return NULL_TREE;
15518
15519   /* Verify that nondeduced template arguments agree with the type
15520      obtained from argument deduction.
15521
15522      For example:
15523
15524        struct A { typedef int X; };
15525        template <class T, class U> struct C {};
15526        template <class T> struct C<T, typename T::X> {};
15527
15528      Then with the instantiation `C<A, int>', we can deduce that
15529      `T' is `A' but unify () does not check whether `typename T::X'
15530      is `int'.  */
15531   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15532   if (spec_args == error_mark_node
15533       /* We only need to check the innermost arguments; the other
15534          arguments will always agree.  */
15535       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15536                               INNERMOST_TEMPLATE_ARGS (args)))
15537     return NULL_TREE;
15538
15539   /* Now that we have bindings for all of the template arguments,
15540      ensure that the arguments deduced for the template template
15541      parameters have compatible template parameter lists.  See the use
15542      of template_template_parm_bindings_ok_p in fn_type_unification
15543      for more information.  */
15544   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15545     return NULL_TREE;
15546
15547   return deduced_args;
15548 }
15549
15550 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15551    Return the TREE_LIST node with the most specialized template, if
15552    any.  If there is no most specialized template, the error_mark_node
15553    is returned.
15554
15555    Note that this function does not look at, or modify, the
15556    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15557    returned is one of the elements of INSTANTIATIONS, callers may
15558    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15559    and retrieve it from the value returned.  */
15560
15561 tree
15562 most_specialized_instantiation (tree templates)
15563 {
15564   tree fn, champ;
15565
15566   ++processing_template_decl;
15567
15568   champ = templates;
15569   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15570     {
15571       int fate = 0;
15572
15573       if (get_bindings (TREE_VALUE (champ),
15574                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15575                         NULL_TREE, /*check_ret=*/false))
15576         fate--;
15577
15578       if (get_bindings (TREE_VALUE (fn),
15579                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15580                         NULL_TREE, /*check_ret=*/false))
15581         fate++;
15582
15583       if (fate == -1)
15584         champ = fn;
15585       else if (!fate)
15586         {
15587           /* Equally specialized, move to next function.  If there
15588              is no next function, nothing's most specialized.  */
15589           fn = TREE_CHAIN (fn);
15590           champ = fn;
15591           if (!fn)
15592             break;
15593         }
15594     }
15595
15596   if (champ)
15597     /* Now verify that champ is better than everything earlier in the
15598        instantiation list.  */
15599     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15600       if (get_bindings (TREE_VALUE (champ),
15601                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15602                         NULL_TREE, /*check_ret=*/false)
15603           || !get_bindings (TREE_VALUE (fn),
15604                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15605                             NULL_TREE, /*check_ret=*/false))
15606         {
15607           champ = NULL_TREE;
15608           break;
15609         }
15610
15611   processing_template_decl--;
15612
15613   if (!champ)
15614     return error_mark_node;
15615
15616   return champ;
15617 }
15618
15619 /* If DECL is a specialization of some template, return the most
15620    general such template.  Otherwise, returns NULL_TREE.
15621
15622    For example, given:
15623
15624      template <class T> struct S { template <class U> void f(U); };
15625
15626    if TMPL is `template <class U> void S<int>::f(U)' this will return
15627    the full template.  This function will not trace past partial
15628    specializations, however.  For example, given in addition:
15629
15630      template <class T> struct S<T*> { template <class U> void f(U); };
15631
15632    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15633    `template <class T> template <class U> S<T*>::f(U)'.  */
15634
15635 tree
15636 most_general_template (tree decl)
15637 {
15638   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15639      an immediate specialization.  */
15640   if (TREE_CODE (decl) == FUNCTION_DECL)
15641     {
15642       if (DECL_TEMPLATE_INFO (decl)) {
15643         decl = DECL_TI_TEMPLATE (decl);
15644
15645         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15646            template friend.  */
15647         if (TREE_CODE (decl) != TEMPLATE_DECL)
15648           return NULL_TREE;
15649       } else
15650         return NULL_TREE;
15651     }
15652
15653   /* Look for more and more general templates.  */
15654   while (DECL_TEMPLATE_INFO (decl))
15655     {
15656       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15657          (See cp-tree.h for details.)  */
15658       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15659         break;
15660
15661       if (CLASS_TYPE_P (TREE_TYPE (decl))
15662           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15663         break;
15664
15665       /* Stop if we run into an explicitly specialized class template.  */
15666       if (!DECL_NAMESPACE_SCOPE_P (decl)
15667           && DECL_CONTEXT (decl)
15668           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15669         break;
15670
15671       decl = DECL_TI_TEMPLATE (decl);
15672     }
15673
15674   return decl;
15675 }
15676
15677 /* Return the most specialized of the class template partial
15678    specializations of TMPL which can produce TYPE, a specialization of
15679    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15680    a _TYPE node corresponding to the partial specialization, while the
15681    TREE_PURPOSE is the set of template arguments that must be
15682    substituted into the TREE_TYPE in order to generate TYPE.
15683
15684    If the choice of partial specialization is ambiguous, a diagnostic
15685    is issued, and the error_mark_node is returned.  If there are no
15686    partial specializations of TMPL matching TYPE, then NULL_TREE is
15687    returned.  */
15688
15689 static tree
15690 most_specialized_class (tree type, tree tmpl)
15691 {
15692   tree list = NULL_TREE;
15693   tree t;
15694   tree champ;
15695   int fate;
15696   bool ambiguous_p;
15697   tree args;
15698   tree outer_args = NULL_TREE;
15699
15700   tmpl = most_general_template (tmpl);
15701   args = CLASSTYPE_TI_ARGS (type);
15702
15703   /* For determining which partial specialization to use, only the
15704      innermost args are interesting.  */
15705   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15706     {
15707       outer_args = strip_innermost_template_args (args, 1);
15708       args = INNERMOST_TEMPLATE_ARGS (args);
15709     }
15710
15711   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15712     {
15713       tree partial_spec_args;
15714       tree spec_args;
15715       tree parms = TREE_VALUE (t);
15716
15717       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15718       if (outer_args)
15719         {
15720           int i;
15721
15722           ++processing_template_decl;
15723
15724           /* Discard the outer levels of args, and then substitute in the
15725              template args from the enclosing class.  */
15726           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15727           partial_spec_args = tsubst_template_args
15728             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15729
15730           /* PARMS already refers to just the innermost parms, but the
15731              template parms in partial_spec_args had their levels lowered
15732              by tsubst, so we need to do the same for the parm list.  We
15733              can't just tsubst the TREE_VEC itself, as tsubst wants to
15734              treat a TREE_VEC as an argument vector.  */
15735           parms = copy_node (parms);
15736           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15737             TREE_VEC_ELT (parms, i) =
15738               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15739
15740           --processing_template_decl;
15741         }
15742       spec_args = get_class_bindings (parms,
15743                                       partial_spec_args,
15744                                       args);
15745       if (spec_args)
15746         {
15747           if (outer_args)
15748             spec_args = add_to_template_args (outer_args, spec_args);
15749           list = tree_cons (spec_args, TREE_VALUE (t), list);
15750           TREE_TYPE (list) = TREE_TYPE (t);
15751         }
15752     }
15753
15754   if (! list)
15755     return NULL_TREE;
15756
15757   ambiguous_p = false;
15758   t = list;
15759   champ = t;
15760   t = TREE_CHAIN (t);
15761   for (; t; t = TREE_CHAIN (t))
15762     {
15763       fate = more_specialized_class (champ, t);
15764       if (fate == 1)
15765         ;
15766       else
15767         {
15768           if (fate == 0)
15769             {
15770               t = TREE_CHAIN (t);
15771               if (! t)
15772                 {
15773                   ambiguous_p = true;
15774                   break;
15775                 }
15776             }
15777           champ = t;
15778         }
15779     }
15780
15781   if (!ambiguous_p)
15782     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15783       {
15784         fate = more_specialized_class (champ, t);
15785         if (fate != 1)
15786           {
15787             ambiguous_p = true;
15788             break;
15789           }
15790       }
15791
15792   if (ambiguous_p)
15793     {
15794       const char *str;
15795       char *spaces = NULL;
15796       error ("ambiguous class template instantiation for %q#T", type);
15797       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
15798       for (t = list; t; t = TREE_CHAIN (t))
15799         {
15800           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
15801           spaces = spaces ? spaces : get_spaces (str);
15802         }
15803       free (spaces);
15804       return error_mark_node;
15805     }
15806
15807   return champ;
15808 }
15809
15810 /* Explicitly instantiate DECL.  */
15811
15812 void
15813 do_decl_instantiation (tree decl, tree storage)
15814 {
15815   tree result = NULL_TREE;
15816   int extern_p = 0;
15817
15818   if (!decl || decl == error_mark_node)
15819     /* An error occurred, for which grokdeclarator has already issued
15820        an appropriate message.  */
15821     return;
15822   else if (! DECL_LANG_SPECIFIC (decl))
15823     {
15824       error ("explicit instantiation of non-template %q#D", decl);
15825       return;
15826     }
15827   else if (TREE_CODE (decl) == VAR_DECL)
15828     {
15829       /* There is an asymmetry here in the way VAR_DECLs and
15830          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15831          the latter, the DECL we get back will be marked as a
15832          template instantiation, and the appropriate
15833          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15834          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15835          should handle VAR_DECLs as it currently handles
15836          FUNCTION_DECLs.  */
15837       if (!DECL_CLASS_SCOPE_P (decl))
15838         {
15839           error ("%qD is not a static data member of a class template", decl);
15840           return;
15841         }
15842       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15843       if (!result || TREE_CODE (result) != VAR_DECL)
15844         {
15845           error ("no matching template for %qD found", decl);
15846           return;
15847         }
15848       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15849         {
15850           error ("type %qT for explicit instantiation %qD does not match "
15851                  "declared type %qT", TREE_TYPE (result), decl,
15852                  TREE_TYPE (decl));
15853           return;
15854         }
15855     }
15856   else if (TREE_CODE (decl) != FUNCTION_DECL)
15857     {
15858       error ("explicit instantiation of %q#D", decl);
15859       return;
15860     }
15861   else
15862     result = decl;
15863
15864   /* Check for various error cases.  Note that if the explicit
15865      instantiation is valid the RESULT will currently be marked as an
15866      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15867      until we get here.  */
15868
15869   if (DECL_TEMPLATE_SPECIALIZATION (result))
15870     {
15871       /* DR 259 [temp.spec].
15872
15873          Both an explicit instantiation and a declaration of an explicit
15874          specialization shall not appear in a program unless the explicit
15875          instantiation follows a declaration of the explicit specialization.
15876
15877          For a given set of template parameters, if an explicit
15878          instantiation of a template appears after a declaration of an
15879          explicit specialization for that template, the explicit
15880          instantiation has no effect.  */
15881       return;
15882     }
15883   else if (DECL_EXPLICIT_INSTANTIATION (result))
15884     {
15885       /* [temp.spec]
15886
15887          No program shall explicitly instantiate any template more
15888          than once.
15889
15890          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15891          the first instantiation was `extern' and the second is not,
15892          and EXTERN_P for the opposite case.  */
15893       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15894         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15895       /* If an "extern" explicit instantiation follows an ordinary
15896          explicit instantiation, the template is instantiated.  */
15897       if (extern_p)
15898         return;
15899     }
15900   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15901     {
15902       error ("no matching template for %qD found", result);
15903       return;
15904     }
15905   else if (!DECL_TEMPLATE_INFO (result))
15906     {
15907       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15908       return;
15909     }
15910
15911   if (storage == NULL_TREE)
15912     ;
15913   else if (storage == ridpointers[(int) RID_EXTERN])
15914     {
15915       if (!in_system_header && (cxx_dialect == cxx98))
15916         pedwarn (input_location, OPT_pedantic, 
15917                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15918                  "instantiations");
15919       extern_p = 1;
15920     }
15921   else
15922     error ("storage class %qD applied to template instantiation", storage);
15923
15924   check_explicit_instantiation_namespace (result);
15925   mark_decl_instantiated (result, extern_p);
15926   if (! extern_p)
15927     instantiate_decl (result, /*defer_ok=*/1,
15928                       /*expl_inst_class_mem_p=*/false);
15929 }
15930
15931 static void
15932 mark_class_instantiated (tree t, int extern_p)
15933 {
15934   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15935   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15936   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15937   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15938   if (! extern_p)
15939     {
15940       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15941       rest_of_type_compilation (t, 1);
15942     }
15943 }
15944
15945 /* Called from do_type_instantiation through binding_table_foreach to
15946    do recursive instantiation for the type bound in ENTRY.  */
15947 static void
15948 bt_instantiate_type_proc (binding_entry entry, void *data)
15949 {
15950   tree storage = *(tree *) data;
15951
15952   if (MAYBE_CLASS_TYPE_P (entry->type)
15953       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15954     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15955 }
15956
15957 /* Called from do_type_instantiation to instantiate a member
15958    (a member function or a static member variable) of an
15959    explicitly instantiated class template.  */
15960 static void
15961 instantiate_class_member (tree decl, int extern_p)
15962 {
15963   mark_decl_instantiated (decl, extern_p);
15964   if (! extern_p)
15965     instantiate_decl (decl, /*defer_ok=*/1,
15966                       /*expl_inst_class_mem_p=*/true);
15967 }
15968
15969 /* Perform an explicit instantiation of template class T.  STORAGE, if
15970    non-null, is the RID for extern, inline or static.  COMPLAIN is
15971    nonzero if this is called from the parser, zero if called recursively,
15972    since the standard is unclear (as detailed below).  */
15973
15974 void
15975 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15976 {
15977   int extern_p = 0;
15978   int nomem_p = 0;
15979   int static_p = 0;
15980   int previous_instantiation_extern_p = 0;
15981
15982   if (TREE_CODE (t) == TYPE_DECL)
15983     t = TREE_TYPE (t);
15984
15985   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15986     {
15987       error ("explicit instantiation of non-template type %qT", t);
15988       return;
15989     }
15990
15991   complete_type (t);
15992
15993   if (!COMPLETE_TYPE_P (t))
15994     {
15995       if (complain & tf_error)
15996         error ("explicit instantiation of %q#T before definition of template",
15997                t);
15998       return;
15999     }
16000
16001   if (storage != NULL_TREE)
16002     {
16003       if (!in_system_header)
16004         {
16005           if (storage == ridpointers[(int) RID_EXTERN])
16006             {
16007               if (cxx_dialect == cxx98)
16008                 pedwarn (input_location, OPT_pedantic, 
16009                          "ISO C++ 1998 forbids the use of %<extern%> on "
16010                          "explicit instantiations");
16011             }
16012           else
16013             pedwarn (input_location, OPT_pedantic, 
16014                      "ISO C++ forbids the use of %qE"
16015                      " on explicit instantiations", storage);
16016         }
16017
16018       if (storage == ridpointers[(int) RID_INLINE])
16019         nomem_p = 1;
16020       else if (storage == ridpointers[(int) RID_EXTERN])
16021         extern_p = 1;
16022       else if (storage == ridpointers[(int) RID_STATIC])
16023         static_p = 1;
16024       else
16025         {
16026           error ("storage class %qD applied to template instantiation",
16027                  storage);
16028           extern_p = 0;
16029         }
16030     }
16031
16032   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16033     {
16034       /* DR 259 [temp.spec].
16035
16036          Both an explicit instantiation and a declaration of an explicit
16037          specialization shall not appear in a program unless the explicit
16038          instantiation follows a declaration of the explicit specialization.
16039
16040          For a given set of template parameters, if an explicit
16041          instantiation of a template appears after a declaration of an
16042          explicit specialization for that template, the explicit
16043          instantiation has no effect.  */
16044       return;
16045     }
16046   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16047     {
16048       /* [temp.spec]
16049
16050          No program shall explicitly instantiate any template more
16051          than once.
16052
16053          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16054          instantiation was `extern'.  If EXTERN_P then the second is.
16055          These cases are OK.  */
16056       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16057
16058       if (!previous_instantiation_extern_p && !extern_p
16059           && (complain & tf_error))
16060         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16061
16062       /* If we've already instantiated the template, just return now.  */
16063       if (!CLASSTYPE_INTERFACE_ONLY (t))
16064         return;
16065     }
16066
16067   check_explicit_instantiation_namespace (TYPE_NAME (t));
16068   mark_class_instantiated (t, extern_p);
16069
16070   if (nomem_p)
16071     return;
16072
16073   {
16074     tree tmp;
16075
16076     /* In contrast to implicit instantiation, where only the
16077        declarations, and not the definitions, of members are
16078        instantiated, we have here:
16079
16080          [temp.explicit]
16081
16082          The explicit instantiation of a class template specialization
16083          implies the instantiation of all of its members not
16084          previously explicitly specialized in the translation unit
16085          containing the explicit instantiation.
16086
16087        Of course, we can't instantiate member template classes, since
16088        we don't have any arguments for them.  Note that the standard
16089        is unclear on whether the instantiation of the members are
16090        *explicit* instantiations or not.  However, the most natural
16091        interpretation is that it should be an explicit instantiation.  */
16092
16093     if (! static_p)
16094       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16095         if (TREE_CODE (tmp) == FUNCTION_DECL
16096             && DECL_TEMPLATE_INSTANTIATION (tmp))
16097           instantiate_class_member (tmp, extern_p);
16098
16099     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16100       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16101         instantiate_class_member (tmp, extern_p);
16102
16103     if (CLASSTYPE_NESTED_UTDS (t))
16104       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16105                              bt_instantiate_type_proc, &storage);
16106   }
16107 }
16108
16109 /* Given a function DECL, which is a specialization of TMPL, modify
16110    DECL to be a re-instantiation of TMPL with the same template
16111    arguments.  TMPL should be the template into which tsubst'ing
16112    should occur for DECL, not the most general template.
16113
16114    One reason for doing this is a scenario like this:
16115
16116      template <class T>
16117      void f(const T&, int i);
16118
16119      void g() { f(3, 7); }
16120
16121      template <class T>
16122      void f(const T& t, const int i) { }
16123
16124    Note that when the template is first instantiated, with
16125    instantiate_template, the resulting DECL will have no name for the
16126    first parameter, and the wrong type for the second.  So, when we go
16127    to instantiate the DECL, we regenerate it.  */
16128
16129 static void
16130 regenerate_decl_from_template (tree decl, tree tmpl)
16131 {
16132   /* The arguments used to instantiate DECL, from the most general
16133      template.  */
16134   tree args;
16135   tree code_pattern;
16136
16137   args = DECL_TI_ARGS (decl);
16138   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16139
16140   /* Make sure that we can see identifiers, and compute access
16141      correctly.  */
16142   push_access_scope (decl);
16143
16144   if (TREE_CODE (decl) == FUNCTION_DECL)
16145     {
16146       tree decl_parm;
16147       tree pattern_parm;
16148       tree specs;
16149       int args_depth;
16150       int parms_depth;
16151
16152       args_depth = TMPL_ARGS_DEPTH (args);
16153       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16154       if (args_depth > parms_depth)
16155         args = get_innermost_template_args (args, parms_depth);
16156
16157       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16158                                               args, tf_error, NULL_TREE);
16159       if (specs)
16160         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16161                                                     specs);
16162
16163       /* Merge parameter declarations.  */
16164       decl_parm = skip_artificial_parms_for (decl,
16165                                              DECL_ARGUMENTS (decl));
16166       pattern_parm
16167         = skip_artificial_parms_for (code_pattern,
16168                                      DECL_ARGUMENTS (code_pattern));
16169       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16170         {
16171           tree parm_type;
16172           tree attributes;
16173           
16174           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16175             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16176           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16177                               NULL_TREE);
16178           parm_type = type_decays_to (parm_type);
16179           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16180             TREE_TYPE (decl_parm) = parm_type;
16181           attributes = DECL_ATTRIBUTES (pattern_parm);
16182           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16183             {
16184               DECL_ATTRIBUTES (decl_parm) = attributes;
16185               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16186             }
16187           decl_parm = TREE_CHAIN (decl_parm);
16188           pattern_parm = TREE_CHAIN (pattern_parm);
16189         }
16190       /* Merge any parameters that match with the function parameter
16191          pack.  */
16192       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16193         {
16194           int i, len;
16195           tree expanded_types;
16196           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16197              the parameters in this function parameter pack.  */
16198           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16199                                                  args, tf_error, NULL_TREE);
16200           len = TREE_VEC_LENGTH (expanded_types);
16201           for (i = 0; i < len; i++)
16202             {
16203               tree parm_type;
16204               tree attributes;
16205           
16206               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16207                 /* Rename the parameter to include the index.  */
16208                 DECL_NAME (decl_parm) = 
16209                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16210               parm_type = TREE_VEC_ELT (expanded_types, i);
16211               parm_type = type_decays_to (parm_type);
16212               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16213                 TREE_TYPE (decl_parm) = parm_type;
16214               attributes = DECL_ATTRIBUTES (pattern_parm);
16215               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16216                 {
16217                   DECL_ATTRIBUTES (decl_parm) = attributes;
16218                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16219                 }
16220               decl_parm = TREE_CHAIN (decl_parm);
16221             }
16222         }
16223       /* Merge additional specifiers from the CODE_PATTERN.  */
16224       if (DECL_DECLARED_INLINE_P (code_pattern)
16225           && !DECL_DECLARED_INLINE_P (decl))
16226         DECL_DECLARED_INLINE_P (decl) = 1;
16227     }
16228   else if (TREE_CODE (decl) == VAR_DECL)
16229     DECL_INITIAL (decl) =
16230       tsubst_expr (DECL_INITIAL (code_pattern), args,
16231                    tf_error, DECL_TI_TEMPLATE (decl),
16232                    /*integral_constant_expression_p=*/false);
16233   else
16234     gcc_unreachable ();
16235
16236   pop_access_scope (decl);
16237 }
16238
16239 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16240    substituted to get DECL.  */
16241
16242 tree
16243 template_for_substitution (tree decl)
16244 {
16245   tree tmpl = DECL_TI_TEMPLATE (decl);
16246
16247   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16248      for the instantiation.  This is not always the most general
16249      template.  Consider, for example:
16250
16251         template <class T>
16252         struct S { template <class U> void f();
16253                    template <> void f<int>(); };
16254
16255      and an instantiation of S<double>::f<int>.  We want TD to be the
16256      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16257   while (/* An instantiation cannot have a definition, so we need a
16258             more general template.  */
16259          DECL_TEMPLATE_INSTANTIATION (tmpl)
16260            /* We must also deal with friend templates.  Given:
16261
16262                 template <class T> struct S {
16263                   template <class U> friend void f() {};
16264                 };
16265
16266               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16267               so far as the language is concerned, but that's still
16268               where we get the pattern for the instantiation from.  On
16269               other hand, if the definition comes outside the class, say:
16270
16271                 template <class T> struct S {
16272                   template <class U> friend void f();
16273                 };
16274                 template <class U> friend void f() {}
16275
16276               we don't need to look any further.  That's what the check for
16277               DECL_INITIAL is for.  */
16278           || (TREE_CODE (decl) == FUNCTION_DECL
16279               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16280               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16281     {
16282       /* The present template, TD, should not be a definition.  If it
16283          were a definition, we should be using it!  Note that we
16284          cannot restructure the loop to just keep going until we find
16285          a template with a definition, since that might go too far if
16286          a specialization was declared, but not defined.  */
16287       gcc_assert (TREE_CODE (decl) != VAR_DECL
16288                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16289
16290       /* Fetch the more general template.  */
16291       tmpl = DECL_TI_TEMPLATE (tmpl);
16292     }
16293
16294   return tmpl;
16295 }
16296
16297 /* Returns true if we need to instantiate this template instance even if we
16298    know we aren't going to emit it..  */
16299
16300 bool
16301 always_instantiate_p (tree decl)
16302 {
16303   /* We always instantiate inline functions so that we can inline them.  An
16304      explicit instantiation declaration prohibits implicit instantiation of
16305      non-inline functions.  With high levels of optimization, we would
16306      normally inline non-inline functions -- but we're not allowed to do
16307      that for "extern template" functions.  Therefore, we check
16308      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16309   return ((TREE_CODE (decl) == FUNCTION_DECL
16310            && DECL_DECLARED_INLINE_P (decl))
16311           /* And we need to instantiate static data members so that
16312              their initializers are available in integral constant
16313              expressions.  */
16314           || (TREE_CODE (decl) == VAR_DECL
16315               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16316 }
16317
16318 /* Produce the definition of D, a _DECL generated from a template.  If
16319    DEFER_OK is nonzero, then we don't have to actually do the
16320    instantiation now; we just have to do it sometime.  Normally it is
16321    an error if this is an explicit instantiation but D is undefined.
16322    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16323    explicitly instantiated class template.  */
16324
16325 tree
16326 instantiate_decl (tree d, int defer_ok,
16327                   bool expl_inst_class_mem_p)
16328 {
16329   tree tmpl = DECL_TI_TEMPLATE (d);
16330   tree gen_args;
16331   tree args;
16332   tree td;
16333   tree code_pattern;
16334   tree spec;
16335   tree gen_tmpl;
16336   bool pattern_defined;
16337   int need_push;
16338   location_t saved_loc = input_location;
16339   bool external_p;
16340
16341   /* This function should only be used to instantiate templates for
16342      functions and static member variables.  */
16343   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16344               || TREE_CODE (d) == VAR_DECL);
16345
16346   /* Variables are never deferred; if instantiation is required, they
16347      are instantiated right away.  That allows for better code in the
16348      case that an expression refers to the value of the variable --
16349      if the variable has a constant value the referring expression can
16350      take advantage of that fact.  */
16351   if (TREE_CODE (d) == VAR_DECL)
16352     defer_ok = 0;
16353
16354   /* Don't instantiate cloned functions.  Instead, instantiate the
16355      functions they cloned.  */
16356   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16357     d = DECL_CLONED_FUNCTION (d);
16358
16359   if (DECL_TEMPLATE_INSTANTIATED (d)
16360       || DECL_TEMPLATE_SPECIALIZATION (d))
16361     /* D has already been instantiated or explicitly specialized, so
16362        there's nothing for us to do here.
16363
16364        It might seem reasonable to check whether or not D is an explicit
16365        instantiation, and, if so, stop here.  But when an explicit
16366        instantiation is deferred until the end of the compilation,
16367        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16368        the instantiation.  */
16369     return d;
16370
16371   /* Check to see whether we know that this template will be
16372      instantiated in some other file, as with "extern template"
16373      extension.  */
16374   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16375
16376   /* In general, we do not instantiate such templates.  */
16377   if (external_p && !always_instantiate_p (d))
16378     return d;
16379
16380   gen_tmpl = most_general_template (tmpl);
16381   gen_args = DECL_TI_ARGS (d);
16382
16383   if (tmpl != gen_tmpl)
16384     /* We should already have the extra args.  */
16385     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16386                 == TMPL_ARGS_DEPTH (gen_args));
16387   /* And what's in the hash table should match D.  */
16388   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16389               || spec == NULL_TREE);
16390
16391   /* This needs to happen before any tsubsting.  */
16392   if (! push_tinst_level (d))
16393     return d;
16394
16395   timevar_push (TV_PARSE);
16396
16397   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16398      for the instantiation.  */
16399   td = template_for_substitution (d);
16400   code_pattern = DECL_TEMPLATE_RESULT (td);
16401
16402   /* We should never be trying to instantiate a member of a class
16403      template or partial specialization.  */
16404   gcc_assert (d != code_pattern);
16405
16406   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16407       || DECL_TEMPLATE_SPECIALIZATION (td))
16408     /* In the case of a friend template whose definition is provided
16409        outside the class, we may have too many arguments.  Drop the
16410        ones we don't need.  The same is true for specializations.  */
16411     args = get_innermost_template_args
16412       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16413   else
16414     args = gen_args;
16415
16416   if (TREE_CODE (d) == FUNCTION_DECL)
16417     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16418   else
16419     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16420
16421   /* We may be in the middle of deferred access check.  Disable it now.  */
16422   push_deferring_access_checks (dk_no_deferred);
16423
16424   /* Unless an explicit instantiation directive has already determined
16425      the linkage of D, remember that a definition is available for
16426      this entity.  */
16427   if (pattern_defined
16428       && !DECL_INTERFACE_KNOWN (d)
16429       && !DECL_NOT_REALLY_EXTERN (d))
16430     mark_definable (d);
16431
16432   input_location = DECL_SOURCE_LOCATION (d);
16433
16434   /* If D is a member of an explicitly instantiated class template,
16435      and no definition is available, treat it like an implicit
16436      instantiation.  */
16437   if (!pattern_defined && expl_inst_class_mem_p
16438       && DECL_EXPLICIT_INSTANTIATION (d))
16439     {
16440       DECL_NOT_REALLY_EXTERN (d) = 0;
16441       DECL_INTERFACE_KNOWN (d) = 0;
16442       SET_DECL_IMPLICIT_INSTANTIATION (d);
16443     }
16444
16445   /* Recheck the substitutions to obtain any warning messages
16446      about ignoring cv qualifiers.  Don't do this for artificial decls,
16447      as it breaks the context-sensitive substitution for lambda op(). */
16448   if (!defer_ok && !DECL_ARTIFICIAL (d))
16449     {
16450       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16451       tree type = TREE_TYPE (gen);
16452
16453       /* Make sure that we can see identifiers, and compute access
16454          correctly.  D is already the target FUNCTION_DECL with the
16455          right context.  */
16456       push_access_scope (d);
16457
16458       if (TREE_CODE (gen) == FUNCTION_DECL)
16459         {
16460           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16461           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16462                                           d);
16463           /* Don't simply tsubst the function type, as that will give
16464              duplicate warnings about poor parameter qualifications.
16465              The function arguments are the same as the decl_arguments
16466              without the top level cv qualifiers.  */
16467           type = TREE_TYPE (type);
16468         }
16469       tsubst (type, gen_args, tf_warning_or_error, d);
16470
16471       pop_access_scope (d);
16472     }
16473
16474   /* Defer all other templates, unless we have been explicitly
16475      forbidden from doing so.  */
16476   if (/* If there is no definition, we cannot instantiate the
16477          template.  */
16478       ! pattern_defined
16479       /* If it's OK to postpone instantiation, do so.  */
16480       || defer_ok
16481       /* If this is a static data member that will be defined
16482          elsewhere, we don't want to instantiate the entire data
16483          member, but we do want to instantiate the initializer so that
16484          we can substitute that elsewhere.  */
16485       || (external_p && TREE_CODE (d) == VAR_DECL))
16486     {
16487       /* The definition of the static data member is now required so
16488          we must substitute the initializer.  */
16489       if (TREE_CODE (d) == VAR_DECL
16490           && !DECL_INITIAL (d)
16491           && DECL_INITIAL (code_pattern))
16492         {
16493           tree ns;
16494           tree init;
16495
16496           ns = decl_namespace_context (d);
16497           push_nested_namespace (ns);
16498           push_nested_class (DECL_CONTEXT (d));
16499           init = tsubst_expr (DECL_INITIAL (code_pattern),
16500                               args,
16501                               tf_warning_or_error, NULL_TREE,
16502                               /*integral_constant_expression_p=*/false);
16503           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16504                           /*asmspec_tree=*/NULL_TREE,
16505                           LOOKUP_ONLYCONVERTING);
16506           pop_nested_class ();
16507           pop_nested_namespace (ns);
16508         }
16509
16510       /* We restore the source position here because it's used by
16511          add_pending_template.  */
16512       input_location = saved_loc;
16513
16514       if (at_eof && !pattern_defined
16515           && DECL_EXPLICIT_INSTANTIATION (d)
16516           && DECL_NOT_REALLY_EXTERN (d))
16517         /* [temp.explicit]
16518
16519            The definition of a non-exported function template, a
16520            non-exported member function template, or a non-exported
16521            member function or static data member of a class template
16522            shall be present in every translation unit in which it is
16523            explicitly instantiated.  */
16524         permerror (input_location,  "explicit instantiation of %qD "
16525                    "but no definition available", d);
16526
16527       /* ??? Historically, we have instantiated inline functions, even
16528          when marked as "extern template".  */
16529       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16530         add_pending_template (d);
16531       goto out;
16532     }
16533   /* Tell the repository that D is available in this translation unit
16534      -- and see if it is supposed to be instantiated here.  */
16535   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16536     {
16537       /* In a PCH file, despite the fact that the repository hasn't
16538          requested instantiation in the PCH it is still possible that
16539          an instantiation will be required in a file that includes the
16540          PCH.  */
16541       if (pch_file)
16542         add_pending_template (d);
16543       /* Instantiate inline functions so that the inliner can do its
16544          job, even though we'll not be emitting a copy of this
16545          function.  */
16546       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16547         goto out;
16548     }
16549
16550   need_push = !cfun || !global_bindings_p ();
16551   if (need_push)
16552     push_to_top_level ();
16553
16554   /* Mark D as instantiated so that recursive calls to
16555      instantiate_decl do not try to instantiate it again.  */
16556   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16557
16558   /* Regenerate the declaration in case the template has been modified
16559      by a subsequent redeclaration.  */
16560   regenerate_decl_from_template (d, td);
16561
16562   /* We already set the file and line above.  Reset them now in case
16563      they changed as a result of calling regenerate_decl_from_template.  */
16564   input_location = DECL_SOURCE_LOCATION (d);
16565
16566   if (TREE_CODE (d) == VAR_DECL)
16567     {
16568       tree init;
16569
16570       /* Clear out DECL_RTL; whatever was there before may not be right
16571          since we've reset the type of the declaration.  */
16572       SET_DECL_RTL (d, NULL_RTX);
16573       DECL_IN_AGGR_P (d) = 0;
16574
16575       /* The initializer is placed in DECL_INITIAL by
16576          regenerate_decl_from_template.  Pull it out so that
16577          cp_finish_decl can process it.  */
16578       init = DECL_INITIAL (d);
16579       DECL_INITIAL (d) = NULL_TREE;
16580       DECL_INITIALIZED_P (d) = 0;
16581
16582       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16583          initializer.  That function will defer actual emission until
16584          we have a chance to determine linkage.  */
16585       DECL_EXTERNAL (d) = 0;
16586
16587       /* Enter the scope of D so that access-checking works correctly.  */
16588       push_nested_class (DECL_CONTEXT (d));
16589       cp_finish_decl (d, init, false, NULL_TREE, 0);
16590       pop_nested_class ();
16591     }
16592   else if (TREE_CODE (d) == FUNCTION_DECL)
16593     {
16594       htab_t saved_local_specializations;
16595       tree subst_decl;
16596       tree tmpl_parm;
16597       tree spec_parm;
16598
16599       /* Save away the current list, in case we are instantiating one
16600          template from within the body of another.  */
16601       saved_local_specializations = local_specializations;
16602
16603       /* Set up the list of local specializations.  */
16604       local_specializations = htab_create (37,
16605                                            hash_local_specialization,
16606                                            eq_local_specializations,
16607                                            NULL);
16608
16609       /* Set up context.  */
16610       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16611
16612       /* Create substitution entries for the parameters.  */
16613       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16614       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16615       spec_parm = DECL_ARGUMENTS (d);
16616       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16617         {
16618           register_local_specialization (spec_parm, tmpl_parm);
16619           spec_parm = skip_artificial_parms_for (d, spec_parm);
16620           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16621         }
16622       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16623         {
16624           register_local_specialization (spec_parm, tmpl_parm);
16625           tmpl_parm = TREE_CHAIN (tmpl_parm);
16626           spec_parm = TREE_CHAIN (spec_parm);
16627         }
16628       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16629         {
16630           /* Register the (value) argument pack as a specialization of
16631              TMPL_PARM, then move on.  */
16632           tree argpack = make_fnparm_pack (spec_parm);
16633           register_local_specialization (argpack, tmpl_parm);
16634           tmpl_parm = TREE_CHAIN (tmpl_parm);
16635           spec_parm = NULL_TREE;
16636         }
16637       gcc_assert (!spec_parm);
16638
16639       /* Substitute into the body of the function.  */
16640       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16641                    tf_warning_or_error, tmpl,
16642                    /*integral_constant_expression_p=*/false);
16643
16644       /* Set the current input_location to the end of the function
16645          so that finish_function knows where we are.  */
16646       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16647
16648       /* We don't need the local specializations any more.  */
16649       htab_delete (local_specializations);
16650       local_specializations = saved_local_specializations;
16651
16652       /* Finish the function.  */
16653       d = finish_function (0);
16654       expand_or_defer_fn (d);
16655     }
16656
16657   /* We're not deferring instantiation any more.  */
16658   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16659
16660   if (need_push)
16661     pop_from_top_level ();
16662
16663 out:
16664   input_location = saved_loc;
16665   pop_deferring_access_checks ();
16666   pop_tinst_level ();
16667
16668   timevar_pop (TV_PARSE);
16669
16670   return d;
16671 }
16672
16673 /* Run through the list of templates that we wish we could
16674    instantiate, and instantiate any we can.  RETRIES is the
16675    number of times we retry pending template instantiation.  */
16676
16677 void
16678 instantiate_pending_templates (int retries)
16679 {
16680   int reconsider;
16681   location_t saved_loc = input_location;
16682
16683   /* Instantiating templates may trigger vtable generation.  This in turn
16684      may require further template instantiations.  We place a limit here
16685      to avoid infinite loop.  */
16686   if (pending_templates && retries >= max_tinst_depth)
16687     {
16688       tree decl = pending_templates->tinst->decl;
16689
16690       error ("template instantiation depth exceeds maximum of %d"
16691              " instantiating %q+D, possibly from virtual table generation"
16692              " (use -ftemplate-depth-NN to increase the maximum)",
16693              max_tinst_depth, decl);
16694       if (TREE_CODE (decl) == FUNCTION_DECL)
16695         /* Pretend that we defined it.  */
16696         DECL_INITIAL (decl) = error_mark_node;
16697       return;
16698     }
16699
16700   do
16701     {
16702       struct pending_template **t = &pending_templates;
16703       struct pending_template *last = NULL;
16704       reconsider = 0;
16705       while (*t)
16706         {
16707           tree instantiation = reopen_tinst_level ((*t)->tinst);
16708           bool complete = false;
16709
16710           if (TYPE_P (instantiation))
16711             {
16712               tree fn;
16713
16714               if (!COMPLETE_TYPE_P (instantiation))
16715                 {
16716                   instantiate_class_template (instantiation);
16717                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16718                     for (fn = TYPE_METHODS (instantiation);
16719                          fn;
16720                          fn = TREE_CHAIN (fn))
16721                       if (! DECL_ARTIFICIAL (fn))
16722                         instantiate_decl (fn,
16723                                           /*defer_ok=*/0,
16724                                           /*expl_inst_class_mem_p=*/false);
16725                   if (COMPLETE_TYPE_P (instantiation))
16726                     reconsider = 1;
16727                 }
16728
16729               complete = COMPLETE_TYPE_P (instantiation);
16730             }
16731           else
16732             {
16733               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16734                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16735                 {
16736                   instantiation
16737                     = instantiate_decl (instantiation,
16738                                         /*defer_ok=*/0,
16739                                         /*expl_inst_class_mem_p=*/false);
16740                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16741                     reconsider = 1;
16742                 }
16743
16744               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16745                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16746             }
16747
16748           if (complete)
16749             /* If INSTANTIATION has been instantiated, then we don't
16750                need to consider it again in the future.  */
16751             *t = (*t)->next;
16752           else
16753             {
16754               last = *t;
16755               t = &(*t)->next;
16756             }
16757           tinst_depth = 0;
16758           current_tinst_level = NULL;
16759         }
16760       last_pending_template = last;
16761     }
16762   while (reconsider);
16763
16764   input_location = saved_loc;
16765 }
16766
16767 /* Substitute ARGVEC into T, which is a list of initializers for
16768    either base class or a non-static data member.  The TREE_PURPOSEs
16769    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16770    instantiate_decl.  */
16771
16772 static tree
16773 tsubst_initializer_list (tree t, tree argvec)
16774 {
16775   tree inits = NULL_TREE;
16776
16777   for (; t; t = TREE_CHAIN (t))
16778     {
16779       tree decl;
16780       tree init;
16781       tree expanded_bases = NULL_TREE;
16782       tree expanded_arguments = NULL_TREE;
16783       int i, len = 1;
16784
16785       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16786         {
16787           tree expr;
16788           tree arg;
16789
16790           /* Expand the base class expansion type into separate base
16791              classes.  */
16792           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16793                                                  tf_warning_or_error,
16794                                                  NULL_TREE);
16795           if (expanded_bases == error_mark_node)
16796             continue;
16797           
16798           /* We'll be building separate TREE_LISTs of arguments for
16799              each base.  */
16800           len = TREE_VEC_LENGTH (expanded_bases);
16801           expanded_arguments = make_tree_vec (len);
16802           for (i = 0; i < len; i++)
16803             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16804
16805           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16806              expand each argument in the TREE_VALUE of t.  */
16807           expr = make_node (EXPR_PACK_EXPANSION);
16808           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16809             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16810
16811           if (TREE_VALUE (t) == void_type_node)
16812             /* VOID_TYPE_NODE is used to indicate
16813                value-initialization.  */
16814             {
16815               for (i = 0; i < len; i++)
16816                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16817             }
16818           else
16819             {
16820               /* Substitute parameter packs into each argument in the
16821                  TREE_LIST.  */
16822               in_base_initializer = 1;
16823               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16824                 {
16825                   tree expanded_exprs;
16826
16827                   /* Expand the argument.  */
16828                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16829                   expanded_exprs 
16830                     = tsubst_pack_expansion (expr, argvec,
16831                                              tf_warning_or_error,
16832                                              NULL_TREE);
16833                   if (expanded_exprs == error_mark_node)
16834                     continue;
16835
16836                   /* Prepend each of the expanded expressions to the
16837                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16838                   for (i = 0; i < len; i++)
16839                     {
16840                       TREE_VEC_ELT (expanded_arguments, i) = 
16841                         tree_cons (NULL_TREE, 
16842                                    TREE_VEC_ELT (expanded_exprs, i),
16843                                    TREE_VEC_ELT (expanded_arguments, i));
16844                     }
16845                 }
16846               in_base_initializer = 0;
16847
16848               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16849                  since we built them backwards.  */
16850               for (i = 0; i < len; i++)
16851                 {
16852                   TREE_VEC_ELT (expanded_arguments, i) = 
16853                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16854                 }
16855             }
16856         }
16857
16858       for (i = 0; i < len; ++i)
16859         {
16860           if (expanded_bases)
16861             {
16862               decl = TREE_VEC_ELT (expanded_bases, i);
16863               decl = expand_member_init (decl);
16864               init = TREE_VEC_ELT (expanded_arguments, i);
16865             }
16866           else
16867             {
16868               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16869                                   tf_warning_or_error, NULL_TREE);
16870
16871               decl = expand_member_init (decl);
16872               if (decl && !DECL_P (decl))
16873                 in_base_initializer = 1;
16874
16875               init = tsubst_expr (TREE_VALUE (t), argvec, 
16876                                   tf_warning_or_error, NULL_TREE,
16877                                   /*integral_constant_expression_p=*/false);
16878               in_base_initializer = 0;
16879             }
16880
16881           if (decl)
16882             {
16883               init = build_tree_list (decl, init);
16884               TREE_CHAIN (init) = inits;
16885               inits = init;
16886             }
16887         }
16888     }
16889   return inits;
16890 }
16891
16892 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16893
16894 static void
16895 set_current_access_from_decl (tree decl)
16896 {
16897   if (TREE_PRIVATE (decl))
16898     current_access_specifier = access_private_node;
16899   else if (TREE_PROTECTED (decl))
16900     current_access_specifier = access_protected_node;
16901   else
16902     current_access_specifier = access_public_node;
16903 }
16904
16905 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16906    is the instantiation (which should have been created with
16907    start_enum) and ARGS are the template arguments to use.  */
16908
16909 static void
16910 tsubst_enum (tree tag, tree newtag, tree args)
16911 {
16912   tree e;
16913
16914   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16915     {
16916       tree value;
16917       tree decl;
16918
16919       decl = TREE_VALUE (e);
16920       /* Note that in a template enum, the TREE_VALUE is the
16921          CONST_DECL, not the corresponding INTEGER_CST.  */
16922       value = tsubst_expr (DECL_INITIAL (decl),
16923                            args, tf_warning_or_error, NULL_TREE,
16924                            /*integral_constant_expression_p=*/true);
16925
16926       /* Give this enumeration constant the correct access.  */
16927       set_current_access_from_decl (decl);
16928
16929       /* Actually build the enumerator itself.  */
16930       build_enumerator (DECL_NAME (decl), value, newtag);
16931     }
16932
16933   finish_enum (newtag);
16934   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16935     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16936 }
16937
16938 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16939    its type -- but without substituting the innermost set of template
16940    arguments.  So, innermost set of template parameters will appear in
16941    the type.  */
16942
16943 tree
16944 get_mostly_instantiated_function_type (tree decl)
16945 {
16946   tree fn_type;
16947   tree tmpl;
16948   tree targs;
16949   tree tparms;
16950   int parm_depth;
16951
16952   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16953   targs = DECL_TI_ARGS (decl);
16954   tparms = DECL_TEMPLATE_PARMS (tmpl);
16955   parm_depth = TMPL_PARMS_DEPTH (tparms);
16956
16957   /* There should be as many levels of arguments as there are levels
16958      of parameters.  */
16959   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16960
16961   fn_type = TREE_TYPE (tmpl);
16962
16963   if (parm_depth == 1)
16964     /* No substitution is necessary.  */
16965     ;
16966   else
16967     {
16968       int i, save_access_control;
16969       tree partial_args;
16970
16971       /* Replace the innermost level of the TARGS with NULL_TREEs to
16972          let tsubst know not to substitute for those parameters.  */
16973       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16974       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16975         SET_TMPL_ARGS_LEVEL (partial_args, i,
16976                              TMPL_ARGS_LEVEL (targs, i));
16977       SET_TMPL_ARGS_LEVEL (partial_args,
16978                            TMPL_ARGS_DEPTH (targs),
16979                            make_tree_vec (DECL_NTPARMS (tmpl)));
16980
16981       /* Disable access control as this function is used only during
16982          name-mangling.  */
16983       save_access_control = flag_access_control;
16984       flag_access_control = 0;
16985
16986       ++processing_template_decl;
16987       /* Now, do the (partial) substitution to figure out the
16988          appropriate function type.  */
16989       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16990       --processing_template_decl;
16991
16992       /* Substitute into the template parameters to obtain the real
16993          innermost set of parameters.  This step is important if the
16994          innermost set of template parameters contains value
16995          parameters whose types depend on outer template parameters.  */
16996       TREE_VEC_LENGTH (partial_args)--;
16997       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16998
16999       flag_access_control = save_access_control;
17000     }
17001
17002   return fn_type;
17003 }
17004
17005 /* Return truthvalue if we're processing a template different from
17006    the last one involved in diagnostics.  */
17007 int
17008 problematic_instantiation_changed (void)
17009 {
17010   return last_template_error_tick != tinst_level_tick;
17011 }
17012
17013 /* Remember current template involved in diagnostics.  */
17014 void
17015 record_last_problematic_instantiation (void)
17016 {
17017   last_template_error_tick = tinst_level_tick;
17018 }
17019
17020 struct tinst_level *
17021 current_instantiation (void)
17022 {
17023   return current_tinst_level;
17024 }
17025
17026 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17027    type. Return zero for ok, nonzero for disallowed. Issue error and
17028    warning messages under control of COMPLAIN.  */
17029
17030 static int
17031 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17032 {
17033   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17034     return 0;
17035   else if (POINTER_TYPE_P (type))
17036     return 0;
17037   else if (TYPE_PTR_TO_MEMBER_P (type))
17038     return 0;
17039   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17040     return 0;
17041   else if (TREE_CODE (type) == TYPENAME_TYPE)
17042     return 0;
17043
17044   if (complain & tf_error)
17045     error ("%q#T is not a valid type for a template constant parameter", type);
17046   return 1;
17047 }
17048
17049 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17050    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17051
17052 static bool
17053 dependent_type_p_r (tree type)
17054 {
17055   tree scope;
17056
17057   /* [temp.dep.type]
17058
17059      A type is dependent if it is:
17060
17061      -- a template parameter. Template template parameters are types
17062         for us (since TYPE_P holds true for them) so we handle
17063         them here.  */
17064   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17065       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17066     return true;
17067   /* -- a qualified-id with a nested-name-specifier which contains a
17068         class-name that names a dependent type or whose unqualified-id
17069         names a dependent type.  */
17070   if (TREE_CODE (type) == TYPENAME_TYPE)
17071     return true;
17072   /* -- a cv-qualified type where the cv-unqualified type is
17073         dependent.  */
17074   type = TYPE_MAIN_VARIANT (type);
17075   /* -- a compound type constructed from any dependent type.  */
17076   if (TYPE_PTR_TO_MEMBER_P (type))
17077     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17078             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17079                                            (type)));
17080   else if (TREE_CODE (type) == POINTER_TYPE
17081            || TREE_CODE (type) == REFERENCE_TYPE)
17082     return dependent_type_p (TREE_TYPE (type));
17083   else if (TREE_CODE (type) == FUNCTION_TYPE
17084            || TREE_CODE (type) == METHOD_TYPE)
17085     {
17086       tree arg_type;
17087
17088       if (dependent_type_p (TREE_TYPE (type)))
17089         return true;
17090       for (arg_type = TYPE_ARG_TYPES (type);
17091            arg_type;
17092            arg_type = TREE_CHAIN (arg_type))
17093         if (dependent_type_p (TREE_VALUE (arg_type)))
17094           return true;
17095       return false;
17096     }
17097   /* -- an array type constructed from any dependent type or whose
17098         size is specified by a constant expression that is
17099         value-dependent.  */
17100   if (TREE_CODE (type) == ARRAY_TYPE)
17101     {
17102       if (TYPE_DOMAIN (type)
17103           && dependent_type_p (TYPE_DOMAIN (type)))
17104         return true;
17105       return dependent_type_p (TREE_TYPE (type));
17106     }
17107   else if (TREE_CODE (type) == INTEGER_TYPE
17108            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17109     {
17110       /* If this is the TYPE_DOMAIN of an array type, consider it
17111          dependent.  We already checked for value-dependence in
17112          compute_array_index_type.  */
17113       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17114     }
17115
17116   /* -- a template-id in which either the template name is a template
17117      parameter ...  */
17118   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17119     return true;
17120   /* ... or any of the template arguments is a dependent type or
17121         an expression that is type-dependent or value-dependent.  */
17122   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17123            && (any_dependent_template_arguments_p
17124                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17125     return true;
17126
17127   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17128      argument of the `typeof' expression is not type-dependent, then
17129      it should already been have resolved.  */
17130   if (TREE_CODE (type) == TYPEOF_TYPE
17131       || TREE_CODE (type) == DECLTYPE_TYPE)
17132     return true;
17133
17134   /* A template argument pack is dependent if any of its packed
17135      arguments are.  */
17136   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17137     {
17138       tree args = ARGUMENT_PACK_ARGS (type);
17139       int i, len = TREE_VEC_LENGTH (args);
17140       for (i = 0; i < len; ++i)
17141         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17142           return true;
17143     }
17144
17145   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17146      be template parameters.  */
17147   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17148     return true;
17149
17150   /* The standard does not specifically mention types that are local
17151      to template functions or local classes, but they should be
17152      considered dependent too.  For example:
17153
17154        template <int I> void f() {
17155          enum E { a = I };
17156          S<sizeof (E)> s;
17157        }
17158
17159      The size of `E' cannot be known until the value of `I' has been
17160      determined.  Therefore, `E' must be considered dependent.  */
17161   scope = TYPE_CONTEXT (type);
17162   if (scope && TYPE_P (scope))
17163     return dependent_type_p (scope);
17164   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17165     return type_dependent_expression_p (scope);
17166
17167   /* Other types are non-dependent.  */
17168   return false;
17169 }
17170
17171 /* Returns TRUE if TYPE is dependent, in the sense of
17172    [temp.dep.type].  */
17173
17174 bool
17175 dependent_type_p (tree type)
17176 {
17177   /* If there are no template parameters in scope, then there can't be
17178      any dependent types.  */
17179   if (!processing_template_decl)
17180     {
17181       /* If we are not processing a template, then nobody should be
17182          providing us with a dependent type.  */
17183       gcc_assert (type);
17184       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17185       return false;
17186     }
17187
17188   /* If the type is NULL, we have not computed a type for the entity
17189      in question; in that case, the type is dependent.  */
17190   if (!type)
17191     return true;
17192
17193   /* Erroneous types can be considered non-dependent.  */
17194   if (type == error_mark_node)
17195     return false;
17196
17197   /* If we have not already computed the appropriate value for TYPE,
17198      do so now.  */
17199   if (!TYPE_DEPENDENT_P_VALID (type))
17200     {
17201       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17202       TYPE_DEPENDENT_P_VALID (type) = 1;
17203     }
17204
17205   return TYPE_DEPENDENT_P (type);
17206 }
17207
17208 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17209    lookup.  In other words, a dependent type that is not the current
17210    instantiation.  */
17211
17212 bool
17213 dependent_scope_p (tree scope)
17214 {
17215   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17216           && !currently_open_class (scope));
17217 }
17218
17219 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17220
17221 static bool
17222 dependent_scope_ref_p (tree expression, bool criterion (tree))
17223 {
17224   tree scope;
17225   tree name;
17226
17227   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17228
17229   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17230     return true;
17231
17232   scope = TREE_OPERAND (expression, 0);
17233   name = TREE_OPERAND (expression, 1);
17234
17235   /* [temp.dep.expr]
17236
17237      An id-expression is type-dependent if it contains a
17238      nested-name-specifier that contains a class-name that names a
17239      dependent type.  */
17240   /* The suggested resolution to Core Issue 224 implies that if the
17241      qualifying type is the current class, then we must peek
17242      inside it.  */
17243   if (DECL_P (name)
17244       && currently_open_class (scope)
17245       && !criterion (name))
17246     return false;
17247   if (dependent_type_p (scope))
17248     return true;
17249
17250   return false;
17251 }
17252
17253 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17254    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17255    expression.  */
17256
17257 bool
17258 value_dependent_expression_p (tree expression)
17259 {
17260   if (!processing_template_decl)
17261     return false;
17262
17263   /* A name declared with a dependent type.  */
17264   if (DECL_P (expression) && type_dependent_expression_p (expression))
17265     return true;
17266
17267   switch (TREE_CODE (expression))
17268     {
17269     case IDENTIFIER_NODE:
17270       /* A name that has not been looked up -- must be dependent.  */
17271       return true;
17272
17273     case TEMPLATE_PARM_INDEX:
17274       /* A non-type template parm.  */
17275       return true;
17276
17277     case CONST_DECL:
17278       /* A non-type template parm.  */
17279       if (DECL_TEMPLATE_PARM_P (expression))
17280         return true;
17281       return value_dependent_expression_p (DECL_INITIAL (expression));
17282
17283     case VAR_DECL:
17284        /* A constant with integral or enumeration type and is initialized
17285           with an expression that is value-dependent.  */
17286       if (DECL_INITIAL (expression)
17287           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17288           && value_dependent_expression_p (DECL_INITIAL (expression)))
17289         return true;
17290       return false;
17291
17292     case DYNAMIC_CAST_EXPR:
17293     case STATIC_CAST_EXPR:
17294     case CONST_CAST_EXPR:
17295     case REINTERPRET_CAST_EXPR:
17296     case CAST_EXPR:
17297       /* These expressions are value-dependent if the type to which
17298          the cast occurs is dependent or the expression being casted
17299          is value-dependent.  */
17300       {
17301         tree type = TREE_TYPE (expression);
17302
17303         if (dependent_type_p (type))
17304           return true;
17305
17306         /* A functional cast has a list of operands.  */
17307         expression = TREE_OPERAND (expression, 0);
17308         if (!expression)
17309           {
17310             /* If there are no operands, it must be an expression such
17311                as "int()". This should not happen for aggregate types
17312                because it would form non-constant expressions.  */
17313             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17314
17315             return false;
17316           }
17317
17318         if (TREE_CODE (expression) == TREE_LIST)
17319           return any_value_dependent_elements_p (expression);
17320
17321         return value_dependent_expression_p (expression);
17322       }
17323
17324     case SIZEOF_EXPR:
17325     case ALIGNOF_EXPR:
17326       /* A `sizeof' expression is value-dependent if the operand is
17327          type-dependent or is a pack expansion.  */
17328       expression = TREE_OPERAND (expression, 0);
17329       if (PACK_EXPANSION_P (expression))
17330         return true;
17331       else if (TYPE_P (expression))
17332         return dependent_type_p (expression);
17333       return type_dependent_expression_p (expression);
17334
17335     case SCOPE_REF:
17336       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17337
17338     case COMPONENT_REF:
17339       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17340               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17341
17342     case CALL_EXPR:
17343       /* A CALL_EXPR may appear in a constant expression if it is a
17344          call to a builtin function, e.g., __builtin_constant_p.  All
17345          such calls are value-dependent.  */
17346       return true;
17347
17348     case NONTYPE_ARGUMENT_PACK:
17349       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17350          is value-dependent.  */
17351       {
17352         tree values = ARGUMENT_PACK_ARGS (expression);
17353         int i, len = TREE_VEC_LENGTH (values);
17354         
17355         for (i = 0; i < len; ++i)
17356           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17357             return true;
17358         
17359         return false;
17360       }
17361
17362     case TRAIT_EXPR:
17363       {
17364         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17365         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17366                 || (type2 ? dependent_type_p (type2) : false));
17367       }
17368
17369     case MODOP_EXPR:
17370       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17371               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17372
17373     default:
17374       /* A constant expression is value-dependent if any subexpression is
17375          value-dependent.  */
17376       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17377         {
17378         case tcc_reference:
17379         case tcc_unary:
17380           return (value_dependent_expression_p
17381                   (TREE_OPERAND (expression, 0)));
17382
17383         case tcc_comparison:
17384         case tcc_binary:
17385           return ((value_dependent_expression_p
17386                    (TREE_OPERAND (expression, 0)))
17387                   || (value_dependent_expression_p
17388                       (TREE_OPERAND (expression, 1))));
17389
17390         case tcc_expression:
17391         case tcc_vl_exp:
17392           {
17393             int i;
17394             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17395               /* In some cases, some of the operands may be missing.
17396                  (For example, in the case of PREDECREMENT_EXPR, the
17397                  amount to increment by may be missing.)  That doesn't
17398                  make the expression dependent.  */
17399               if (TREE_OPERAND (expression, i)
17400                   && (value_dependent_expression_p
17401                       (TREE_OPERAND (expression, i))))
17402                 return true;
17403             return false;
17404           }
17405
17406         default:
17407           break;
17408         }
17409     }
17410
17411   /* The expression is not value-dependent.  */
17412   return false;
17413 }
17414
17415 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17416    [temp.dep.expr].  */
17417
17418 bool
17419 type_dependent_expression_p (tree expression)
17420 {
17421   if (!processing_template_decl)
17422     return false;
17423
17424   if (expression == error_mark_node)
17425     return false;
17426
17427   /* An unresolved name is always dependent.  */
17428   if (TREE_CODE (expression) == IDENTIFIER_NODE
17429       || TREE_CODE (expression) == USING_DECL)
17430     return true;
17431
17432   /* Some expression forms are never type-dependent.  */
17433   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17434       || TREE_CODE (expression) == SIZEOF_EXPR
17435       || TREE_CODE (expression) == ALIGNOF_EXPR
17436       || TREE_CODE (expression) == TRAIT_EXPR
17437       || TREE_CODE (expression) == TYPEID_EXPR
17438       || TREE_CODE (expression) == DELETE_EXPR
17439       || TREE_CODE (expression) == VEC_DELETE_EXPR
17440       || TREE_CODE (expression) == THROW_EXPR)
17441     return false;
17442
17443   /* The types of these expressions depends only on the type to which
17444      the cast occurs.  */
17445   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17446       || TREE_CODE (expression) == STATIC_CAST_EXPR
17447       || TREE_CODE (expression) == CONST_CAST_EXPR
17448       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17449       || TREE_CODE (expression) == CAST_EXPR)
17450     return dependent_type_p (TREE_TYPE (expression));
17451
17452   /* The types of these expressions depends only on the type created
17453      by the expression.  */
17454   if (TREE_CODE (expression) == NEW_EXPR
17455       || TREE_CODE (expression) == VEC_NEW_EXPR)
17456     {
17457       /* For NEW_EXPR tree nodes created inside a template, either
17458          the object type itself or a TREE_LIST may appear as the
17459          operand 1.  */
17460       tree type = TREE_OPERAND (expression, 1);
17461       if (TREE_CODE (type) == TREE_LIST)
17462         /* This is an array type.  We need to check array dimensions
17463            as well.  */
17464         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17465                || value_dependent_expression_p
17466                     (TREE_OPERAND (TREE_VALUE (type), 1));
17467       else
17468         return dependent_type_p (type);
17469     }
17470
17471   if (TREE_CODE (expression) == SCOPE_REF
17472       && dependent_scope_ref_p (expression,
17473                                 type_dependent_expression_p))
17474     return true;
17475
17476   if (TREE_CODE (expression) == FUNCTION_DECL
17477       && DECL_LANG_SPECIFIC (expression)
17478       && DECL_TEMPLATE_INFO (expression)
17479       && (any_dependent_template_arguments_p
17480           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17481     return true;
17482
17483   if (TREE_CODE (expression) == TEMPLATE_DECL
17484       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17485     return false;
17486
17487   if (TREE_CODE (expression) == STMT_EXPR)
17488     expression = stmt_expr_value_expr (expression);
17489
17490   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17491     {
17492       tree elt;
17493       unsigned i;
17494
17495       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17496         {
17497           if (type_dependent_expression_p (elt))
17498             return true;
17499         }
17500       return false;
17501     }
17502
17503   if (TREE_TYPE (expression) == unknown_type_node)
17504     {
17505       if (TREE_CODE (expression) == ADDR_EXPR)
17506         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17507       if (TREE_CODE (expression) == COMPONENT_REF
17508           || TREE_CODE (expression) == OFFSET_REF)
17509         {
17510           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17511             return true;
17512           expression = TREE_OPERAND (expression, 1);
17513           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17514             return false;
17515         }
17516       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17517       if (TREE_CODE (expression) == SCOPE_REF)
17518         return false;
17519
17520       if (TREE_CODE (expression) == BASELINK)
17521         expression = BASELINK_FUNCTIONS (expression);
17522
17523       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17524         {
17525           if (any_dependent_template_arguments_p
17526               (TREE_OPERAND (expression, 1)))
17527             return true;
17528           expression = TREE_OPERAND (expression, 0);
17529         }
17530       gcc_assert (TREE_CODE (expression) == OVERLOAD
17531                   || TREE_CODE (expression) == FUNCTION_DECL);
17532
17533       while (expression)
17534         {
17535           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17536             return true;
17537           expression = OVL_NEXT (expression);
17538         }
17539       return false;
17540     }
17541
17542   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17543
17544   return (dependent_type_p (TREE_TYPE (expression)));
17545 }
17546
17547 /* Like type_dependent_expression_p, but it also works while not processing
17548    a template definition, i.e. during substitution or mangling.  */
17549
17550 bool
17551 type_dependent_expression_p_push (tree expr)
17552 {
17553   bool b;
17554   ++processing_template_decl;
17555   b = type_dependent_expression_p (expr);
17556   --processing_template_decl;
17557   return b;
17558 }
17559
17560 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17561
17562 bool
17563 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17564 {
17565   unsigned int i;
17566   tree arg;
17567
17568   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17569     {
17570       if (type_dependent_expression_p (arg))
17571         return true;
17572     }
17573   return false;
17574 }
17575
17576 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17577    expressions) contains any value-dependent expressions.  */
17578
17579 bool
17580 any_value_dependent_elements_p (const_tree list)
17581 {
17582   for (; list; list = TREE_CHAIN (list))
17583     if (value_dependent_expression_p (TREE_VALUE (list)))
17584       return true;
17585
17586   return false;
17587 }
17588
17589 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17590
17591 bool
17592 dependent_template_arg_p (tree arg)
17593 {
17594   if (!processing_template_decl)
17595     return false;
17596
17597   if (TREE_CODE (arg) == TEMPLATE_DECL
17598       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17599     return dependent_template_p (arg);
17600   else if (ARGUMENT_PACK_P (arg))
17601     {
17602       tree args = ARGUMENT_PACK_ARGS (arg);
17603       int i, len = TREE_VEC_LENGTH (args);
17604       for (i = 0; i < len; ++i)
17605         {
17606           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17607             return true;
17608         }
17609
17610       return false;
17611     }
17612   else if (TYPE_P (arg))
17613     return dependent_type_p (arg);
17614   else
17615     return (type_dependent_expression_p (arg)
17616             || value_dependent_expression_p (arg));
17617 }
17618
17619 /* Returns true if ARGS (a collection of template arguments) contains
17620    any types that require structural equality testing.  */
17621
17622 bool
17623 any_template_arguments_need_structural_equality_p (tree args)
17624 {
17625   int i;
17626   int j;
17627
17628   if (!args)
17629     return false;
17630   if (args == error_mark_node)
17631     return true;
17632
17633   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17634     {
17635       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17636       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17637         {
17638           tree arg = TREE_VEC_ELT (level, j);
17639           tree packed_args = NULL_TREE;
17640           int k, len = 1;
17641
17642           if (ARGUMENT_PACK_P (arg))
17643             {
17644               /* Look inside the argument pack.  */
17645               packed_args = ARGUMENT_PACK_ARGS (arg);
17646               len = TREE_VEC_LENGTH (packed_args);
17647             }
17648
17649           for (k = 0; k < len; ++k)
17650             {
17651               if (packed_args)
17652                 arg = TREE_VEC_ELT (packed_args, k);
17653
17654               if (error_operand_p (arg))
17655                 return true;
17656               else if (TREE_CODE (arg) == TEMPLATE_DECL
17657                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17658                 continue;
17659               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17660                 return true;
17661               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17662                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17663                 return true;
17664             }
17665         }
17666     }
17667
17668   return false;
17669 }
17670
17671 /* Returns true if ARGS (a collection of template arguments) contains
17672    any dependent arguments.  */
17673
17674 bool
17675 any_dependent_template_arguments_p (const_tree args)
17676 {
17677   int i;
17678   int j;
17679
17680   if (!args)
17681     return false;
17682   if (args == error_mark_node)
17683     return true;
17684
17685   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17686     {
17687       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17688       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17689         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17690           return true;
17691     }
17692
17693   return false;
17694 }
17695
17696 /* Returns TRUE if the template TMPL is dependent.  */
17697
17698 bool
17699 dependent_template_p (tree tmpl)
17700 {
17701   if (TREE_CODE (tmpl) == OVERLOAD)
17702     {
17703       while (tmpl)
17704         {
17705           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17706             return true;
17707           tmpl = OVL_CHAIN (tmpl);
17708         }
17709       return false;
17710     }
17711
17712   /* Template template parameters are dependent.  */
17713   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17714       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17715     return true;
17716   /* So are names that have not been looked up.  */
17717   if (TREE_CODE (tmpl) == SCOPE_REF
17718       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17719     return true;
17720   /* So are member templates of dependent classes.  */
17721   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17722     return dependent_type_p (DECL_CONTEXT (tmpl));
17723   return false;
17724 }
17725
17726 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17727
17728 bool
17729 dependent_template_id_p (tree tmpl, tree args)
17730 {
17731   return (dependent_template_p (tmpl)
17732           || any_dependent_template_arguments_p (args));
17733 }
17734
17735 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17736    is dependent.  */
17737
17738 bool
17739 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17740 {
17741   int i;
17742
17743   if (!processing_template_decl)
17744     return false;
17745
17746   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17747     {
17748       tree decl = TREE_VEC_ELT (declv, i);
17749       tree init = TREE_VEC_ELT (initv, i);
17750       tree cond = TREE_VEC_ELT (condv, i);
17751       tree incr = TREE_VEC_ELT (incrv, i);
17752
17753       if (type_dependent_expression_p (decl))
17754         return true;
17755
17756       if (init && type_dependent_expression_p (init))
17757         return true;
17758
17759       if (type_dependent_expression_p (cond))
17760         return true;
17761
17762       if (COMPARISON_CLASS_P (cond)
17763           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17764               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17765         return true;
17766
17767       if (TREE_CODE (incr) == MODOP_EXPR)
17768         {
17769           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17770               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17771             return true;
17772         }
17773       else if (type_dependent_expression_p (incr))
17774         return true;
17775       else if (TREE_CODE (incr) == MODIFY_EXPR)
17776         {
17777           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17778             return true;
17779           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17780             {
17781               tree t = TREE_OPERAND (incr, 1);
17782               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17783                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17784                 return true;
17785             }
17786         }
17787     }
17788
17789   return false;
17790 }
17791
17792 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17793    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17794    no such TYPE can be found.  Note that this function peers inside
17795    uninstantiated templates and therefore should be used only in
17796    extremely limited situations.  ONLY_CURRENT_P restricts this
17797    peering to the currently open classes hierarchy (which is required
17798    when comparing types).  */
17799
17800 tree
17801 resolve_typename_type (tree type, bool only_current_p)
17802 {
17803   tree scope;
17804   tree name;
17805   tree decl;
17806   int quals;
17807   tree pushed_scope;
17808   tree result;
17809
17810   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17811
17812   scope = TYPE_CONTEXT (type);
17813   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17814      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17815      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17816      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17817      identifier  of the TYPENAME_TYPE anymore.
17818      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17819      TYPENAME_TYPE instead, we avoid messing up with a possible
17820      typedef variant case.  */
17821   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17822
17823   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17824      it first before we can figure out what NAME refers to.  */
17825   if (TREE_CODE (scope) == TYPENAME_TYPE)
17826     scope = resolve_typename_type (scope, only_current_p);
17827   /* If we don't know what SCOPE refers to, then we cannot resolve the
17828      TYPENAME_TYPE.  */
17829   if (TREE_CODE (scope) == TYPENAME_TYPE)
17830     return type;
17831   /* If the SCOPE is a template type parameter, we have no way of
17832      resolving the name.  */
17833   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17834     return type;
17835   /* If the SCOPE is not the current instantiation, there's no reason
17836      to look inside it.  */
17837   if (only_current_p && !currently_open_class (scope))
17838     return type;
17839   /* If this is a typedef, we don't want to look inside (c++/11987).  */
17840   if (typedef_variant_p (type))
17841     return type;
17842   /* If SCOPE isn't the template itself, it will not have a valid
17843      TYPE_FIELDS list.  */
17844   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17845     /* scope is either the template itself or a compatible instantiation
17846        like X<T>, so look up the name in the original template.  */
17847     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17848   else
17849     /* scope is a partial instantiation, so we can't do the lookup or we
17850        will lose the template arguments.  */
17851     return type;
17852   /* Enter the SCOPE so that name lookup will be resolved as if we
17853      were in the class definition.  In particular, SCOPE will no
17854      longer be considered a dependent type.  */
17855   pushed_scope = push_scope (scope);
17856   /* Look up the declaration.  */
17857   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17858
17859   result = NULL_TREE;
17860   
17861   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17862      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17863   if (!decl)
17864     /*nop*/;
17865   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17866            && TREE_CODE (decl) == TYPE_DECL)
17867     {
17868       result = TREE_TYPE (decl);
17869       if (result == error_mark_node)
17870         result = NULL_TREE;
17871     }
17872   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17873            && DECL_CLASS_TEMPLATE_P (decl))
17874     {
17875       tree tmpl;
17876       tree args;
17877       /* Obtain the template and the arguments.  */
17878       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17879       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17880       /* Instantiate the template.  */
17881       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17882                                       /*entering_scope=*/0,
17883                                       tf_error | tf_user);
17884       if (result == error_mark_node)
17885         result = NULL_TREE;
17886     }
17887   
17888   /* Leave the SCOPE.  */
17889   if (pushed_scope)
17890     pop_scope (pushed_scope);
17891
17892   /* If we failed to resolve it, return the original typename.  */
17893   if (!result)
17894     return type;
17895   
17896   /* If lookup found a typename type, resolve that too.  */
17897   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17898     {
17899       /* Ill-formed programs can cause infinite recursion here, so we
17900          must catch that.  */
17901       TYPENAME_IS_RESOLVING_P (type) = 1;
17902       result = resolve_typename_type (result, only_current_p);
17903       TYPENAME_IS_RESOLVING_P (type) = 0;
17904     }
17905   
17906   /* Qualify the resulting type.  */
17907   quals = cp_type_quals (type);
17908   if (quals)
17909     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17910
17911   return result;
17912 }
17913
17914 /* EXPR is an expression which is not type-dependent.  Return a proxy
17915    for EXPR that can be used to compute the types of larger
17916    expressions containing EXPR.  */
17917
17918 tree
17919 build_non_dependent_expr (tree expr)
17920 {
17921   tree inner_expr;
17922
17923   /* Preserve null pointer constants so that the type of things like
17924      "p == 0" where "p" is a pointer can be determined.  */
17925   if (null_ptr_cst_p (expr))
17926     return expr;
17927   /* Preserve OVERLOADs; the functions must be available to resolve
17928      types.  */
17929   inner_expr = expr;
17930   if (TREE_CODE (inner_expr) == STMT_EXPR)
17931     inner_expr = stmt_expr_value_expr (inner_expr);
17932   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17933     inner_expr = TREE_OPERAND (inner_expr, 0);
17934   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17935     inner_expr = TREE_OPERAND (inner_expr, 1);
17936   if (is_overloaded_fn (inner_expr)
17937       || TREE_CODE (inner_expr) == OFFSET_REF)
17938     return expr;
17939   /* There is no need to return a proxy for a variable.  */
17940   if (TREE_CODE (expr) == VAR_DECL)
17941     return expr;
17942   /* Preserve string constants; conversions from string constants to
17943      "char *" are allowed, even though normally a "const char *"
17944      cannot be used to initialize a "char *".  */
17945   if (TREE_CODE (expr) == STRING_CST)
17946     return expr;
17947   /* Preserve arithmetic constants, as an optimization -- there is no
17948      reason to create a new node.  */
17949   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17950     return expr;
17951   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17952      There is at least one place where we want to know that a
17953      particular expression is a throw-expression: when checking a ?:
17954      expression, there are special rules if the second or third
17955      argument is a throw-expression.  */
17956   if (TREE_CODE (expr) == THROW_EXPR)
17957     return expr;
17958
17959   if (TREE_CODE (expr) == COND_EXPR)
17960     return build3 (COND_EXPR,
17961                    TREE_TYPE (expr),
17962                    TREE_OPERAND (expr, 0),
17963                    (TREE_OPERAND (expr, 1)
17964                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17965                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17966                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17967   if (TREE_CODE (expr) == COMPOUND_EXPR
17968       && !COMPOUND_EXPR_OVERLOADED (expr))
17969     return build2 (COMPOUND_EXPR,
17970                    TREE_TYPE (expr),
17971                    TREE_OPERAND (expr, 0),
17972                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17973
17974   /* If the type is unknown, it can't really be non-dependent */
17975   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17976
17977   /* Otherwise, build a NON_DEPENDENT_EXPR.
17978
17979      REFERENCE_TYPEs are not stripped for expressions in templates
17980      because doing so would play havoc with mangling.  Consider, for
17981      example:
17982
17983        template <typename T> void f<T& g>() { g(); }
17984
17985      In the body of "f", the expression for "g" will have
17986      REFERENCE_TYPE, even though the standard says that it should
17987      not.  The reason is that we must preserve the syntactic form of
17988      the expression so that mangling (say) "f<g>" inside the body of
17989      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17990      stripped here.  */
17991   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17992 }
17993
17994 /* ARGS is a vector of expressions as arguments to a function call.
17995    Replace the arguments with equivalent non-dependent expressions.
17996    This modifies ARGS in place.  */
17997
17998 void
17999 make_args_non_dependent (VEC(tree,gc) *args)
18000 {
18001   unsigned int ix;
18002   tree arg;
18003
18004   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18005     {
18006       tree newarg = build_non_dependent_expr (arg);
18007       if (newarg != arg)
18008         VEC_replace (tree, args, ix, newarg);
18009     }
18010 }
18011
18012 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18013    with a level one deeper than the actual template parms.  */
18014
18015 tree
18016 make_auto (void)
18017 {
18018   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18019   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18020                                TYPE_DECL, get_identifier ("auto"), au);
18021   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18022   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18023     (0, processing_template_decl + 1, processing_template_decl + 1,
18024      TYPE_NAME (au), NULL_TREE);
18025   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18026   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18027   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18028
18029   return au;
18030 }
18031
18032 /* Given type ARG, return std::initializer_list<ARG>.  */
18033
18034 static tree
18035 listify (tree arg)
18036 {
18037   tree std_init_list = namespace_binding
18038     (get_identifier ("initializer_list"), std_node);
18039   tree argvec;
18040   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18041     {    
18042       error ("deducing from brace-enclosed initializer list requires "
18043              "#include <initializer_list>");
18044       return error_mark_node;
18045     }
18046   argvec = make_tree_vec (1);
18047   TREE_VEC_ELT (argvec, 0) = arg;
18048   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18049                                 NULL_TREE, 0, tf_warning_or_error);
18050 }
18051
18052 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18053
18054 static tree
18055 listify_autos (tree type, tree auto_node)
18056 {
18057   tree init_auto = listify (auto_node);
18058   tree argvec = make_tree_vec (1);
18059   TREE_VEC_ELT (argvec, 0) = init_auto;
18060   if (processing_template_decl)
18061     argvec = add_to_template_args (current_template_args (), argvec);
18062   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18063 }
18064
18065 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18066    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18067
18068 tree
18069 do_auto_deduction (tree type, tree init, tree auto_node)
18070 {
18071   tree parms, tparms, targs;
18072   tree args[1];
18073   int val;
18074
18075   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18076      with either a new invented type template parameter U or, if the
18077      initializer is a braced-init-list (8.5.4), with
18078      std::initializer_list<U>.  */
18079   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18080     type = listify_autos (type, auto_node);
18081
18082   parms = build_tree_list (NULL_TREE, type);
18083   args[0] = init;
18084   tparms = make_tree_vec (1);
18085   targs = make_tree_vec (1);
18086   TREE_VEC_ELT (tparms, 0)
18087     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18088   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18089                                DEDUCE_CALL, LOOKUP_NORMAL);
18090   if (val > 0)
18091     {
18092       error ("unable to deduce %qT from %qE", type, init);
18093       return error_mark_node;
18094     }
18095
18096   /* If the list of declarators contains more than one declarator, the type
18097      of each declared variable is determined as described above. If the
18098      type deduced for the template parameter U is not the same in each
18099      deduction, the program is ill-formed.  */
18100   if (TREE_TYPE (auto_node)
18101       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18102     {
18103       error ("inconsistent deduction for %qT: %qT and then %qT",
18104              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18105       return error_mark_node;
18106     }
18107   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18108
18109   if (processing_template_decl)
18110     targs = add_to_template_args (current_template_args (), targs);
18111   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18112 }
18113
18114 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18115    result.  */
18116
18117 tree
18118 splice_late_return_type (tree type, tree late_return_type)
18119 {
18120   tree argvec;
18121
18122   if (late_return_type == NULL_TREE)
18123     return type;
18124   argvec = make_tree_vec (1);
18125   TREE_VEC_ELT (argvec, 0) = late_return_type;
18126   if (processing_template_decl)
18127     argvec = add_to_template_args (current_template_args (), argvec);
18128   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18129 }
18130
18131 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18132
18133 bool
18134 is_auto (const_tree type)
18135 {
18136   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18137       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18138     return true;
18139   else
18140     return false;
18141 }
18142
18143 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18144    appear as a type-specifier for the declaration in question, we don't
18145    have to look through the whole type.  */
18146
18147 tree
18148 type_uses_auto (tree type)
18149 {
18150   enum tree_code code;
18151   if (is_auto (type))
18152     return type;
18153
18154   code = TREE_CODE (type);
18155
18156   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18157       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18158       || code == METHOD_TYPE || code == ARRAY_TYPE)
18159     return type_uses_auto (TREE_TYPE (type));
18160
18161   if (TYPE_PTRMEMFUNC_P (type))
18162     return type_uses_auto (TREE_TYPE (TREE_TYPE
18163                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18164
18165   return NULL_TREE;
18166 }
18167
18168 /* For a given template T, return the vector of typedefs referenced
18169    in T for which access check is needed at T instantiation time.
18170    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18171    Those typedefs were added to T by the function
18172    append_type_to_template_for_access_check.  */
18173
18174 VEC(qualified_typedef_usage_t,gc)*
18175 get_types_needing_access_check (tree t)
18176 {
18177   tree ti;
18178   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18179
18180   if (!t || t == error_mark_node)
18181     return NULL;
18182
18183   if (!(ti = get_template_info (t)))
18184     return NULL;
18185
18186   if (CLASS_TYPE_P (t)
18187       || TREE_CODE (t) == FUNCTION_DECL)
18188     {
18189       if (!TI_TEMPLATE (ti))
18190         return NULL;
18191
18192       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18193     }
18194
18195   return result;
18196 }
18197
18198 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18199    tied to T. That list of typedefs will be access checked at
18200    T instantiation time.
18201    T is either a FUNCTION_DECL or a RECORD_TYPE.
18202    TYPE_DECL is a TYPE_DECL node representing a typedef.
18203    SCOPE is the scope through which TYPE_DECL is accessed.
18204    LOCATION is the location of the usage point of TYPE_DECL.
18205
18206    This function is a subroutine of
18207    append_type_to_template_for_access_check.  */
18208
18209 static void
18210 append_type_to_template_for_access_check_1 (tree t,
18211                                             tree type_decl,
18212                                             tree scope,
18213                                             location_t location)
18214 {
18215   qualified_typedef_usage_t typedef_usage;
18216   tree ti;
18217
18218   if (!t || t == error_mark_node)
18219     return;
18220
18221   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18222                || CLASS_TYPE_P (t))
18223               && type_decl
18224               && TREE_CODE (type_decl) == TYPE_DECL
18225               && scope);
18226
18227   if (!(ti = get_template_info (t)))
18228     return;
18229
18230   gcc_assert (TI_TEMPLATE (ti));
18231
18232   typedef_usage.typedef_decl = type_decl;
18233   typedef_usage.context = scope;
18234   typedef_usage.locus = location;
18235
18236   VEC_safe_push (qualified_typedef_usage_t, gc,
18237                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18238                  &typedef_usage);
18239 }
18240
18241 /* Append TYPE_DECL to the template TEMPL.
18242    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18243    At TEMPL instanciation time, TYPE_DECL will be checked to see
18244    if it can be accessed through SCOPE.
18245    LOCATION is the location of the usage point of TYPE_DECL.
18246
18247    e.g. consider the following code snippet:
18248
18249      class C
18250      {
18251        typedef int myint;
18252      };
18253
18254      template<class U> struct S
18255      {
18256        C::myint mi; // <-- usage point of the typedef C::myint
18257      };
18258
18259      S<char> s;
18260
18261    At S<char> instantiation time, we need to check the access of C::myint
18262    In other words, we need to check the access of the myint typedef through
18263    the C scope. For that purpose, this function will add the myint typedef
18264    and the scope C through which its being accessed to a list of typedefs
18265    tied to the template S. That list will be walked at template instantiation
18266    time and access check performed on each typedefs it contains.
18267    Note that this particular code snippet should yield an error because
18268    myint is private to C.  */
18269
18270 void
18271 append_type_to_template_for_access_check (tree templ,
18272                                           tree type_decl,
18273                                           tree scope,
18274                                           location_t location)
18275 {
18276   qualified_typedef_usage_t *iter;
18277   int i;
18278
18279   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18280
18281   /* Make sure we don't append the type to the template twice.  */
18282   for (i = 0;
18283        VEC_iterate (qualified_typedef_usage_t,
18284                     get_types_needing_access_check (templ),
18285                     i, iter);
18286        ++i)
18287     if (iter->typedef_decl == type_decl && scope == iter->context)
18288       return;
18289
18290   append_type_to_template_for_access_check_1 (templ, type_decl,
18291                                               scope, location);
18292 }
18293
18294 /* Set up the hash tables for template instantiations.  */
18295
18296 void
18297 init_template_processing (void)
18298 {
18299   decl_specializations = htab_create_ggc (37,
18300                                           hash_specialization,
18301                                           eq_specializations,
18302                                           ggc_free);
18303   type_specializations = htab_create_ggc (37,
18304                                           hash_specialization,
18305                                           eq_specializations,
18306                                           ggc_free);
18307 }
18308
18309 #include "gt-cp-pt.h"