OSDN Git Service

527fe04f5a8ac4254603cafa78b8712b17ff67f1
[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 "pointer-set.h"
36 #include "flags.h"
37 #include "c-common.h"
38 #include "cp-tree.h"
39 #include "cp-objcp-common.h"
40 #include "tree-inline.h"
41 #include "decl.h"
42 #include "output.h"
43 #include "except.h"
44 #include "toplev.h"
45 #include "rtl.h"
46 #include "timevar.h"
47 #include "tree-iterator.h"
48 #include "vecprim.h"
49
50 /* The type of functions taking a tree, and some additional data, and
51    returning an int.  */
52 typedef int (*tree_fn_t) (tree, void*);
53
54 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
55    instantiations have been deferred, either because their definitions
56    were not yet available, or because we were putting off doing the work.  */
57 struct GTY (()) pending_template {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64
65 int processing_template_parmlist;
66 static int template_header_count;
67
68 static GTY(()) tree saved_trees;
69 static VEC(int,heap) *inline_parm_levels;
70
71 static GTY(()) struct tinst_level *current_tinst_level;
72
73 static GTY(()) tree saved_access_scope;
74
75 /* Live only within one (recursive) call to tsubst_expr.  We use
76    this to pass the statement expression node from the STMT_EXPR
77    to the EXPR_STMT that is its result.  */
78 static tree cur_stmt_expr;
79
80 /* A map from local variable declarations in the body of the template
81    presently being instantiated to the corresponding instantiated
82    local variables.  */
83 static htab_t local_specializations;
84
85 typedef struct GTY(()) spec_entry
86 {
87   tree tmpl;
88   tree args;
89   tree spec;
90 } spec_entry;
91
92 static GTY ((param_is (spec_entry)))
93   htab_t decl_specializations;
94
95 static GTY ((param_is (spec_entry)))
96   htab_t type_specializations;
97
98 /* Contains canonical template parameter types. The vector is indexed by
99    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
100    TREE_LIST, whose TREE_VALUEs contain the canonical template
101    parameters of various types and levels.  */
102 static GTY(()) VEC(tree,gc) *canonical_template_parms;
103
104 #define UNIFY_ALLOW_NONE 0
105 #define UNIFY_ALLOW_MORE_CV_QUAL 1
106 #define UNIFY_ALLOW_LESS_CV_QUAL 2
107 #define UNIFY_ALLOW_DERIVED 4
108 #define UNIFY_ALLOW_INTEGER 8
109 #define UNIFY_ALLOW_OUTER_LEVEL 16
110 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
111 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
112
113 static void push_access_scope (tree);
114 static void pop_access_scope (tree);
115 static bool resolve_overloaded_unification (tree, tree, tree, tree,
116                                             unification_kind_t, int);
117 static int try_one_overload (tree, tree, tree, tree, tree,
118                              unification_kind_t, int, bool);
119 static int unify (tree, tree, tree, tree, int);
120 static void add_pending_template (tree);
121 static int push_tinst_level (tree);
122 static void pop_tinst_level (void);
123 static tree reopen_tinst_level (struct tinst_level *);
124 static tree tsubst_initializer_list (tree, tree);
125 static tree get_class_bindings (tree, tree, tree);
126 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
127                                    bool, bool);
128 static void tsubst_enum (tree, tree, tree);
129 static tree add_to_template_args (tree, tree);
130 static tree add_outermost_template_args (tree, tree);
131 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
132 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
133                                              tree);
134 static int type_unification_real (tree, tree, tree, const tree *,
135                                   unsigned int, int, unification_kind_t, int);
136 static void note_template_header (int);
137 static tree convert_nontype_argument_function (tree, tree);
138 static tree convert_nontype_argument (tree, tree);
139 static tree convert_template_argument (tree, tree, tree,
140                                        tsubst_flags_t, int, tree);
141 static int for_each_template_parm (tree, tree_fn_t, void*,
142                                    struct pointer_set_t*, bool);
143 static tree expand_template_argument_pack (tree);
144 static tree build_template_parm_index (int, int, int, tree, tree);
145 static bool inline_needs_template_parms (tree);
146 static void push_inline_template_parms_recursive (tree, int);
147 static tree retrieve_local_specialization (tree);
148 static void register_local_specialization (tree, tree);
149 static hashval_t hash_specialization (const void *p);
150 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
151 static int mark_template_parm (tree, void *);
152 static int template_parm_this_level_p (tree, void *);
153 static tree tsubst_friend_function (tree, tree);
154 static tree tsubst_friend_class (tree, tree);
155 static int can_complete_type_without_circularity (tree);
156 static tree get_bindings (tree, tree, tree, bool);
157 static int template_decl_level (tree);
158 static int check_cv_quals_for_unify (int, tree, tree);
159 static void template_parm_level_and_index (tree, int*, int*);
160 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
161 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
163 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
164 static void regenerate_decl_from_template (tree, tree);
165 static tree most_specialized_class (tree, tree);
166 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
167 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
168 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
169 static bool check_specialization_scope (void);
170 static tree process_partial_specialization (tree);
171 static void set_current_access_from_decl (tree);
172 static tree get_template_base (tree, tree, tree, tree);
173 static tree try_class_unification (tree, tree, tree, tree);
174 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
175                                            tree, tree);
176 static bool template_template_parm_bindings_ok_p (tree, tree);
177 static int template_args_equal (tree, tree);
178 static void tsubst_default_arguments (tree);
179 static tree for_each_template_parm_r (tree *, int *, void *);
180 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
181 static void copy_default_args_to_explicit_spec (tree);
182 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
183 static int eq_local_specializations (const void *, const void *);
184 static bool dependent_template_arg_p (tree);
185 static bool any_template_arguments_need_structural_equality_p (tree);
186 static bool dependent_type_p_r (tree);
187 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
188 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_decl (tree, tree, tsubst_flags_t);
191 static void perform_typedefs_access_check (tree tmpl, tree targs);
192 static void append_type_to_template_for_access_check_1 (tree, tree, tree);
193 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
194
195 /* Make the current scope suitable for access checking when we are
196    processing T.  T can be FUNCTION_DECL for instantiated function
197    template, or VAR_DECL for static member variable (need by
198    instantiate_decl).  */
199
200 static void
201 push_access_scope (tree t)
202 {
203   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
204               || TREE_CODE (t) == VAR_DECL);
205
206   if (DECL_FRIEND_CONTEXT (t))
207     push_nested_class (DECL_FRIEND_CONTEXT (t));
208   else if (DECL_CLASS_SCOPE_P (t))
209     push_nested_class (DECL_CONTEXT (t));
210   else
211     push_to_top_level ();
212
213   if (TREE_CODE (t) == FUNCTION_DECL)
214     {
215       saved_access_scope = tree_cons
216         (NULL_TREE, current_function_decl, saved_access_scope);
217       current_function_decl = t;
218     }
219 }
220
221 /* Restore the scope set up by push_access_scope.  T is the node we
222    are processing.  */
223
224 static void
225 pop_access_scope (tree t)
226 {
227   if (TREE_CODE (t) == FUNCTION_DECL)
228     {
229       current_function_decl = TREE_VALUE (saved_access_scope);
230       saved_access_scope = TREE_CHAIN (saved_access_scope);
231     }
232
233   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
234     pop_nested_class ();
235   else
236     pop_from_top_level ();
237 }
238
239 /* Do any processing required when DECL (a member template
240    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
241    to DECL, unless it is a specialization, in which case the DECL
242    itself is returned.  */
243
244 tree
245 finish_member_template_decl (tree decl)
246 {
247   if (decl == error_mark_node)
248     return error_mark_node;
249
250   gcc_assert (DECL_P (decl));
251
252   if (TREE_CODE (decl) == TYPE_DECL)
253     {
254       tree type;
255
256       type = TREE_TYPE (decl);
257       if (type == error_mark_node)
258         return error_mark_node;
259       if (MAYBE_CLASS_TYPE_P (type)
260           && CLASSTYPE_TEMPLATE_INFO (type)
261           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
262         {
263           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
264           check_member_template (tmpl);
265           return tmpl;
266         }
267       return NULL_TREE;
268     }
269   else if (TREE_CODE (decl) == FIELD_DECL)
270     error ("data member %qD cannot be a member template", decl);
271   else if (DECL_TEMPLATE_INFO (decl))
272     {
273       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
274         {
275           check_member_template (DECL_TI_TEMPLATE (decl));
276           return DECL_TI_TEMPLATE (decl);
277         }
278       else
279         return decl;
280     }
281   else
282     error ("invalid member template declaration %qD", decl);
283
284   return error_mark_node;
285 }
286
287 /* Return the template info node corresponding to T, whatever T is.  */
288
289 tree
290 get_template_info (tree t)
291 {
292   tree tinfo = NULL_TREE;
293
294   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
295     tinfo = DECL_TEMPLATE_INFO (t);
296
297   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
298     t = TREE_TYPE (t);
299
300   if (TAGGED_TYPE_P (t))
301     tinfo = TYPE_TEMPLATE_INFO (t);
302
303   return tinfo;
304 }
305
306 /* Returns the template nesting level of the indicated class TYPE.
307
308    For example, in:
309      template <class T>
310      struct A
311      {
312        template <class U>
313        struct B {};
314      };
315
316    A<T>::B<U> has depth two, while A<T> has depth one.
317    Both A<T>::B<int> and A<int>::B<U> have depth one, if
318    they are instantiations, not specializations.
319
320    This function is guaranteed to return 0 if passed NULL_TREE so
321    that, for example, `template_class_depth (current_class_type)' is
322    always safe.  */
323
324 int
325 template_class_depth (tree type)
326 {
327   int depth;
328
329   for (depth = 0;
330        type && TREE_CODE (type) != NAMESPACE_DECL;
331        type = (TREE_CODE (type) == FUNCTION_DECL)
332          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
333     {
334       tree tinfo = get_template_info (type);
335
336       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
337           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
338         ++depth;
339     }
340
341   return depth;
342 }
343
344 /* Subroutine of maybe_begin_member_template_processing.
345    Returns true if processing DECL needs us to push template parms.  */
346
347 static bool
348 inline_needs_template_parms (tree decl)
349 {
350   if (! DECL_TEMPLATE_INFO (decl))
351     return false;
352
353   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
354           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
355 }
356
357 /* Subroutine of maybe_begin_member_template_processing.
358    Push the template parms in PARMS, starting from LEVELS steps into the
359    chain, and ending at the beginning, since template parms are listed
360    innermost first.  */
361
362 static void
363 push_inline_template_parms_recursive (tree parmlist, int levels)
364 {
365   tree parms = TREE_VALUE (parmlist);
366   int i;
367
368   if (levels > 1)
369     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
370
371   ++processing_template_decl;
372   current_template_parms
373     = tree_cons (size_int (processing_template_decl),
374                  parms, current_template_parms);
375   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
376
377   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
378                NULL);
379   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
380     {
381       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
382
383       if (parm == error_mark_node)
384         continue;
385
386       gcc_assert (DECL_P (parm));
387
388       switch (TREE_CODE (parm))
389         {
390         case TYPE_DECL:
391         case TEMPLATE_DECL:
392           pushdecl (parm);
393           break;
394
395         case PARM_DECL:
396           {
397             /* Make a CONST_DECL as is done in process_template_parm.
398                It is ugly that we recreate this here; the original
399                version built in process_template_parm is no longer
400                available.  */
401             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
402                                     CONST_DECL, DECL_NAME (parm),
403                                     TREE_TYPE (parm));
404             DECL_ARTIFICIAL (decl) = 1;
405             TREE_CONSTANT (decl) = 1;
406             TREE_READONLY (decl) = 1;
407             DECL_INITIAL (decl) = DECL_INITIAL (parm);
408             SET_DECL_TEMPLATE_PARM_P (decl);
409             pushdecl (decl);
410           }
411           break;
412
413         default:
414           gcc_unreachable ();
415         }
416     }
417 }
418
419 /* Restore the template parameter context for a member template or
420    a friend template defined in a class definition.  */
421
422 void
423 maybe_begin_member_template_processing (tree decl)
424 {
425   tree parms;
426   int levels = 0;
427
428   if (inline_needs_template_parms (decl))
429     {
430       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
431       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
432
433       if (DECL_TEMPLATE_SPECIALIZATION (decl))
434         {
435           --levels;
436           parms = TREE_CHAIN (parms);
437         }
438
439       push_inline_template_parms_recursive (parms, levels);
440     }
441
442   /* Remember how many levels of template parameters we pushed so that
443      we can pop them later.  */
444   VEC_safe_push (int, heap, inline_parm_levels, levels);
445 }
446
447 /* Undo the effects of maybe_begin_member_template_processing.  */
448
449 void
450 maybe_end_member_template_processing (void)
451 {
452   int i;
453   int last;
454
455   if (VEC_length (int, inline_parm_levels) == 0)
456     return;
457
458   last = VEC_pop (int, inline_parm_levels);
459   for (i = 0; i < last; ++i)
460     {
461       --processing_template_decl;
462       current_template_parms = TREE_CHAIN (current_template_parms);
463       poplevel (0, 0, 0);
464     }
465 }
466
467 /* Return a new template argument vector which contains all of ARGS,
468    but has as its innermost set of arguments the EXTRA_ARGS.  */
469
470 static tree
471 add_to_template_args (tree args, tree extra_args)
472 {
473   tree new_args;
474   int extra_depth;
475   int i;
476   int j;
477
478   extra_depth = TMPL_ARGS_DEPTH (extra_args);
479   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
480
481   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
482     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
483
484   for (j = 1; j <= extra_depth; ++j, ++i)
485     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
486
487   return new_args;
488 }
489
490 /* Like add_to_template_args, but only the outermost ARGS are added to
491    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
492    (EXTRA_ARGS) levels are added.  This function is used to combine
493    the template arguments from a partial instantiation with the
494    template arguments used to attain the full instantiation from the
495    partial instantiation.  */
496
497 static tree
498 add_outermost_template_args (tree args, tree extra_args)
499 {
500   tree new_args;
501
502   /* If there are more levels of EXTRA_ARGS than there are ARGS,
503      something very fishy is going on.  */
504   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
505
506   /* If *all* the new arguments will be the EXTRA_ARGS, just return
507      them.  */
508   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
509     return extra_args;
510
511   /* For the moment, we make ARGS look like it contains fewer levels.  */
512   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
513
514   new_args = add_to_template_args (args, extra_args);
515
516   /* Now, we restore ARGS to its full dimensions.  */
517   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
518
519   return new_args;
520 }
521
522 /* Return the N levels of innermost template arguments from the ARGS.  */
523
524 tree
525 get_innermost_template_args (tree args, int n)
526 {
527   tree new_args;
528   int extra_levels;
529   int i;
530
531   gcc_assert (n >= 0);
532
533   /* If N is 1, just return the innermost set of template arguments.  */
534   if (n == 1)
535     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
536
537   /* If we're not removing anything, just return the arguments we were
538      given.  */
539   extra_levels = TMPL_ARGS_DEPTH (args) - n;
540   gcc_assert (extra_levels >= 0);
541   if (extra_levels == 0)
542     return args;
543
544   /* Make a new set of arguments, not containing the outer arguments.  */
545   new_args = make_tree_vec (n);
546   for (i = 1; i <= n; ++i)
547     SET_TMPL_ARGS_LEVEL (new_args, i,
548                          TMPL_ARGS_LEVEL (args, i + extra_levels));
549
550   return new_args;
551 }
552
553 /* The inverse of get_innermost_template_args: Return all but the innermost
554    EXTRA_LEVELS levels of template arguments from the ARGS.  */
555
556 static tree
557 strip_innermost_template_args (tree args, int extra_levels)
558 {
559   tree new_args;
560   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
561   int i;
562
563   gcc_assert (n >= 0);
564
565   /* If N is 1, just return the outermost set of template arguments.  */
566   if (n == 1)
567     return TMPL_ARGS_LEVEL (args, 1);
568
569   /* If we're not removing anything, just return the arguments we were
570      given.  */
571   gcc_assert (extra_levels >= 0);
572   if (extra_levels == 0)
573     return args;
574
575   /* Make a new set of arguments, not containing the inner arguments.  */
576   new_args = make_tree_vec (n);
577   for (i = 1; i <= n; ++i)
578     SET_TMPL_ARGS_LEVEL (new_args, i,
579                          TMPL_ARGS_LEVEL (args, i));
580
581   return new_args;
582 }
583
584 /* We've got a template header coming up; push to a new level for storing
585    the parms.  */
586
587 void
588 begin_template_parm_list (void)
589 {
590   /* We use a non-tag-transparent scope here, which causes pushtag to
591      put tags in this scope, rather than in the enclosing class or
592      namespace scope.  This is the right thing, since we want
593      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
594      global template class, push_template_decl handles putting the
595      TEMPLATE_DECL into top-level scope.  For a nested template class,
596      e.g.:
597
598        template <class T> struct S1 {
599          template <class T> struct S2 {};
600        };
601
602      pushtag contains special code to call pushdecl_with_scope on the
603      TEMPLATE_DECL for S2.  */
604   begin_scope (sk_template_parms, NULL);
605   ++processing_template_decl;
606   ++processing_template_parmlist;
607   note_template_header (0);
608 }
609
610 /* This routine is called when a specialization is declared.  If it is
611    invalid to declare a specialization here, an error is reported and
612    false is returned, otherwise this routine will return true.  */
613
614 static bool
615 check_specialization_scope (void)
616 {
617   tree scope = current_scope ();
618
619   /* [temp.expl.spec]
620
621      An explicit specialization shall be declared in the namespace of
622      which the template is a member, or, for member templates, in the
623      namespace of which the enclosing class or enclosing class
624      template is a member.  An explicit specialization of a member
625      function, member class or static data member of a class template
626      shall be declared in the namespace of which the class template
627      is a member.  */
628   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
629     {
630       error ("explicit specialization in non-namespace scope %qD", scope);
631       return false;
632     }
633
634   /* [temp.expl.spec]
635
636      In an explicit specialization declaration for a member of a class
637      template or a member template that appears in namespace scope,
638      the member template and some of its enclosing class templates may
639      remain unspecialized, except that the declaration shall not
640      explicitly specialize a class member template if its enclosing
641      class templates are not explicitly specialized as well.  */
642   if (current_template_parms)
643     {
644       error ("enclosing class templates are not explicitly specialized");
645       return false;
646     }
647
648   return true;
649 }
650
651 /* We've just seen template <>.  */
652
653 bool
654 begin_specialization (void)
655 {
656   begin_scope (sk_template_spec, NULL);
657   note_template_header (1);
658   return check_specialization_scope ();
659 }
660
661 /* Called at then end of processing a declaration preceded by
662    template<>.  */
663
664 void
665 end_specialization (void)
666 {
667   finish_scope ();
668   reset_specialization ();
669 }
670
671 /* Any template <>'s that we have seen thus far are not referring to a
672    function specialization.  */
673
674 void
675 reset_specialization (void)
676 {
677   processing_specialization = 0;
678   template_header_count = 0;
679 }
680
681 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
682    it was of the form template <>.  */
683
684 static void
685 note_template_header (int specialization)
686 {
687   processing_specialization = specialization;
688   template_header_count++;
689 }
690
691 /* We're beginning an explicit instantiation.  */
692
693 void
694 begin_explicit_instantiation (void)
695 {
696   gcc_assert (!processing_explicit_instantiation);
697   processing_explicit_instantiation = true;
698 }
699
700
701 void
702 end_explicit_instantiation (void)
703 {
704   gcc_assert (processing_explicit_instantiation);
705   processing_explicit_instantiation = false;
706 }
707
708 /* An explicit specialization or partial specialization TMPL is being
709    declared.  Check that the namespace in which the specialization is
710    occurring is permissible.  Returns false iff it is invalid to
711    specialize TMPL in the current namespace.  */
712
713 static bool
714 check_specialization_namespace (tree tmpl)
715 {
716   tree tpl_ns = decl_namespace_context (tmpl);
717
718   /* [tmpl.expl.spec]
719
720      An explicit specialization shall be declared in the namespace of
721      which the template is a member, or, for member templates, in the
722      namespace of which the enclosing class or enclosing class
723      template is a member.  An explicit specialization of a member
724      function, member class or static data member of a class template
725      shall be declared in the namespace of which the class template is
726      a member.  */
727   if (is_associated_namespace (current_namespace, tpl_ns))
728     /* Same or super-using namespace.  */
729     return true;
730   else
731     {
732       permerror (input_location, "specialization of %qD in different namespace", tmpl);
733       permerror (input_location, "  from definition of %q+#D", tmpl);
734       return false;
735     }
736 }
737
738 /* SPEC is an explicit instantiation.  Check that it is valid to
739    perform this explicit instantiation in the current namespace.  */
740
741 static void
742 check_explicit_instantiation_namespace (tree spec)
743 {
744   tree ns;
745
746   /* DR 275: An explicit instantiation shall appear in an enclosing
747      namespace of its template.  */
748   ns = decl_namespace_context (spec);
749   if (!is_ancestor (current_namespace, ns))
750     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
751                "(which does not enclose namespace %qD)",
752                spec, current_namespace, ns);
753 }
754
755 /* The TYPE is being declared.  If it is a template type, that means it
756    is a partial specialization.  Do appropriate error-checking.  */
757
758 tree
759 maybe_process_partial_specialization (tree type)
760 {
761   tree context;
762
763   if (type == error_mark_node)
764     return error_mark_node;
765
766   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
767     {
768       error ("name of class shadows template template parameter %qD",
769              TYPE_NAME (type));
770       return error_mark_node;
771     }
772
773   context = TYPE_CONTEXT (type);
774
775   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
776     {
777       /* This is for ordinary explicit specialization and partial
778          specialization of a template class such as:
779
780            template <> class C<int>;
781
782          or:
783
784            template <class T> class C<T*>;
785
786          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
787
788       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
789           && !COMPLETE_TYPE_P (type))
790         {
791           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
792           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
793           if (processing_template_decl)
794             {
795               if (push_template_decl (TYPE_MAIN_DECL (type))
796                   == error_mark_node)
797                 return error_mark_node;
798             }
799         }
800       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
801         error ("specialization of %qT after instantiation", type);
802     }
803   else if (CLASS_TYPE_P (type)
804            && !CLASSTYPE_USE_TEMPLATE (type)
805            && CLASSTYPE_TEMPLATE_INFO (type)
806            && context && CLASS_TYPE_P (context)
807            && CLASSTYPE_TEMPLATE_INFO (context))
808     {
809       /* This is for an explicit specialization of member class
810          template according to [temp.expl.spec/18]:
811
812            template <> template <class U> class C<int>::D;
813
814          The context `C<int>' must be an implicit instantiation.
815          Otherwise this is just a member class template declared
816          earlier like:
817
818            template <> class C<int> { template <class U> class D; };
819            template <> template <class U> class C<int>::D;
820
821          In the first case, `C<int>::D' is a specialization of `C<T>::D'
822          while in the second case, `C<int>::D' is a primary template
823          and `C<T>::D' may not exist.  */
824
825       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
826           && !COMPLETE_TYPE_P (type))
827         {
828           tree t;
829           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
830
831           if (current_namespace
832               != decl_namespace_context (tmpl))
833             {
834               permerror (input_location, "specializing %q#T in different namespace", type);
835               permerror (input_location, "  from definition of %q+#D", tmpl);
836             }
837
838           /* Check for invalid specialization after instantiation:
839
840                template <> template <> class C<int>::D<int>;
841                template <> template <class U> class C<int>::D;  */
842
843           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
844                t; t = TREE_CHAIN (t))
845             {
846               tree inst = TREE_VALUE (t);
847               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
848                 {
849                   /* We already have a full specialization of this partial
850                      instantiation.  Reassign it to the new member
851                      specialization template.  */
852                   spec_entry elt;
853                   spec_entry **slot;
854
855                   elt.tmpl = most_general_template (tmpl);
856                   elt.args = CLASSTYPE_TI_ARGS (inst);
857                   elt.spec = inst;
858
859                   htab_remove_elt (type_specializations, &elt);
860
861                   elt.tmpl = tmpl;
862                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
863
864                   slot = (spec_entry **)
865                     htab_find_slot (type_specializations, &elt, INSERT);
866                   *slot = GGC_NEW (spec_entry);
867                   **slot = elt;
868                 }
869               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
870                 /* But if we've had an implicit instantiation, that's a
871                    problem ([temp.expl.spec]/6).  */
872                 error ("specialization %qT after instantiation %qT",
873                        type, inst);
874             }
875
876           /* Mark TYPE as a specialization.  And as a result, we only
877              have one level of template argument for the innermost
878              class template.  */
879           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
880           CLASSTYPE_TI_ARGS (type)
881             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
882         }
883     }
884   else if (processing_specialization)
885     {
886       error ("explicit specialization of non-template %qT", type);
887       return error_mark_node;
888     }
889
890   return type;
891 }
892
893 /* Returns nonzero if we can optimize the retrieval of specializations
894    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
895    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
896
897 static inline bool
898 optimize_specialization_lookup_p (tree tmpl)
899 {
900   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
901           && DECL_CLASS_SCOPE_P (tmpl)
902           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
903              parameter.  */
904           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
905           /* The optimized lookup depends on the fact that the
906              template arguments for the member function template apply
907              purely to the containing class, which is not true if the
908              containing class is an explicit or partial
909              specialization.  */
910           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
911           && !DECL_MEMBER_TEMPLATE_P (tmpl)
912           && !DECL_CONV_FN_P (tmpl)
913           /* It is possible to have a template that is not a member
914              template and is not a member of a template class:
915
916              template <typename T>
917              struct S { friend A::f(); };
918
919              Here, the friend function is a template, but the context does
920              not have template information.  The optimized lookup relies
921              on having ARGS be the template arguments for both the class
922              and the function template.  */
923           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
924 }
925
926 /* Retrieve the specialization (in the sense of [temp.spec] - a
927    specialization is either an instantiation or an explicit
928    specialization) of TMPL for the given template ARGS.  If there is
929    no such specialization, return NULL_TREE.  The ARGS are a vector of
930    arguments, or a vector of vectors of arguments, in the case of
931    templates with more than one level of parameters.
932
933    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
934    then we search for a partial specialization matching ARGS.  This
935    parameter is ignored if TMPL is not a class template.  */
936
937 static tree
938 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
939 {
940   if (args == error_mark_node)
941     return NULL_TREE;
942
943   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
944
945   /* There should be as many levels of arguments as there are
946      levels of parameters.  */
947   gcc_assert (TMPL_ARGS_DEPTH (args)
948               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
949
950   if (optimize_specialization_lookup_p (tmpl))
951     {
952       tree class_template;
953       tree class_specialization;
954       VEC(tree,gc) *methods;
955       tree fns;
956       int idx;
957
958       /* The template arguments actually apply to the containing
959          class.  Find the class specialization with those
960          arguments.  */
961       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
962       class_specialization
963         = retrieve_specialization (class_template, args, 0);
964       if (!class_specialization)
965         return NULL_TREE;
966       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
967          for the specialization.  */
968       idx = class_method_index_for_fn (class_specialization, tmpl);
969       if (idx == -1)
970         return NULL_TREE;
971       /* Iterate through the methods with the indicated name, looking
972          for the one that has an instance of TMPL.  */
973       methods = CLASSTYPE_METHOD_VEC (class_specialization);
974       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
975         {
976           tree fn = OVL_CURRENT (fns);
977           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
978             return fn;
979         }
980       return NULL_TREE;
981     }
982   else
983     {
984       spec_entry *found;
985       spec_entry elt;
986       htab_t specializations;
987
988       elt.tmpl = tmpl;
989       elt.args = args;
990       elt.spec = NULL_TREE;
991
992       if (DECL_CLASS_TEMPLATE_P (tmpl))
993         specializations = type_specializations;
994       else
995         specializations = decl_specializations;
996
997       if (hash == 0)
998         hash = hash_specialization (&elt);
999       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1000       if (found)
1001         return found->spec;
1002     }
1003
1004   return NULL_TREE;
1005 }
1006
1007 /* Like retrieve_specialization, but for local declarations.  */
1008
1009 static tree
1010 retrieve_local_specialization (tree tmpl)
1011 {
1012   tree spec;
1013
1014   if (local_specializations == NULL)
1015     return NULL_TREE;
1016
1017   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1018                                      htab_hash_pointer (tmpl));
1019   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1020 }
1021
1022 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1023
1024 int
1025 is_specialization_of (tree decl, tree tmpl)
1026 {
1027   tree t;
1028
1029   if (TREE_CODE (decl) == FUNCTION_DECL)
1030     {
1031       for (t = decl;
1032            t != NULL_TREE;
1033            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1034         if (t == tmpl)
1035           return 1;
1036     }
1037   else
1038     {
1039       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1040
1041       for (t = TREE_TYPE (decl);
1042            t != NULL_TREE;
1043            t = CLASSTYPE_USE_TEMPLATE (t)
1044              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1045         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1046           return 1;
1047     }
1048
1049   return 0;
1050 }
1051
1052 /* Returns nonzero iff DECL is a specialization of friend declaration
1053    FRIEND_DECL according to [temp.friend].  */
1054
1055 bool
1056 is_specialization_of_friend (tree decl, tree friend_decl)
1057 {
1058   bool need_template = true;
1059   int template_depth;
1060
1061   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1062               || TREE_CODE (decl) == TYPE_DECL);
1063
1064   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1065      of a template class, we want to check if DECL is a specialization
1066      if this.  */
1067   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1068       && DECL_TEMPLATE_INFO (friend_decl)
1069       && !DECL_USE_TEMPLATE (friend_decl))
1070     {
1071       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1072       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1073       need_template = false;
1074     }
1075   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1076            && !PRIMARY_TEMPLATE_P (friend_decl))
1077     need_template = false;
1078
1079   /* There is nothing to do if this is not a template friend.  */
1080   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1081     return false;
1082
1083   if (is_specialization_of (decl, friend_decl))
1084     return true;
1085
1086   /* [temp.friend/6]
1087      A member of a class template may be declared to be a friend of a
1088      non-template class.  In this case, the corresponding member of
1089      every specialization of the class template is a friend of the
1090      class granting friendship.
1091
1092      For example, given a template friend declaration
1093
1094        template <class T> friend void A<T>::f();
1095
1096      the member function below is considered a friend
1097
1098        template <> struct A<int> {
1099          void f();
1100        };
1101
1102      For this type of template friend, TEMPLATE_DEPTH below will be
1103      nonzero.  To determine if DECL is a friend of FRIEND, we first
1104      check if the enclosing class is a specialization of another.  */
1105
1106   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1107   if (template_depth
1108       && DECL_CLASS_SCOPE_P (decl)
1109       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1110                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1111     {
1112       /* Next, we check the members themselves.  In order to handle
1113          a few tricky cases, such as when FRIEND_DECL's are
1114
1115            template <class T> friend void A<T>::g(T t);
1116            template <class T> template <T t> friend void A<T>::h();
1117
1118          and DECL's are
1119
1120            void A<int>::g(int);
1121            template <int> void A<int>::h();
1122
1123          we need to figure out ARGS, the template arguments from
1124          the context of DECL.  This is required for template substitution
1125          of `T' in the function parameter of `g' and template parameter
1126          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1127
1128       tree context = DECL_CONTEXT (decl);
1129       tree args = NULL_TREE;
1130       int current_depth = 0;
1131
1132       while (current_depth < template_depth)
1133         {
1134           if (CLASSTYPE_TEMPLATE_INFO (context))
1135             {
1136               if (current_depth == 0)
1137                 args = TYPE_TI_ARGS (context);
1138               else
1139                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1140               current_depth++;
1141             }
1142           context = TYPE_CONTEXT (context);
1143         }
1144
1145       if (TREE_CODE (decl) == FUNCTION_DECL)
1146         {
1147           bool is_template;
1148           tree friend_type;
1149           tree decl_type;
1150           tree friend_args_type;
1151           tree decl_args_type;
1152
1153           /* Make sure that both DECL and FRIEND_DECL are templates or
1154              non-templates.  */
1155           is_template = DECL_TEMPLATE_INFO (decl)
1156                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1157           if (need_template ^ is_template)
1158             return false;
1159           else if (is_template)
1160             {
1161               /* If both are templates, check template parameter list.  */
1162               tree friend_parms
1163                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1164                                          args, tf_none);
1165               if (!comp_template_parms
1166                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1167                       friend_parms))
1168                 return false;
1169
1170               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1171             }
1172           else
1173             decl_type = TREE_TYPE (decl);
1174
1175           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1176                                               tf_none, NULL_TREE);
1177           if (friend_type == error_mark_node)
1178             return false;
1179
1180           /* Check if return types match.  */
1181           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1182             return false;
1183
1184           /* Check if function parameter types match, ignoring the
1185              `this' parameter.  */
1186           friend_args_type = TYPE_ARG_TYPES (friend_type);
1187           decl_args_type = TYPE_ARG_TYPES (decl_type);
1188           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1189             friend_args_type = TREE_CHAIN (friend_args_type);
1190           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1191             decl_args_type = TREE_CHAIN (decl_args_type);
1192
1193           return compparms (decl_args_type, friend_args_type);
1194         }
1195       else
1196         {
1197           /* DECL is a TYPE_DECL */
1198           bool is_template;
1199           tree decl_type = TREE_TYPE (decl);
1200
1201           /* Make sure that both DECL and FRIEND_DECL are templates or
1202              non-templates.  */
1203           is_template
1204             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1205               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1206
1207           if (need_template ^ is_template)
1208             return false;
1209           else if (is_template)
1210             {
1211               tree friend_parms;
1212               /* If both are templates, check the name of the two
1213                  TEMPLATE_DECL's first because is_friend didn't.  */
1214               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1215                   != DECL_NAME (friend_decl))
1216                 return false;
1217
1218               /* Now check template parameter list.  */
1219               friend_parms
1220                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1221                                          args, tf_none);
1222               return comp_template_parms
1223                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1224                  friend_parms);
1225             }
1226           else
1227             return (DECL_NAME (decl)
1228                     == DECL_NAME (friend_decl));
1229         }
1230     }
1231   return false;
1232 }
1233
1234 /* Register the specialization SPEC as a specialization of TMPL with
1235    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1236    is actually just a friend declaration.  Returns SPEC, or an
1237    equivalent prior declaration, if available.  */
1238
1239 static tree
1240 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1241                          hashval_t hash)
1242 {
1243   tree fn;
1244   spec_entry **slot = NULL;
1245   spec_entry elt;
1246
1247   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1248
1249   if (TREE_CODE (spec) == FUNCTION_DECL
1250       && uses_template_parms (DECL_TI_ARGS (spec)))
1251     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1252        register it; we want the corresponding TEMPLATE_DECL instead.
1253        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1254        the more obvious `uses_template_parms (spec)' to avoid problems
1255        with default function arguments.  In particular, given
1256        something like this:
1257
1258           template <class T> void f(T t1, T t = T())
1259
1260        the default argument expression is not substituted for in an
1261        instantiation unless and until it is actually needed.  */
1262     return spec;
1263
1264   if (optimize_specialization_lookup_p (tmpl))
1265     /* We don't put these specializations in the hash table, but we might
1266        want to give an error about a mismatch.  */
1267     fn = retrieve_specialization (tmpl, args, 0);
1268   else
1269     {
1270       elt.tmpl = tmpl;
1271       elt.args = args;
1272       elt.spec = spec;
1273
1274       if (hash == 0)
1275         hash = hash_specialization (&elt);
1276
1277       slot = (spec_entry **)
1278         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1279       if (*slot)
1280         fn = (*slot)->spec;
1281       else
1282         fn = NULL_TREE;
1283     }
1284
1285   /* We can sometimes try to re-register a specialization that we've
1286      already got.  In particular, regenerate_decl_from_template calls
1287      duplicate_decls which will update the specialization list.  But,
1288      we'll still get called again here anyhow.  It's more convenient
1289      to simply allow this than to try to prevent it.  */
1290   if (fn == spec)
1291     return spec;
1292   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1293     {
1294       if (DECL_TEMPLATE_INSTANTIATION (fn))
1295         {
1296           if (TREE_USED (fn)
1297               || DECL_EXPLICIT_INSTANTIATION (fn))
1298             {
1299               error ("specialization of %qD after instantiation",
1300                      fn);
1301               return error_mark_node;
1302             }
1303           else
1304             {
1305               tree clone;
1306               /* This situation should occur only if the first
1307                  specialization is an implicit instantiation, the
1308                  second is an explicit specialization, and the
1309                  implicit instantiation has not yet been used.  That
1310                  situation can occur if we have implicitly
1311                  instantiated a member function and then specialized
1312                  it later.
1313
1314                  We can also wind up here if a friend declaration that
1315                  looked like an instantiation turns out to be a
1316                  specialization:
1317
1318                    template <class T> void foo(T);
1319                    class S { friend void foo<>(int) };
1320                    template <> void foo(int);
1321
1322                  We transform the existing DECL in place so that any
1323                  pointers to it become pointers to the updated
1324                  declaration.
1325
1326                  If there was a definition for the template, but not
1327                  for the specialization, we want this to look as if
1328                  there were no definition, and vice versa.  */
1329               DECL_INITIAL (fn) = NULL_TREE;
1330               duplicate_decls (spec, fn, is_friend);
1331               /* The call to duplicate_decls will have applied
1332                  [temp.expl.spec]:
1333
1334                    An explicit specialization of a function template
1335                    is inline only if it is explicitly declared to be,
1336                    and independently of whether its function template
1337                    is.
1338
1339                 to the primary function; now copy the inline bits to
1340                 the various clones.  */
1341               FOR_EACH_CLONE (clone, fn)
1342                 DECL_DECLARED_INLINE_P (clone)
1343                   = DECL_DECLARED_INLINE_P (fn);
1344               check_specialization_namespace (fn);
1345
1346               return fn;
1347             }
1348         }
1349       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1350         {
1351           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1352             /* Dup decl failed, but this is a new definition. Set the
1353                line number so any errors match this new
1354                definition.  */
1355             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1356
1357           return fn;
1358         }
1359     }
1360   else if (fn)
1361     return duplicate_decls (spec, fn, is_friend);
1362
1363   /* A specialization must be declared in the same namespace as the
1364      template it is specializing.  */
1365   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1366       && !check_specialization_namespace (tmpl))
1367     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1368
1369   if (!optimize_specialization_lookup_p (tmpl))
1370     {
1371       gcc_assert (tmpl && args && spec);
1372       *slot = GGC_NEW (spec_entry);
1373       **slot = elt;
1374       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1375           && PRIMARY_TEMPLATE_P (tmpl)
1376           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1377         /* TMPL is a forward declaration of a template function; keep a list
1378            of all specializations in case we need to reassign them to a friend
1379            template later in tsubst_friend_function.  */
1380         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1381           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1382     }
1383
1384   return spec;
1385 }
1386
1387 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1388    TMPL and ARGS members, ignores SPEC.  */
1389
1390 static int
1391 eq_specializations (const void *p1, const void *p2)
1392 {
1393   const spec_entry *e1 = (const spec_entry *)p1;
1394   const spec_entry *e2 = (const spec_entry *)p2;
1395
1396   return (e1->tmpl == e2->tmpl
1397           && comp_template_args (e1->args, e2->args));
1398 }
1399
1400 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1401
1402 static hashval_t
1403 hash_tmpl_and_args (tree tmpl, tree args)
1404 {
1405   hashval_t val = DECL_UID (tmpl);
1406   return iterative_hash_template_arg (args, val);
1407 }
1408
1409 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1410    ignoring SPEC.  */
1411
1412 static hashval_t
1413 hash_specialization (const void *p)
1414 {
1415   const spec_entry *e = (const spec_entry *)p;
1416   return hash_tmpl_and_args (e->tmpl, e->args);
1417 }
1418
1419 /* Recursively calculate a hash value for a template argument ARG, for use
1420    in the hash tables of template specializations.  */
1421
1422 static hashval_t
1423 iterative_hash_template_arg (tree arg, hashval_t val)
1424 {
1425   unsigned HOST_WIDE_INT i;
1426   enum tree_code code;
1427   char tclass;
1428
1429   if (arg == NULL_TREE)
1430     return iterative_hash_object (arg, val);
1431
1432   if (!TYPE_P (arg))
1433     STRIP_NOPS (arg);
1434
1435   code = TREE_CODE (arg);
1436   tclass = TREE_CODE_CLASS (code);
1437
1438   val = iterative_hash_object (code, val);
1439
1440   switch (code)
1441     {
1442     case ERROR_MARK:
1443       return val;
1444
1445     case IDENTIFIER_NODE:
1446       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1447
1448     case TREE_VEC:
1449       {
1450         int i, len = TREE_VEC_LENGTH (arg);
1451         for (i = 0; i < len; ++i)
1452           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1453         return val;
1454       }
1455
1456     case TYPE_PACK_EXPANSION:
1457     case EXPR_PACK_EXPANSION:
1458       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1459
1460     case ARGUMENT_PACK_SELECT:
1461       /* We can get one of these when re-hashing a previous entry in the middle
1462          of substituting into a pack expansion.  Just look through it...  */
1463       arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1464       /* ...and fall through.  */
1465     case TYPE_ARGUMENT_PACK:
1466     case NONTYPE_ARGUMENT_PACK:
1467       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1468
1469     case TREE_LIST:
1470       for (; arg; arg = TREE_CHAIN (arg))
1471         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1472       return val;
1473
1474     case OVERLOAD:
1475       for (; arg; arg = OVL_CHAIN (arg))
1476         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1477       return val;
1478
1479     case CONSTRUCTOR:
1480       {
1481         tree field, value;
1482         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1483           {
1484             val = iterative_hash_template_arg (field, val);
1485             val = iterative_hash_template_arg (value, val);
1486           }
1487         return val;
1488       }
1489
1490     case PARM_DECL:
1491       val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1492       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1493
1494     case TARGET_EXPR:
1495       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1496
1497     case PTRMEM_CST:
1498       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1499       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1500
1501     case TEMPLATE_PARM_INDEX:
1502       val = iterative_hash_template_arg
1503         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1504       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1505       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1506
1507     case TRAIT_EXPR:
1508       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1509       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1510       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1511
1512     case BASELINK:
1513       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1514                                          val);
1515       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1516                                           val);
1517
1518     case MODOP_EXPR:
1519       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1520       code = TREE_CODE (TREE_OPERAND (arg, 1));
1521       val = iterative_hash_object (code, val);
1522       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1523
1524     default:
1525       switch (tclass)
1526         {
1527         case tcc_type:
1528           if (TYPE_CANONICAL (arg))
1529             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1530                                           val);
1531           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1532             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1533           /* Otherwise just compare the types during lookup.  */
1534           return val;
1535
1536         case tcc_declaration:
1537         case tcc_constant:
1538           return iterative_hash_expr (arg, val);
1539
1540         default:
1541           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1542           {
1543             unsigned n = TREE_OPERAND_LENGTH (arg);
1544             for (i = 0; i < n; ++i)
1545               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1546             return val;
1547           }
1548         }
1549     }
1550   gcc_unreachable ();
1551   return 0;
1552 }
1553
1554 /* Unregister the specialization SPEC as a specialization of TMPL.
1555    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1556    if the SPEC was listed as a specialization of TMPL.
1557
1558    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1559
1560 bool
1561 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1562 {
1563   spec_entry **slot;
1564   spec_entry elt;
1565
1566   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1567   elt.args = TI_ARGS (tinfo);
1568   elt.spec = NULL_TREE;
1569
1570   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1571   if (*slot)
1572     {
1573       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1574       gcc_assert (new_spec != NULL_TREE);
1575       (*slot)->spec = new_spec;
1576       return 1;
1577     }
1578
1579   return 0;
1580 }
1581
1582 /* Compare an entry in the local specializations hash table P1 (which
1583    is really a pointer to a TREE_LIST) with P2 (which is really a
1584    DECL).  */
1585
1586 static int
1587 eq_local_specializations (const void *p1, const void *p2)
1588 {
1589   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1590 }
1591
1592 /* Hash P1, an entry in the local specializations table.  */
1593
1594 static hashval_t
1595 hash_local_specialization (const void* p1)
1596 {
1597   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1598 }
1599
1600 /* Like register_specialization, but for local declarations.  We are
1601    registering SPEC, an instantiation of TMPL.  */
1602
1603 static void
1604 register_local_specialization (tree spec, tree tmpl)
1605 {
1606   void **slot;
1607
1608   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1609                                    htab_hash_pointer (tmpl), INSERT);
1610   *slot = build_tree_list (spec, tmpl);
1611 }
1612
1613 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1614    specialized class.  */
1615
1616 bool
1617 explicit_class_specialization_p (tree type)
1618 {
1619   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1620     return false;
1621   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1622 }
1623
1624 /* Print the list of candidate FNS in an error message.  */
1625
1626 void
1627 print_candidates (tree fns)
1628 {
1629   tree fn;
1630
1631   const char *str = "candidates are:";
1632
1633   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1634     {
1635       tree f;
1636
1637       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1638         error ("%s %+#D", str, OVL_CURRENT (f));
1639       str = "               ";
1640     }
1641 }
1642
1643 /* Returns the template (one of the functions given by TEMPLATE_ID)
1644    which can be specialized to match the indicated DECL with the
1645    explicit template args given in TEMPLATE_ID.  The DECL may be
1646    NULL_TREE if none is available.  In that case, the functions in
1647    TEMPLATE_ID are non-members.
1648
1649    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1650    specialization of a member template.
1651
1652    The TEMPLATE_COUNT is the number of references to qualifying
1653    template classes that appeared in the name of the function. See
1654    check_explicit_specialization for a more accurate description.
1655
1656    TSK indicates what kind of template declaration (if any) is being
1657    declared.  TSK_TEMPLATE indicates that the declaration given by
1658    DECL, though a FUNCTION_DECL, has template parameters, and is
1659    therefore a template function.
1660
1661    The template args (those explicitly specified and those deduced)
1662    are output in a newly created vector *TARGS_OUT.
1663
1664    If it is impossible to determine the result, an error message is
1665    issued.  The error_mark_node is returned to indicate failure.  */
1666
1667 static tree
1668 determine_specialization (tree template_id,
1669                           tree decl,
1670                           tree* targs_out,
1671                           int need_member_template,
1672                           int template_count,
1673                           tmpl_spec_kind tsk)
1674 {
1675   tree fns;
1676   tree targs;
1677   tree explicit_targs;
1678   tree candidates = NULL_TREE;
1679   /* A TREE_LIST of templates of which DECL may be a specialization.
1680      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1681      corresponding TREE_PURPOSE is the set of template arguments that,
1682      when used to instantiate the template, would produce a function
1683      with the signature of DECL.  */
1684   tree templates = NULL_TREE;
1685   int header_count;
1686   struct cp_binding_level *b;
1687
1688   *targs_out = NULL_TREE;
1689
1690   if (template_id == error_mark_node || decl == error_mark_node)
1691     return error_mark_node;
1692
1693   fns = TREE_OPERAND (template_id, 0);
1694   explicit_targs = TREE_OPERAND (template_id, 1);
1695
1696   if (fns == error_mark_node)
1697     return error_mark_node;
1698
1699   /* Check for baselinks.  */
1700   if (BASELINK_P (fns))
1701     fns = BASELINK_FUNCTIONS (fns);
1702
1703   if (!is_overloaded_fn (fns))
1704     {
1705       error ("%qD is not a function template", fns);
1706       return error_mark_node;
1707     }
1708
1709   /* Count the number of template headers specified for this
1710      specialization.  */
1711   header_count = 0;
1712   for (b = current_binding_level;
1713        b->kind == sk_template_parms;
1714        b = b->level_chain)
1715     ++header_count;
1716
1717   for (; fns; fns = OVL_NEXT (fns))
1718     {
1719       tree fn = OVL_CURRENT (fns);
1720
1721       if (TREE_CODE (fn) == TEMPLATE_DECL)
1722         {
1723           tree decl_arg_types;
1724           tree fn_arg_types;
1725
1726           /* In case of explicit specialization, we need to check if
1727              the number of template headers appearing in the specialization
1728              is correct. This is usually done in check_explicit_specialization,
1729              but the check done there cannot be exhaustive when specializing
1730              member functions. Consider the following code:
1731
1732              template <> void A<int>::f(int);
1733              template <> template <> void A<int>::f(int);
1734
1735              Assuming that A<int> is not itself an explicit specialization
1736              already, the first line specializes "f" which is a non-template
1737              member function, whilst the second line specializes "f" which
1738              is a template member function. So both lines are syntactically
1739              correct, and check_explicit_specialization does not reject
1740              them.
1741
1742              Here, we can do better, as we are matching the specialization
1743              against the declarations. We count the number of template
1744              headers, and we check if they match TEMPLATE_COUNT + 1
1745              (TEMPLATE_COUNT is the number of qualifying template classes,
1746              plus there must be another header for the member template
1747              itself).
1748
1749              Notice that if header_count is zero, this is not a
1750              specialization but rather a template instantiation, so there
1751              is no check we can perform here.  */
1752           if (header_count && header_count != template_count + 1)
1753             continue;
1754
1755           /* Check that the number of template arguments at the
1756              innermost level for DECL is the same as for FN.  */
1757           if (current_binding_level->kind == sk_template_parms
1758               && !current_binding_level->explicit_spec_p
1759               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1760                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1761                                       (current_template_parms))))
1762             continue;
1763
1764           /* DECL might be a specialization of FN.  */
1765           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1766           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1767
1768           /* For a non-static member function, we need to make sure
1769              that the const qualification is the same.  Since
1770              get_bindings does not try to merge the "this" parameter,
1771              we must do the comparison explicitly.  */
1772           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1773               && !same_type_p (TREE_VALUE (fn_arg_types),
1774                                TREE_VALUE (decl_arg_types)))
1775             continue;
1776
1777           /* Skip the "this" parameter and, for constructors of
1778              classes with virtual bases, the VTT parameter.  A
1779              full specialization of a constructor will have a VTT
1780              parameter, but a template never will.  */ 
1781           decl_arg_types 
1782             = skip_artificial_parms_for (decl, decl_arg_types);
1783           fn_arg_types 
1784             = skip_artificial_parms_for (fn, fn_arg_types);
1785
1786           /* Check that the number of function parameters matches.
1787              For example,
1788                template <class T> void f(int i = 0);
1789                template <> void f<int>();
1790              The specialization f<int> is invalid but is not caught
1791              by get_bindings below.  */
1792           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1793             continue;
1794
1795           /* Function templates cannot be specializations; there are
1796              no partial specializations of functions.  Therefore, if
1797              the type of DECL does not match FN, there is no
1798              match.  */
1799           if (tsk == tsk_template)
1800             {
1801               if (compparms (fn_arg_types, decl_arg_types))
1802                 candidates = tree_cons (NULL_TREE, fn, candidates);
1803               continue;
1804             }
1805
1806           /* See whether this function might be a specialization of this
1807              template.  */
1808           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1809
1810           if (!targs)
1811             /* We cannot deduce template arguments that when used to
1812                specialize TMPL will produce DECL.  */
1813             continue;
1814
1815           /* Save this template, and the arguments deduced.  */
1816           templates = tree_cons (targs, fn, templates);
1817         }
1818       else if (need_member_template)
1819         /* FN is an ordinary member function, and we need a
1820            specialization of a member template.  */
1821         ;
1822       else if (TREE_CODE (fn) != FUNCTION_DECL)
1823         /* We can get IDENTIFIER_NODEs here in certain erroneous
1824            cases.  */
1825         ;
1826       else if (!DECL_FUNCTION_MEMBER_P (fn))
1827         /* This is just an ordinary non-member function.  Nothing can
1828            be a specialization of that.  */
1829         ;
1830       else if (DECL_ARTIFICIAL (fn))
1831         /* Cannot specialize functions that are created implicitly.  */
1832         ;
1833       else
1834         {
1835           tree decl_arg_types;
1836
1837           /* This is an ordinary member function.  However, since
1838              we're here, we can assume it's enclosing class is a
1839              template class.  For example,
1840
1841                template <typename T> struct S { void f(); };
1842                template <> void S<int>::f() {}
1843
1844              Here, S<int>::f is a non-template, but S<int> is a
1845              template class.  If FN has the same type as DECL, we
1846              might be in business.  */
1847
1848           if (!DECL_TEMPLATE_INFO (fn))
1849             /* Its enclosing class is an explicit specialization
1850                of a template class.  This is not a candidate.  */
1851             continue;
1852
1853           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1854                             TREE_TYPE (TREE_TYPE (fn))))
1855             /* The return types differ.  */
1856             continue;
1857
1858           /* Adjust the type of DECL in case FN is a static member.  */
1859           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1860           if (DECL_STATIC_FUNCTION_P (fn)
1861               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1862             decl_arg_types = TREE_CHAIN (decl_arg_types);
1863
1864           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1865                          decl_arg_types))
1866             /* They match!  */
1867             candidates = tree_cons (NULL_TREE, fn, candidates);
1868         }
1869     }
1870
1871   if (templates && TREE_CHAIN (templates))
1872     {
1873       /* We have:
1874
1875            [temp.expl.spec]
1876
1877            It is possible for a specialization with a given function
1878            signature to be instantiated from more than one function
1879            template.  In such cases, explicit specification of the
1880            template arguments must be used to uniquely identify the
1881            function template specialization being specialized.
1882
1883          Note that here, there's no suggestion that we're supposed to
1884          determine which of the candidate templates is most
1885          specialized.  However, we, also have:
1886
1887            [temp.func.order]
1888
1889            Partial ordering of overloaded function template
1890            declarations is used in the following contexts to select
1891            the function template to which a function template
1892            specialization refers:
1893
1894            -- when an explicit specialization refers to a function
1895               template.
1896
1897          So, we do use the partial ordering rules, at least for now.
1898          This extension can only serve to make invalid programs valid,
1899          so it's safe.  And, there is strong anecdotal evidence that
1900          the committee intended the partial ordering rules to apply;
1901          the EDG front end has that behavior, and John Spicer claims
1902          that the committee simply forgot to delete the wording in
1903          [temp.expl.spec].  */
1904       tree tmpl = most_specialized_instantiation (templates);
1905       if (tmpl != error_mark_node)
1906         {
1907           templates = tmpl;
1908           TREE_CHAIN (templates) = NULL_TREE;
1909         }
1910     }
1911
1912   if (templates == NULL_TREE && candidates == NULL_TREE)
1913     {
1914       error ("template-id %qD for %q+D does not match any template "
1915              "declaration", template_id, decl);
1916       return error_mark_node;
1917     }
1918   else if ((templates && TREE_CHAIN (templates))
1919            || (candidates && TREE_CHAIN (candidates))
1920            || (templates && candidates))
1921     {
1922       error ("ambiguous template specialization %qD for %q+D",
1923              template_id, decl);
1924       chainon (candidates, templates);
1925       print_candidates (candidates);
1926       return error_mark_node;
1927     }
1928
1929   /* We have one, and exactly one, match.  */
1930   if (candidates)
1931     {
1932       tree fn = TREE_VALUE (candidates);
1933       *targs_out = copy_node (DECL_TI_ARGS (fn));
1934       /* DECL is a re-declaration or partial instantiation of a template
1935          function.  */
1936       if (TREE_CODE (fn) == TEMPLATE_DECL)
1937         return fn;
1938       /* It was a specialization of an ordinary member function in a
1939          template class.  */
1940       return DECL_TI_TEMPLATE (fn);
1941     }
1942
1943   /* It was a specialization of a template.  */
1944   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1945   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1946     {
1947       *targs_out = copy_node (targs);
1948       SET_TMPL_ARGS_LEVEL (*targs_out,
1949                            TMPL_ARGS_DEPTH (*targs_out),
1950                            TREE_PURPOSE (templates));
1951     }
1952   else
1953     *targs_out = TREE_PURPOSE (templates);
1954   return TREE_VALUE (templates);
1955 }
1956
1957 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1958    but with the default argument values filled in from those in the
1959    TMPL_TYPES.  */
1960
1961 static tree
1962 copy_default_args_to_explicit_spec_1 (tree spec_types,
1963                                       tree tmpl_types)
1964 {
1965   tree new_spec_types;
1966
1967   if (!spec_types)
1968     return NULL_TREE;
1969
1970   if (spec_types == void_list_node)
1971     return void_list_node;
1972
1973   /* Substitute into the rest of the list.  */
1974   new_spec_types =
1975     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1976                                           TREE_CHAIN (tmpl_types));
1977
1978   /* Add the default argument for this parameter.  */
1979   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1980                          TREE_VALUE (spec_types),
1981                          new_spec_types);
1982 }
1983
1984 /* DECL is an explicit specialization.  Replicate default arguments
1985    from the template it specializes.  (That way, code like:
1986
1987      template <class T> void f(T = 3);
1988      template <> void f(double);
1989      void g () { f (); }
1990
1991    works, as required.)  An alternative approach would be to look up
1992    the correct default arguments at the call-site, but this approach
1993    is consistent with how implicit instantiations are handled.  */
1994
1995 static void
1996 copy_default_args_to_explicit_spec (tree decl)
1997 {
1998   tree tmpl;
1999   tree spec_types;
2000   tree tmpl_types;
2001   tree new_spec_types;
2002   tree old_type;
2003   tree new_type;
2004   tree t;
2005   tree object_type = NULL_TREE;
2006   tree in_charge = NULL_TREE;
2007   tree vtt = NULL_TREE;
2008
2009   /* See if there's anything we need to do.  */
2010   tmpl = DECL_TI_TEMPLATE (decl);
2011   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2012   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2013     if (TREE_PURPOSE (t))
2014       break;
2015   if (!t)
2016     return;
2017
2018   old_type = TREE_TYPE (decl);
2019   spec_types = TYPE_ARG_TYPES (old_type);
2020
2021   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2022     {
2023       /* Remove the this pointer, but remember the object's type for
2024          CV quals.  */
2025       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2026       spec_types = TREE_CHAIN (spec_types);
2027       tmpl_types = TREE_CHAIN (tmpl_types);
2028
2029       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2030         {
2031           /* DECL may contain more parameters than TMPL due to the extra
2032              in-charge parameter in constructors and destructors.  */
2033           in_charge = spec_types;
2034           spec_types = TREE_CHAIN (spec_types);
2035         }
2036       if (DECL_HAS_VTT_PARM_P (decl))
2037         {
2038           vtt = spec_types;
2039           spec_types = TREE_CHAIN (spec_types);
2040         }
2041     }
2042
2043   /* Compute the merged default arguments.  */
2044   new_spec_types =
2045     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2046
2047   /* Compute the new FUNCTION_TYPE.  */
2048   if (object_type)
2049     {
2050       if (vtt)
2051         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2052                                          TREE_VALUE (vtt),
2053                                          new_spec_types);
2054
2055       if (in_charge)
2056         /* Put the in-charge parameter back.  */
2057         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2058                                          TREE_VALUE (in_charge),
2059                                          new_spec_types);
2060
2061       new_type = build_method_type_directly (object_type,
2062                                              TREE_TYPE (old_type),
2063                                              new_spec_types);
2064     }
2065   else
2066     new_type = build_function_type (TREE_TYPE (old_type),
2067                                     new_spec_types);
2068   new_type = cp_build_type_attribute_variant (new_type,
2069                                               TYPE_ATTRIBUTES (old_type));
2070   new_type = build_exception_variant (new_type,
2071                                       TYPE_RAISES_EXCEPTIONS (old_type));
2072   TREE_TYPE (decl) = new_type;
2073 }
2074
2075 /* Check to see if the function just declared, as indicated in
2076    DECLARATOR, and in DECL, is a specialization of a function
2077    template.  We may also discover that the declaration is an explicit
2078    instantiation at this point.
2079
2080    Returns DECL, or an equivalent declaration that should be used
2081    instead if all goes well.  Issues an error message if something is
2082    amiss.  Returns error_mark_node if the error is not easily
2083    recoverable.
2084
2085    FLAGS is a bitmask consisting of the following flags:
2086
2087    2: The function has a definition.
2088    4: The function is a friend.
2089
2090    The TEMPLATE_COUNT is the number of references to qualifying
2091    template classes that appeared in the name of the function.  For
2092    example, in
2093
2094      template <class T> struct S { void f(); };
2095      void S<int>::f();
2096
2097    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2098    classes are not counted in the TEMPLATE_COUNT, so that in
2099
2100      template <class T> struct S {};
2101      template <> struct S<int> { void f(); }
2102      template <> void S<int>::f();
2103
2104    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2105    invalid; there should be no template <>.)
2106
2107    If the function is a specialization, it is marked as such via
2108    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2109    is set up correctly, and it is added to the list of specializations
2110    for that template.  */
2111
2112 tree
2113 check_explicit_specialization (tree declarator,
2114                                tree decl,
2115                                int template_count,
2116                                int flags)
2117 {
2118   int have_def = flags & 2;
2119   int is_friend = flags & 4;
2120   int specialization = 0;
2121   int explicit_instantiation = 0;
2122   int member_specialization = 0;
2123   tree ctype = DECL_CLASS_CONTEXT (decl);
2124   tree dname = DECL_NAME (decl);
2125   tmpl_spec_kind tsk;
2126
2127   if (is_friend)
2128     {
2129       if (!processing_specialization)
2130         tsk = tsk_none;
2131       else
2132         tsk = tsk_excessive_parms;
2133     }
2134   else
2135     tsk = current_tmpl_spec_kind (template_count);
2136
2137   switch (tsk)
2138     {
2139     case tsk_none:
2140       if (processing_specialization)
2141         {
2142           specialization = 1;
2143           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2144         }
2145       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2146         {
2147           if (is_friend)
2148             /* This could be something like:
2149
2150                template <class T> void f(T);
2151                class S { friend void f<>(int); }  */
2152             specialization = 1;
2153           else
2154             {
2155               /* This case handles bogus declarations like template <>
2156                  template <class T> void f<int>(); */
2157
2158               error ("template-id %qD in declaration of primary template",
2159                      declarator);
2160               return decl;
2161             }
2162         }
2163       break;
2164
2165     case tsk_invalid_member_spec:
2166       /* The error has already been reported in
2167          check_specialization_scope.  */
2168       return error_mark_node;
2169
2170     case tsk_invalid_expl_inst:
2171       error ("template parameter list used in explicit instantiation");
2172
2173       /* Fall through.  */
2174
2175     case tsk_expl_inst:
2176       if (have_def)
2177         error ("definition provided for explicit instantiation");
2178
2179       explicit_instantiation = 1;
2180       break;
2181
2182     case tsk_excessive_parms:
2183     case tsk_insufficient_parms:
2184       if (tsk == tsk_excessive_parms)
2185         error ("too many template parameter lists in declaration of %qD",
2186                decl);
2187       else if (template_header_count)
2188         error("too few template parameter lists in declaration of %qD", decl);
2189       else
2190         error("explicit specialization of %qD must be introduced by "
2191               "%<template <>%>", decl);
2192
2193       /* Fall through.  */
2194     case tsk_expl_spec:
2195       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2196       if (ctype)
2197         member_specialization = 1;
2198       else
2199         specialization = 1;
2200       break;
2201
2202     case tsk_template:
2203       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2204         {
2205           /* This case handles bogus declarations like template <>
2206              template <class T> void f<int>(); */
2207
2208           if (uses_template_parms (declarator))
2209             error ("function template partial specialization %qD "
2210                    "is not allowed", declarator);
2211           else
2212             error ("template-id %qD in declaration of primary template",
2213                    declarator);
2214           return decl;
2215         }
2216
2217       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2218         /* This is a specialization of a member template, without
2219            specialization the containing class.  Something like:
2220
2221              template <class T> struct S {
2222                template <class U> void f (U);
2223              };
2224              template <> template <class U> void S<int>::f(U) {}
2225
2226            That's a specialization -- but of the entire template.  */
2227         specialization = 1;
2228       break;
2229
2230     default:
2231       gcc_unreachable ();
2232     }
2233
2234   if (specialization || member_specialization)
2235     {
2236       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2237       for (; t; t = TREE_CHAIN (t))
2238         if (TREE_PURPOSE (t))
2239           {
2240             permerror (input_location, 
2241                        "default argument specified in explicit specialization");
2242             break;
2243           }
2244     }
2245
2246   if (specialization || member_specialization || explicit_instantiation)
2247     {
2248       tree tmpl = NULL_TREE;
2249       tree targs = NULL_TREE;
2250
2251       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2252       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2253         {
2254           tree fns;
2255
2256           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2257           if (ctype)
2258             fns = dname;
2259           else
2260             {
2261               /* If there is no class context, the explicit instantiation
2262                  must be at namespace scope.  */
2263               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2264
2265               /* Find the namespace binding, using the declaration
2266                  context.  */
2267               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2268                                            false, true);
2269               if (fns == error_mark_node || !is_overloaded_fn (fns))
2270                 {
2271                   error ("%qD is not a template function", dname);
2272                   fns = error_mark_node;
2273                 }
2274               else
2275                 {
2276                   tree fn = OVL_CURRENT (fns);
2277                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2278                                                 CP_DECL_CONTEXT (fn)))
2279                     error ("%qD is not declared in %qD",
2280                            decl, current_namespace);
2281                 }
2282             }
2283
2284           declarator = lookup_template_function (fns, NULL_TREE);
2285         }
2286
2287       if (declarator == error_mark_node)
2288         return error_mark_node;
2289
2290       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2291         {
2292           if (!explicit_instantiation)
2293             /* A specialization in class scope.  This is invalid,
2294                but the error will already have been flagged by
2295                check_specialization_scope.  */
2296             return error_mark_node;
2297           else
2298             {
2299               /* It's not valid to write an explicit instantiation in
2300                  class scope, e.g.:
2301
2302                    class C { template void f(); }
2303
2304                    This case is caught by the parser.  However, on
2305                    something like:
2306
2307                    template class C { void f(); };
2308
2309                    (which is invalid) we can get here.  The error will be
2310                    issued later.  */
2311               ;
2312             }
2313
2314           return decl;
2315         }
2316       else if (ctype != NULL_TREE
2317                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2318                    IDENTIFIER_NODE))
2319         {
2320           /* Find the list of functions in ctype that have the same
2321              name as the declared function.  */
2322           tree name = TREE_OPERAND (declarator, 0);
2323           tree fns = NULL_TREE;
2324           int idx;
2325
2326           if (constructor_name_p (name, ctype))
2327             {
2328               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2329
2330               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2331                   : !CLASSTYPE_DESTRUCTORS (ctype))
2332                 {
2333                   /* From [temp.expl.spec]:
2334
2335                      If such an explicit specialization for the member
2336                      of a class template names an implicitly-declared
2337                      special member function (clause _special_), the
2338                      program is ill-formed.
2339
2340                      Similar language is found in [temp.explicit].  */
2341                   error ("specialization of implicitly-declared special member function");
2342                   return error_mark_node;
2343                 }
2344
2345               name = is_constructor ? ctor_identifier : dtor_identifier;
2346             }
2347
2348           if (!DECL_CONV_FN_P (decl))
2349             {
2350               idx = lookup_fnfields_1 (ctype, name);
2351               if (idx >= 0)
2352                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2353             }
2354           else
2355             {
2356               VEC(tree,gc) *methods;
2357               tree ovl;
2358
2359               /* For a type-conversion operator, we cannot do a
2360                  name-based lookup.  We might be looking for `operator
2361                  int' which will be a specialization of `operator T'.
2362                  So, we find *all* the conversion operators, and then
2363                  select from them.  */
2364               fns = NULL_TREE;
2365
2366               methods = CLASSTYPE_METHOD_VEC (ctype);
2367               if (methods)
2368                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2369                      VEC_iterate (tree, methods, idx, ovl);
2370                      ++idx)
2371                   {
2372                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2373                       /* There are no more conversion functions.  */
2374                       break;
2375
2376                     /* Glue all these conversion functions together
2377                        with those we already have.  */
2378                     for (; ovl; ovl = OVL_NEXT (ovl))
2379                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2380                   }
2381             }
2382
2383           if (fns == NULL_TREE)
2384             {
2385               error ("no member function %qD declared in %qT", name, ctype);
2386               return error_mark_node;
2387             }
2388           else
2389             TREE_OPERAND (declarator, 0) = fns;
2390         }
2391
2392       /* Figure out what exactly is being specialized at this point.
2393          Note that for an explicit instantiation, even one for a
2394          member function, we cannot tell apriori whether the
2395          instantiation is for a member template, or just a member
2396          function of a template class.  Even if a member template is
2397          being instantiated, the member template arguments may be
2398          elided if they can be deduced from the rest of the
2399          declaration.  */
2400       tmpl = determine_specialization (declarator, decl,
2401                                        &targs,
2402                                        member_specialization,
2403                                        template_count,
2404                                        tsk);
2405
2406       if (!tmpl || tmpl == error_mark_node)
2407         /* We couldn't figure out what this declaration was
2408            specializing.  */
2409         return error_mark_node;
2410       else
2411         {
2412           tree gen_tmpl = most_general_template (tmpl);
2413
2414           if (explicit_instantiation)
2415             {
2416               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2417                  is done by do_decl_instantiation later.  */
2418
2419               int arg_depth = TMPL_ARGS_DEPTH (targs);
2420               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2421
2422               if (arg_depth > parm_depth)
2423                 {
2424                   /* If TMPL is not the most general template (for
2425                      example, if TMPL is a friend template that is
2426                      injected into namespace scope), then there will
2427                      be too many levels of TARGS.  Remove some of them
2428                      here.  */
2429                   int i;
2430                   tree new_targs;
2431
2432                   new_targs = make_tree_vec (parm_depth);
2433                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2434                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2435                       = TREE_VEC_ELT (targs, i);
2436                   targs = new_targs;
2437                 }
2438
2439               return instantiate_template (tmpl, targs, tf_error);
2440             }
2441
2442           /* If we thought that the DECL was a member function, but it
2443              turns out to be specializing a static member function,
2444              make DECL a static member function as well.  */
2445           if (DECL_STATIC_FUNCTION_P (tmpl)
2446               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2447             revert_static_member_fn (decl);
2448
2449           /* If this is a specialization of a member template of a
2450              template class, we want to return the TEMPLATE_DECL, not
2451              the specialization of it.  */
2452           if (tsk == tsk_template)
2453             {
2454               tree result = DECL_TEMPLATE_RESULT (tmpl);
2455               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2456               DECL_INITIAL (result) = NULL_TREE;
2457               if (have_def)
2458                 {
2459                   tree parm;
2460                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2461                   DECL_SOURCE_LOCATION (result)
2462                     = DECL_SOURCE_LOCATION (decl);
2463                   /* We want to use the argument list specified in the
2464                      definition, not in the original declaration.  */
2465                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2466                   for (parm = DECL_ARGUMENTS (result); parm;
2467                        parm = TREE_CHAIN (parm))
2468                     DECL_CONTEXT (parm) = result;
2469                 }
2470               return register_specialization (tmpl, gen_tmpl, targs,
2471                                               is_friend, 0);
2472             }
2473
2474           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2475           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2476
2477           /* Inherit default function arguments from the template
2478              DECL is specializing.  */
2479           copy_default_args_to_explicit_spec (decl);
2480
2481           /* This specialization has the same protection as the
2482              template it specializes.  */
2483           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2484           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2485
2486           /* 7.1.1-1 [dcl.stc]
2487
2488              A storage-class-specifier shall not be specified in an
2489              explicit specialization...
2490
2491              The parser rejects these, so unless action is taken here,
2492              explicit function specializations will always appear with
2493              global linkage.
2494
2495              The action recommended by the C++ CWG in response to C++
2496              defect report 605 is to make the storage class and linkage
2497              of the explicit specialization match the templated function:
2498
2499              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2500            */
2501           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2502             {
2503               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2504               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2505
2506               /* This specialization has the same linkage and visibility as
2507                  the function template it specializes.  */
2508               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2509               if (! TREE_PUBLIC (decl))
2510                 {
2511                   DECL_INTERFACE_KNOWN (decl) = 1;
2512                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2513                 }
2514               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2515               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2516                 {
2517                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2518                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2519                 }
2520             }
2521
2522           /* If DECL is a friend declaration, declared using an
2523              unqualified name, the namespace associated with DECL may
2524              have been set incorrectly.  For example, in:
2525
2526                template <typename T> void f(T);
2527                namespace N {
2528                  struct S { friend void f<int>(int); }
2529                }
2530
2531              we will have set the DECL_CONTEXT for the friend
2532              declaration to N, rather than to the global namespace.  */
2533           if (DECL_NAMESPACE_SCOPE_P (decl))
2534             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2535
2536           if (is_friend && !have_def)
2537             /* This is not really a declaration of a specialization.
2538                It's just the name of an instantiation.  But, it's not
2539                a request for an instantiation, either.  */
2540             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2541           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2542             /* This is indeed a specialization.  In case of constructors
2543                and destructors, we need in-charge and not-in-charge
2544                versions in V3 ABI.  */
2545             clone_function_decl (decl, /*update_method_vec_p=*/0);
2546
2547           /* Register this specialization so that we can find it
2548              again.  */
2549           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2550         }
2551     }
2552
2553   return decl;
2554 }
2555
2556 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2557    parameters.  These are represented in the same format used for
2558    DECL_TEMPLATE_PARMS.  */
2559
2560 int
2561 comp_template_parms (const_tree parms1, const_tree parms2)
2562 {
2563   const_tree p1;
2564   const_tree p2;
2565
2566   if (parms1 == parms2)
2567     return 1;
2568
2569   for (p1 = parms1, p2 = parms2;
2570        p1 != NULL_TREE && p2 != NULL_TREE;
2571        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2572     {
2573       tree t1 = TREE_VALUE (p1);
2574       tree t2 = TREE_VALUE (p2);
2575       int i;
2576
2577       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2578       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2579
2580       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2581         return 0;
2582
2583       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2584         {
2585           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2586           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2587
2588           /* If either of the template parameters are invalid, assume
2589              they match for the sake of error recovery. */
2590           if (parm1 == error_mark_node || parm2 == error_mark_node)
2591             return 1;
2592
2593           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2594             return 0;
2595
2596           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2597               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2598                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2599             continue;
2600           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2601             return 0;
2602         }
2603     }
2604
2605   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2606     /* One set of parameters has more parameters lists than the
2607        other.  */
2608     return 0;
2609
2610   return 1;
2611 }
2612
2613 /* Determine whether PARM is a parameter pack.  */
2614 bool 
2615 template_parameter_pack_p (const_tree parm)
2616 {
2617   /* Determine if we have a non-type template parameter pack.  */
2618   if (TREE_CODE (parm) == PARM_DECL)
2619     return (DECL_TEMPLATE_PARM_P (parm) 
2620             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2621
2622   /* If this is a list of template parameters, we could get a
2623      TYPE_DECL or a TEMPLATE_DECL.  */ 
2624   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2625     parm = TREE_TYPE (parm);
2626
2627   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2628            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2629           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2630 }
2631
2632 /* Determine whether ARGS describes a variadic template args list,
2633    i.e., one that is terminated by a template argument pack.  */
2634 static bool 
2635 template_args_variadic_p (tree args)
2636 {
2637   int nargs;
2638   tree last_parm;
2639
2640   if (args == NULL_TREE)
2641     return false;
2642
2643   args = INNERMOST_TEMPLATE_ARGS (args);
2644   nargs = TREE_VEC_LENGTH (args);
2645
2646   if (nargs == 0)
2647     return false;
2648
2649   last_parm = TREE_VEC_ELT (args, nargs - 1);
2650
2651   return ARGUMENT_PACK_P (last_parm);
2652 }
2653
2654 /* Generate a new name for the parameter pack name NAME (an
2655    IDENTIFIER_NODE) that incorporates its */
2656 static tree
2657 make_ith_pack_parameter_name (tree name, int i)
2658 {
2659   /* Munge the name to include the parameter index.  */
2660   char numbuf[128];
2661   char* newname;
2662   
2663   sprintf(numbuf, "%i", i);
2664   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2665   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2666   return get_identifier (newname);
2667 }
2668
2669 /* Structure used to track the progress of find_parameter_packs_r.  */
2670 struct find_parameter_pack_data 
2671 {
2672   /* TREE_LIST that will contain all of the parameter packs found by
2673      the traversal.  */
2674   tree* parameter_packs;
2675
2676   /* Set of AST nodes that have been visited by the traversal.  */
2677   struct pointer_set_t *visited;
2678 };
2679
2680 /* Identifies all of the argument packs that occur in a template
2681    argument and appends them to the TREE_LIST inside DATA, which is a
2682    find_parameter_pack_data structure. This is a subroutine of
2683    make_pack_expansion and uses_parameter_packs.  */
2684 static tree
2685 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2686 {
2687   tree t = *tp;
2688   struct find_parameter_pack_data* ppd = 
2689     (struct find_parameter_pack_data*)data;
2690   bool parameter_pack_p = false;
2691
2692   /* Identify whether this is a parameter pack or not.  */
2693   switch (TREE_CODE (t))
2694     {
2695     case TEMPLATE_PARM_INDEX:
2696       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2697         parameter_pack_p = true;
2698       break;
2699
2700     case TEMPLATE_TYPE_PARM:
2701     case TEMPLATE_TEMPLATE_PARM:
2702       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2703         parameter_pack_p = true;
2704       break;
2705
2706     case PARM_DECL:
2707       if (FUNCTION_PARAMETER_PACK_P (t))
2708         {
2709           /* We don't want to walk into the type of a PARM_DECL,
2710              because we don't want to see the type parameter pack.  */
2711           *walk_subtrees = 0;
2712           parameter_pack_p = true;
2713         }
2714       break;
2715
2716     default:
2717       /* Not a parameter pack.  */
2718       break;
2719     }
2720
2721   if (parameter_pack_p)
2722     {
2723       /* Add this parameter pack to the list.  */
2724       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2725     }
2726
2727   if (TYPE_P (t))
2728     cp_walk_tree (&TYPE_CONTEXT (t), 
2729                   &find_parameter_packs_r, ppd, ppd->visited);
2730
2731   /* This switch statement will return immediately if we don't find a
2732      parameter pack.  */
2733   switch (TREE_CODE (t)) 
2734     {
2735     case TEMPLATE_PARM_INDEX:
2736       return NULL_TREE;
2737
2738     case BOUND_TEMPLATE_TEMPLATE_PARM:
2739       /* Check the template itself.  */
2740       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2741                     &find_parameter_packs_r, ppd, ppd->visited);
2742       /* Check the template arguments.  */
2743       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2744                     ppd->visited);
2745       *walk_subtrees = 0;
2746       return NULL_TREE;
2747
2748     case TEMPLATE_TYPE_PARM:
2749     case TEMPLATE_TEMPLATE_PARM:
2750       return NULL_TREE;
2751
2752     case PARM_DECL:
2753       return NULL_TREE;
2754
2755     case RECORD_TYPE:
2756       if (TYPE_PTRMEMFUNC_P (t))
2757         return NULL_TREE;
2758       /* Fall through.  */
2759
2760     case UNION_TYPE:
2761     case ENUMERAL_TYPE:
2762       if (TYPE_TEMPLATE_INFO (t))
2763         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2764                       &find_parameter_packs_r, ppd, ppd->visited);
2765
2766       *walk_subtrees = 0;
2767       return NULL_TREE;
2768
2769     case TEMPLATE_DECL:
2770       cp_walk_tree (&TREE_TYPE (t),
2771                     &find_parameter_packs_r, ppd, ppd->visited);
2772       return NULL_TREE;
2773  
2774     case TYPENAME_TYPE:
2775       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2776                    ppd, ppd->visited);
2777       *walk_subtrees = 0;
2778       return NULL_TREE;
2779       
2780     case TYPE_PACK_EXPANSION:
2781     case EXPR_PACK_EXPANSION:
2782       *walk_subtrees = 0;
2783       return NULL_TREE;
2784
2785     case INTEGER_TYPE:
2786       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2787                     ppd, ppd->visited);
2788       *walk_subtrees = 0;
2789       return NULL_TREE;
2790
2791     case IDENTIFIER_NODE:
2792       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2793                     ppd->visited);
2794       *walk_subtrees = 0;
2795       return NULL_TREE;
2796
2797     default:
2798       return NULL_TREE;
2799     }
2800
2801   return NULL_TREE;
2802 }
2803
2804 /* Determines if the expression or type T uses any parameter packs.  */
2805 bool
2806 uses_parameter_packs (tree t)
2807 {
2808   tree parameter_packs = NULL_TREE;
2809   struct find_parameter_pack_data ppd;
2810   ppd.parameter_packs = &parameter_packs;
2811   ppd.visited = pointer_set_create ();
2812   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2813   pointer_set_destroy (ppd.visited);
2814   return parameter_packs != NULL_TREE;
2815 }
2816
2817 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2818    representation a base-class initializer into a parameter pack
2819    expansion. If all goes well, the resulting node will be an
2820    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2821    respectively.  */
2822 tree 
2823 make_pack_expansion (tree arg)
2824 {
2825   tree result;
2826   tree parameter_packs = NULL_TREE;
2827   bool for_types = false;
2828   struct find_parameter_pack_data ppd;
2829
2830   if (!arg || arg == error_mark_node)
2831     return arg;
2832
2833   if (TREE_CODE (arg) == TREE_LIST)
2834     {
2835       /* The only time we will see a TREE_LIST here is for a base
2836          class initializer.  In this case, the TREE_PURPOSE will be a
2837          _TYPE node (representing the base class expansion we're
2838          initializing) and the TREE_VALUE will be a TREE_LIST
2839          containing the initialization arguments. 
2840
2841          The resulting expansion looks somewhat different from most
2842          expansions. Rather than returning just one _EXPANSION, we
2843          return a TREE_LIST whose TREE_PURPOSE is a
2844          TYPE_PACK_EXPANSION containing the bases that will be
2845          initialized.  The TREE_VALUE will be identical to the
2846          original TREE_VALUE, which is a list of arguments that will
2847          be passed to each base.  We do not introduce any new pack
2848          expansion nodes into the TREE_VALUE (although it is possible
2849          that some already exist), because the TREE_PURPOSE and
2850          TREE_VALUE all need to be expanded together with the same
2851          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2852          resulting TREE_PURPOSE will mention the parameter packs in
2853          both the bases and the arguments to the bases.  */
2854       tree purpose;
2855       tree value;
2856       tree parameter_packs = NULL_TREE;
2857
2858       /* Determine which parameter packs will be used by the base
2859          class expansion.  */
2860       ppd.visited = pointer_set_create ();
2861       ppd.parameter_packs = &parameter_packs;
2862       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2863                     &ppd, ppd.visited);
2864
2865       if (parameter_packs == NULL_TREE)
2866         {
2867           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2868           pointer_set_destroy (ppd.visited);
2869           return error_mark_node;
2870         }
2871
2872       if (TREE_VALUE (arg) != void_type_node)
2873         {
2874           /* Collect the sets of parameter packs used in each of the
2875              initialization arguments.  */
2876           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2877             {
2878               /* Determine which parameter packs will be expanded in this
2879                  argument.  */
2880               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2881                             &ppd, ppd.visited);
2882             }
2883         }
2884
2885       pointer_set_destroy (ppd.visited);
2886
2887       /* Create the pack expansion type for the base type.  */
2888       purpose = make_node (TYPE_PACK_EXPANSION);
2889       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2890       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2891
2892       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2893          they will rarely be compared to anything.  */
2894       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2895
2896       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2897     }
2898
2899   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2900     for_types = true;
2901
2902   /* Build the PACK_EXPANSION_* node.  */
2903   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2904   SET_PACK_EXPANSION_PATTERN (result, arg);
2905   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2906     {
2907       /* Propagate type and const-expression information.  */
2908       TREE_TYPE (result) = TREE_TYPE (arg);
2909       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2910     }
2911   else
2912     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2913        they will rarely be compared to anything.  */
2914     SET_TYPE_STRUCTURAL_EQUALITY (result);
2915
2916   /* Determine which parameter packs will be expanded.  */
2917   ppd.parameter_packs = &parameter_packs;
2918   ppd.visited = pointer_set_create ();
2919   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2920   pointer_set_destroy (ppd.visited);
2921
2922   /* Make sure we found some parameter packs.  */
2923   if (parameter_packs == NULL_TREE)
2924     {
2925       if (TYPE_P (arg))
2926         error ("expansion pattern %<%T%> contains no argument packs", arg);
2927       else
2928         error ("expansion pattern %<%E%> contains no argument packs", arg);
2929       return error_mark_node;
2930     }
2931   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2932
2933   return result;
2934 }
2935
2936 /* Checks T for any "bare" parameter packs, which have not yet been
2937    expanded, and issues an error if any are found. This operation can
2938    only be done on full expressions or types (e.g., an expression
2939    statement, "if" condition, etc.), because we could have expressions like:
2940
2941      foo(f(g(h(args)))...)
2942
2943    where "args" is a parameter pack. check_for_bare_parameter_packs
2944    should not be called for the subexpressions args, h(args),
2945    g(h(args)), or f(g(h(args))), because we would produce erroneous
2946    error messages. 
2947
2948    Returns TRUE and emits an error if there were bare parameter packs,
2949    returns FALSE otherwise.  */
2950 bool 
2951 check_for_bare_parameter_packs (tree t)
2952 {
2953   tree parameter_packs = NULL_TREE;
2954   struct find_parameter_pack_data ppd;
2955
2956   if (!processing_template_decl || !t || t == error_mark_node)
2957     return false;
2958
2959   if (TREE_CODE (t) == TYPE_DECL)
2960     t = TREE_TYPE (t);
2961
2962   ppd.parameter_packs = &parameter_packs;
2963   ppd.visited = pointer_set_create ();
2964   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2965   pointer_set_destroy (ppd.visited);
2966
2967   if (parameter_packs) 
2968     {
2969       error ("parameter packs not expanded with %<...%>:");
2970       while (parameter_packs)
2971         {
2972           tree pack = TREE_VALUE (parameter_packs);
2973           tree name = NULL_TREE;
2974
2975           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2976               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2977             name = TYPE_NAME (pack);
2978           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2979             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2980           else
2981             name = DECL_NAME (pack);
2982
2983           if (name)
2984             inform (input_location, "        %qD", name);
2985           else
2986             inform (input_location, "        <anonymous>");
2987
2988           parameter_packs = TREE_CHAIN (parameter_packs);
2989         }
2990
2991       return true;
2992     }
2993
2994   return false;
2995 }
2996
2997 /* Expand any parameter packs that occur in the template arguments in
2998    ARGS.  */
2999 tree
3000 expand_template_argument_pack (tree args)
3001 {
3002   tree result_args = NULL_TREE;
3003   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3004   int num_result_args = -1;
3005
3006   /* First, determine if we need to expand anything, and the number of
3007      slots we'll need.  */
3008   for (in_arg = 0; in_arg < nargs; ++in_arg)
3009     {
3010       tree arg = TREE_VEC_ELT (args, in_arg);
3011       if (ARGUMENT_PACK_P (arg))
3012         {
3013           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3014           if (num_result_args < 0)
3015             num_result_args = in_arg + num_packed;
3016           else
3017             num_result_args += num_packed;
3018         }
3019       else
3020         {
3021           if (num_result_args >= 0)
3022             num_result_args++;
3023         }
3024     }
3025
3026   /* If no expansion is necessary, we're done.  */
3027   if (num_result_args < 0)
3028     return args;
3029
3030   /* Expand arguments.  */
3031   result_args = make_tree_vec (num_result_args);
3032   for (in_arg = 0; in_arg < nargs; ++in_arg)
3033     {
3034       tree arg = TREE_VEC_ELT (args, in_arg);
3035       if (ARGUMENT_PACK_P (arg))
3036         {
3037           tree packed = ARGUMENT_PACK_ARGS (arg);
3038           int i, num_packed = TREE_VEC_LENGTH (packed);
3039           for (i = 0; i < num_packed; ++i, ++out_arg)
3040             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3041         }
3042       else
3043         {
3044           TREE_VEC_ELT (result_args, out_arg) = arg;
3045           ++out_arg;
3046         }
3047     }
3048
3049   return result_args;
3050 }
3051
3052 /* Checks if DECL shadows a template parameter.
3053
3054    [temp.local]: A template-parameter shall not be redeclared within its
3055    scope (including nested scopes).
3056
3057    Emits an error and returns TRUE if the DECL shadows a parameter,
3058    returns FALSE otherwise.  */
3059
3060 bool
3061 check_template_shadow (tree decl)
3062 {
3063   tree olddecl;
3064
3065   /* If we're not in a template, we can't possibly shadow a template
3066      parameter.  */
3067   if (!current_template_parms)
3068     return true;
3069
3070   /* Figure out what we're shadowing.  */
3071   if (TREE_CODE (decl) == OVERLOAD)
3072     decl = OVL_CURRENT (decl);
3073   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3074
3075   /* If there's no previous binding for this name, we're not shadowing
3076      anything, let alone a template parameter.  */
3077   if (!olddecl)
3078     return true;
3079
3080   /* If we're not shadowing a template parameter, we're done.  Note
3081      that OLDDECL might be an OVERLOAD (or perhaps even an
3082      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3083      node.  */
3084   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3085     return true;
3086
3087   /* We check for decl != olddecl to avoid bogus errors for using a
3088      name inside a class.  We check TPFI to avoid duplicate errors for
3089      inline member templates.  */
3090   if (decl == olddecl
3091       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3092     return true;
3093
3094   error ("declaration of %q+#D", decl);
3095   error (" shadows template parm %q+#D", olddecl);
3096   return false;
3097 }
3098
3099 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3100    ORIG_LEVEL, DECL, and TYPE.  */
3101
3102 static tree
3103 build_template_parm_index (int index,
3104                            int level,
3105                            int orig_level,
3106                            tree decl,
3107                            tree type)
3108 {
3109   tree t = make_node (TEMPLATE_PARM_INDEX);
3110   TEMPLATE_PARM_IDX (t) = index;
3111   TEMPLATE_PARM_LEVEL (t) = level;
3112   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3113   TEMPLATE_PARM_DECL (t) = decl;
3114   TREE_TYPE (t) = type;
3115   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3116   TREE_READONLY (t) = TREE_READONLY (decl);
3117
3118   return t;
3119 }
3120
3121 /* Find the canonical type parameter for the given template type
3122    parameter.  Returns the canonical type parameter, which may be TYPE
3123    if no such parameter existed.  */
3124 static tree
3125 canonical_type_parameter (tree type)
3126 {
3127   tree list;
3128   int idx = TEMPLATE_TYPE_IDX (type);
3129   if (!canonical_template_parms)
3130     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3131
3132   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3133     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3134
3135   list = VEC_index (tree, canonical_template_parms, idx);
3136   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3137     list = TREE_CHAIN (list);
3138
3139   if (list)
3140     return TREE_VALUE (list);
3141   else
3142     {
3143       VEC_replace(tree, canonical_template_parms, idx,
3144                   tree_cons (NULL_TREE, type, 
3145                              VEC_index (tree, canonical_template_parms, idx)));
3146       return type;
3147     }
3148 }
3149
3150 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3151    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3152    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3153    new one is created.  */
3154
3155 static tree
3156 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3157                             tsubst_flags_t complain)
3158 {
3159   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3160       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3161           != TEMPLATE_PARM_LEVEL (index) - levels))
3162     {
3163       tree orig_decl = TEMPLATE_PARM_DECL (index);
3164       tree decl, t;
3165
3166       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3167                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3168       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3169       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3170       DECL_ARTIFICIAL (decl) = 1;
3171       SET_DECL_TEMPLATE_PARM_P (decl);
3172
3173       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3174                                      TEMPLATE_PARM_LEVEL (index) - levels,
3175                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3176                                      decl, type);
3177       TEMPLATE_PARM_DESCENDANTS (index) = t;
3178       TEMPLATE_PARM_PARAMETER_PACK (t) 
3179         = TEMPLATE_PARM_PARAMETER_PACK (index);
3180
3181         /* Template template parameters need this.  */
3182       if (TREE_CODE (decl) == TEMPLATE_DECL)
3183         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3184           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3185            args, complain);
3186     }
3187
3188   return TEMPLATE_PARM_DESCENDANTS (index);
3189 }
3190
3191 /* Process information from new template parameter PARM and append it to the
3192    LIST being built.  This new parameter is a non-type parameter iff
3193    IS_NON_TYPE is true. This new parameter is a parameter
3194    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3195    PARM_LOC.  */
3196
3197 tree
3198 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3199                        bool is_parameter_pack)
3200 {
3201   tree decl = 0;
3202   tree defval;
3203   tree err_parm_list;
3204   int idx = 0;
3205
3206   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3207   defval = TREE_PURPOSE (parm);
3208
3209   if (list)
3210     {
3211       tree p = tree_last (list);
3212
3213       if (p && TREE_VALUE (p) != error_mark_node)
3214         {
3215           p = TREE_VALUE (p);
3216           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3217             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3218           else
3219             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3220         }
3221
3222       ++idx;
3223     }
3224   else
3225     idx = 0;
3226
3227   if (is_non_type)
3228     {
3229       parm = TREE_VALUE (parm);
3230
3231       SET_DECL_TEMPLATE_PARM_P (parm);
3232
3233       if (TREE_TYPE (parm) == error_mark_node)
3234         {
3235           err_parm_list = build_tree_list (defval, parm);
3236           TREE_VALUE (err_parm_list) = error_mark_node;
3237            return chainon (list, err_parm_list);
3238         }
3239       else
3240       {
3241         /* [temp.param]
3242
3243            The top-level cv-qualifiers on the template-parameter are
3244            ignored when determining its type.  */
3245         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3246         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3247           {
3248             err_parm_list = build_tree_list (defval, parm);
3249             TREE_VALUE (err_parm_list) = error_mark_node;
3250              return chainon (list, err_parm_list);
3251           }
3252
3253         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3254           {
3255             /* This template parameter is not a parameter pack, but it
3256                should be. Complain about "bare" parameter packs.  */
3257             check_for_bare_parameter_packs (TREE_TYPE (parm));
3258             
3259             /* Recover by calling this a parameter pack.  */
3260             is_parameter_pack = true;
3261           }
3262       }
3263
3264       /* A template parameter is not modifiable.  */
3265       TREE_CONSTANT (parm) = 1;
3266       TREE_READONLY (parm) = 1;
3267       decl = build_decl (parm_loc,
3268                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3269       TREE_CONSTANT (decl) = 1;
3270       TREE_READONLY (decl) = 1;
3271       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3272         = build_template_parm_index (idx, processing_template_decl,
3273                                      processing_template_decl,
3274                                      decl, TREE_TYPE (parm));
3275
3276       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3277         = is_parameter_pack;
3278     }
3279   else
3280     {
3281       tree t;
3282       parm = TREE_VALUE (TREE_VALUE (parm));
3283
3284       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3285         {
3286           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3287           /* This is for distinguishing between real templates and template
3288              template parameters */
3289           TREE_TYPE (parm) = t;
3290           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3291           decl = parm;
3292         }
3293       else
3294         {
3295           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3296           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3297           decl = build_decl (parm_loc,
3298                              TYPE_DECL, parm, t);
3299         }
3300
3301       TYPE_NAME (t) = decl;
3302       TYPE_STUB_DECL (t) = decl;
3303       parm = decl;
3304       TEMPLATE_TYPE_PARM_INDEX (t)
3305         = build_template_parm_index (idx, processing_template_decl,
3306                                      processing_template_decl,
3307                                      decl, TREE_TYPE (parm));
3308       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3309       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3310     }
3311   DECL_ARTIFICIAL (decl) = 1;
3312   SET_DECL_TEMPLATE_PARM_P (decl);
3313   pushdecl (decl);
3314   parm = build_tree_list (defval, parm);
3315   return chainon (list, parm);
3316 }
3317
3318 /* The end of a template parameter list has been reached.  Process the
3319    tree list into a parameter vector, converting each parameter into a more
3320    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3321    as PARM_DECLs.  */
3322
3323 tree
3324 end_template_parm_list (tree parms)
3325 {
3326   int nparms;
3327   tree parm, next;
3328   tree saved_parmlist = make_tree_vec (list_length (parms));
3329
3330   current_template_parms
3331     = tree_cons (size_int (processing_template_decl),
3332                  saved_parmlist, current_template_parms);
3333
3334   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3335     {
3336       next = TREE_CHAIN (parm);
3337       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3338       TREE_CHAIN (parm) = NULL_TREE;
3339     }
3340
3341   --processing_template_parmlist;
3342
3343   return saved_parmlist;
3344 }
3345
3346 /* end_template_decl is called after a template declaration is seen.  */
3347
3348 void
3349 end_template_decl (void)
3350 {
3351   reset_specialization ();
3352
3353   if (! processing_template_decl)
3354     return;
3355
3356   /* This matches the pushlevel in begin_template_parm_list.  */
3357   finish_scope ();
3358
3359   --processing_template_decl;
3360   current_template_parms = TREE_CHAIN (current_template_parms);
3361 }
3362
3363 /* Within the declaration of a template, return all levels of template
3364    parameters that apply.  The template parameters are represented as
3365    a TREE_VEC, in the form documented in cp-tree.h for template
3366    arguments.  */
3367
3368 static tree
3369 current_template_args (void)
3370 {
3371   tree header;
3372   tree args = NULL_TREE;
3373   int length = TMPL_PARMS_DEPTH (current_template_parms);
3374   int l = length;
3375
3376   /* If there is only one level of template parameters, we do not
3377      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3378      TREE_VEC containing the arguments.  */
3379   if (length > 1)
3380     args = make_tree_vec (length);
3381
3382   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3383     {
3384       tree a = copy_node (TREE_VALUE (header));
3385       int i;
3386
3387       TREE_TYPE (a) = NULL_TREE;
3388       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3389         {
3390           tree t = TREE_VEC_ELT (a, i);
3391
3392           /* T will be a list if we are called from within a
3393              begin/end_template_parm_list pair, but a vector directly
3394              if within a begin/end_member_template_processing pair.  */
3395           if (TREE_CODE (t) == TREE_LIST)
3396             {
3397               t = TREE_VALUE (t);
3398
3399               if (!error_operand_p (t))
3400                 {
3401                   if (TREE_CODE (t) == TYPE_DECL
3402                       || TREE_CODE (t) == TEMPLATE_DECL)
3403                     {
3404                       t = TREE_TYPE (t);
3405                       
3406                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3407                         {
3408                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3409                              with a single element, which expands T.  */
3410                           tree vec = make_tree_vec (1);
3411                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3412                           
3413                           t = make_node (TYPE_ARGUMENT_PACK);
3414                           SET_ARGUMENT_PACK_ARGS (t, vec);
3415                         }
3416                     }
3417                   else
3418                     {
3419                       t = DECL_INITIAL (t);
3420                       
3421                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3422                         {
3423                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3424                              with a single element, which expands T.  */
3425                           tree vec = make_tree_vec (1);
3426                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3427                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3428                           
3429                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3430                           SET_ARGUMENT_PACK_ARGS (t, vec);
3431                           TREE_TYPE (t) = type;
3432                         }
3433                     }
3434                   TREE_VEC_ELT (a, i) = t;
3435                 }
3436             }
3437         }
3438
3439       if (length > 1)
3440         TREE_VEC_ELT (args, --l) = a;
3441       else
3442         args = a;
3443     }
3444
3445   return args;
3446 }
3447
3448 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3449    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3450    a member template.  Used by push_template_decl below.  */
3451
3452 static tree
3453 build_template_decl (tree decl, tree parms, bool member_template_p)
3454 {
3455   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3456   DECL_TEMPLATE_PARMS (tmpl) = parms;
3457   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3458   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3459
3460   return tmpl;
3461 }
3462
3463 struct template_parm_data
3464 {
3465   /* The level of the template parameters we are currently
3466      processing.  */
3467   int level;
3468
3469   /* The index of the specialization argument we are currently
3470      processing.  */
3471   int current_arg;
3472
3473   /* An array whose size is the number of template parameters.  The
3474      elements are nonzero if the parameter has been used in any one
3475      of the arguments processed so far.  */
3476   int* parms;
3477
3478   /* An array whose size is the number of template arguments.  The
3479      elements are nonzero if the argument makes use of template
3480      parameters of this level.  */
3481   int* arg_uses_template_parms;
3482 };
3483
3484 /* Subroutine of push_template_decl used to see if each template
3485    parameter in a partial specialization is used in the explicit
3486    argument list.  If T is of the LEVEL given in DATA (which is
3487    treated as a template_parm_data*), then DATA->PARMS is marked
3488    appropriately.  */
3489
3490 static int
3491 mark_template_parm (tree t, void* data)
3492 {
3493   int level;
3494   int idx;
3495   struct template_parm_data* tpd = (struct template_parm_data*) data;
3496
3497   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3498     {
3499       level = TEMPLATE_PARM_LEVEL (t);
3500       idx = TEMPLATE_PARM_IDX (t);
3501     }
3502   else
3503     {
3504       level = TEMPLATE_TYPE_LEVEL (t);
3505       idx = TEMPLATE_TYPE_IDX (t);
3506     }
3507
3508   if (level == tpd->level)
3509     {
3510       tpd->parms[idx] = 1;
3511       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3512     }
3513
3514   /* Return zero so that for_each_template_parm will continue the
3515      traversal of the tree; we want to mark *every* template parm.  */
3516   return 0;
3517 }
3518
3519 /* Process the partial specialization DECL.  */
3520
3521 static tree
3522 process_partial_specialization (tree decl)
3523 {
3524   tree type = TREE_TYPE (decl);
3525   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3526   tree specargs = CLASSTYPE_TI_ARGS (type);
3527   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3528   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3529   tree inner_parms;
3530   int nargs = TREE_VEC_LENGTH (inner_args);
3531   int ntparms;
3532   int  i;
3533   int did_error_intro = 0;
3534   struct template_parm_data tpd;
3535   struct template_parm_data tpd2;
3536
3537   gcc_assert (current_template_parms);
3538
3539   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3540   ntparms = TREE_VEC_LENGTH (inner_parms);
3541
3542   /* We check that each of the template parameters given in the
3543      partial specialization is used in the argument list to the
3544      specialization.  For example:
3545
3546        template <class T> struct S;
3547        template <class T> struct S<T*>;
3548
3549      The second declaration is OK because `T*' uses the template
3550      parameter T, whereas
3551
3552        template <class T> struct S<int>;
3553
3554      is no good.  Even trickier is:
3555
3556        template <class T>
3557        struct S1
3558        {
3559           template <class U>
3560           struct S2;
3561           template <class U>
3562           struct S2<T>;
3563        };
3564
3565      The S2<T> declaration is actually invalid; it is a
3566      full-specialization.  Of course,
3567
3568           template <class U>
3569           struct S2<T (*)(U)>;
3570
3571      or some such would have been OK.  */
3572   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3573   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3574   memset (tpd.parms, 0, sizeof (int) * ntparms);
3575
3576   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3577   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3578   for (i = 0; i < nargs; ++i)
3579     {
3580       tpd.current_arg = i;
3581       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3582                               &mark_template_parm,
3583                               &tpd,
3584                               NULL,
3585                               /*include_nondeduced_p=*/false);
3586     }
3587   for (i = 0; i < ntparms; ++i)
3588     if (tpd.parms[i] == 0)
3589       {
3590         /* One of the template parms was not used in the
3591            specialization.  */
3592         if (!did_error_intro)
3593           {
3594             error ("template parameters not used in partial specialization:");
3595             did_error_intro = 1;
3596           }
3597
3598         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3599       }
3600
3601   /* [temp.class.spec]
3602
3603      The argument list of the specialization shall not be identical to
3604      the implicit argument list of the primary template.  */
3605   if (comp_template_args
3606       (inner_args,
3607        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3608                                                    (maintmpl)))))
3609     error ("partial specialization %qT does not specialize any template arguments", type);
3610
3611   /* [temp.class.spec]
3612
3613      A partially specialized non-type argument expression shall not
3614      involve template parameters of the partial specialization except
3615      when the argument expression is a simple identifier.
3616
3617      The type of a template parameter corresponding to a specialized
3618      non-type argument shall not be dependent on a parameter of the
3619      specialization. 
3620
3621      Also, we verify that pack expansions only occur at the
3622      end of the argument list.  */
3623   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3624   tpd2.parms = 0;
3625   for (i = 0; i < nargs; ++i)
3626     {
3627       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3628       tree arg = TREE_VEC_ELT (inner_args, i);
3629       tree packed_args = NULL_TREE;
3630       int j, len = 1;
3631
3632       if (ARGUMENT_PACK_P (arg))
3633         {
3634           /* Extract the arguments from the argument pack. We'll be
3635              iterating over these in the following loop.  */
3636           packed_args = ARGUMENT_PACK_ARGS (arg);
3637           len = TREE_VEC_LENGTH (packed_args);
3638         }
3639
3640       for (j = 0; j < len; j++)
3641         {
3642           if (packed_args)
3643             /* Get the Jth argument in the parameter pack.  */
3644             arg = TREE_VEC_ELT (packed_args, j);
3645
3646           if (PACK_EXPANSION_P (arg))
3647             {
3648               /* Pack expansions must come at the end of the
3649                  argument list.  */
3650               if ((packed_args && j < len - 1)
3651                   || (!packed_args && i < nargs - 1))
3652                 {
3653                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3654                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3655                   else
3656                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3657
3658                   if (packed_args)
3659                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3660                 }
3661             }
3662
3663           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3664             /* We only care about the pattern.  */
3665             arg = PACK_EXPANSION_PATTERN (arg);
3666
3667           if (/* These first two lines are the `non-type' bit.  */
3668               !TYPE_P (arg)
3669               && TREE_CODE (arg) != TEMPLATE_DECL
3670               /* This next line is the `argument expression is not just a
3671                  simple identifier' condition and also the `specialized
3672                  non-type argument' bit.  */
3673               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3674             {
3675               if ((!packed_args && tpd.arg_uses_template_parms[i])
3676                   || (packed_args && uses_template_parms (arg)))
3677                 error ("template argument %qE involves template parameter(s)",
3678                        arg);
3679               else 
3680                 {
3681                   /* Look at the corresponding template parameter,
3682                      marking which template parameters its type depends
3683                      upon.  */
3684                   tree type = TREE_TYPE (parm);
3685
3686                   if (!tpd2.parms)
3687                     {
3688                       /* We haven't yet initialized TPD2.  Do so now.  */
3689                       tpd2.arg_uses_template_parms 
3690                         = (int *) alloca (sizeof (int) * nargs);
3691                       /* The number of parameters here is the number in the
3692                          main template, which, as checked in the assertion
3693                          above, is NARGS.  */
3694                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3695                       tpd2.level = 
3696                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3697                     }
3698
3699                   /* Mark the template parameters.  But this time, we're
3700                      looking for the template parameters of the main
3701                      template, not in the specialization.  */
3702                   tpd2.current_arg = i;
3703                   tpd2.arg_uses_template_parms[i] = 0;
3704                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3705                   for_each_template_parm (type,
3706                                           &mark_template_parm,
3707                                           &tpd2,
3708                                           NULL,
3709                                           /*include_nondeduced_p=*/false);
3710
3711                   if (tpd2.arg_uses_template_parms [i])
3712                     {
3713                       /* The type depended on some template parameters.
3714                          If they are fully specialized in the
3715                          specialization, that's OK.  */
3716                       int j;
3717                       for (j = 0; j < nargs; ++j)
3718                         if (tpd2.parms[j] != 0
3719                             && tpd.arg_uses_template_parms [j])
3720                           {
3721                             error ("type %qT of template argument %qE depends "
3722                                    "on template parameter(s)", 
3723                                    type,
3724                                    arg);
3725                             break;
3726                           }
3727                     }
3728                 }
3729             }
3730         }
3731     }
3732
3733   /* We should only get here once.  */
3734   gcc_assert (!COMPLETE_TYPE_P (type));
3735
3736   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3737     = tree_cons (specargs, inner_parms,
3738                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3739   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3740   return decl;
3741 }
3742
3743 /* Check that a template declaration's use of default arguments and
3744    parameter packs is not invalid.  Here, PARMS are the template
3745    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3746    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3747    specialization.
3748    
3749
3750    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3751    declaration (but not a definition); 1 indicates a declaration, 2
3752    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3753    emitted for extraneous default arguments.
3754
3755    Returns TRUE if there were no errors found, FALSE otherwise. */
3756
3757 bool
3758 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3759                          int is_partial, int is_friend_decl)
3760 {
3761   const char *msg;
3762   int last_level_to_check;
3763   tree parm_level;
3764   bool no_errors = true;
3765
3766   /* [temp.param]
3767
3768      A default template-argument shall not be specified in a
3769      function template declaration or a function template definition, nor
3770      in the template-parameter-list of the definition of a member of a
3771      class template.  */
3772
3773   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3774     /* You can't have a function template declaration in a local
3775        scope, nor you can you define a member of a class template in a
3776        local scope.  */
3777     return true;
3778
3779   if (current_class_type
3780       && !TYPE_BEING_DEFINED (current_class_type)
3781       && DECL_LANG_SPECIFIC (decl)
3782       && DECL_DECLARES_FUNCTION_P (decl)
3783       /* If this is either a friend defined in the scope of the class
3784          or a member function.  */
3785       && (DECL_FUNCTION_MEMBER_P (decl)
3786           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3787           : DECL_FRIEND_CONTEXT (decl)
3788           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3789           : false)
3790       /* And, if it was a member function, it really was defined in
3791          the scope of the class.  */
3792       && (!DECL_FUNCTION_MEMBER_P (decl)
3793           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3794     /* We already checked these parameters when the template was
3795        declared, so there's no need to do it again now.  This function
3796        was defined in class scope, but we're processing it's body now
3797        that the class is complete.  */
3798     return true;
3799
3800   /* Core issue 226 (C++0x only): the following only applies to class
3801      templates.  */
3802   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3803     {
3804       /* [temp.param]
3805
3806          If a template-parameter has a default template-argument, all
3807          subsequent template-parameters shall have a default
3808          template-argument supplied.  */
3809       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3810         {
3811           tree inner_parms = TREE_VALUE (parm_level);
3812           int ntparms = TREE_VEC_LENGTH (inner_parms);
3813           int seen_def_arg_p = 0;
3814           int i;
3815
3816           for (i = 0; i < ntparms; ++i)
3817             {
3818               tree parm = TREE_VEC_ELT (inner_parms, i);
3819
3820               if (parm == error_mark_node)
3821                 continue;
3822
3823               if (TREE_PURPOSE (parm))
3824                 seen_def_arg_p = 1;
3825               else if (seen_def_arg_p
3826                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3827                 {
3828                   error ("no default argument for %qD", TREE_VALUE (parm));
3829                   /* For better subsequent error-recovery, we indicate that
3830                      there should have been a default argument.  */
3831                   TREE_PURPOSE (parm) = error_mark_node;
3832                   no_errors = false;
3833                 }
3834               else if (is_primary
3835                        && !is_partial
3836                        && !is_friend_decl
3837                        /* Don't complain about an enclosing partial
3838                           specialization.  */
3839                        && parm_level == parms
3840                        && TREE_CODE (decl) == TYPE_DECL
3841                        && i < ntparms - 1
3842                        && template_parameter_pack_p (TREE_VALUE (parm)))
3843                 {
3844                   /* A primary class template can only have one
3845                      parameter pack, at the end of the template
3846                      parameter list.  */
3847
3848                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3849                     error ("parameter pack %qE must be at the end of the"
3850                            " template parameter list", TREE_VALUE (parm));
3851                   else
3852                     error ("parameter pack %qT must be at the end of the"
3853                            " template parameter list", 
3854                            TREE_TYPE (TREE_VALUE (parm)));
3855
3856                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3857                     = error_mark_node;
3858                   no_errors = false;
3859                 }
3860             }
3861         }
3862     }
3863
3864   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3865       || is_partial 
3866       || !is_primary
3867       || is_friend_decl)
3868     /* For an ordinary class template, default template arguments are
3869        allowed at the innermost level, e.g.:
3870          template <class T = int>
3871          struct S {};
3872        but, in a partial specialization, they're not allowed even
3873        there, as we have in [temp.class.spec]:
3874
3875          The template parameter list of a specialization shall not
3876          contain default template argument values.
3877
3878        So, for a partial specialization, or for a function template
3879        (in C++98/C++03), we look at all of them.  */
3880     ;
3881   else
3882     /* But, for a primary class template that is not a partial
3883        specialization we look at all template parameters except the
3884        innermost ones.  */
3885     parms = TREE_CHAIN (parms);
3886
3887   /* Figure out what error message to issue.  */
3888   if (is_friend_decl == 2)
3889     msg = "default template arguments may not be used in function template friend re-declaration";
3890   else if (is_friend_decl)
3891     msg = "default template arguments may not be used in function template friend declarations";
3892   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3893     msg = "default template arguments may not be used in function templates";
3894   else if (is_partial)
3895     msg = "default template arguments may not be used in partial specializations";
3896   else
3897     msg = "default argument for template parameter for class enclosing %qD";
3898
3899   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3900     /* If we're inside a class definition, there's no need to
3901        examine the parameters to the class itself.  On the one
3902        hand, they will be checked when the class is defined, and,
3903        on the other, default arguments are valid in things like:
3904          template <class T = double>
3905          struct S { template <class U> void f(U); };
3906        Here the default argument for `S' has no bearing on the
3907        declaration of `f'.  */
3908     last_level_to_check = template_class_depth (current_class_type) + 1;
3909   else
3910     /* Check everything.  */
3911     last_level_to_check = 0;
3912
3913   for (parm_level = parms;
3914        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3915        parm_level = TREE_CHAIN (parm_level))
3916     {
3917       tree inner_parms = TREE_VALUE (parm_level);
3918       int i;
3919       int ntparms;
3920
3921       ntparms = TREE_VEC_LENGTH (inner_parms);
3922       for (i = 0; i < ntparms; ++i)
3923         {
3924           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3925             continue;
3926
3927           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3928             {
3929               if (msg)
3930                 {
3931                   no_errors = false;
3932                   if (is_friend_decl == 2)
3933                     return no_errors;
3934
3935                   error (msg, decl);
3936                   msg = 0;
3937                 }
3938
3939               /* Clear out the default argument so that we are not
3940                  confused later.  */
3941               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3942             }
3943         }
3944
3945       /* At this point, if we're still interested in issuing messages,
3946          they must apply to classes surrounding the object declared.  */
3947       if (msg)
3948         msg = "default argument for template parameter for class enclosing %qD";
3949     }
3950
3951   return no_errors;
3952 }
3953
3954 /* Worker for push_template_decl_real, called via
3955    for_each_template_parm.  DATA is really an int, indicating the
3956    level of the parameters we are interested in.  If T is a template
3957    parameter of that level, return nonzero.  */
3958
3959 static int
3960 template_parm_this_level_p (tree t, void* data)
3961 {
3962   int this_level = *(int *)data;
3963   int level;
3964
3965   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3966     level = TEMPLATE_PARM_LEVEL (t);
3967   else
3968     level = TEMPLATE_TYPE_LEVEL (t);
3969   return level == this_level;
3970 }
3971
3972 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3973    parameters given by current_template_args, or reuses a
3974    previously existing one, if appropriate.  Returns the DECL, or an
3975    equivalent one, if it is replaced via a call to duplicate_decls.
3976
3977    If IS_FRIEND is true, DECL is a friend declaration.  */
3978
3979 tree
3980 push_template_decl_real (tree decl, bool is_friend)
3981 {
3982   tree tmpl;
3983   tree args;
3984   tree info;
3985   tree ctx;
3986   int primary;
3987   int is_partial;
3988   int new_template_p = 0;
3989   /* True if the template is a member template, in the sense of
3990      [temp.mem].  */
3991   bool member_template_p = false;
3992
3993   if (decl == error_mark_node || !current_template_parms)
3994     return error_mark_node;
3995
3996   /* See if this is a partial specialization.  */
3997   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3998                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3999                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4000
4001   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4002     is_friend = true;
4003
4004   if (is_friend)
4005     /* For a friend, we want the context of the friend function, not
4006        the type of which it is a friend.  */
4007     ctx = DECL_CONTEXT (decl);
4008   else if (CP_DECL_CONTEXT (decl)
4009            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4010     /* In the case of a virtual function, we want the class in which
4011        it is defined.  */
4012     ctx = CP_DECL_CONTEXT (decl);
4013   else
4014     /* Otherwise, if we're currently defining some class, the DECL
4015        is assumed to be a member of the class.  */
4016     ctx = current_scope ();
4017
4018   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4019     ctx = NULL_TREE;
4020
4021   if (!DECL_CONTEXT (decl))
4022     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4023
4024   /* See if this is a primary template.  */
4025   if (is_friend && ctx)
4026     /* A friend template that specifies a class context, i.e.
4027          template <typename T> friend void A<T>::f();
4028        is not primary.  */
4029     primary = 0;
4030   else
4031     primary = template_parm_scope_p ();
4032
4033   if (primary)
4034     {
4035       if (DECL_CLASS_SCOPE_P (decl))
4036         member_template_p = true;
4037       if (TREE_CODE (decl) == TYPE_DECL
4038           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4039         {
4040           error ("template class without a name");
4041           return error_mark_node;
4042         }
4043       else if (TREE_CODE (decl) == FUNCTION_DECL)
4044         {
4045           if (DECL_DESTRUCTOR_P (decl))
4046             {
4047               /* [temp.mem]
4048
4049                  A destructor shall not be a member template.  */
4050               error ("destructor %qD declared as member template", decl);
4051               return error_mark_node;
4052             }
4053           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4054               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4055                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4056                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4057                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4058                       == void_list_node)))
4059             {
4060               /* [basic.stc.dynamic.allocation]
4061
4062                  An allocation function can be a function
4063                  template. ... Template allocation functions shall
4064                  have two or more parameters.  */
4065               error ("invalid template declaration of %qD", decl);
4066               return error_mark_node;
4067             }
4068         }
4069       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4070                && CLASS_TYPE_P (TREE_TYPE (decl)))
4071         /* OK */;
4072       else
4073         {
4074           error ("template declaration of %q#D", decl);
4075           return error_mark_node;
4076         }
4077     }
4078
4079   /* Check to see that the rules regarding the use of default
4080      arguments are not being violated.  */
4081   check_default_tmpl_args (decl, current_template_parms,
4082                            primary, is_partial, /*is_friend_decl=*/0);
4083
4084   /* Ensure that there are no parameter packs in the type of this
4085      declaration that have not been expanded.  */
4086   if (TREE_CODE (decl) == FUNCTION_DECL)
4087     {
4088       /* Check each of the arguments individually to see if there are
4089          any bare parameter packs.  */
4090       tree type = TREE_TYPE (decl);
4091       tree arg = DECL_ARGUMENTS (decl);
4092       tree argtype = TYPE_ARG_TYPES (type);
4093
4094       while (arg && argtype)
4095         {
4096           if (!FUNCTION_PARAMETER_PACK_P (arg)
4097               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4098             {
4099             /* This is a PARM_DECL that contains unexpanded parameter
4100                packs. We have already complained about this in the
4101                check_for_bare_parameter_packs call, so just replace
4102                these types with ERROR_MARK_NODE.  */
4103               TREE_TYPE (arg) = error_mark_node;
4104               TREE_VALUE (argtype) = error_mark_node;
4105             }
4106
4107           arg = TREE_CHAIN (arg);
4108           argtype = TREE_CHAIN (argtype);
4109         }
4110
4111       /* Check for bare parameter packs in the return type and the
4112          exception specifiers.  */
4113       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4114         /* Errors were already issued, set return type to int
4115            as the frontend doesn't expect error_mark_node as
4116            the return type.  */
4117         TREE_TYPE (type) = integer_type_node;
4118       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4119         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4120     }
4121   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4122     {
4123       TREE_TYPE (decl) = error_mark_node;
4124       return error_mark_node;
4125     }
4126
4127   if (is_partial)
4128     return process_partial_specialization (decl);
4129
4130   args = current_template_args ();
4131
4132   if (!ctx
4133       || TREE_CODE (ctx) == FUNCTION_DECL
4134       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4135       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4136     {
4137       if (DECL_LANG_SPECIFIC (decl)
4138           && DECL_TEMPLATE_INFO (decl)
4139           && DECL_TI_TEMPLATE (decl))
4140         tmpl = DECL_TI_TEMPLATE (decl);
4141       /* If DECL is a TYPE_DECL for a class-template, then there won't
4142          be DECL_LANG_SPECIFIC.  The information equivalent to
4143          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4144       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4145                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4146                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4147         {
4148           /* Since a template declaration already existed for this
4149              class-type, we must be redeclaring it here.  Make sure
4150              that the redeclaration is valid.  */
4151           redeclare_class_template (TREE_TYPE (decl),
4152                                     current_template_parms);
4153           /* We don't need to create a new TEMPLATE_DECL; just use the
4154              one we already had.  */
4155           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4156         }
4157       else
4158         {
4159           tmpl = build_template_decl (decl, current_template_parms,
4160                                       member_template_p);
4161           new_template_p = 1;
4162
4163           if (DECL_LANG_SPECIFIC (decl)
4164               && DECL_TEMPLATE_SPECIALIZATION (decl))
4165             {
4166               /* A specialization of a member template of a template
4167                  class.  */
4168               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4169               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4170               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4171             }
4172         }
4173     }
4174   else
4175     {
4176       tree a, t, current, parms;
4177       int i;
4178       tree tinfo = get_template_info (decl);
4179
4180       if (!tinfo)
4181         {
4182           error ("template definition of non-template %q#D", decl);
4183           return error_mark_node;
4184         }
4185
4186       tmpl = TI_TEMPLATE (tinfo);
4187
4188       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4189           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4190           && DECL_TEMPLATE_SPECIALIZATION (decl)
4191           && DECL_MEMBER_TEMPLATE_P (tmpl))
4192         {
4193           tree new_tmpl;
4194
4195           /* The declaration is a specialization of a member
4196              template, declared outside the class.  Therefore, the
4197              innermost template arguments will be NULL, so we
4198              replace them with the arguments determined by the
4199              earlier call to check_explicit_specialization.  */
4200           args = DECL_TI_ARGS (decl);
4201
4202           new_tmpl
4203             = build_template_decl (decl, current_template_parms,
4204                                    member_template_p);
4205           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4206           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4207           DECL_TI_TEMPLATE (decl) = new_tmpl;
4208           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4209           DECL_TEMPLATE_INFO (new_tmpl)
4210             = tree_cons (tmpl, args, NULL_TREE);
4211
4212           register_specialization (new_tmpl,
4213                                    most_general_template (tmpl),
4214                                    args,
4215                                    is_friend, 0);
4216           return decl;
4217         }
4218
4219       /* Make sure the template headers we got make sense.  */
4220
4221       parms = DECL_TEMPLATE_PARMS (tmpl);
4222       i = TMPL_PARMS_DEPTH (parms);
4223       if (TMPL_ARGS_DEPTH (args) != i)
4224         {
4225           error ("expected %d levels of template parms for %q#D, got %d",
4226                  i, decl, TMPL_ARGS_DEPTH (args));
4227         }
4228       else
4229         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4230           {
4231             a = TMPL_ARGS_LEVEL (args, i);
4232             t = INNERMOST_TEMPLATE_PARMS (parms);
4233
4234             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4235               {
4236                 if (current == decl)
4237                   error ("got %d template parameters for %q#D",
4238                          TREE_VEC_LENGTH (a), decl);
4239                 else
4240                   error ("got %d template parameters for %q#T",
4241                          TREE_VEC_LENGTH (a), current);
4242                 error ("  but %d required", TREE_VEC_LENGTH (t));
4243                 return error_mark_node;
4244               }
4245
4246             if (current == decl)
4247               current = ctx;
4248             else
4249               current = (TYPE_P (current)
4250                          ? TYPE_CONTEXT (current)
4251                          : DECL_CONTEXT (current));
4252           }
4253
4254       /* Check that the parms are used in the appropriate qualifying scopes
4255          in the declarator.  */
4256       if (!comp_template_args
4257           (TI_ARGS (tinfo),
4258            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4259         {
4260           error ("\
4261 template arguments to %qD do not match original template %qD",
4262                  decl, DECL_TEMPLATE_RESULT (tmpl));
4263           if (!uses_template_parms (TI_ARGS (tinfo)))
4264             inform (input_location, "use template<> for an explicit specialization");
4265           /* Avoid crash in import_export_decl.  */
4266           DECL_INTERFACE_KNOWN (decl) = 1;
4267           return error_mark_node;
4268         }
4269     }
4270
4271   DECL_TEMPLATE_RESULT (tmpl) = decl;
4272   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4273
4274   /* Push template declarations for global functions and types.  Note
4275      that we do not try to push a global template friend declared in a
4276      template class; such a thing may well depend on the template
4277      parameters of the class.  */
4278   if (new_template_p && !ctx
4279       && !(is_friend && template_class_depth (current_class_type) > 0))
4280     {
4281       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4282       if (tmpl == error_mark_node)
4283         return error_mark_node;
4284
4285       /* Hide template friend classes that haven't been declared yet.  */
4286       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4287         {
4288           DECL_ANTICIPATED (tmpl) = 1;
4289           DECL_FRIEND_P (tmpl) = 1;
4290         }
4291     }
4292
4293   if (primary)
4294     {
4295       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4296       int i;
4297
4298       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4299       if (DECL_CONV_FN_P (tmpl))
4300         {
4301           int depth = TMPL_PARMS_DEPTH (parms);
4302
4303           /* It is a conversion operator. See if the type converted to
4304              depends on innermost template operands.  */
4305
4306           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4307                                          depth))
4308             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4309         }
4310
4311       /* Give template template parms a DECL_CONTEXT of the template
4312          for which they are a parameter.  */
4313       parms = INNERMOST_TEMPLATE_PARMS (parms);
4314       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4315         {
4316           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4317           if (TREE_CODE (parm) == TEMPLATE_DECL)
4318             DECL_CONTEXT (parm) = tmpl;
4319         }
4320     }
4321
4322   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4323      back to its most general template.  If TMPL is a specialization,
4324      ARGS may only have the innermost set of arguments.  Add the missing
4325      argument levels if necessary.  */
4326   if (DECL_TEMPLATE_INFO (tmpl))
4327     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4328
4329   info = tree_cons (tmpl, args, NULL_TREE);
4330
4331   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4332     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4333   else if (DECL_LANG_SPECIFIC (decl))
4334     DECL_TEMPLATE_INFO (decl) = info;
4335
4336   return DECL_TEMPLATE_RESULT (tmpl);
4337 }
4338
4339 tree
4340 push_template_decl (tree decl)
4341 {
4342   return push_template_decl_real (decl, false);
4343 }
4344
4345 /* Called when a class template TYPE is redeclared with the indicated
4346    template PARMS, e.g.:
4347
4348      template <class T> struct S;
4349      template <class T> struct S {};  */
4350
4351 bool
4352 redeclare_class_template (tree type, tree parms)
4353 {
4354   tree tmpl;
4355   tree tmpl_parms;
4356   int i;
4357
4358   if (!TYPE_TEMPLATE_INFO (type))
4359     {
4360       error ("%qT is not a template type", type);
4361       return false;
4362     }
4363
4364   tmpl = TYPE_TI_TEMPLATE (type);
4365   if (!PRIMARY_TEMPLATE_P (tmpl))
4366     /* The type is nested in some template class.  Nothing to worry
4367        about here; there are no new template parameters for the nested
4368        type.  */
4369     return true;
4370
4371   if (!parms)
4372     {
4373       error ("template specifiers not specified in declaration of %qD",
4374              tmpl);
4375       return false;
4376     }
4377
4378   parms = INNERMOST_TEMPLATE_PARMS (parms);
4379   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4380
4381   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4382     {
4383       error ("redeclared with %d template parameter(s)", 
4384              TREE_VEC_LENGTH (parms));
4385       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4386              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4387       return false;
4388     }
4389
4390   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4391     {
4392       tree tmpl_parm;
4393       tree parm;
4394       tree tmpl_default;
4395       tree parm_default;
4396
4397       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4398           || TREE_VEC_ELT (parms, i) == error_mark_node)
4399         continue;
4400
4401       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4402       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4403       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4404       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4405
4406       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4407          TEMPLATE_DECL.  */
4408       if (tmpl_parm != error_mark_node
4409           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4410               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4411                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4412               || (TREE_CODE (tmpl_parm) != PARM_DECL
4413                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4414                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4415               || (TREE_CODE (tmpl_parm) == PARM_DECL
4416                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4417                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4418         {
4419           error ("template parameter %q+#D", tmpl_parm);
4420           error ("redeclared here as %q#D", parm);
4421           return false;
4422         }
4423
4424       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4425         {
4426           /* We have in [temp.param]:
4427
4428              A template-parameter may not be given default arguments
4429              by two different declarations in the same scope.  */
4430           error ("redefinition of default argument for %q#D", parm);
4431           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4432           return false;
4433         }
4434
4435       if (parm_default != NULL_TREE)
4436         /* Update the previous template parameters (which are the ones
4437            that will really count) with the new default value.  */
4438         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4439       else if (tmpl_default != NULL_TREE)
4440         /* Update the new parameters, too; they'll be used as the
4441            parameters for any members.  */
4442         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4443     }
4444
4445     return true;
4446 }
4447
4448 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4449    (possibly simplified) expression.  */
4450
4451 tree
4452 fold_non_dependent_expr (tree expr)
4453 {
4454   if (expr == NULL_TREE)
4455     return NULL_TREE;
4456
4457   /* If we're in a template, but EXPR isn't value dependent, simplify
4458      it.  We're supposed to treat:
4459
4460        template <typename T> void f(T[1 + 1]);
4461        template <typename T> void f(T[2]);
4462
4463      as two declarations of the same function, for example.  */
4464   if (processing_template_decl
4465       && !type_dependent_expression_p (expr)
4466       && !value_dependent_expression_p (expr))
4467     {
4468       HOST_WIDE_INT saved_processing_template_decl;
4469
4470       saved_processing_template_decl = processing_template_decl;
4471       processing_template_decl = 0;
4472       expr = tsubst_copy_and_build (expr,
4473                                     /*args=*/NULL_TREE,
4474                                     tf_error,
4475                                     /*in_decl=*/NULL_TREE,
4476                                     /*function_p=*/false,
4477                                     /*integral_constant_expression_p=*/true);
4478       processing_template_decl = saved_processing_template_decl;
4479     }
4480   return expr;
4481 }
4482
4483 /* EXPR is an expression which is used in a constant-expression context.
4484    For instance, it could be a VAR_DECL with a constant initializer.
4485    Extract the innermost constant expression.
4486
4487    This is basically a more powerful version of
4488    integral_constant_value, which can be used also in templates where
4489    initializers can maintain a syntactic rather than semantic form
4490    (even if they are non-dependent, for access-checking purposes).  */
4491
4492 static tree
4493 fold_decl_constant_value (tree expr)
4494 {
4495   tree const_expr = expr;
4496   do
4497     {
4498       expr = fold_non_dependent_expr (const_expr);
4499       const_expr = integral_constant_value (expr);
4500     }
4501   while (expr != const_expr);
4502
4503   return expr;
4504 }
4505
4506 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4507    must be a function or a pointer-to-function type, as specified
4508    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4509    and check that the resulting function has external linkage.  */
4510
4511 static tree
4512 convert_nontype_argument_function (tree type, tree expr)
4513 {
4514   tree fns = expr;
4515   tree fn, fn_no_ptr;
4516
4517   fn = instantiate_type (type, fns, tf_none);
4518   if (fn == error_mark_node)
4519     return error_mark_node;
4520
4521   fn_no_ptr = fn;
4522   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4523     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4524   if (TREE_CODE (fn_no_ptr) == BASELINK)
4525     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4526  
4527   /* [temp.arg.nontype]/1
4528
4529      A template-argument for a non-type, non-template template-parameter
4530      shall be one of:
4531      [...]
4532      -- the address of an object or function with external linkage.  */
4533   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4534     {
4535       error ("%qE is not a valid template argument for type %qT "
4536              "because function %qD has not external linkage",
4537              expr, type, fn_no_ptr);
4538       return NULL_TREE;
4539     }
4540
4541   return fn;
4542 }
4543
4544 /* Attempt to convert the non-type template parameter EXPR to the
4545    indicated TYPE.  If the conversion is successful, return the
4546    converted value.  If the conversion is unsuccessful, return
4547    NULL_TREE if we issued an error message, or error_mark_node if we
4548    did not.  We issue error messages for out-and-out bad template
4549    parameters, but not simply because the conversion failed, since we
4550    might be just trying to do argument deduction.  Both TYPE and EXPR
4551    must be non-dependent.
4552
4553    The conversion follows the special rules described in
4554    [temp.arg.nontype], and it is much more strict than an implicit
4555    conversion.
4556
4557    This function is called twice for each template argument (see
4558    lookup_template_class for a more accurate description of this
4559    problem). This means that we need to handle expressions which
4560    are not valid in a C++ source, but can be created from the
4561    first call (for instance, casts to perform conversions). These
4562    hacks can go away after we fix the double coercion problem.  */
4563
4564 static tree
4565 convert_nontype_argument (tree type, tree expr)
4566 {
4567   tree expr_type;
4568
4569   /* Detect immediately string literals as invalid non-type argument.
4570      This special-case is not needed for correctness (we would easily
4571      catch this later), but only to provide better diagnostic for this
4572      common user mistake. As suggested by DR 100, we do not mention
4573      linkage issues in the diagnostic as this is not the point.  */
4574   if (TREE_CODE (expr) == STRING_CST)
4575     {
4576       error ("%qE is not a valid template argument for type %qT "
4577              "because string literals can never be used in this context",
4578              expr, type);
4579       return NULL_TREE;
4580     }
4581
4582   /* If we are in a template, EXPR may be non-dependent, but still
4583      have a syntactic, rather than semantic, form.  For example, EXPR
4584      might be a SCOPE_REF, rather than the VAR_DECL to which the
4585      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4586      so that access checking can be performed when the template is
4587      instantiated -- but here we need the resolved form so that we can
4588      convert the argument.  */
4589   expr = fold_non_dependent_expr (expr);
4590   if (error_operand_p (expr))
4591     return error_mark_node;
4592   expr_type = TREE_TYPE (expr);
4593
4594   /* HACK: Due to double coercion, we can get a
4595      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4596      which is the tree that we built on the first call (see
4597      below when coercing to reference to object or to reference to
4598      function). We just strip everything and get to the arg.
4599      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4600      for examples.  */
4601   if (TREE_CODE (expr) == NOP_EXPR)
4602     {
4603       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4604         {
4605           /* ??? Maybe we could use convert_from_reference here, but we
4606              would need to relax its constraints because the NOP_EXPR
4607              could actually change the type to something more cv-qualified,
4608              and this is not folded by convert_from_reference.  */
4609           tree addr = TREE_OPERAND (expr, 0);
4610           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4611           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4612           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4613           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4614                       (TREE_TYPE (expr_type),
4615                        TREE_TYPE (TREE_TYPE (addr))));
4616
4617           expr = TREE_OPERAND (addr, 0);
4618           expr_type = TREE_TYPE (expr);
4619         }
4620
4621       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4622          parameter is a pointer to object, through decay and
4623          qualification conversion. Let's strip everything.  */
4624       else if (TYPE_PTROBV_P (type))
4625         {
4626           STRIP_NOPS (expr);
4627           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4628           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4629           /* Skip the ADDR_EXPR only if it is part of the decay for
4630              an array. Otherwise, it is part of the original argument
4631              in the source code.  */
4632           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4633             expr = TREE_OPERAND (expr, 0);
4634           expr_type = TREE_TYPE (expr);
4635         }
4636     }
4637
4638   /* [temp.arg.nontype]/5, bullet 1
4639
4640      For a non-type template-parameter of integral or enumeration type,
4641      integral promotions (_conv.prom_) and integral conversions
4642      (_conv.integral_) are applied.  */
4643   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4644     {
4645       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4646         return error_mark_node;
4647
4648       expr = fold_decl_constant_value (expr);
4649       /* Notice that there are constant expressions like '4 % 0' which
4650          do not fold into integer constants.  */
4651       if (TREE_CODE (expr) != INTEGER_CST)
4652         {
4653           error ("%qE is not a valid template argument for type %qT "
4654                  "because it is a non-constant expression", expr, type);
4655           return NULL_TREE;
4656         }
4657
4658       /* At this point, an implicit conversion does what we want,
4659          because we already know that the expression is of integral
4660          type.  */
4661       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4662       if (expr == error_mark_node)
4663         return error_mark_node;
4664
4665       /* Conversion was allowed: fold it to a bare integer constant.  */
4666       expr = fold (expr);
4667     }
4668   /* [temp.arg.nontype]/5, bullet 2
4669
4670      For a non-type template-parameter of type pointer to object,
4671      qualification conversions (_conv.qual_) and the array-to-pointer
4672      conversion (_conv.array_) are applied.  */
4673   else if (TYPE_PTROBV_P (type))
4674     {
4675       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4676
4677          A template-argument for a non-type, non-template template-parameter
4678          shall be one of: [...]
4679
4680          -- the name of a non-type template-parameter;
4681          -- the address of an object or function with external linkage, [...]
4682             expressed as "& id-expression" where the & is optional if the name
4683             refers to a function or array, or if the corresponding
4684             template-parameter is a reference.
4685
4686         Here, we do not care about functions, as they are invalid anyway
4687         for a parameter of type pointer-to-object.  */
4688
4689       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4690         /* Non-type template parameters are OK.  */
4691         ;
4692       else if (TREE_CODE (expr) != ADDR_EXPR
4693                && TREE_CODE (expr_type) != ARRAY_TYPE)
4694         {
4695           if (TREE_CODE (expr) == VAR_DECL)
4696             {
4697               error ("%qD is not a valid template argument "
4698                      "because %qD is a variable, not the address of "
4699                      "a variable",
4700                      expr, expr);
4701               return NULL_TREE;
4702             }
4703           /* Other values, like integer constants, might be valid
4704              non-type arguments of some other type.  */
4705           return error_mark_node;
4706         }
4707       else
4708         {
4709           tree decl;
4710
4711           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4712                   ? TREE_OPERAND (expr, 0) : expr);
4713           if (TREE_CODE (decl) != VAR_DECL)
4714             {
4715               error ("%qE is not a valid template argument of type %qT "
4716                      "because %qE is not a variable",
4717                      expr, type, decl);
4718               return NULL_TREE;
4719             }
4720           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4721             {
4722               error ("%qE is not a valid template argument of type %qT "
4723                      "because %qD does not have external linkage",
4724                      expr, type, decl);
4725               return NULL_TREE;
4726             }
4727         }
4728
4729       expr = decay_conversion (expr);
4730       if (expr == error_mark_node)
4731         return error_mark_node;
4732
4733       expr = perform_qualification_conversions (type, expr);
4734       if (expr == error_mark_node)
4735         return error_mark_node;
4736     }
4737   /* [temp.arg.nontype]/5, bullet 3
4738
4739      For a non-type template-parameter of type reference to object, no
4740      conversions apply. The type referred to by the reference may be more
4741      cv-qualified than the (otherwise identical) type of the
4742      template-argument. The template-parameter is bound directly to the
4743      template-argument, which must be an lvalue.  */
4744   else if (TYPE_REF_OBJ_P (type))
4745     {
4746       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4747                                                       expr_type))
4748         return error_mark_node;
4749
4750       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4751         {
4752           error ("%qE is not a valid template argument for type %qT "
4753                  "because of conflicts in cv-qualification", expr, type);
4754           return NULL_TREE;
4755         }
4756
4757       if (!real_lvalue_p (expr))
4758         {
4759           error ("%qE is not a valid template argument for type %qT "
4760                  "because it is not an lvalue", expr, type);
4761           return NULL_TREE;
4762         }
4763
4764       /* [temp.arg.nontype]/1
4765
4766          A template-argument for a non-type, non-template template-parameter
4767          shall be one of: [...]
4768
4769          -- the address of an object or function with external linkage.  */
4770       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4771         {
4772           error ("%qE is not a valid template argument for type %qT "
4773                  "because object %qD has not external linkage",
4774                  expr, type, expr);
4775           return NULL_TREE;
4776         }
4777
4778       expr = build_nop (type, build_address (expr));
4779     }
4780   /* [temp.arg.nontype]/5, bullet 4
4781
4782      For a non-type template-parameter of type pointer to function, only
4783      the function-to-pointer conversion (_conv.func_) is applied. If the
4784      template-argument represents a set of overloaded functions (or a
4785      pointer to such), the matching function is selected from the set
4786      (_over.over_).  */
4787   else if (TYPE_PTRFN_P (type))
4788     {
4789       /* If the argument is a template-id, we might not have enough
4790          context information to decay the pointer.  */
4791       if (!type_unknown_p (expr_type))
4792         {
4793           expr = decay_conversion (expr);
4794           if (expr == error_mark_node)
4795             return error_mark_node;
4796         }
4797
4798       expr = convert_nontype_argument_function (type, expr);
4799       if (!expr || expr == error_mark_node)
4800         return expr;
4801
4802       if (TREE_CODE (expr) != ADDR_EXPR)
4803         {
4804           error ("%qE is not a valid template argument for type %qT", expr, type);
4805           error ("it must be the address of a function with external linkage");
4806           return NULL_TREE;
4807         }
4808     }
4809   /* [temp.arg.nontype]/5, bullet 5
4810
4811      For a non-type template-parameter of type reference to function, no
4812      conversions apply. If the template-argument represents a set of
4813      overloaded functions, the matching function is selected from the set
4814      (_over.over_).  */
4815   else if (TYPE_REFFN_P (type))
4816     {
4817       if (TREE_CODE (expr) == ADDR_EXPR)
4818         {
4819           error ("%qE is not a valid template argument for type %qT "
4820                  "because it is a pointer", expr, type);
4821           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4822           return NULL_TREE;
4823         }
4824
4825       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4826       if (!expr || expr == error_mark_node)
4827         return expr;
4828
4829       expr = build_nop (type, build_address (expr));
4830     }
4831   /* [temp.arg.nontype]/5, bullet 6
4832
4833      For a non-type template-parameter of type pointer to member function,
4834      no conversions apply. If the template-argument represents a set of
4835      overloaded member functions, the matching member function is selected
4836      from the set (_over.over_).  */
4837   else if (TYPE_PTRMEMFUNC_P (type))
4838     {
4839       expr = instantiate_type (type, expr, tf_none);
4840       if (expr == error_mark_node)
4841         return error_mark_node;
4842
4843       /* There is no way to disable standard conversions in
4844          resolve_address_of_overloaded_function (called by
4845          instantiate_type). It is possible that the call succeeded by
4846          converting &B::I to &D::I (where B is a base of D), so we need
4847          to reject this conversion here.
4848
4849          Actually, even if there was a way to disable standard conversions,
4850          it would still be better to reject them here so that we can
4851          provide a superior diagnostic.  */
4852       if (!same_type_p (TREE_TYPE (expr), type))
4853         {
4854           /* Make sure we are just one standard conversion off.  */
4855           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4856           error ("%qE is not a valid template argument for type %qT "
4857                  "because it is of type %qT", expr, type,
4858                  TREE_TYPE (expr));
4859           inform (input_location, "standard conversions are not allowed in this context");
4860           return NULL_TREE;
4861         }
4862     }
4863   /* [temp.arg.nontype]/5, bullet 7
4864
4865      For a non-type template-parameter of type pointer to data member,
4866      qualification conversions (_conv.qual_) are applied.  */
4867   else if (TYPE_PTRMEM_P (type))
4868     {
4869       expr = perform_qualification_conversions (type, expr);
4870       if (expr == error_mark_node)
4871         return expr;
4872     }
4873   /* A template non-type parameter must be one of the above.  */
4874   else
4875     gcc_unreachable ();
4876
4877   /* Sanity check: did we actually convert the argument to the
4878      right type?  */
4879   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4880   return expr;
4881 }
4882
4883 /* Subroutine of coerce_template_template_parms, which returns 1 if
4884    PARM_PARM and ARG_PARM match using the rule for the template
4885    parameters of template template parameters. Both PARM and ARG are
4886    template parameters; the rest of the arguments are the same as for
4887    coerce_template_template_parms.
4888  */
4889 static int
4890 coerce_template_template_parm (tree parm,
4891                               tree arg,
4892                               tsubst_flags_t complain,
4893                               tree in_decl,
4894                               tree outer_args)
4895 {
4896   if (arg == NULL_TREE || arg == error_mark_node
4897       || parm == NULL_TREE || parm == error_mark_node)
4898     return 0;
4899   
4900   if (TREE_CODE (arg) != TREE_CODE (parm))
4901     return 0;
4902   
4903   switch (TREE_CODE (parm))
4904     {
4905     case TEMPLATE_DECL:
4906       /* We encounter instantiations of templates like
4907          template <template <template <class> class> class TT>
4908          class C;  */
4909       {
4910         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4911         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4912         
4913         if (!coerce_template_template_parms
4914             (parmparm, argparm, complain, in_decl, outer_args))
4915           return 0;
4916       }
4917       /* Fall through.  */
4918       
4919     case TYPE_DECL:
4920       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4921           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4922         /* Argument is a parameter pack but parameter is not.  */
4923         return 0;
4924       break;
4925       
4926     case PARM_DECL:
4927       /* The tsubst call is used to handle cases such as
4928          
4929            template <int> class C {};
4930            template <class T, template <T> class TT> class D {};
4931            D<int, C> d;
4932
4933          i.e. the parameter list of TT depends on earlier parameters.  */
4934       if (!uses_template_parms (TREE_TYPE (arg))
4935           && !same_type_p
4936                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4937                  TREE_TYPE (arg)))
4938         return 0;
4939       
4940       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4941           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4942         /* Argument is a parameter pack but parameter is not.  */
4943         return 0;
4944       
4945       break;
4946
4947     default:
4948       gcc_unreachable ();
4949     }
4950
4951   return 1;
4952 }
4953
4954
4955 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4956    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4957    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4958    or PARM_DECL.
4959
4960    Consider the example:
4961      template <class T> class A;
4962      template<template <class U> class TT> class B;
4963
4964    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4965    the parameters to A, and OUTER_ARGS contains A.  */
4966
4967 static int
4968 coerce_template_template_parms (tree parm_parms,
4969                                 tree arg_parms,
4970                                 tsubst_flags_t complain,
4971                                 tree in_decl,
4972                                 tree outer_args)
4973 {
4974   int nparms, nargs, i;
4975   tree parm, arg;
4976   int variadic_p = 0;
4977
4978   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4979   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4980
4981   nparms = TREE_VEC_LENGTH (parm_parms);
4982   nargs = TREE_VEC_LENGTH (arg_parms);
4983
4984   /* Determine whether we have a parameter pack at the end of the
4985      template template parameter's template parameter list.  */
4986   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4987     {
4988       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4989       
4990       if (parm == error_mark_node)
4991         return 0;
4992
4993       switch (TREE_CODE (parm))
4994         {
4995         case TEMPLATE_DECL:
4996         case TYPE_DECL:
4997           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4998             variadic_p = 1;
4999           break;
5000           
5001         case PARM_DECL:
5002           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5003             variadic_p = 1;
5004           break;
5005           
5006         default:
5007           gcc_unreachable ();
5008         }
5009     }
5010  
5011   if (nargs != nparms
5012       && !(variadic_p && nargs >= nparms - 1))
5013     return 0;
5014
5015   /* Check all of the template parameters except the parameter pack at
5016      the end (if any).  */
5017   for (i = 0; i < nparms - variadic_p; ++i)
5018     {
5019       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5020           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5021         continue;
5022
5023       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5024       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5025
5026       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5027                                           outer_args))
5028         return 0;
5029
5030     }
5031
5032   if (variadic_p)
5033     {
5034       /* Check each of the template parameters in the template
5035          argument against the template parameter pack at the end of
5036          the template template parameter.  */
5037       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5038         return 0;
5039
5040       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5041
5042       for (; i < nargs; ++i)
5043         {
5044           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5045             continue;
5046  
5047           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5048  
5049           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5050                                               outer_args))
5051             return 0;
5052         }
5053     }
5054
5055   return 1;
5056 }
5057
5058 /* Verifies that the deduced template arguments (in TARGS) for the
5059    template template parameters (in TPARMS) represent valid bindings,
5060    by comparing the template parameter list of each template argument
5061    to the template parameter list of its corresponding template
5062    template parameter, in accordance with DR150. This
5063    routine can only be called after all template arguments have been
5064    deduced. It will return TRUE if all of the template template
5065    parameter bindings are okay, FALSE otherwise.  */
5066 bool 
5067 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5068 {
5069   int i, ntparms = TREE_VEC_LENGTH (tparms);
5070   bool ret = true;
5071
5072   /* We're dealing with template parms in this process.  */
5073   ++processing_template_decl;
5074
5075   targs = INNERMOST_TEMPLATE_ARGS (targs);
5076
5077   for (i = 0; i < ntparms; ++i)
5078     {
5079       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5080       tree targ = TREE_VEC_ELT (targs, i);
5081
5082       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5083         {
5084           tree packed_args = NULL_TREE;
5085           int idx, len = 1;
5086
5087           if (ARGUMENT_PACK_P (targ))
5088             {
5089               /* Look inside the argument pack.  */
5090               packed_args = ARGUMENT_PACK_ARGS (targ);
5091               len = TREE_VEC_LENGTH (packed_args);
5092             }
5093
5094           for (idx = 0; idx < len; ++idx)
5095             {
5096               tree targ_parms = NULL_TREE;
5097
5098               if (packed_args)
5099                 /* Extract the next argument from the argument
5100                    pack.  */
5101                 targ = TREE_VEC_ELT (packed_args, idx);
5102
5103               if (PACK_EXPANSION_P (targ))
5104                 /* Look at the pattern of the pack expansion.  */
5105                 targ = PACK_EXPANSION_PATTERN (targ);
5106
5107               /* Extract the template parameters from the template
5108                  argument.  */
5109               if (TREE_CODE (targ) == TEMPLATE_DECL)
5110                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5111               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5112                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5113
5114               /* Verify that we can coerce the template template
5115                  parameters from the template argument to the template
5116                  parameter.  This requires an exact match.  */
5117               if (targ_parms
5118                   && !coerce_template_template_parms
5119                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5120                         targ_parms,
5121                         tf_none,
5122                         tparm,
5123                         targs))
5124                 {
5125                   ret = false;
5126                   goto out;
5127                 }
5128             }
5129         }
5130     }
5131
5132  out:
5133
5134   --processing_template_decl;
5135   return ret;
5136 }
5137
5138 /* Convert the indicated template ARG as necessary to match the
5139    indicated template PARM.  Returns the converted ARG, or
5140    error_mark_node if the conversion was unsuccessful.  Error and
5141    warning messages are issued under control of COMPLAIN.  This
5142    conversion is for the Ith parameter in the parameter list.  ARGS is
5143    the full set of template arguments deduced so far.  */
5144
5145 static tree
5146 convert_template_argument (tree parm,
5147                            tree arg,
5148                            tree args,
5149                            tsubst_flags_t complain,
5150                            int i,
5151                            tree in_decl)
5152 {
5153   tree orig_arg;
5154   tree val;
5155   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5156
5157   if (TREE_CODE (arg) == TREE_LIST
5158       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5159     {
5160       /* The template argument was the name of some
5161          member function.  That's usually
5162          invalid, but static members are OK.  In any
5163          case, grab the underlying fields/functions
5164          and issue an error later if required.  */
5165       orig_arg = TREE_VALUE (arg);
5166       TREE_TYPE (arg) = unknown_type_node;
5167     }
5168
5169   orig_arg = arg;
5170
5171   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5172   requires_type = (TREE_CODE (parm) == TYPE_DECL
5173                    || requires_tmpl_type);
5174
5175   /* When determining whether an argument pack expansion is a template,
5176      look at the pattern.  */
5177   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5178     arg = PACK_EXPANSION_PATTERN (arg);
5179
5180   is_tmpl_type = 
5181     ((TREE_CODE (arg) == TEMPLATE_DECL
5182       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5183      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5184      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5185
5186   if (is_tmpl_type
5187       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5188           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5189     arg = TYPE_STUB_DECL (arg);
5190
5191   is_type = TYPE_P (arg) || is_tmpl_type;
5192
5193   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5194       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5195     {
5196       permerror (input_location, "to refer to a type member of a template parameter, "
5197                  "use %<typename %E%>", orig_arg);
5198
5199       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5200                                      TREE_OPERAND (arg, 1),
5201                                      typename_type,
5202                                      complain & tf_error);
5203       arg = orig_arg;
5204       is_type = 1;
5205     }
5206   if (is_type != requires_type)
5207     {
5208       if (in_decl)
5209         {
5210           if (complain & tf_error)
5211             {
5212               error ("type/value mismatch at argument %d in template "
5213                      "parameter list for %qD",
5214                      i + 1, in_decl);
5215               if (is_type)
5216                 error ("  expected a constant of type %qT, got %qT",
5217                        TREE_TYPE (parm),
5218                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5219               else if (requires_tmpl_type)
5220                 error ("  expected a class template, got %qE", orig_arg);
5221               else
5222                 error ("  expected a type, got %qE", orig_arg);
5223             }
5224         }
5225       return error_mark_node;
5226     }
5227   if (is_tmpl_type ^ requires_tmpl_type)
5228     {
5229       if (in_decl && (complain & tf_error))
5230         {
5231           error ("type/value mismatch at argument %d in template "
5232                  "parameter list for %qD",
5233                  i + 1, in_decl);
5234           if (is_tmpl_type)
5235             error ("  expected a type, got %qT", DECL_NAME (arg));
5236           else
5237             error ("  expected a class template, got %qT", orig_arg);
5238         }
5239       return error_mark_node;
5240     }
5241
5242   if (is_type)
5243     {
5244       if (requires_tmpl_type)
5245         {
5246           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5247             /* The number of argument required is not known yet.
5248                Just accept it for now.  */
5249             val = TREE_TYPE (arg);
5250           else
5251             {
5252               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5253               tree argparm;
5254
5255               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5256
5257               if (coerce_template_template_parms (parmparm, argparm,
5258                                                   complain, in_decl,
5259                                                   args))
5260                 {
5261                   val = orig_arg;
5262
5263                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5264                      TEMPLATE_DECL.  */
5265                   if (val != error_mark_node)
5266                     {
5267                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5268                         val = TREE_TYPE (val);
5269                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5270                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5271                         {
5272                           val = TREE_TYPE (arg);
5273                           val = make_pack_expansion (val);
5274                         }
5275                     }
5276                 }
5277               else
5278                 {
5279                   if (in_decl && (complain & tf_error))
5280                     {
5281                       error ("type/value mismatch at argument %d in "
5282                              "template parameter list for %qD",
5283                              i + 1, in_decl);
5284                       error ("  expected a template of type %qD, got %qD",
5285                              parm, orig_arg);
5286                     }
5287
5288                   val = error_mark_node;
5289                 }
5290             }
5291         }
5292       else
5293         val = orig_arg;
5294       /* We only form one instance of each template specialization.
5295          Therefore, if we use a non-canonical variant (i.e., a
5296          typedef), any future messages referring to the type will use
5297          the typedef, which is confusing if those future uses do not
5298          themselves also use the typedef.  */
5299       if (TYPE_P (val))
5300         val = strip_typedefs (val);
5301     }
5302   else
5303     {
5304       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5305
5306       if (invalid_nontype_parm_type_p (t, complain))
5307         return error_mark_node;
5308
5309       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5310         {
5311           if (same_type_p (t, TREE_TYPE (orig_arg)))
5312             val = orig_arg;
5313           else
5314             {
5315               /* Not sure if this is reachable, but it doesn't hurt
5316                  to be robust.  */
5317               error ("type mismatch in nontype parameter pack");
5318               val = error_mark_node;
5319             }
5320         }
5321       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5322         /* We used to call digest_init here.  However, digest_init
5323            will report errors, which we don't want when complain
5324            is zero.  More importantly, digest_init will try too
5325            hard to convert things: for example, `0' should not be
5326            converted to pointer type at this point according to
5327            the standard.  Accepting this is not merely an
5328            extension, since deciding whether or not these
5329            conversions can occur is part of determining which
5330            function template to call, or whether a given explicit
5331            argument specification is valid.  */
5332         val = convert_nontype_argument (t, orig_arg);
5333       else
5334         val = orig_arg;
5335
5336       if (val == NULL_TREE)
5337         val = error_mark_node;
5338       else if (val == error_mark_node && (complain & tf_error))
5339         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5340     }
5341
5342   return val;
5343 }
5344
5345 /* Coerces the remaining template arguments in INNER_ARGS (from
5346    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5347    Returns the coerced argument pack. PARM_IDX is the position of this
5348    parameter in the template parameter list. ARGS is the original
5349    template argument list.  */
5350 static tree
5351 coerce_template_parameter_pack (tree parms,
5352                                 int parm_idx,
5353                                 tree args,
5354                                 tree inner_args,
5355                                 int arg_idx,
5356                                 tree new_args,
5357                                 int* lost,
5358                                 tree in_decl,
5359                                 tsubst_flags_t complain)
5360 {
5361   tree parm = TREE_VEC_ELT (parms, parm_idx);
5362   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5363   tree packed_args;
5364   tree argument_pack;
5365   tree packed_types = NULL_TREE;
5366
5367   if (arg_idx > nargs)
5368     arg_idx = nargs;
5369
5370   packed_args = make_tree_vec (nargs - arg_idx);
5371
5372   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5373       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5374     {
5375       /* When the template parameter is a non-type template
5376          parameter pack whose type uses parameter packs, we need
5377          to look at each of the template arguments
5378          separately. Build a vector of the types for these
5379          non-type template parameters in PACKED_TYPES.  */
5380       tree expansion 
5381         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5382       packed_types = tsubst_pack_expansion (expansion, args,
5383                                             complain, in_decl);
5384
5385       if (packed_types == error_mark_node)
5386         return error_mark_node;
5387
5388       /* Check that we have the right number of arguments.  */
5389       if (arg_idx < nargs
5390           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5391           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5392         {
5393           int needed_parms 
5394             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5395           error ("wrong number of template arguments (%d, should be %d)",
5396                  nargs, needed_parms);
5397           return error_mark_node;
5398         }
5399
5400       /* If we aren't able to check the actual arguments now
5401          (because they haven't been expanded yet), we can at least
5402          verify that all of the types used for the non-type
5403          template parameter pack are, in fact, valid for non-type
5404          template parameters.  */
5405       if (arg_idx < nargs 
5406           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5407         {
5408           int j, len = TREE_VEC_LENGTH (packed_types);
5409           for (j = 0; j < len; ++j)
5410             {
5411               tree t = TREE_VEC_ELT (packed_types, j);
5412               if (invalid_nontype_parm_type_p (t, complain))
5413                 return error_mark_node;
5414             }
5415         }
5416     }
5417
5418   /* Convert the remaining arguments, which will be a part of the
5419      parameter pack "parm".  */
5420   for (; arg_idx < nargs; ++arg_idx)
5421     {
5422       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5423       tree actual_parm = TREE_VALUE (parm);
5424
5425       if (packed_types && !PACK_EXPANSION_P (arg))
5426         {
5427           /* When we have a vector of types (corresponding to the
5428              non-type template parameter pack that uses parameter
5429              packs in its type, as mention above), and the
5430              argument is not an expansion (which expands to a
5431              currently unknown number of arguments), clone the
5432              parm and give it the next type in PACKED_TYPES.  */
5433           actual_parm = copy_node (actual_parm);
5434           TREE_TYPE (actual_parm) = 
5435             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5436         }
5437
5438       if (arg != error_mark_node)
5439         arg = convert_template_argument (actual_parm, 
5440                                          arg, new_args, complain, parm_idx,
5441                                          in_decl);
5442       if (arg == error_mark_node)
5443         (*lost)++;
5444       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5445     }
5446
5447   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5448       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5449     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5450   else
5451     {
5452       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5453       TREE_TYPE (argument_pack) 
5454         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5455       TREE_CONSTANT (argument_pack) = 1;
5456     }
5457
5458   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5459   return argument_pack;
5460 }
5461
5462 /* Convert all template arguments to their appropriate types, and
5463    return a vector containing the innermost resulting template
5464    arguments.  If any error occurs, return error_mark_node. Error and
5465    warning messages are issued under control of COMPLAIN.
5466
5467    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5468    for arguments not specified in ARGS.  Otherwise, if
5469    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5470    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5471    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5472    ARGS.  */
5473
5474 static tree
5475 coerce_template_parms (tree parms,
5476                        tree args,
5477                        tree in_decl,
5478                        tsubst_flags_t complain,
5479                        bool require_all_args,
5480                        bool use_default_args)
5481 {
5482   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5483   tree inner_args;
5484   tree new_args;
5485   tree new_inner_args;
5486   int saved_unevaluated_operand;
5487   int saved_inhibit_evaluation_warnings;
5488
5489   /* When used as a boolean value, indicates whether this is a
5490      variadic template parameter list. Since it's an int, we can also
5491      subtract it from nparms to get the number of non-variadic
5492      parameters.  */
5493   int variadic_p = 0;
5494
5495   nparms = TREE_VEC_LENGTH (parms);
5496
5497   /* Determine if there are any parameter packs.  */
5498   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5499     {
5500       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5501       if (template_parameter_pack_p (tparm))
5502         ++variadic_p;
5503     }
5504
5505   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5506   /* If there are 0 or 1 parameter packs, we need to expand any argument
5507      packs so that we can deduce a parameter pack from some non-packed args
5508      followed by an argument pack, as in variadic85.C.  If there are more
5509      than that, we need to leave argument packs intact so the arguments are
5510      assigned to the right parameter packs.  This should only happen when
5511      dealing with a nested class inside a partial specialization of a class
5512      template, as in variadic92.C.  */
5513   if (variadic_p <= 1)
5514     inner_args = expand_template_argument_pack (inner_args);
5515
5516   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5517   if ((nargs > nparms && !variadic_p)
5518       || (nargs < nparms - variadic_p
5519           && require_all_args
5520           && (!use_default_args
5521               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5522                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5523     {
5524       if (complain & tf_error)
5525         {
5526           const char *or_more = "";
5527           if (variadic_p)
5528             {
5529               or_more = " or more";
5530               --nparms;
5531             }
5532
5533           error ("wrong number of template arguments (%d, should be %d%s)",
5534                  nargs, nparms, or_more);
5535
5536           if (in_decl)
5537             error ("provided for %q+D", in_decl);
5538         }
5539
5540       return error_mark_node;
5541     }
5542
5543   /* We need to evaluate the template arguments, even though this
5544      template-id may be nested within a "sizeof".  */
5545   saved_unevaluated_operand = cp_unevaluated_operand;
5546   cp_unevaluated_operand = 0;
5547   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5548   c_inhibit_evaluation_warnings = 0;
5549   new_inner_args = make_tree_vec (nparms);
5550   new_args = add_outermost_template_args (args, new_inner_args);
5551   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5552     {
5553       tree arg;
5554       tree parm;
5555
5556       /* Get the Ith template parameter.  */
5557       parm = TREE_VEC_ELT (parms, parm_idx);
5558  
5559       if (parm == error_mark_node)
5560       {
5561         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5562         continue;
5563       }
5564
5565       /* Calculate the next argument.  */
5566       if (arg_idx < nargs)
5567         arg = TREE_VEC_ELT (inner_args, arg_idx);
5568       else
5569         arg = NULL_TREE;
5570
5571       if (template_parameter_pack_p (TREE_VALUE (parm))
5572           && !(arg && ARGUMENT_PACK_P (arg)))
5573         {
5574           /* All remaining arguments will be placed in the
5575              template parameter pack PARM.  */
5576           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5577                                                 inner_args, arg_idx,
5578                                                 new_args, &lost,
5579                                                 in_decl, complain);
5580
5581           /* Store this argument.  */
5582           if (arg == error_mark_node)
5583             lost++;
5584           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5585
5586           /* We are done with all of the arguments.  */
5587           arg_idx = nargs;
5588           
5589           continue;
5590         }
5591       else if (arg)
5592         {
5593           if (PACK_EXPANSION_P (arg))
5594             {
5595               if (complain & tf_error)
5596                 {
5597                   /* FIXME this restriction was removed by N2555; see
5598                      bug 35722.  */
5599                   /* If ARG is a pack expansion, but PARM is not a
5600                      template parameter pack (if it were, we would have
5601                      handled it above), we're trying to expand into a
5602                      fixed-length argument list.  */
5603                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5604                     sorry ("cannot expand %<%E%> into a fixed-length "
5605                            "argument list", arg);
5606                   else
5607                     sorry ("cannot expand %<%T%> into a fixed-length "
5608                            "argument list", arg);
5609                 }
5610               return error_mark_node;
5611             }
5612         }
5613       else if (require_all_args)
5614         /* There must be a default arg in this case.  */
5615         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5616                                    complain, in_decl);
5617       else
5618         break;
5619
5620       if (arg == error_mark_node)
5621         {
5622           if (complain & tf_error)
5623             error ("template argument %d is invalid", arg_idx + 1);
5624         }
5625       else if (!arg)
5626         /* This only occurs if there was an error in the template
5627            parameter list itself (which we would already have
5628            reported) that we are trying to recover from, e.g., a class
5629            template with a parameter list such as
5630            template<typename..., typename>.  */
5631         return error_mark_node;
5632       else
5633         arg = convert_template_argument (TREE_VALUE (parm),
5634                                          arg, new_args, complain, 
5635                                          parm_idx, in_decl);
5636
5637       if (arg == error_mark_node)
5638         lost++;
5639       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5640     }
5641   cp_unevaluated_operand = saved_unevaluated_operand;
5642   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5643
5644   if (lost)
5645     return error_mark_node;
5646
5647   return new_inner_args;
5648 }
5649
5650 /* Returns 1 if template args OT and NT are equivalent.  */
5651
5652 static int
5653 template_args_equal (tree ot, tree nt)
5654 {
5655   if (nt == ot)
5656     return 1;
5657
5658   if (TREE_CODE (nt) == TREE_VEC)
5659     /* For member templates */
5660     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5661   else if (PACK_EXPANSION_P (ot))
5662     return PACK_EXPANSION_P (nt) 
5663       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5664                               PACK_EXPANSION_PATTERN (nt));
5665   else if (ARGUMENT_PACK_P (ot))
5666     {
5667       int i, len;
5668       tree opack, npack;
5669
5670       if (!ARGUMENT_PACK_P (nt))
5671         return 0;
5672
5673       opack = ARGUMENT_PACK_ARGS (ot);
5674       npack = ARGUMENT_PACK_ARGS (nt);
5675       len = TREE_VEC_LENGTH (opack);
5676       if (TREE_VEC_LENGTH (npack) != len)
5677         return 0;
5678       for (i = 0; i < len; ++i)
5679         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5680                                   TREE_VEC_ELT (npack, i)))
5681           return 0;
5682       return 1;
5683     }
5684   else if (TYPE_P (nt))
5685     return TYPE_P (ot) && same_type_p (ot, nt);
5686   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5687     return 0;
5688   else
5689     return cp_tree_equal (ot, nt);
5690 }
5691
5692 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5693    of template arguments.  Returns 0 otherwise.  */
5694
5695 int
5696 comp_template_args (tree oldargs, tree newargs)
5697 {
5698   int i;
5699
5700   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5701     return 0;
5702
5703   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5704     {
5705       tree nt = TREE_VEC_ELT (newargs, i);
5706       tree ot = TREE_VEC_ELT (oldargs, i);
5707
5708       if (! template_args_equal (ot, nt))
5709         return 0;
5710     }
5711   return 1;
5712 }
5713
5714 static void
5715 add_pending_template (tree d)
5716 {
5717   tree ti = (TYPE_P (d)
5718              ? CLASSTYPE_TEMPLATE_INFO (d)
5719              : DECL_TEMPLATE_INFO (d));
5720   struct pending_template *pt;
5721   int level;
5722
5723   if (TI_PENDING_TEMPLATE_FLAG (ti))
5724     return;
5725
5726   /* We are called both from instantiate_decl, where we've already had a
5727      tinst_level pushed, and instantiate_template, where we haven't.
5728      Compensate.  */
5729   level = !current_tinst_level || current_tinst_level->decl != d;
5730
5731   if (level)
5732     push_tinst_level (d);
5733
5734   pt = GGC_NEW (struct pending_template);
5735   pt->next = NULL;
5736   pt->tinst = current_tinst_level;
5737   if (last_pending_template)
5738     last_pending_template->next = pt;
5739   else
5740     pending_templates = pt;
5741
5742   last_pending_template = pt;
5743
5744   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5745
5746   if (level)
5747     pop_tinst_level ();
5748 }
5749
5750
5751 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5752    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5753    documentation for TEMPLATE_ID_EXPR.  */
5754
5755 tree
5756 lookup_template_function (tree fns, tree arglist)
5757 {
5758   tree type;
5759
5760   if (fns == error_mark_node || arglist == error_mark_node)
5761     return error_mark_node;
5762
5763   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5764   gcc_assert (fns && (is_overloaded_fn (fns)
5765                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5766
5767   if (BASELINK_P (fns))
5768     {
5769       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5770                                          unknown_type_node,
5771                                          BASELINK_FUNCTIONS (fns),
5772                                          arglist);
5773       return fns;
5774     }
5775
5776   type = TREE_TYPE (fns);
5777   if (TREE_CODE (fns) == OVERLOAD || !type)
5778     type = unknown_type_node;
5779
5780   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5781 }
5782
5783 /* Within the scope of a template class S<T>, the name S gets bound
5784    (in build_self_reference) to a TYPE_DECL for the class, not a
5785    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5786    or one of its enclosing classes, and that type is a template,
5787    return the associated TEMPLATE_DECL.  Otherwise, the original
5788    DECL is returned.  */
5789
5790 tree
5791 maybe_get_template_decl_from_type_decl (tree decl)
5792 {
5793   return (decl != NULL_TREE
5794           && TREE_CODE (decl) == TYPE_DECL
5795           && DECL_ARTIFICIAL (decl)
5796           && CLASS_TYPE_P (TREE_TYPE (decl))
5797           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5798     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5799 }
5800
5801 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5802    parameters, find the desired type.
5803
5804    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5805
5806    IN_DECL, if non-NULL, is the template declaration we are trying to
5807    instantiate.
5808
5809    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5810    the class we are looking up.
5811
5812    Issue error and warning messages under control of COMPLAIN.
5813
5814    If the template class is really a local class in a template
5815    function, then the FUNCTION_CONTEXT is the function in which it is
5816    being instantiated.
5817
5818    ??? Note that this function is currently called *twice* for each
5819    template-id: the first time from the parser, while creating the
5820    incomplete type (finish_template_type), and the second type during the
5821    real instantiation (instantiate_template_class). This is surely something
5822    that we want to avoid. It also causes some problems with argument
5823    coercion (see convert_nontype_argument for more information on this).  */
5824
5825 tree
5826 lookup_template_class (tree d1,
5827                        tree arglist,
5828                        tree in_decl,
5829                        tree context,
5830                        int entering_scope,
5831                        tsubst_flags_t complain)
5832 {
5833   tree templ = NULL_TREE, parmlist;
5834   tree t;
5835   spec_entry **slot;
5836   spec_entry *entry;
5837   spec_entry elt;
5838   hashval_t hash;
5839
5840   timevar_push (TV_NAME_LOOKUP);
5841
5842   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5843     {
5844       tree value = innermost_non_namespace_value (d1);
5845       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5846         templ = value;
5847       else
5848         {
5849           if (context)
5850             push_decl_namespace (context);
5851           templ = lookup_name (d1);
5852           templ = maybe_get_template_decl_from_type_decl (templ);
5853           if (context)
5854             pop_decl_namespace ();
5855         }
5856       if (templ)
5857         context = DECL_CONTEXT (templ);
5858     }
5859   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5860     {
5861       tree type = TREE_TYPE (d1);
5862
5863       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5864          an implicit typename for the second A.  Deal with it.  */
5865       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5866         type = TREE_TYPE (type);
5867
5868       if (CLASSTYPE_TEMPLATE_INFO (type))
5869         {
5870           templ = CLASSTYPE_TI_TEMPLATE (type);
5871           d1 = DECL_NAME (templ);
5872         }
5873     }
5874   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5875            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5876     {
5877       templ = TYPE_TI_TEMPLATE (d1);
5878       d1 = DECL_NAME (templ);
5879     }
5880   else if (TREE_CODE (d1) == TEMPLATE_DECL
5881            && DECL_TEMPLATE_RESULT (d1)
5882            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5883     {
5884       templ = d1;
5885       d1 = DECL_NAME (templ);
5886       context = DECL_CONTEXT (templ);
5887     }
5888
5889   /* Issue an error message if we didn't find a template.  */
5890   if (! templ)
5891     {
5892       if (complain & tf_error)
5893         error ("%qT is not a template", d1);
5894       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5895     }
5896
5897   if (TREE_CODE (templ) != TEMPLATE_DECL
5898          /* Make sure it's a user visible template, if it was named by
5899             the user.  */
5900       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5901           && !PRIMARY_TEMPLATE_P (templ)))
5902     {
5903       if (complain & tf_error)
5904         {
5905           error ("non-template type %qT used as a template", d1);
5906           if (in_decl)
5907             error ("for template declaration %q+D", in_decl);
5908         }
5909       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5910     }
5911
5912   complain &= ~tf_user;
5913
5914   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5915     {
5916       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5917          template arguments */
5918
5919       tree parm;
5920       tree arglist2;
5921       tree outer;
5922
5923       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5924
5925       /* Consider an example where a template template parameter declared as
5926
5927            template <class T, class U = std::allocator<T> > class TT
5928
5929          The template parameter level of T and U are one level larger than
5930          of TT.  To proper process the default argument of U, say when an
5931          instantiation `TT<int>' is seen, we need to build the full
5932          arguments containing {int} as the innermost level.  Outer levels,
5933          available when not appearing as default template argument, can be
5934          obtained from the arguments of the enclosing template.
5935
5936          Suppose that TT is later substituted with std::vector.  The above
5937          instantiation is `TT<int, std::allocator<T> >' with TT at
5938          level 1, and T at level 2, while the template arguments at level 1
5939          becomes {std::vector} and the inner level 2 is {int}.  */
5940
5941       outer = DECL_CONTEXT (templ);
5942       if (outer)
5943         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5944       else if (current_template_parms)
5945         /* This is an argument of the current template, so we haven't set
5946            DECL_CONTEXT yet.  */
5947         outer = current_template_args ();
5948
5949       if (outer)
5950         arglist = add_to_template_args (outer, arglist);
5951
5952       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5953                                         complain,
5954                                         /*require_all_args=*/true,
5955                                         /*use_default_args=*/true);
5956       if (arglist2 == error_mark_node
5957           || (!uses_template_parms (arglist2)
5958               && check_instantiated_args (templ, arglist2, complain)))
5959         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5960
5961       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5962       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5963     }
5964   else
5965     {
5966       tree template_type = TREE_TYPE (templ);
5967       tree gen_tmpl;
5968       tree type_decl;
5969       tree found = NULL_TREE;
5970       int arg_depth;
5971       int parm_depth;
5972       int is_partial_instantiation;
5973
5974       gen_tmpl = most_general_template (templ);
5975       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5976       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5977       arg_depth = TMPL_ARGS_DEPTH (arglist);
5978
5979       if (arg_depth == 1 && parm_depth > 1)
5980         {
5981           /* We've been given an incomplete set of template arguments.
5982              For example, given:
5983
5984                template <class T> struct S1 {
5985                  template <class U> struct S2 {};
5986                  template <class U> struct S2<U*> {};
5987                 };
5988
5989              we will be called with an ARGLIST of `U*', but the
5990              TEMPLATE will be `template <class T> template
5991              <class U> struct S1<T>::S2'.  We must fill in the missing
5992              arguments.  */
5993           arglist
5994             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5995                                            arglist);
5996           arg_depth = TMPL_ARGS_DEPTH (arglist);
5997         }
5998
5999       /* Now we should have enough arguments.  */
6000       gcc_assert (parm_depth == arg_depth);
6001
6002       /* From here on, we're only interested in the most general
6003          template.  */
6004
6005       /* Calculate the BOUND_ARGS.  These will be the args that are
6006          actually tsubst'd into the definition to create the
6007          instantiation.  */
6008       if (parm_depth > 1)
6009         {
6010           /* We have multiple levels of arguments to coerce, at once.  */
6011           int i;
6012           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6013
6014           tree bound_args = make_tree_vec (parm_depth);
6015
6016           for (i = saved_depth,
6017                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6018                i > 0 && t != NULL_TREE;
6019                --i, t = TREE_CHAIN (t))
6020             {
6021               tree a = coerce_template_parms (TREE_VALUE (t),
6022                                               arglist, gen_tmpl,
6023                                               complain,
6024                                               /*require_all_args=*/true,
6025                                               /*use_default_args=*/true);
6026
6027               /* Don't process further if one of the levels fails.  */
6028               if (a == error_mark_node)
6029                 {
6030                   /* Restore the ARGLIST to its full size.  */
6031                   TREE_VEC_LENGTH (arglist) = saved_depth;
6032                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6033                 }
6034
6035               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6036
6037               /* We temporarily reduce the length of the ARGLIST so
6038                  that coerce_template_parms will see only the arguments
6039                  corresponding to the template parameters it is
6040                  examining.  */
6041               TREE_VEC_LENGTH (arglist)--;
6042             }
6043
6044           /* Restore the ARGLIST to its full size.  */
6045           TREE_VEC_LENGTH (arglist) = saved_depth;
6046
6047           arglist = bound_args;
6048         }
6049       else
6050         arglist
6051           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6052                                    INNERMOST_TEMPLATE_ARGS (arglist),
6053                                    gen_tmpl,
6054                                    complain,
6055                                    /*require_all_args=*/true,
6056                                    /*use_default_args=*/true);
6057
6058       if (arglist == error_mark_node)
6059         /* We were unable to bind the arguments.  */
6060         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6061
6062       /* In the scope of a template class, explicit references to the
6063          template class refer to the type of the template, not any
6064          instantiation of it.  For example, in:
6065
6066            template <class T> class C { void f(C<T>); }
6067
6068          the `C<T>' is just the same as `C'.  Outside of the
6069          class, however, such a reference is an instantiation.  */
6070       if ((entering_scope
6071            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6072            || currently_open_class (template_type))
6073           /* comp_template_args is expensive, check it last.  */
6074           && comp_template_args (TYPE_TI_ARGS (template_type),
6075                                  arglist))
6076         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6077
6078       /* If we already have this specialization, return it.  */
6079       elt.tmpl = gen_tmpl;
6080       elt.args = arglist;
6081       hash = hash_specialization (&elt);
6082       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6083                                                   &elt, hash);
6084
6085       if (entry)
6086         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6087
6088       /* This type is a "partial instantiation" if any of the template
6089          arguments still involve template parameters.  Note that we set
6090          IS_PARTIAL_INSTANTIATION for partial specializations as
6091          well.  */
6092       is_partial_instantiation = uses_template_parms (arglist);
6093
6094       /* If the deduced arguments are invalid, then the binding
6095          failed.  */
6096       if (!is_partial_instantiation
6097           && check_instantiated_args (gen_tmpl,
6098                                       INNERMOST_TEMPLATE_ARGS (arglist),
6099                                       complain))
6100         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6101
6102       if (!is_partial_instantiation
6103           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6104           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6105         {
6106           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6107                                       DECL_NAME (gen_tmpl),
6108                                       /*tag_scope=*/ts_global);
6109           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6110         }
6111
6112       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6113                         complain, in_decl);
6114       if (!context)
6115         context = global_namespace;
6116
6117       /* Create the type.  */
6118       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6119         {
6120           if (!is_partial_instantiation)
6121             {
6122               set_current_access_from_decl (TYPE_NAME (template_type));
6123               t = start_enum (TYPE_IDENTIFIER (template_type),
6124                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6125                                       arglist, complain, in_decl),
6126                               SCOPED_ENUM_P (template_type));
6127             }
6128           else
6129             {
6130               /* We don't want to call start_enum for this type, since
6131                  the values for the enumeration constants may involve
6132                  template parameters.  And, no one should be interested
6133                  in the enumeration constants for such a type.  */
6134               t = make_node (ENUMERAL_TYPE);
6135               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6136             }
6137         }
6138       else
6139         {
6140           t = make_class_type (TREE_CODE (template_type));
6141           CLASSTYPE_DECLARED_CLASS (t)
6142             = CLASSTYPE_DECLARED_CLASS (template_type);
6143           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6144           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6145
6146           /* A local class.  Make sure the decl gets registered properly.  */
6147           if (context == current_function_decl)
6148             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6149
6150           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6151             /* This instantiation is another name for the primary
6152                template type. Set the TYPE_CANONICAL field
6153                appropriately. */
6154             TYPE_CANONICAL (t) = template_type;
6155           else if (any_template_arguments_need_structural_equality_p (arglist))
6156             /* Some of the template arguments require structural
6157                equality testing, so this template class requires
6158                structural equality testing. */
6159             SET_TYPE_STRUCTURAL_EQUALITY (t);
6160         }
6161
6162       /* If we called start_enum or pushtag above, this information
6163          will already be set up.  */
6164       if (!TYPE_NAME (t))
6165         {
6166           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6167
6168           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6169           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6170           TYPE_STUB_DECL (t) = type_decl;
6171           DECL_SOURCE_LOCATION (type_decl)
6172             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6173         }
6174       else
6175         type_decl = TYPE_NAME (t);
6176
6177       TREE_PRIVATE (type_decl)
6178         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6179       TREE_PROTECTED (type_decl)
6180         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6181       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6182         {
6183           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6184           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6185         }
6186
6187       /* Set up the template information.  We have to figure out which
6188          template is the immediate parent if this is a full
6189          instantiation.  */
6190       if (parm_depth == 1 || is_partial_instantiation
6191           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6192         /* This case is easy; there are no member templates involved.  */
6193         found = gen_tmpl;
6194       else
6195         {
6196           /* This is a full instantiation of a member template.  Find
6197              the partial instantiation of which this is an instance.  */
6198
6199           /* Temporarily reduce by one the number of levels in the ARGLIST
6200              so as to avoid comparing the last set of arguments.  */
6201           TREE_VEC_LENGTH (arglist)--;
6202           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6203           TREE_VEC_LENGTH (arglist)++;
6204           found = CLASSTYPE_TI_TEMPLATE (found);
6205         }
6206
6207       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6208
6209       elt.spec = t;
6210       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6211                                                        &elt, hash, INSERT);
6212       *slot = GGC_NEW (spec_entry);
6213       **slot = elt;
6214
6215       /* Note this use of the partial instantiation so we can check it
6216          later in maybe_process_partial_specialization.  */
6217       DECL_TEMPLATE_INSTANTIATIONS (templ)
6218         = tree_cons (arglist, t,
6219                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6220
6221       if (TREE_CODE (t) == ENUMERAL_TYPE
6222           && !is_partial_instantiation)
6223         /* Now that the type has been registered on the instantiations
6224            list, we set up the enumerators.  Because the enumeration
6225            constants may involve the enumeration type itself, we make
6226            sure to register the type first, and then create the
6227            constants.  That way, doing tsubst_expr for the enumeration
6228            constants won't result in recursive calls here; we'll find
6229            the instantiation and exit above.  */
6230         tsubst_enum (template_type, t, arglist);
6231
6232       if (is_partial_instantiation)
6233         /* If the type makes use of template parameters, the
6234            code that generates debugging information will crash.  */
6235         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6236
6237       /* Possibly limit visibility based on template args.  */
6238       TREE_PUBLIC (type_decl) = 1;
6239       determine_visibility (type_decl);
6240
6241       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6242     }
6243   timevar_pop (TV_NAME_LOOKUP);
6244 }
6245 \f
6246 struct pair_fn_data
6247 {
6248   tree_fn_t fn;
6249   void *data;
6250   /* True when we should also visit template parameters that occur in
6251      non-deduced contexts.  */
6252   bool include_nondeduced_p;
6253   struct pointer_set_t *visited;
6254 };
6255
6256 /* Called from for_each_template_parm via walk_tree.  */
6257
6258 static tree
6259 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6260 {
6261   tree t = *tp;
6262   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6263   tree_fn_t fn = pfd->fn;
6264   void *data = pfd->data;
6265
6266   if (TYPE_P (t)
6267       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6268       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6269                                  pfd->include_nondeduced_p))
6270     return error_mark_node;
6271
6272   switch (TREE_CODE (t))
6273     {
6274     case RECORD_TYPE:
6275       if (TYPE_PTRMEMFUNC_P (t))
6276         break;
6277       /* Fall through.  */
6278
6279     case UNION_TYPE:
6280     case ENUMERAL_TYPE:
6281       if (!TYPE_TEMPLATE_INFO (t))
6282         *walk_subtrees = 0;
6283       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6284                                        fn, data, pfd->visited, 
6285                                        pfd->include_nondeduced_p))
6286         return error_mark_node;
6287       break;
6288
6289     case INTEGER_TYPE:
6290       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6291                                   fn, data, pfd->visited, 
6292                                   pfd->include_nondeduced_p)
6293           || for_each_template_parm (TYPE_MAX_VALUE (t),
6294                                      fn, data, pfd->visited,
6295                                      pfd->include_nondeduced_p))
6296         return error_mark_node;
6297       break;
6298
6299     case METHOD_TYPE:
6300       /* Since we're not going to walk subtrees, we have to do this
6301          explicitly here.  */
6302       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6303                                   pfd->visited, pfd->include_nondeduced_p))
6304         return error_mark_node;
6305       /* Fall through.  */
6306
6307     case FUNCTION_TYPE:
6308       /* Check the return type.  */
6309       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6310                                   pfd->include_nondeduced_p))
6311         return error_mark_node;
6312
6313       /* Check the parameter types.  Since default arguments are not
6314          instantiated until they are needed, the TYPE_ARG_TYPES may
6315          contain expressions that involve template parameters.  But,
6316          no-one should be looking at them yet.  And, once they're
6317          instantiated, they don't contain template parameters, so
6318          there's no point in looking at them then, either.  */
6319       {
6320         tree parm;
6321
6322         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6323           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6324                                       pfd->visited, pfd->include_nondeduced_p))
6325             return error_mark_node;
6326
6327         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6328            want walk_tree walking into them itself.  */
6329         *walk_subtrees = 0;
6330       }
6331       break;
6332
6333     case TYPEOF_TYPE:
6334       if (pfd->include_nondeduced_p
6335           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6336                                      pfd->visited, 
6337                                      pfd->include_nondeduced_p))
6338         return error_mark_node;
6339       break;
6340
6341     case FUNCTION_DECL:
6342     case VAR_DECL:
6343       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6344           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6345                                      pfd->visited, pfd->include_nondeduced_p))
6346         return error_mark_node;
6347       /* Fall through.  */
6348
6349     case PARM_DECL:
6350     case CONST_DECL:
6351       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6352           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6353                                      pfd->visited, pfd->include_nondeduced_p))
6354         return error_mark_node;
6355       if (DECL_CONTEXT (t)
6356           && pfd->include_nondeduced_p
6357           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6358                                      pfd->visited, pfd->include_nondeduced_p))
6359         return error_mark_node;
6360       break;
6361
6362     case BOUND_TEMPLATE_TEMPLATE_PARM:
6363       /* Record template parameters such as `T' inside `TT<T>'.  */
6364       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6365                                   pfd->include_nondeduced_p))
6366         return error_mark_node;
6367       /* Fall through.  */
6368
6369     case TEMPLATE_TEMPLATE_PARM:
6370     case TEMPLATE_TYPE_PARM:
6371     case TEMPLATE_PARM_INDEX:
6372       if (fn && (*fn)(t, data))
6373         return error_mark_node;
6374       else if (!fn)
6375         return error_mark_node;
6376       break;
6377
6378     case TEMPLATE_DECL:
6379       /* A template template parameter is encountered.  */
6380       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6381           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6382                                      pfd->include_nondeduced_p))
6383         return error_mark_node;
6384
6385       /* Already substituted template template parameter */
6386       *walk_subtrees = 0;
6387       break;
6388
6389     case TYPENAME_TYPE:
6390       if (!fn
6391           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6392                                      data, pfd->visited, 
6393                                      pfd->include_nondeduced_p))
6394         return error_mark_node;
6395       break;
6396
6397     case CONSTRUCTOR:
6398       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6399           && pfd->include_nondeduced_p
6400           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6401                                      (TREE_TYPE (t)), fn, data,
6402                                      pfd->visited, pfd->include_nondeduced_p))
6403         return error_mark_node;
6404       break;
6405
6406     case INDIRECT_REF:
6407     case COMPONENT_REF:
6408       /* If there's no type, then this thing must be some expression
6409          involving template parameters.  */
6410       if (!fn && !TREE_TYPE (t))
6411         return error_mark_node;
6412       break;
6413
6414     case MODOP_EXPR:
6415     case CAST_EXPR:
6416     case REINTERPRET_CAST_EXPR:
6417     case CONST_CAST_EXPR:
6418     case STATIC_CAST_EXPR:
6419     case DYNAMIC_CAST_EXPR:
6420     case ARROW_EXPR:
6421     case DOTSTAR_EXPR:
6422     case TYPEID_EXPR:
6423     case PSEUDO_DTOR_EXPR:
6424       if (!fn)
6425         return error_mark_node;
6426       break;
6427
6428     default:
6429       break;
6430     }
6431
6432   /* We didn't find any template parameters we liked.  */
6433   return NULL_TREE;
6434 }
6435
6436 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6437    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6438    call FN with the parameter and the DATA.
6439    If FN returns nonzero, the iteration is terminated, and
6440    for_each_template_parm returns 1.  Otherwise, the iteration
6441    continues.  If FN never returns a nonzero value, the value
6442    returned by for_each_template_parm is 0.  If FN is NULL, it is
6443    considered to be the function which always returns 1.
6444
6445    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6446    parameters that occur in non-deduced contexts.  When false, only
6447    visits those template parameters that can be deduced.  */
6448
6449 static int
6450 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6451                         struct pointer_set_t *visited,
6452                         bool include_nondeduced_p)
6453 {
6454   struct pair_fn_data pfd;
6455   int result;
6456
6457   /* Set up.  */
6458   pfd.fn = fn;
6459   pfd.data = data;
6460   pfd.include_nondeduced_p = include_nondeduced_p;
6461
6462   /* Walk the tree.  (Conceptually, we would like to walk without
6463      duplicates, but for_each_template_parm_r recursively calls
6464      for_each_template_parm, so we would need to reorganize a fair
6465      bit to use walk_tree_without_duplicates, so we keep our own
6466      visited list.)  */
6467   if (visited)
6468     pfd.visited = visited;
6469   else
6470     pfd.visited = pointer_set_create ();
6471   result = cp_walk_tree (&t,
6472                          for_each_template_parm_r,
6473                          &pfd,
6474                          pfd.visited) != NULL_TREE;
6475
6476   /* Clean up.  */
6477   if (!visited)
6478     {
6479       pointer_set_destroy (pfd.visited);
6480       pfd.visited = 0;
6481     }
6482
6483   return result;
6484 }
6485
6486 /* Returns true if T depends on any template parameter.  */
6487
6488 int
6489 uses_template_parms (tree t)
6490 {
6491   bool dependent_p;
6492   int saved_processing_template_decl;
6493
6494   saved_processing_template_decl = processing_template_decl;
6495   if (!saved_processing_template_decl)
6496     processing_template_decl = 1;
6497   if (TYPE_P (t))
6498     dependent_p = dependent_type_p (t);
6499   else if (TREE_CODE (t) == TREE_VEC)
6500     dependent_p = any_dependent_template_arguments_p (t);
6501   else if (TREE_CODE (t) == TREE_LIST)
6502     dependent_p = (uses_template_parms (TREE_VALUE (t))
6503                    || uses_template_parms (TREE_CHAIN (t)));
6504   else if (TREE_CODE (t) == TYPE_DECL)
6505     dependent_p = dependent_type_p (TREE_TYPE (t));
6506   else if (DECL_P (t)
6507            || EXPR_P (t)
6508            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6509            || TREE_CODE (t) == OVERLOAD
6510            || TREE_CODE (t) == BASELINK
6511            || TREE_CODE (t) == IDENTIFIER_NODE
6512            || TREE_CODE (t) == TRAIT_EXPR
6513            || TREE_CODE (t) == CONSTRUCTOR
6514            || CONSTANT_CLASS_P (t))
6515     dependent_p = (type_dependent_expression_p (t)
6516                    || value_dependent_expression_p (t));
6517   else
6518     {
6519       gcc_assert (t == error_mark_node);
6520       dependent_p = false;
6521     }
6522
6523   processing_template_decl = saved_processing_template_decl;
6524
6525   return dependent_p;
6526 }
6527
6528 /* Returns true if T depends on any template parameter with level LEVEL.  */
6529
6530 int
6531 uses_template_parms_level (tree t, int level)
6532 {
6533   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6534                                  /*include_nondeduced_p=*/true);
6535 }
6536
6537 static int tinst_depth;
6538 extern int max_tinst_depth;
6539 #ifdef GATHER_STATISTICS
6540 int depth_reached;
6541 #endif
6542 static int tinst_level_tick;
6543 static int last_template_error_tick;
6544
6545 /* We're starting to instantiate D; record the template instantiation context
6546    for diagnostics and to restore it later.  */
6547
6548 static int
6549 push_tinst_level (tree d)
6550 {
6551   struct tinst_level *new_level;
6552
6553   if (tinst_depth >= max_tinst_depth)
6554     {
6555       /* If the instantiation in question still has unbound template parms,
6556          we don't really care if we can't instantiate it, so just return.
6557          This happens with base instantiation for implicit `typename'.  */
6558       if (uses_template_parms (d))
6559         return 0;
6560
6561       last_template_error_tick = tinst_level_tick;
6562       error ("template instantiation depth exceeds maximum of %d (use "
6563              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6564              max_tinst_depth, d);
6565
6566       print_instantiation_context ();
6567
6568       return 0;
6569     }
6570
6571   new_level = GGC_NEW (struct tinst_level);
6572   new_level->decl = d;
6573   new_level->locus = input_location;
6574   new_level->in_system_header_p = in_system_header;
6575   new_level->next = current_tinst_level;
6576   current_tinst_level = new_level;
6577
6578   ++tinst_depth;
6579 #ifdef GATHER_STATISTICS
6580   if (tinst_depth > depth_reached)
6581     depth_reached = tinst_depth;
6582 #endif
6583
6584   ++tinst_level_tick;
6585   return 1;
6586 }
6587
6588 /* We're done instantiating this template; return to the instantiation
6589    context.  */
6590
6591 static void
6592 pop_tinst_level (void)
6593 {
6594   /* Restore the filename and line number stashed away when we started
6595      this instantiation.  */
6596   input_location = current_tinst_level->locus;
6597   current_tinst_level = current_tinst_level->next;
6598   --tinst_depth;
6599   ++tinst_level_tick;
6600 }
6601
6602 /* We're instantiating a deferred template; restore the template
6603    instantiation context in which the instantiation was requested, which
6604    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6605
6606 static tree
6607 reopen_tinst_level (struct tinst_level *level)
6608 {
6609   struct tinst_level *t;
6610
6611   tinst_depth = 0;
6612   for (t = level; t; t = t->next)
6613     ++tinst_depth;
6614
6615   current_tinst_level = level;
6616   pop_tinst_level ();
6617   return level->decl;
6618 }
6619
6620 /* Returns the TINST_LEVEL which gives the original instantiation
6621    context.  */
6622
6623 struct tinst_level *
6624 outermost_tinst_level (void)
6625 {
6626   struct tinst_level *level = current_tinst_level;
6627   if (level)
6628     while (level->next)
6629       level = level->next;
6630   return level;
6631 }
6632
6633 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6634
6635 bool
6636 parameter_of_template_p (tree parm, tree templ)
6637 {
6638   tree parms;
6639   int i;
6640
6641   if (!parm || !templ)
6642     return false;
6643
6644   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6645   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6646
6647   parms = DECL_TEMPLATE_PARMS (templ);
6648   parms = INNERMOST_TEMPLATE_PARMS (parms);
6649
6650   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6651     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6652       return true;
6653
6654   return false;
6655 }
6656
6657 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6658    vector of template arguments, as for tsubst.
6659
6660    Returns an appropriate tsubst'd friend declaration.  */
6661
6662 static tree
6663 tsubst_friend_function (tree decl, tree args)
6664 {
6665   tree new_friend;
6666
6667   if (TREE_CODE (decl) == FUNCTION_DECL
6668       && DECL_TEMPLATE_INSTANTIATION (decl)
6669       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6670     /* This was a friend declared with an explicit template
6671        argument list, e.g.:
6672
6673        friend void f<>(T);
6674
6675        to indicate that f was a template instantiation, not a new
6676        function declaration.  Now, we have to figure out what
6677        instantiation of what template.  */
6678     {
6679       tree template_id, arglist, fns;
6680       tree new_args;
6681       tree tmpl;
6682       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6683
6684       /* Friend functions are looked up in the containing namespace scope.
6685          We must enter that scope, to avoid finding member functions of the
6686          current class with same name.  */
6687       push_nested_namespace (ns);
6688       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6689                          tf_warning_or_error, NULL_TREE,
6690                          /*integral_constant_expression_p=*/false);
6691       pop_nested_namespace (ns);
6692       arglist = tsubst (DECL_TI_ARGS (decl), args,
6693                         tf_warning_or_error, NULL_TREE);
6694       template_id = lookup_template_function (fns, arglist);
6695
6696       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6697       tmpl = determine_specialization (template_id, new_friend,
6698                                        &new_args,
6699                                        /*need_member_template=*/0,
6700                                        TREE_VEC_LENGTH (args),
6701                                        tsk_none);
6702       return instantiate_template (tmpl, new_args, tf_error);
6703     }
6704
6705   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6706
6707   /* The NEW_FRIEND will look like an instantiation, to the
6708      compiler, but is not an instantiation from the point of view of
6709      the language.  For example, we might have had:
6710
6711      template <class T> struct S {
6712        template <class U> friend void f(T, U);
6713      };
6714
6715      Then, in S<int>, template <class U> void f(int, U) is not an
6716      instantiation of anything.  */
6717   if (new_friend == error_mark_node)
6718     return error_mark_node;
6719
6720   DECL_USE_TEMPLATE (new_friend) = 0;
6721   if (TREE_CODE (decl) == TEMPLATE_DECL)
6722     {
6723       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6724       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6725         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6726     }
6727
6728   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6729      is not a template instantiation and should not be mangled like
6730      one.  Therefore, we forget the mangling here; we'll recompute it
6731      later if we need it.  */
6732   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6733     {
6734       SET_DECL_RTL (new_friend, NULL_RTX);
6735       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6736     }
6737
6738   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6739     {
6740       tree old_decl;
6741       tree new_friend_template_info;
6742       tree new_friend_result_template_info;
6743       tree ns;
6744       int  new_friend_is_defn;
6745
6746       /* We must save some information from NEW_FRIEND before calling
6747          duplicate decls since that function will free NEW_FRIEND if
6748          possible.  */
6749       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6750       new_friend_is_defn =
6751             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6752                            (template_for_substitution (new_friend)))
6753              != NULL_TREE);
6754       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6755         {
6756           /* This declaration is a `primary' template.  */
6757           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6758
6759           new_friend_result_template_info
6760             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6761         }
6762       else
6763         new_friend_result_template_info = NULL_TREE;
6764
6765       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6766       if (new_friend_is_defn)
6767         DECL_INITIAL (new_friend) = error_mark_node;
6768
6769       /* Inside pushdecl_namespace_level, we will push into the
6770          current namespace. However, the friend function should go
6771          into the namespace of the template.  */
6772       ns = decl_namespace_context (new_friend);
6773       push_nested_namespace (ns);
6774       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6775       pop_nested_namespace (ns);
6776
6777       if (old_decl == error_mark_node)
6778         return error_mark_node;
6779
6780       if (old_decl != new_friend)
6781         {
6782           /* This new friend declaration matched an existing
6783              declaration.  For example, given:
6784
6785                template <class T> void f(T);
6786                template <class U> class C {
6787                  template <class T> friend void f(T) {}
6788                };
6789
6790              the friend declaration actually provides the definition
6791              of `f', once C has been instantiated for some type.  So,
6792              old_decl will be the out-of-class template declaration,
6793              while new_friend is the in-class definition.
6794
6795              But, if `f' was called before this point, the
6796              instantiation of `f' will have DECL_TI_ARGS corresponding
6797              to `T' but not to `U', references to which might appear
6798              in the definition of `f'.  Previously, the most general
6799              template for an instantiation of `f' was the out-of-class
6800              version; now it is the in-class version.  Therefore, we
6801              run through all specialization of `f', adding to their
6802              DECL_TI_ARGS appropriately.  In particular, they need a
6803              new set of outer arguments, corresponding to the
6804              arguments for this class instantiation.
6805
6806              The same situation can arise with something like this:
6807
6808                friend void f(int);
6809                template <class T> class C {
6810                  friend void f(T) {}
6811                };
6812
6813              when `C<int>' is instantiated.  Now, `f(int)' is defined
6814              in the class.  */
6815
6816           if (!new_friend_is_defn)
6817             /* On the other hand, if the in-class declaration does
6818                *not* provide a definition, then we don't want to alter
6819                existing definitions.  We can just leave everything
6820                alone.  */
6821             ;
6822           else
6823             {
6824               tree new_template = TI_TEMPLATE (new_friend_template_info);
6825               tree new_args = TI_ARGS (new_friend_template_info);
6826
6827               /* Overwrite whatever template info was there before, if
6828                  any, with the new template information pertaining to
6829                  the declaration.  */
6830               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6831
6832               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6833                 /* We should have called reregister_specialization in
6834                    duplicate_decls.  */
6835                 gcc_assert (retrieve_specialization (new_template,
6836                                                      new_args, 0)
6837                             == old_decl);
6838               else
6839                 {
6840                   tree t;
6841
6842                   /* Indicate that the old function template is a partial
6843                      instantiation.  */
6844                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6845                     = new_friend_result_template_info;
6846
6847                   gcc_assert (new_template
6848                               == most_general_template (new_template));
6849                   gcc_assert (new_template != old_decl);
6850
6851                   /* Reassign any specializations already in the hash table
6852                      to the new more general template, and add the
6853                      additional template args.  */
6854                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
6855                        t != NULL_TREE;
6856                        t = TREE_CHAIN (t))
6857                     {
6858                       tree spec = TREE_VALUE (t);
6859                       spec_entry elt;
6860
6861                       elt.tmpl = old_decl;
6862                       elt.args = DECL_TI_ARGS (spec);
6863                       elt.spec = NULL_TREE;
6864
6865                       htab_remove_elt (decl_specializations, &elt);
6866
6867                       DECL_TI_ARGS (spec)
6868                         = add_outermost_template_args (new_args,
6869                                                        DECL_TI_ARGS (spec));
6870
6871                       register_specialization
6872                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
6873
6874                     }
6875                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
6876                 }
6877             }
6878
6879           /* The information from NEW_FRIEND has been merged into OLD_DECL
6880              by duplicate_decls.  */
6881           new_friend = old_decl;
6882         }
6883     }
6884   else
6885     {
6886       tree context = DECL_CONTEXT (new_friend);
6887       bool dependent_p;
6888
6889       /* In the code
6890            template <class T> class C {
6891              template <class U> friend void C1<U>::f (); // case 1
6892              friend void C2<T>::f ();                    // case 2
6893            };
6894          we only need to make sure CONTEXT is a complete type for
6895          case 2.  To distinguish between the two cases, we note that
6896          CONTEXT of case 1 remains dependent type after tsubst while
6897          this isn't true for case 2.  */
6898       ++processing_template_decl;
6899       dependent_p = dependent_type_p (context);
6900       --processing_template_decl;
6901
6902       if (!dependent_p
6903           && !complete_type_or_else (context, NULL_TREE))
6904         return error_mark_node;
6905
6906       if (COMPLETE_TYPE_P (context))
6907         {
6908           /* Check to see that the declaration is really present, and,
6909              possibly obtain an improved declaration.  */
6910           tree fn = check_classfn (context,
6911                                    new_friend, NULL_TREE);
6912
6913           if (fn)
6914             new_friend = fn;
6915         }
6916     }
6917
6918   return new_friend;
6919 }
6920
6921 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6922    template arguments, as for tsubst.
6923
6924    Returns an appropriate tsubst'd friend type or error_mark_node on
6925    failure.  */
6926
6927 static tree
6928 tsubst_friend_class (tree friend_tmpl, tree args)
6929 {
6930   tree friend_type;
6931   tree tmpl;
6932   tree context;
6933
6934   context = DECL_CONTEXT (friend_tmpl);
6935
6936   if (context)
6937     {
6938       if (TREE_CODE (context) == NAMESPACE_DECL)
6939         push_nested_namespace (context);
6940       else
6941         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6942     }
6943
6944   /* Look for a class template declaration.  We look for hidden names
6945      because two friend declarations of the same template are the
6946      same.  For example, in:
6947
6948        struct A { 
6949          template <typename> friend class F;
6950        };
6951        template <typename> struct B { 
6952          template <typename> friend class F;
6953        };
6954
6955      both F templates are the same.  */
6956   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6957                            /*block_p=*/true, 0, 
6958                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6959
6960   /* But, if we don't find one, it might be because we're in a
6961      situation like this:
6962
6963        template <class T>
6964        struct S {
6965          template <class U>
6966          friend struct S;
6967        };
6968
6969      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6970      for `S<int>', not the TEMPLATE_DECL.  */
6971   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6972     {
6973       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6974       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6975     }
6976
6977   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6978     {
6979       /* The friend template has already been declared.  Just
6980          check to see that the declarations match, and install any new
6981          default parameters.  We must tsubst the default parameters,
6982          of course.  We only need the innermost template parameters
6983          because that is all that redeclare_class_template will look
6984          at.  */
6985       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6986           > TMPL_ARGS_DEPTH (args))
6987         {
6988           tree parms;
6989           location_t saved_input_location;
6990           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6991                                          args, tf_warning_or_error);
6992
6993           saved_input_location = input_location;
6994           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6995           redeclare_class_template (TREE_TYPE (tmpl), parms);
6996           input_location = saved_input_location;
6997           
6998         }
6999
7000       friend_type = TREE_TYPE (tmpl);
7001     }
7002   else
7003     {
7004       /* The friend template has not already been declared.  In this
7005          case, the instantiation of the template class will cause the
7006          injection of this template into the global scope.  */
7007       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7008       if (tmpl == error_mark_node)
7009         return error_mark_node;
7010
7011       /* The new TMPL is not an instantiation of anything, so we
7012          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7013          the new type because that is supposed to be the corresponding
7014          template decl, i.e., TMPL.  */
7015       DECL_USE_TEMPLATE (tmpl) = 0;
7016       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7017       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7018       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7019         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7020
7021       /* Inject this template into the global scope.  */
7022       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7023     }
7024
7025   if (context)
7026     {
7027       if (TREE_CODE (context) == NAMESPACE_DECL)
7028         pop_nested_namespace (context);
7029       else
7030         pop_nested_class ();
7031     }
7032
7033   return friend_type;
7034 }
7035
7036 /* Returns zero if TYPE cannot be completed later due to circularity.
7037    Otherwise returns one.  */
7038
7039 static int
7040 can_complete_type_without_circularity (tree type)
7041 {
7042   if (type == NULL_TREE || type == error_mark_node)
7043     return 0;
7044   else if (COMPLETE_TYPE_P (type))
7045     return 1;
7046   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7047     return can_complete_type_without_circularity (TREE_TYPE (type));
7048   else if (CLASS_TYPE_P (type)
7049            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7050     return 0;
7051   else
7052     return 1;
7053 }
7054
7055 /* Apply any attributes which had to be deferred until instantiation
7056    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7057    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7058
7059 static void
7060 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7061                                 tree args, tsubst_flags_t complain, tree in_decl)
7062 {
7063   tree last_dep = NULL_TREE;
7064   tree t;
7065   tree *p;
7066
7067   for (t = attributes; t; t = TREE_CHAIN (t))
7068     if (ATTR_IS_DEPENDENT (t))
7069       {
7070         last_dep = t;
7071         attributes = copy_list (attributes);
7072         break;
7073       }
7074
7075   if (DECL_P (*decl_p))
7076     {
7077       if (TREE_TYPE (*decl_p) == error_mark_node)
7078         return;
7079       p = &DECL_ATTRIBUTES (*decl_p);
7080     }
7081   else
7082     p = &TYPE_ATTRIBUTES (*decl_p);
7083
7084   if (last_dep)
7085     {
7086       tree late_attrs = NULL_TREE;
7087       tree *q = &late_attrs;
7088
7089       for (*p = attributes; *p; )
7090         {
7091           t = *p;
7092           if (ATTR_IS_DEPENDENT (t))
7093             {
7094               *p = TREE_CHAIN (t);
7095               TREE_CHAIN (t) = NULL_TREE;
7096               /* If the first attribute argument is an identifier, don't
7097                  pass it through tsubst.  Attributes like mode, format,
7098                  cleanup and several target specific attributes expect it
7099                  unmodified.  */
7100               if (TREE_VALUE (t)
7101                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7102                   && TREE_VALUE (TREE_VALUE (t))
7103                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7104                       == IDENTIFIER_NODE))
7105                 {
7106                   tree chain
7107                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7108                                    in_decl,
7109                                    /*integral_constant_expression_p=*/false);
7110                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7111                     TREE_VALUE (t)
7112                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7113                                    chain);
7114                 }
7115               else
7116                 TREE_VALUE (t)
7117                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7118                                  /*integral_constant_expression_p=*/false);
7119               *q = t;
7120               q = &TREE_CHAIN (t);
7121             }
7122           else
7123             p = &TREE_CHAIN (t);
7124         }
7125
7126       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7127     }
7128 }
7129
7130 /* Perform (or defer) access check for typedefs that were referenced
7131    from within the template TMPL code.
7132    This is a subroutine of instantiate_template and instantiate_class_template.
7133    TMPL is the template to consider and TARGS is the list of arguments of
7134    that template.  */
7135
7136 static void
7137 perform_typedefs_access_check (tree tmpl, tree targs)
7138 {
7139   tree t;
7140
7141   if (!tmpl
7142       || (TREE_CODE (tmpl) != RECORD_TYPE
7143           && TREE_CODE (tmpl) != FUNCTION_DECL))
7144     return;
7145
7146   for (t = get_types_needing_access_check (tmpl); t; t = TREE_CHAIN (t))
7147     {
7148       tree type_decl = TREE_PURPOSE (t);
7149       tree type_scope = TREE_VALUE (t);
7150
7151       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7152         continue;
7153
7154       if (uses_template_parms (type_decl))
7155         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7156       if (uses_template_parms (type_scope))
7157         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7158
7159       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7160                                      type_decl, type_decl);
7161     }
7162 }
7163
7164 tree
7165 instantiate_class_template (tree type)
7166 {
7167   tree templ, args, pattern, t, member;
7168   tree typedecl;
7169   tree pbinfo;
7170   tree base_list;
7171
7172   if (type == error_mark_node)
7173     return error_mark_node;
7174
7175   if (TYPE_BEING_DEFINED (type)
7176       || COMPLETE_TYPE_P (type)
7177       || dependent_type_p (type))
7178     return type;
7179
7180   /* Figure out which template is being instantiated.  */
7181   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7182   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7183
7184   /* Determine what specialization of the original template to
7185      instantiate.  */
7186   t = most_specialized_class (type, templ);
7187   if (t == error_mark_node)
7188     {
7189       TYPE_BEING_DEFINED (type) = 1;
7190       return error_mark_node;
7191     }
7192   else if (t)
7193     {
7194       /* This TYPE is actually an instantiation of a partial
7195          specialization.  We replace the innermost set of ARGS with
7196          the arguments appropriate for substitution.  For example,
7197          given:
7198
7199            template <class T> struct S {};
7200            template <class T> struct S<T*> {};
7201
7202          and supposing that we are instantiating S<int*>, ARGS will
7203          presently be {int*} -- but we need {int}.  */
7204       pattern = TREE_TYPE (t);
7205       args = TREE_PURPOSE (t);
7206     }
7207   else
7208     {
7209       pattern = TREE_TYPE (templ);
7210       args = CLASSTYPE_TI_ARGS (type);
7211     }
7212
7213   /* If the template we're instantiating is incomplete, then clearly
7214      there's nothing we can do.  */
7215   if (!COMPLETE_TYPE_P (pattern))
7216     return type;
7217
7218   /* If we've recursively instantiated too many templates, stop.  */
7219   if (! push_tinst_level (type))
7220     return type;
7221
7222   /* Now we're really doing the instantiation.  Mark the type as in
7223      the process of being defined.  */
7224   TYPE_BEING_DEFINED (type) = 1;
7225
7226   /* We may be in the middle of deferred access check.  Disable
7227      it now.  */
7228   push_deferring_access_checks (dk_no_deferred);
7229
7230   push_to_top_level ();
7231
7232   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7233
7234   /* Set the input location to the most specialized template definition.
7235      This is needed if tsubsting causes an error.  */
7236   typedecl = TYPE_MAIN_DECL (pattern);
7237   input_location = DECL_SOURCE_LOCATION (typedecl);
7238
7239   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7240   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7241   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7242   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7243   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7244   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7245   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7246   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7247   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7248   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7249   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7250   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7251   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7252   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7253   if (ANON_AGGR_TYPE_P (pattern))
7254     SET_ANON_AGGR_TYPE_P (type);
7255   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7256     {
7257       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7258       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7259     }
7260
7261   pbinfo = TYPE_BINFO (pattern);
7262
7263   /* We should never instantiate a nested class before its enclosing
7264      class; we need to look up the nested class by name before we can
7265      instantiate it, and that lookup should instantiate the enclosing
7266      class.  */
7267   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7268               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7269               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7270
7271   base_list = NULL_TREE;
7272   if (BINFO_N_BASE_BINFOS (pbinfo))
7273     {
7274       tree pbase_binfo;
7275       tree context = TYPE_CONTEXT (type);
7276       tree pushed_scope;
7277       int i;
7278
7279       /* We must enter the scope containing the type, as that is where
7280          the accessibility of types named in dependent bases are
7281          looked up from.  */
7282       pushed_scope = push_scope (context ? context : global_namespace);
7283
7284       /* Substitute into each of the bases to determine the actual
7285          basetypes.  */
7286       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7287         {
7288           tree base;
7289           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7290           tree expanded_bases = NULL_TREE;
7291           int idx, len = 1;
7292
7293           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7294             {
7295               expanded_bases = 
7296                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7297                                        args, tf_error, NULL_TREE);
7298               if (expanded_bases == error_mark_node)
7299                 continue;
7300
7301               len = TREE_VEC_LENGTH (expanded_bases);
7302             }
7303
7304           for (idx = 0; idx < len; idx++)
7305             {
7306               if (expanded_bases)
7307                 /* Extract the already-expanded base class.  */
7308                 base = TREE_VEC_ELT (expanded_bases, idx);
7309               else
7310                 /* Substitute to figure out the base class.  */
7311                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7312                                NULL_TREE);
7313
7314               if (base == error_mark_node)
7315                 continue;
7316
7317               base_list = tree_cons (access, base, base_list);
7318               if (BINFO_VIRTUAL_P (pbase_binfo))
7319                 TREE_TYPE (base_list) = integer_type_node;
7320             }
7321         }
7322
7323       /* The list is now in reverse order; correct that.  */
7324       base_list = nreverse (base_list);
7325
7326       if (pushed_scope)
7327         pop_scope (pushed_scope);
7328     }
7329   /* Now call xref_basetypes to set up all the base-class
7330      information.  */
7331   xref_basetypes (type, base_list);
7332
7333   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7334                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7335                                   args, tf_error, NULL_TREE);
7336
7337   /* Now that our base classes are set up, enter the scope of the
7338      class, so that name lookups into base classes, etc. will work
7339      correctly.  This is precisely analogous to what we do in
7340      begin_class_definition when defining an ordinary non-template
7341      class, except we also need to push the enclosing classes.  */
7342   push_nested_class (type);
7343
7344   /* Now members are processed in the order of declaration.  */
7345   for (member = CLASSTYPE_DECL_LIST (pattern);
7346        member; member = TREE_CHAIN (member))
7347     {
7348       tree t = TREE_VALUE (member);
7349
7350       if (TREE_PURPOSE (member))
7351         {
7352           if (TYPE_P (t))
7353             {
7354               /* Build new CLASSTYPE_NESTED_UTDS.  */
7355
7356               tree newtag;
7357               bool class_template_p;
7358
7359               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7360                                   && TYPE_LANG_SPECIFIC (t)
7361                                   && CLASSTYPE_IS_TEMPLATE (t));
7362               /* If the member is a class template, then -- even after
7363                  substitution -- there may be dependent types in the
7364                  template argument list for the class.  We increment
7365                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7366                  that function will assume that no types are dependent
7367                  when outside of a template.  */
7368               if (class_template_p)
7369                 ++processing_template_decl;
7370               newtag = tsubst (t, args, tf_error, NULL_TREE);
7371               if (class_template_p)
7372                 --processing_template_decl;
7373               if (newtag == error_mark_node)
7374                 continue;
7375
7376               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7377                 {
7378                   tree name = TYPE_IDENTIFIER (t);
7379
7380                   if (class_template_p)
7381                     /* Unfortunately, lookup_template_class sets
7382                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7383                        instantiation (i.e., for the type of a member
7384                        template class nested within a template class.)
7385                        This behavior is required for
7386                        maybe_process_partial_specialization to work
7387                        correctly, but is not accurate in this case;
7388                        the TAG is not an instantiation of anything.
7389                        (The corresponding TEMPLATE_DECL is an
7390                        instantiation, but the TYPE is not.) */
7391                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7392
7393                   /* Now, we call pushtag to put this NEWTAG into the scope of
7394                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7395                      pushtag calling push_template_decl.  We don't have to do
7396                      this for enums because it will already have been done in
7397                      tsubst_enum.  */
7398                   if (name)
7399                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7400                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7401                 }
7402             }
7403           else if (TREE_CODE (t) == FUNCTION_DECL
7404                    || DECL_FUNCTION_TEMPLATE_P (t))
7405             {
7406               /* Build new TYPE_METHODS.  */
7407               tree r;
7408
7409               if (TREE_CODE (t) == TEMPLATE_DECL)
7410                 ++processing_template_decl;
7411               r = tsubst (t, args, tf_error, NULL_TREE);
7412               if (TREE_CODE (t) == TEMPLATE_DECL)
7413                 --processing_template_decl;
7414               set_current_access_from_decl (r);
7415               finish_member_declaration (r);
7416             }
7417           else
7418             {
7419               /* Build new TYPE_FIELDS.  */
7420               if (TREE_CODE (t) == STATIC_ASSERT)
7421                 {
7422                   tree condition = 
7423                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7424                                  tf_warning_or_error, NULL_TREE,
7425                                  /*integral_constant_expression_p=*/true);
7426                   finish_static_assert (condition,
7427                                         STATIC_ASSERT_MESSAGE (t), 
7428                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7429                                         /*member_p=*/true);
7430                 }
7431               else if (TREE_CODE (t) != CONST_DECL)
7432                 {
7433                   tree r;
7434
7435                   /* The file and line for this declaration, to
7436                      assist in error message reporting.  Since we
7437                      called push_tinst_level above, we don't need to
7438                      restore these.  */
7439                   input_location = DECL_SOURCE_LOCATION (t);
7440
7441                   if (TREE_CODE (t) == TEMPLATE_DECL)
7442                     ++processing_template_decl;
7443                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7444                   if (TREE_CODE (t) == TEMPLATE_DECL)
7445                     --processing_template_decl;
7446                   if (TREE_CODE (r) == VAR_DECL)
7447                     {
7448                       /* In [temp.inst]:
7449
7450                            [t]he initialization (and any associated
7451                            side-effects) of a static data member does
7452                            not occur unless the static data member is
7453                            itself used in a way that requires the
7454                            definition of the static data member to
7455                            exist.
7456
7457                          Therefore, we do not substitute into the
7458                          initialized for the static data member here.  */
7459                       finish_static_data_member_decl
7460                         (r,
7461                          /*init=*/NULL_TREE,
7462                          /*init_const_expr_p=*/false,
7463                          /*asmspec_tree=*/NULL_TREE,
7464                          /*flags=*/0);
7465                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7466                         check_static_variable_definition (r, TREE_TYPE (r));
7467                     }
7468                   else if (TREE_CODE (r) == FIELD_DECL)
7469                     {
7470                       /* Determine whether R has a valid type and can be
7471                          completed later.  If R is invalid, then it is
7472                          replaced by error_mark_node so that it will not be
7473                          added to TYPE_FIELDS.  */
7474                       tree rtype = TREE_TYPE (r);
7475                       if (can_complete_type_without_circularity (rtype))
7476                         complete_type (rtype);
7477
7478                       if (!COMPLETE_TYPE_P (rtype))
7479                         {
7480                           cxx_incomplete_type_error (r, rtype);
7481                           r = error_mark_node;
7482                         }
7483                     }
7484
7485                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7486                      such a thing will already have been added to the field
7487                      list by tsubst_enum in finish_member_declaration in the
7488                      CLASSTYPE_NESTED_UTDS case above.  */
7489                   if (!(TREE_CODE (r) == TYPE_DECL
7490                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7491                         && DECL_ARTIFICIAL (r)))
7492                     {
7493                       set_current_access_from_decl (r);
7494                       finish_member_declaration (r);
7495                     }
7496                 }
7497             }
7498         }
7499       else
7500         {
7501           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7502             {
7503               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7504
7505               tree friend_type = t;
7506               bool adjust_processing_template_decl = false;
7507
7508               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7509                 {
7510                   /* template <class T> friend class C;  */
7511                   friend_type = tsubst_friend_class (friend_type, args);
7512                   adjust_processing_template_decl = true;
7513                 }
7514               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7515                 {
7516                   /* template <class T> friend class C::D;  */
7517                   friend_type = tsubst (friend_type, args,
7518                                         tf_warning_or_error, NULL_TREE);
7519                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7520                     friend_type = TREE_TYPE (friend_type);
7521                   adjust_processing_template_decl = true;
7522                 }
7523               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7524                 {
7525                   /* This could be either
7526
7527                        friend class T::C;
7528
7529                      when dependent_type_p is false or
7530
7531                        template <class U> friend class T::C;
7532
7533                      otherwise.  */
7534                   friend_type = tsubst (friend_type, args,
7535                                         tf_warning_or_error, NULL_TREE);
7536                   /* Bump processing_template_decl for correct
7537                      dependent_type_p calculation.  */
7538                   ++processing_template_decl;
7539                   if (dependent_type_p (friend_type))
7540                     adjust_processing_template_decl = true;
7541                   --processing_template_decl;
7542                 }
7543               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7544                        && hidden_name_p (TYPE_NAME (friend_type)))
7545                 {
7546                   /* friend class C;
7547
7548                      where C hasn't been declared yet.  Let's lookup name
7549                      from namespace scope directly, bypassing any name that
7550                      come from dependent base class.  */
7551                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7552
7553                   /* The call to xref_tag_from_type does injection for friend
7554                      classes.  */
7555                   push_nested_namespace (ns);
7556                   friend_type =
7557                     xref_tag_from_type (friend_type, NULL_TREE,
7558                                         /*tag_scope=*/ts_current);
7559                   pop_nested_namespace (ns);
7560                 }
7561               else if (uses_template_parms (friend_type))
7562                 /* friend class C<T>;  */
7563                 friend_type = tsubst (friend_type, args,
7564                                       tf_warning_or_error, NULL_TREE);
7565               /* Otherwise it's
7566
7567                    friend class C;
7568
7569                  where C is already declared or
7570
7571                    friend class C<int>;
7572
7573                  We don't have to do anything in these cases.  */
7574
7575               if (adjust_processing_template_decl)
7576                 /* Trick make_friend_class into realizing that the friend
7577                    we're adding is a template, not an ordinary class.  It's
7578                    important that we use make_friend_class since it will
7579                    perform some error-checking and output cross-reference
7580                    information.  */
7581                 ++processing_template_decl;
7582
7583               if (friend_type != error_mark_node)
7584                 make_friend_class (type, friend_type, /*complain=*/false);
7585
7586               if (adjust_processing_template_decl)
7587                 --processing_template_decl;
7588             }
7589           else
7590             {
7591               /* Build new DECL_FRIENDLIST.  */
7592               tree r;
7593
7594               /* The file and line for this declaration, to
7595                  assist in error message reporting.  Since we
7596                  called push_tinst_level above, we don't need to
7597                  restore these.  */
7598               input_location = DECL_SOURCE_LOCATION (t);
7599
7600               if (TREE_CODE (t) == TEMPLATE_DECL)
7601                 {
7602                   ++processing_template_decl;
7603                   push_deferring_access_checks (dk_no_check);
7604                 }
7605
7606               r = tsubst_friend_function (t, args);
7607               add_friend (type, r, /*complain=*/false);
7608               if (TREE_CODE (t) == TEMPLATE_DECL)
7609                 {
7610                   pop_deferring_access_checks ();
7611                   --processing_template_decl;
7612                 }
7613             }
7614         }
7615     }
7616
7617   /* Set the file and line number information to whatever is given for
7618      the class itself.  This puts error messages involving generated
7619      implicit functions at a predictable point, and the same point
7620      that would be used for non-template classes.  */
7621   input_location = DECL_SOURCE_LOCATION (typedecl);
7622
7623   unreverse_member_declarations (type);
7624   finish_struct_1 (type);
7625   TYPE_BEING_DEFINED (type) = 0;
7626
7627   /* Now that the class is complete, instantiate default arguments for
7628      any member functions.  We don't do this earlier because the
7629      default arguments may reference members of the class.  */
7630   if (!PRIMARY_TEMPLATE_P (templ))
7631     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7632       if (TREE_CODE (t) == FUNCTION_DECL
7633           /* Implicitly generated member functions will not have template
7634              information; they are not instantiations, but instead are
7635              created "fresh" for each instantiation.  */
7636           && DECL_TEMPLATE_INFO (t))
7637         tsubst_default_arguments (t);
7638
7639   /* Some typedefs referenced from within the template code need to be access
7640      checked at template instantiation time, i.e now. These types were
7641      added to the template at parsing time. Let's get those and perform
7642      the access checks then.  */
7643   perform_typedefs_access_check (pattern, args);
7644   perform_deferred_access_checks ();
7645   pop_nested_class ();
7646   pop_from_top_level ();
7647   pop_deferring_access_checks ();
7648   pop_tinst_level ();
7649
7650   /* The vtable for a template class can be emitted in any translation
7651      unit in which the class is instantiated.  When there is no key
7652      method, however, finish_struct_1 will already have added TYPE to
7653      the keyed_classes list.  */
7654   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7655     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7656
7657   return type;
7658 }
7659
7660 static tree
7661 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7662 {
7663   tree r;
7664
7665   if (!t)
7666     r = t;
7667   else if (TYPE_P (t))
7668     r = tsubst (t, args, complain, in_decl);
7669   else
7670     {
7671       r = tsubst_expr (t, args, complain, in_decl,
7672                        /*integral_constant_expression_p=*/true);
7673       r = fold_non_dependent_expr (r);
7674     }
7675   return r;
7676 }
7677
7678 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7679    NONTYPE_ARGUMENT_PACK.  */
7680
7681 static tree
7682 make_fnparm_pack (tree spec_parm)
7683 {
7684   /* Collect all of the extra "packed" parameters into an
7685      argument pack.  */
7686   tree parmvec;
7687   tree parmtypevec;
7688   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7689   tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
7690   int i, len = list_length (spec_parm);
7691
7692   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7693   parmvec = make_tree_vec (len);
7694   parmtypevec = make_tree_vec (len);
7695   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7696     {
7697       TREE_VEC_ELT (parmvec, i) = spec_parm;
7698       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7699     }
7700
7701   /* Build the argument packs.  */
7702   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7703   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7704   TREE_TYPE (argpack) = argtypepack;
7705
7706   return argpack;
7707 }        
7708
7709 /* Substitute ARGS into T, which is an pack expansion
7710    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7711    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7712    (if only a partial substitution could be performed) or
7713    ERROR_MARK_NODE if there was an error.  */
7714 tree
7715 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7716                        tree in_decl)
7717 {
7718   tree pattern;
7719   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7720   tree first_arg_pack; int i, len = -1;
7721   tree result;
7722   int incomplete = 0;
7723   bool very_local_specializations = false;
7724
7725   gcc_assert (PACK_EXPANSION_P (t));
7726   pattern = PACK_EXPANSION_PATTERN (t);
7727
7728   /* Determine the argument packs that will instantiate the parameter
7729      packs used in the expansion expression. While we're at it,
7730      compute the number of arguments to be expanded and make sure it
7731      is consistent.  */
7732   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7733        pack = TREE_CHAIN (pack))
7734     {
7735       tree parm_pack = TREE_VALUE (pack);
7736       tree arg_pack = NULL_TREE;
7737       tree orig_arg = NULL_TREE;
7738
7739       if (TREE_CODE (parm_pack) == PARM_DECL)
7740         {
7741           arg_pack = retrieve_local_specialization (parm_pack);
7742           if (arg_pack == NULL_TREE)
7743             {
7744               /* This can happen for a parameter name used later in a function
7745                  declaration (such as in a late-specified return type).  Just
7746                  make a dummy decl, since it's only used for its type.  */
7747               gcc_assert (cp_unevaluated_operand != 0);
7748               arg_pack = tsubst_decl (parm_pack, args, complain);
7749               arg_pack = make_fnparm_pack (arg_pack);
7750             }
7751         }
7752       else
7753         {
7754           int level, idx, levels;
7755           template_parm_level_and_index (parm_pack, &level, &idx);
7756
7757           levels = TMPL_ARGS_DEPTH (args);
7758           if (level <= levels)
7759             arg_pack = TMPL_ARG (args, level, idx);
7760         }
7761
7762       orig_arg = arg_pack;
7763       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7764         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7765       
7766       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7767         /* This can only happen if we forget to expand an argument
7768            pack somewhere else. Just return an error, silently.  */
7769         {
7770           result = make_tree_vec (1);
7771           TREE_VEC_ELT (result, 0) = error_mark_node;
7772           return result;
7773         }
7774
7775       if (arg_pack
7776           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7777           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7778         {
7779           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7780           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7781           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7782               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7783             /* The argument pack that the parameter maps to is just an
7784                expansion of the parameter itself, such as one would
7785                find in the implicit typedef of a class inside the
7786                class itself.  Consider this parameter "unsubstituted",
7787                so that we will maintain the outer pack expansion.  */
7788             arg_pack = NULL_TREE;
7789         }
7790           
7791       if (arg_pack)
7792         {
7793           int my_len = 
7794             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7795
7796           /* It's all-or-nothing with incomplete argument packs.  */
7797           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7798             return error_mark_node;
7799           
7800           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7801             incomplete = 1;
7802
7803           if (len < 0)
7804             {
7805               len = my_len;
7806               first_arg_pack = arg_pack;
7807             }
7808           else if (len != my_len)
7809             {
7810               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7811                 error ("mismatched argument pack lengths while expanding "
7812                        "%<%T%>",
7813                        pattern);
7814               else
7815                 error ("mismatched argument pack lengths while expanding "
7816                        "%<%E%>",
7817                        pattern);
7818               return error_mark_node;
7819             }
7820
7821           /* Keep track of the parameter packs and their corresponding
7822              argument packs.  */
7823           packs = tree_cons (parm_pack, arg_pack, packs);
7824           TREE_TYPE (packs) = orig_arg;
7825         }
7826       else
7827         /* We can't substitute for this parameter pack.  */
7828         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7829                                          TREE_VALUE (pack),
7830                                          unsubstituted_packs);
7831     }
7832
7833   /* We cannot expand this expansion expression, because we don't have
7834      all of the argument packs we need. Substitute into the pattern
7835      and return a PACK_EXPANSION_*. The caller will need to deal with
7836      that.  */
7837   if (unsubstituted_packs)
7838     {
7839       tree new_pat;
7840       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7841         new_pat = tsubst_expr (pattern, args, complain, in_decl,
7842                                /*integral_constant_expression_p=*/false);
7843       else
7844         new_pat = tsubst (pattern, args, complain, in_decl);
7845       return make_pack_expansion (new_pat);
7846     }
7847
7848   /* We could not find any argument packs that work.  */
7849   if (len < 0)
7850     return error_mark_node;
7851
7852   if (!local_specializations)
7853     {
7854       /* We're in a late-specified return type, so we don't have a local
7855          specializations table.  Create one for doing this expansion.  */
7856       very_local_specializations = true;
7857       local_specializations = htab_create (37,
7858                                            hash_local_specialization,
7859                                            eq_local_specializations,
7860                                            NULL);
7861     }
7862
7863   /* For each argument in each argument pack, substitute into the
7864      pattern.  */
7865   result = make_tree_vec (len + incomplete);
7866   for (i = 0; i < len + incomplete; ++i)
7867     {
7868       /* For parameter pack, change the substitution of the parameter
7869          pack to the ith argument in its argument pack, then expand
7870          the pattern.  */
7871       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7872         {
7873           tree parm = TREE_PURPOSE (pack);
7874
7875           if (TREE_CODE (parm) == PARM_DECL)
7876             {
7877               /* Select the Ith argument from the pack.  */
7878               tree arg = make_node (ARGUMENT_PACK_SELECT);
7879               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7880               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7881               mark_used (parm);
7882               register_local_specialization (arg, parm);
7883             }
7884           else
7885             {
7886               tree value = parm;
7887               int idx, level;
7888               template_parm_level_and_index (parm, &level, &idx);
7889               
7890               if (i < len) 
7891                 {
7892                   /* Select the Ith argument from the pack. */
7893                   value = make_node (ARGUMENT_PACK_SELECT);
7894                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7895                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7896                 }
7897
7898               /* Update the corresponding argument.  */
7899               TMPL_ARG (args, level, idx) = value;
7900             }
7901         }
7902
7903       /* Substitute into the PATTERN with the altered arguments.  */
7904       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7905         TREE_VEC_ELT (result, i) = 
7906           tsubst_expr (pattern, args, complain, in_decl,
7907                        /*integral_constant_expression_p=*/false);
7908       else
7909         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7910
7911       if (i == len)
7912         /* When we have incomplete argument packs, the last "expanded"
7913            result is itself a pack expansion, which allows us
7914            to deduce more arguments.  */
7915         TREE_VEC_ELT (result, i) = 
7916           make_pack_expansion (TREE_VEC_ELT (result, i));
7917
7918       if (TREE_VEC_ELT (result, i) == error_mark_node)
7919         {
7920           result = error_mark_node;
7921           break;
7922         }
7923     }
7924
7925   /* Update ARGS to restore the substitution from parameter packs to
7926      their argument packs.  */
7927   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7928     {
7929       tree parm = TREE_PURPOSE (pack);
7930
7931       if (TREE_CODE (parm) == PARM_DECL)
7932         register_local_specialization (TREE_TYPE (pack), parm);
7933       else
7934         {
7935           int idx, level;
7936           template_parm_level_and_index (parm, &level, &idx);
7937           
7938           /* Update the corresponding argument.  */
7939           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7940             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7941               TREE_TYPE (pack);
7942           else
7943             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7944         }
7945     }
7946
7947   if (very_local_specializations)
7948     {
7949       htab_delete (local_specializations);
7950       local_specializations = NULL;
7951     }
7952   
7953   return result;
7954 }
7955
7956 /* Substitute ARGS into the vector or list of template arguments T.  */
7957
7958 static tree
7959 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7960 {
7961   tree orig_t = t;
7962   int len = TREE_VEC_LENGTH (t);
7963   int need_new = 0, i, expanded_len_adjust = 0, out;
7964   tree *elts = (tree *) alloca (len * sizeof (tree));
7965
7966   for (i = 0; i < len; i++)
7967     {
7968       tree orig_arg = TREE_VEC_ELT (t, i);
7969       tree new_arg;
7970
7971       if (TREE_CODE (orig_arg) == TREE_VEC)
7972         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7973       else if (PACK_EXPANSION_P (orig_arg))
7974         {
7975           /* Substitute into an expansion expression.  */
7976           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7977
7978           if (TREE_CODE (new_arg) == TREE_VEC)
7979             /* Add to the expanded length adjustment the number of
7980                expanded arguments. We subtract one from this
7981                measurement, because the argument pack expression
7982                itself is already counted as 1 in
7983                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7984                the argument pack is empty.  */
7985             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7986         }
7987       else if (ARGUMENT_PACK_P (orig_arg))
7988         {
7989           /* Substitute into each of the arguments.  */
7990           new_arg = make_node (TREE_CODE (orig_arg));
7991           
7992           SET_ARGUMENT_PACK_ARGS (
7993             new_arg,
7994             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7995                                   args, complain, in_decl));
7996
7997           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7998             new_arg = error_mark_node;
7999
8000           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8001             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8002                                           complain, in_decl);
8003             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8004
8005             if (TREE_TYPE (new_arg) == error_mark_node)
8006               new_arg = error_mark_node;
8007           }
8008         }
8009       else
8010         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8011
8012       if (new_arg == error_mark_node)
8013         return error_mark_node;
8014
8015       elts[i] = new_arg;
8016       if (new_arg != orig_arg)
8017         need_new = 1;
8018     }
8019
8020   if (!need_new)
8021     return t;
8022
8023   /* Make space for the expanded arguments coming from template
8024      argument packs.  */
8025   t = make_tree_vec (len + expanded_len_adjust);
8026   for (i = 0, out = 0; i < len; i++)
8027     {
8028       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8029            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8030           && TREE_CODE (elts[i]) == TREE_VEC)
8031         {
8032           int idx;
8033
8034           /* Now expand the template argument pack "in place".  */
8035           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8036             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8037         }
8038       else
8039         {
8040           TREE_VEC_ELT (t, out) = elts[i];
8041           out++;
8042         }
8043     }
8044
8045   return t;
8046 }
8047
8048 /* Return the result of substituting ARGS into the template parameters
8049    given by PARMS.  If there are m levels of ARGS and m + n levels of
8050    PARMS, then the result will contain n levels of PARMS.  For
8051    example, if PARMS is `template <class T> template <class U>
8052    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8053    result will be `template <int*, double, class V>'.  */
8054
8055 static tree
8056 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8057 {
8058   tree r = NULL_TREE;
8059   tree* new_parms;
8060
8061   /* When substituting into a template, we must set
8062      PROCESSING_TEMPLATE_DECL as the template parameters may be
8063      dependent if they are based on one-another, and the dependency
8064      predicates are short-circuit outside of templates.  */
8065   ++processing_template_decl;
8066
8067   for (new_parms = &r;
8068        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8069        new_parms = &(TREE_CHAIN (*new_parms)),
8070          parms = TREE_CHAIN (parms))
8071     {
8072       tree new_vec =
8073         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8074       int i;
8075
8076       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8077         {
8078           tree tuple;
8079           tree default_value;
8080           tree parm_decl;
8081
8082           if (parms == error_mark_node)
8083             continue;
8084
8085           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8086
8087           if (tuple == error_mark_node)
8088             continue;
8089
8090           default_value = TREE_PURPOSE (tuple);
8091           parm_decl = TREE_VALUE (tuple);
8092
8093           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8094           if (TREE_CODE (parm_decl) == PARM_DECL
8095               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8096             parm_decl = error_mark_node;
8097           default_value = tsubst_template_arg (default_value, args,
8098                                                complain, NULL_TREE);
8099
8100           tuple = build_tree_list (default_value, parm_decl);
8101           TREE_VEC_ELT (new_vec, i) = tuple;
8102         }
8103
8104       *new_parms =
8105         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8106                              - TMPL_ARGS_DEPTH (args)),
8107                    new_vec, NULL_TREE);
8108     }
8109
8110   --processing_template_decl;
8111
8112   return r;
8113 }
8114
8115 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8116    type T.  If T is not an aggregate or enumeration type, it is
8117    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8118    ENTERING_SCOPE is nonzero, T is the context for a template which
8119    we are presently tsubst'ing.  Return the substituted value.  */
8120
8121 static tree
8122 tsubst_aggr_type (tree t,
8123                   tree args,
8124                   tsubst_flags_t complain,
8125                   tree in_decl,
8126                   int entering_scope)
8127 {
8128   if (t == NULL_TREE)
8129     return NULL_TREE;
8130
8131   switch (TREE_CODE (t))
8132     {
8133     case RECORD_TYPE:
8134       if (TYPE_PTRMEMFUNC_P (t))
8135         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8136
8137       /* Else fall through.  */
8138     case ENUMERAL_TYPE:
8139     case UNION_TYPE:
8140       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8141         {
8142           tree argvec;
8143           tree context;
8144           tree r;
8145           int saved_unevaluated_operand;
8146           int saved_inhibit_evaluation_warnings;
8147
8148           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8149           saved_unevaluated_operand = cp_unevaluated_operand;
8150           cp_unevaluated_operand = 0;
8151           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8152           c_inhibit_evaluation_warnings = 0;
8153
8154           /* First, determine the context for the type we are looking
8155              up.  */
8156           context = TYPE_CONTEXT (t);
8157           if (context)
8158             {
8159               context = tsubst_aggr_type (context, args, complain,
8160                                           in_decl, /*entering_scope=*/1);
8161               /* If context is a nested class inside a class template,
8162                  it may still need to be instantiated (c++/33959).  */
8163               if (TYPE_P (context))
8164                 context = complete_type (context);
8165             }
8166
8167           /* Then, figure out what arguments are appropriate for the
8168              type we are trying to find.  For example, given:
8169
8170                template <class T> struct S;
8171                template <class T, class U> void f(T, U) { S<U> su; }
8172
8173              and supposing that we are instantiating f<int, double>,
8174              then our ARGS will be {int, double}, but, when looking up
8175              S we only want {double}.  */
8176           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8177                                          complain, in_decl);
8178           if (argvec == error_mark_node)
8179             r = error_mark_node;
8180           else
8181             {
8182               r = lookup_template_class (t, argvec, in_decl, context,
8183                                          entering_scope, complain);
8184               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8185             }
8186
8187           cp_unevaluated_operand = saved_unevaluated_operand;
8188           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8189
8190           return r;
8191         }
8192       else
8193         /* This is not a template type, so there's nothing to do.  */
8194         return t;
8195
8196     default:
8197       return tsubst (t, args, complain, in_decl);
8198     }
8199 }
8200
8201 /* Substitute into the default argument ARG (a default argument for
8202    FN), which has the indicated TYPE.  */
8203
8204 tree
8205 tsubst_default_argument (tree fn, tree type, tree arg)
8206 {
8207   tree saved_class_ptr = NULL_TREE;
8208   tree saved_class_ref = NULL_TREE;
8209
8210   /* This default argument came from a template.  Instantiate the
8211      default argument here, not in tsubst.  In the case of
8212      something like:
8213
8214        template <class T>
8215        struct S {
8216          static T t();
8217          void f(T = t());
8218        };
8219
8220      we must be careful to do name lookup in the scope of S<T>,
8221      rather than in the current class.  */
8222   push_access_scope (fn);
8223   /* The "this" pointer is not valid in a default argument.  */
8224   if (cfun)
8225     {
8226       saved_class_ptr = current_class_ptr;
8227       cp_function_chain->x_current_class_ptr = NULL_TREE;
8228       saved_class_ref = current_class_ref;
8229       cp_function_chain->x_current_class_ref = NULL_TREE;
8230     }
8231
8232   push_deferring_access_checks(dk_no_deferred);
8233   /* The default argument expression may cause implicitly defined
8234      member functions to be synthesized, which will result in garbage
8235      collection.  We must treat this situation as if we were within
8236      the body of function so as to avoid collecting live data on the
8237      stack.  */
8238   ++function_depth;
8239   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8240                      tf_warning_or_error, NULL_TREE,
8241                      /*integral_constant_expression_p=*/false);
8242   --function_depth;
8243   pop_deferring_access_checks();
8244
8245   /* Restore the "this" pointer.  */
8246   if (cfun)
8247     {
8248       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8249       cp_function_chain->x_current_class_ref = saved_class_ref;
8250     }
8251
8252   pop_access_scope (fn);
8253
8254   /* Make sure the default argument is reasonable.  */
8255   arg = check_default_argument (type, arg);
8256
8257   return arg;
8258 }
8259
8260 /* Substitute into all the default arguments for FN.  */
8261
8262 static void
8263 tsubst_default_arguments (tree fn)
8264 {
8265   tree arg;
8266   tree tmpl_args;
8267
8268   tmpl_args = DECL_TI_ARGS (fn);
8269
8270   /* If this function is not yet instantiated, we certainly don't need
8271      its default arguments.  */
8272   if (uses_template_parms (tmpl_args))
8273     return;
8274
8275   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8276        arg;
8277        arg = TREE_CHAIN (arg))
8278     if (TREE_PURPOSE (arg))
8279       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8280                                                     TREE_VALUE (arg),
8281                                                     TREE_PURPOSE (arg));
8282 }
8283
8284 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8285    result of the substitution.  Issue error and warning messages under
8286    control of COMPLAIN.  */
8287
8288 static tree
8289 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8290 {
8291   location_t saved_loc;
8292   tree r = NULL_TREE;
8293   tree in_decl = t;
8294   hashval_t hash = 0;
8295
8296   /* Set the filename and linenumber to improve error-reporting.  */
8297   saved_loc = input_location;
8298   input_location = DECL_SOURCE_LOCATION (t);
8299
8300   switch (TREE_CODE (t))
8301     {
8302     case TEMPLATE_DECL:
8303       {
8304         /* We can get here when processing a member function template,
8305            member class template, and template template parameter of
8306            a template class.  */
8307         tree decl = DECL_TEMPLATE_RESULT (t);
8308         tree spec;
8309         tree tmpl_args;
8310         tree full_args;
8311
8312         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8313           {
8314             /* Template template parameter is treated here.  */
8315             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8316             if (new_type == error_mark_node)
8317               return error_mark_node;
8318
8319             r = copy_decl (t);
8320             TREE_CHAIN (r) = NULL_TREE;
8321             TREE_TYPE (r) = new_type;
8322             DECL_TEMPLATE_RESULT (r)
8323               = build_decl (DECL_SOURCE_LOCATION (decl),
8324                             TYPE_DECL, DECL_NAME (decl), new_type);
8325             DECL_TEMPLATE_PARMS (r)
8326               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8327                                        complain);
8328             TYPE_NAME (new_type) = r;
8329             break;
8330           }
8331
8332         /* We might already have an instance of this template.
8333            The ARGS are for the surrounding class type, so the
8334            full args contain the tsubst'd args for the context,
8335            plus the innermost args from the template decl.  */
8336         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8337           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8338           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8339         /* Because this is a template, the arguments will still be
8340            dependent, even after substitution.  If
8341            PROCESSING_TEMPLATE_DECL is not set, the dependency
8342            predicates will short-circuit.  */
8343         ++processing_template_decl;
8344         full_args = tsubst_template_args (tmpl_args, args,
8345                                           complain, in_decl);
8346         --processing_template_decl;
8347         if (full_args == error_mark_node)
8348           return error_mark_node;
8349
8350         /* tsubst_template_args doesn't copy the vector if
8351            nothing changed.  But, *something* should have
8352            changed.  */
8353         gcc_assert (full_args != tmpl_args);
8354
8355         hash = hash_tmpl_and_args (t, full_args);
8356         spec = retrieve_specialization (t, full_args, hash);
8357         if (spec != NULL_TREE)
8358           {
8359             r = spec;
8360             break;
8361           }
8362
8363         /* Make a new template decl.  It will be similar to the
8364            original, but will record the current template arguments.
8365            We also create a new function declaration, which is just
8366            like the old one, but points to this new template, rather
8367            than the old one.  */
8368         r = copy_decl (t);
8369         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8370         TREE_CHAIN (r) = NULL_TREE;
8371
8372         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8373
8374         if (TREE_CODE (decl) == TYPE_DECL)
8375           {
8376             tree new_type;
8377             ++processing_template_decl;
8378             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8379             --processing_template_decl;
8380             if (new_type == error_mark_node)
8381               return error_mark_node;
8382
8383             TREE_TYPE (r) = new_type;
8384             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8385             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8386             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8387             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8388           }
8389         else
8390           {
8391             tree new_decl;
8392             ++processing_template_decl;
8393             new_decl = tsubst (decl, args, complain, in_decl);
8394             --processing_template_decl;
8395             if (new_decl == error_mark_node)
8396               return error_mark_node;
8397
8398             DECL_TEMPLATE_RESULT (r) = new_decl;
8399             DECL_TI_TEMPLATE (new_decl) = r;
8400             TREE_TYPE (r) = TREE_TYPE (new_decl);
8401             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8402             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8403           }
8404
8405         SET_DECL_IMPLICIT_INSTANTIATION (r);
8406         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8407         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8408
8409         /* The template parameters for this new template are all the
8410            template parameters for the old template, except the
8411            outermost level of parameters.  */
8412         DECL_TEMPLATE_PARMS (r)
8413           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8414                                    complain);
8415
8416         if (PRIMARY_TEMPLATE_P (t))
8417           DECL_PRIMARY_TEMPLATE (r) = r;
8418
8419         if (TREE_CODE (decl) != TYPE_DECL)
8420           /* Record this non-type partial instantiation.  */
8421           register_specialization (r, t,
8422                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8423                                    false, hash);
8424       }
8425       break;
8426
8427     case FUNCTION_DECL:
8428       {
8429         tree ctx;
8430         tree argvec = NULL_TREE;
8431         tree *friends;
8432         tree gen_tmpl;
8433         tree type;
8434         int member;
8435         int args_depth;
8436         int parms_depth;
8437
8438         /* Nobody should be tsubst'ing into non-template functions.  */
8439         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8440
8441         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8442           {
8443             tree spec;
8444             bool dependent_p;
8445
8446             /* If T is not dependent, just return it.  We have to
8447                increment PROCESSING_TEMPLATE_DECL because
8448                value_dependent_expression_p assumes that nothing is
8449                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8450             ++processing_template_decl;
8451             dependent_p = value_dependent_expression_p (t);
8452             --processing_template_decl;
8453             if (!dependent_p)
8454               return t;
8455
8456             /* Calculate the most general template of which R is a
8457                specialization, and the complete set of arguments used to
8458                specialize R.  */
8459             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8460             argvec = tsubst_template_args (DECL_TI_ARGS
8461                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8462                                            args, complain, in_decl);
8463
8464             /* Check to see if we already have this specialization.  */
8465             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8466             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8467
8468             if (spec)
8469               {
8470                 r = spec;
8471                 break;
8472               }
8473
8474             /* We can see more levels of arguments than parameters if
8475                there was a specialization of a member template, like
8476                this:
8477
8478                  template <class T> struct S { template <class U> void f(); }
8479                  template <> template <class U> void S<int>::f(U);
8480
8481                Here, we'll be substituting into the specialization,
8482                because that's where we can find the code we actually
8483                want to generate, but we'll have enough arguments for
8484                the most general template.
8485
8486                We also deal with the peculiar case:
8487
8488                  template <class T> struct S {
8489                    template <class U> friend void f();
8490                  };
8491                  template <class U> void f() {}
8492                  template S<int>;
8493                  template void f<double>();
8494
8495                Here, the ARGS for the instantiation of will be {int,
8496                double}.  But, we only need as many ARGS as there are
8497                levels of template parameters in CODE_PATTERN.  We are
8498                careful not to get fooled into reducing the ARGS in
8499                situations like:
8500
8501                  template <class T> struct S { template <class U> void f(U); }
8502                  template <class T> template <> void S<T>::f(int) {}
8503
8504                which we can spot because the pattern will be a
8505                specialization in this case.  */
8506             args_depth = TMPL_ARGS_DEPTH (args);
8507             parms_depth =
8508               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8509             if (args_depth > parms_depth
8510                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8511               args = get_innermost_template_args (args, parms_depth);
8512           }
8513         else
8514           {
8515             /* This special case arises when we have something like this:
8516
8517                  template <class T> struct S {
8518                    friend void f<int>(int, double);
8519                  };
8520
8521                Here, the DECL_TI_TEMPLATE for the friend declaration
8522                will be an IDENTIFIER_NODE.  We are being called from
8523                tsubst_friend_function, and we want only to create a
8524                new decl (R) with appropriate types so that we can call
8525                determine_specialization.  */
8526             gen_tmpl = NULL_TREE;
8527           }
8528
8529         if (DECL_CLASS_SCOPE_P (t))
8530           {
8531             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8532               member = 2;
8533             else
8534               member = 1;
8535             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8536                                     complain, t, /*entering_scope=*/1);
8537           }
8538         else
8539           {
8540             member = 0;
8541             ctx = DECL_CONTEXT (t);
8542           }
8543         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8544         if (type == error_mark_node)
8545           return error_mark_node;
8546
8547         /* We do NOT check for matching decls pushed separately at this
8548            point, as they may not represent instantiations of this
8549            template, and in any case are considered separate under the
8550            discrete model.  */
8551         r = copy_decl (t);
8552         DECL_USE_TEMPLATE (r) = 0;
8553         TREE_TYPE (r) = type;
8554         /* Clear out the mangled name and RTL for the instantiation.  */
8555         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8556         SET_DECL_RTL (r, NULL_RTX);
8557         /* Leave DECL_INITIAL set on deleted instantiations.  */
8558         if (!DECL_DELETED_FN (r))
8559           DECL_INITIAL (r) = NULL_TREE;
8560         DECL_CONTEXT (r) = ctx;
8561
8562         if (member && DECL_CONV_FN_P (r))
8563           /* Type-conversion operator.  Reconstruct the name, in
8564              case it's the name of one of the template's parameters.  */
8565           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8566
8567         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8568                                      complain, t);
8569         DECL_RESULT (r) = NULL_TREE;
8570
8571         TREE_STATIC (r) = 0;
8572         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8573         DECL_EXTERNAL (r) = 1;
8574         /* If this is an instantiation of a function with internal
8575            linkage, we already know what object file linkage will be
8576            assigned to the instantiation.  */
8577         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8578         DECL_DEFER_OUTPUT (r) = 0;
8579         TREE_CHAIN (r) = NULL_TREE;
8580         DECL_PENDING_INLINE_INFO (r) = 0;
8581         DECL_PENDING_INLINE_P (r) = 0;
8582         DECL_SAVED_TREE (r) = NULL_TREE;
8583         DECL_STRUCT_FUNCTION (r) = NULL;
8584         TREE_USED (r) = 0;
8585         /* We'll re-clone as appropriate in instantiate_template.  */
8586         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8587
8588         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8589            this in the special friend case mentioned above where
8590            GEN_TMPL is NULL.  */
8591         if (gen_tmpl)
8592           {
8593             DECL_TEMPLATE_INFO (r)
8594               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8595             SET_DECL_IMPLICIT_INSTANTIATION (r);
8596             register_specialization (r, gen_tmpl, argvec, false, hash);
8597
8598             /* We're not supposed to instantiate default arguments
8599                until they are called, for a template.  But, for a
8600                declaration like:
8601
8602                  template <class T> void f ()
8603                  { extern void g(int i = T()); }
8604
8605                we should do the substitution when the template is
8606                instantiated.  We handle the member function case in
8607                instantiate_class_template since the default arguments
8608                might refer to other members of the class.  */
8609             if (!member
8610                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8611                 && !uses_template_parms (argvec))
8612               tsubst_default_arguments (r);
8613           }
8614         else
8615           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8616
8617         /* Copy the list of befriending classes.  */
8618         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8619              *friends;
8620              friends = &TREE_CHAIN (*friends))
8621           {
8622             *friends = copy_node (*friends);
8623             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8624                                             args, complain,
8625                                             in_decl);
8626           }
8627
8628         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8629           {
8630             maybe_retrofit_in_chrg (r);
8631             if (DECL_CONSTRUCTOR_P (r))
8632               grok_ctor_properties (ctx, r);
8633             /* If this is an instantiation of a member template, clone it.
8634                If it isn't, that'll be handled by
8635                clone_constructors_and_destructors.  */
8636             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8637               clone_function_decl (r, /*update_method_vec_p=*/0);
8638           }
8639         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8640                  && !grok_op_properties (r, (complain & tf_error) != 0))
8641           return error_mark_node;
8642
8643         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8644           SET_DECL_FRIEND_CONTEXT (r,
8645                                    tsubst (DECL_FRIEND_CONTEXT (t),
8646                                             args, complain, in_decl));
8647
8648         /* Possibly limit visibility based on template args.  */
8649         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8650         if (DECL_VISIBILITY_SPECIFIED (t))
8651           {
8652             DECL_VISIBILITY_SPECIFIED (r) = 0;
8653             DECL_ATTRIBUTES (r)
8654               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8655           }
8656         determine_visibility (r);
8657
8658         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8659                                         args, complain, in_decl);
8660       }
8661       break;
8662
8663     case PARM_DECL:
8664       {
8665         tree type = NULL_TREE;
8666         int i, len = 1;
8667         tree expanded_types = NULL_TREE;
8668         tree prev_r = NULL_TREE;
8669         tree first_r = NULL_TREE;
8670
8671         if (FUNCTION_PARAMETER_PACK_P (t))
8672           {
8673             /* If there is a local specialization that isn't a
8674                parameter pack, it means that we're doing a "simple"
8675                substitution from inside tsubst_pack_expansion. Just
8676                return the local specialization (which will be a single
8677                parm).  */
8678             tree spec = retrieve_local_specialization (t);
8679             if (spec 
8680                 && TREE_CODE (spec) == PARM_DECL
8681                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8682               return spec;
8683
8684             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8685                the parameters in this function parameter pack.  */
8686             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8687                                                     complain, in_decl);
8688             if (TREE_CODE (expanded_types) == TREE_VEC)
8689               {
8690                 len = TREE_VEC_LENGTH (expanded_types);
8691
8692                 /* Zero-length parameter packs are boring. Just substitute
8693                    into the chain.  */
8694                 if (len == 0)
8695                   return tsubst (TREE_CHAIN (t), args, complain, 
8696                                  TREE_CHAIN (t));
8697               }
8698             else
8699               {
8700                 /* All we did was update the type. Make a note of that.  */
8701                 type = expanded_types;
8702                 expanded_types = NULL_TREE;
8703               }
8704           }
8705
8706         /* Loop through all of the parameter's we'll build. When T is
8707            a function parameter pack, LEN is the number of expanded
8708            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8709         r = NULL_TREE;
8710         for (i = 0; i < len; ++i)
8711           {
8712             prev_r = r;
8713             r = copy_node (t);
8714             if (DECL_TEMPLATE_PARM_P (t))
8715               SET_DECL_TEMPLATE_PARM_P (r);
8716
8717             if (expanded_types)
8718               /* We're on the Ith parameter of the function parameter
8719                  pack.  */
8720               {
8721                 /* Get the Ith type.  */
8722                 type = TREE_VEC_ELT (expanded_types, i);
8723
8724                 if (DECL_NAME (r))
8725                   /* Rename the parameter to include the index.  */
8726                   DECL_NAME (r) =
8727                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8728               }
8729             else if (!type)
8730               /* We're dealing with a normal parameter.  */
8731               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8732
8733             type = type_decays_to (type);
8734             TREE_TYPE (r) = type;
8735             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8736
8737             if (DECL_INITIAL (r))
8738               {
8739                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8740                   DECL_INITIAL (r) = TREE_TYPE (r);
8741                 else
8742                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8743                                              complain, in_decl);
8744               }
8745
8746             DECL_CONTEXT (r) = NULL_TREE;
8747
8748             if (!DECL_TEMPLATE_PARM_P (r))
8749               DECL_ARG_TYPE (r) = type_passed_as (type);
8750
8751             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8752                                             args, complain, in_decl);
8753
8754             /* Keep track of the first new parameter we
8755                generate. That's what will be returned to the
8756                caller.  */
8757             if (!first_r)
8758               first_r = r;
8759
8760             /* Build a proper chain of parameters when substituting
8761                into a function parameter pack.  */
8762             if (prev_r)
8763               TREE_CHAIN (prev_r) = r;
8764           }
8765
8766         if (TREE_CHAIN (t))
8767           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8768                                    complain, TREE_CHAIN (t));
8769
8770         /* FIRST_R contains the start of the chain we've built.  */
8771         r = first_r;
8772       }
8773       break;
8774
8775     case FIELD_DECL:
8776       {
8777         tree type;
8778
8779         r = copy_decl (t);
8780         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8781         if (type == error_mark_node)
8782           return error_mark_node;
8783         TREE_TYPE (r) = type;
8784         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8785
8786         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8787         DECL_INITIAL (r)
8788           = tsubst_expr (DECL_INITIAL (t), args,
8789                          complain, in_decl,
8790                          /*integral_constant_expression_p=*/true);
8791         /* We don't have to set DECL_CONTEXT here; it is set by
8792            finish_member_declaration.  */
8793         TREE_CHAIN (r) = NULL_TREE;
8794         if (VOID_TYPE_P (type))
8795           error ("instantiation of %q+D as type %qT", r, type);
8796
8797         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8798                                         args, complain, in_decl);
8799       }
8800       break;
8801
8802     case USING_DECL:
8803       /* We reach here only for member using decls.  */
8804       if (DECL_DEPENDENT_P (t))
8805         {
8806           r = do_class_using_decl
8807             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8808              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8809           if (!r)
8810             r = error_mark_node;
8811           else
8812             {
8813               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8814               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8815             }
8816         }
8817       else
8818         {
8819           r = copy_node (t);
8820           TREE_CHAIN (r) = NULL_TREE;
8821         }
8822       break;
8823
8824     case TYPE_DECL:
8825     case VAR_DECL:
8826       {
8827         tree argvec = NULL_TREE;
8828         tree gen_tmpl = NULL_TREE;
8829         tree spec;
8830         tree tmpl = NULL_TREE;
8831         tree ctx;
8832         tree type = NULL_TREE;
8833         bool local_p;
8834
8835         if (TREE_CODE (t) == TYPE_DECL
8836             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8837           {
8838             /* If this is the canonical decl, we don't have to
8839                mess with instantiations, and often we can't (for
8840                typename, template type parms and such).  Note that
8841                TYPE_NAME is not correct for the above test if
8842                we've copied the type for a typedef.  */
8843             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8844             if (type == error_mark_node)
8845               return error_mark_node;
8846             r = TYPE_NAME (type);
8847             break;
8848           }
8849
8850         /* Check to see if we already have the specialization we
8851            need.  */
8852         spec = NULL_TREE;
8853         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8854           {
8855             /* T is a static data member or namespace-scope entity.
8856                We have to substitute into namespace-scope variables
8857                (even though such entities are never templates) because
8858                of cases like:
8859                
8860                  template <class T> void f() { extern T t; }
8861
8862                where the entity referenced is not known until
8863                instantiation time.  */
8864             local_p = false;
8865             ctx = DECL_CONTEXT (t);
8866             if (DECL_CLASS_SCOPE_P (t))
8867               {
8868                 ctx = tsubst_aggr_type (ctx, args,
8869                                         complain,
8870                                         in_decl, /*entering_scope=*/1);
8871                 /* If CTX is unchanged, then T is in fact the
8872                    specialization we want.  That situation occurs when
8873                    referencing a static data member within in its own
8874                    class.  We can use pointer equality, rather than
8875                    same_type_p, because DECL_CONTEXT is always
8876                    canonical.  */
8877                 if (ctx == DECL_CONTEXT (t))
8878                   spec = t;
8879               }
8880
8881             if (!spec)
8882               {
8883                 tmpl = DECL_TI_TEMPLATE (t);
8884                 gen_tmpl = most_general_template (tmpl);
8885                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8886                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
8887                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
8888               }
8889           }
8890         else
8891           {
8892             /* A local variable.  */
8893             local_p = true;
8894             /* Subsequent calls to pushdecl will fill this in.  */
8895             ctx = NULL_TREE;
8896             spec = retrieve_local_specialization (t);
8897           }
8898         /* If we already have the specialization we need, there is
8899            nothing more to do.  */ 
8900         if (spec)
8901           {
8902             r = spec;
8903             break;
8904           }
8905
8906         /* Create a new node for the specialization we need.  */
8907         r = copy_decl (t);
8908         if (type == NULL_TREE)
8909           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8910         if (TREE_CODE (r) == VAR_DECL)
8911           {
8912             /* Even if the original location is out of scope, the
8913                newly substituted one is not.  */
8914             DECL_DEAD_FOR_LOCAL (r) = 0;
8915             DECL_INITIALIZED_P (r) = 0;
8916             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8917             if (type == error_mark_node)
8918               return error_mark_node;
8919             if (TREE_CODE (type) == FUNCTION_TYPE)
8920               {
8921                 /* It may seem that this case cannot occur, since:
8922
8923                      typedef void f();
8924                      void g() { f x; }
8925
8926                    declares a function, not a variable.  However:
8927       
8928                      typedef void f();
8929                      template <typename T> void g() { T t; }
8930                      template void g<f>();
8931
8932                    is an attempt to declare a variable with function
8933                    type.  */
8934                 error ("variable %qD has function type",
8935                        /* R is not yet sufficiently initialized, so we
8936                           just use its name.  */
8937                        DECL_NAME (r));
8938                 return error_mark_node;
8939               }
8940             type = complete_type (type);
8941             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8942               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8943             type = check_var_type (DECL_NAME (r), type);
8944
8945             if (DECL_HAS_VALUE_EXPR_P (t))
8946               {
8947                 tree ve = DECL_VALUE_EXPR (t);
8948                 ve = tsubst_expr (ve, args, complain, in_decl,
8949                                   /*constant_expression_p=*/false);
8950                 SET_DECL_VALUE_EXPR (r, ve);
8951               }
8952           }
8953         else if (DECL_SELF_REFERENCE_P (t))
8954           SET_DECL_SELF_REFERENCE_P (r);
8955         TREE_TYPE (r) = type;
8956         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8957         DECL_CONTEXT (r) = ctx;
8958         /* Clear out the mangled name and RTL for the instantiation.  */
8959         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8960         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8961           SET_DECL_RTL (r, NULL_RTX);
8962         /* The initializer must not be expanded until it is required;
8963            see [temp.inst].  */
8964         DECL_INITIAL (r) = NULL_TREE;
8965         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8966           SET_DECL_RTL (r, NULL_RTX);
8967         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8968         if (TREE_CODE (r) == VAR_DECL)
8969           {
8970             /* Possibly limit visibility based on template args.  */
8971             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8972             if (DECL_VISIBILITY_SPECIFIED (t))
8973               {
8974                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8975                 DECL_ATTRIBUTES (r)
8976                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8977               }
8978             determine_visibility (r);
8979           }
8980         /* Preserve a typedef that names a type.  */
8981         else if (TREE_CODE (r) == TYPE_DECL
8982                  && DECL_ORIGINAL_TYPE (t)
8983                  && type != error_mark_node)
8984           {
8985             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8986                                              args, complain, in_decl);
8987             TREE_TYPE (r) = type = build_variant_type_copy (type);
8988             TYPE_NAME (type) = r;
8989           }
8990
8991         if (!local_p)
8992           {
8993             /* A static data member declaration is always marked
8994                external when it is declared in-class, even if an
8995                initializer is present.  We mimic the non-template
8996                processing here.  */
8997             DECL_EXTERNAL (r) = 1;
8998
8999             register_specialization (r, gen_tmpl, argvec, false, hash);
9000             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
9001             SET_DECL_IMPLICIT_INSTANTIATION (r);
9002           }
9003         else
9004           register_local_specialization (r, t);
9005
9006         TREE_CHAIN (r) = NULL_TREE;
9007
9008         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9009                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9010                                         args, complain, in_decl);
9011         layout_decl (r, 0);
9012       }
9013       break;
9014
9015     default:
9016       gcc_unreachable ();
9017     }
9018
9019   /* Restore the file and line information.  */
9020   input_location = saved_loc;
9021
9022   return r;
9023 }
9024
9025 /* Substitute into the ARG_TYPES of a function type.  */
9026
9027 static tree
9028 tsubst_arg_types (tree arg_types,
9029                   tree args,
9030                   tsubst_flags_t complain,
9031                   tree in_decl)
9032 {
9033   tree remaining_arg_types;
9034   tree type = NULL_TREE;
9035   int i = 1;
9036   tree expanded_args = NULL_TREE;
9037   tree default_arg;
9038
9039   if (!arg_types || arg_types == void_list_node)
9040     return arg_types;
9041
9042   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9043                                           args, complain, in_decl);
9044   if (remaining_arg_types == error_mark_node)
9045     return error_mark_node;
9046
9047   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9048     {
9049       /* For a pack expansion, perform substitution on the
9050          entire expression. Later on, we'll handle the arguments
9051          one-by-one.  */
9052       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9053                                             args, complain, in_decl);
9054
9055       if (TREE_CODE (expanded_args) == TREE_VEC)
9056         /* So that we'll spin through the parameters, one by one.  */
9057         i = TREE_VEC_LENGTH (expanded_args);
9058       else
9059         {
9060           /* We only partially substituted into the parameter
9061              pack. Our type is TYPE_PACK_EXPANSION.  */
9062           type = expanded_args;
9063           expanded_args = NULL_TREE;
9064         }
9065     }
9066
9067   while (i > 0) {
9068     --i;
9069     
9070     if (expanded_args)
9071       type = TREE_VEC_ELT (expanded_args, i);
9072     else if (!type)
9073       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9074
9075     if (type == error_mark_node)
9076       return error_mark_node;
9077     if (VOID_TYPE_P (type))
9078       {
9079         if (complain & tf_error)
9080           {
9081             error ("invalid parameter type %qT", type);
9082             if (in_decl)
9083               error ("in declaration %q+D", in_decl);
9084           }
9085         return error_mark_node;
9086     }
9087     
9088     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9089        top-level qualifiers as required.  */
9090     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9091
9092     /* We do not substitute into default arguments here.  The standard
9093        mandates that they be instantiated only when needed, which is
9094        done in build_over_call.  */
9095     default_arg = TREE_PURPOSE (arg_types);
9096
9097     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9098       {
9099         /* We've instantiated a template before its default arguments
9100            have been parsed.  This can happen for a nested template
9101            class, and is not an error unless we require the default
9102            argument in a call of this function.  */
9103         remaining_arg_types = 
9104           tree_cons (default_arg, type, remaining_arg_types);
9105         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9106                        remaining_arg_types);
9107       }
9108     else
9109       remaining_arg_types = 
9110         hash_tree_cons (default_arg, type, remaining_arg_types);
9111   }
9112         
9113   return remaining_arg_types;
9114 }
9115
9116 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9117    *not* handle the exception-specification for FNTYPE, because the
9118    initial substitution of explicitly provided template parameters
9119    during argument deduction forbids substitution into the
9120    exception-specification:
9121
9122      [temp.deduct]
9123
9124      All references in the function type of the function template to  the
9125      corresponding template parameters are replaced by the specified tem-
9126      plate argument values.  If a substitution in a template parameter or
9127      in  the function type of the function template results in an invalid
9128      type, type deduction fails.  [Note: The equivalent  substitution  in
9129      exception specifications is done only when the function is instanti-
9130      ated, at which point a program is  ill-formed  if  the  substitution
9131      results in an invalid type.]  */
9132
9133 static tree
9134 tsubst_function_type (tree t,
9135                       tree args,
9136                       tsubst_flags_t complain,
9137                       tree in_decl)
9138 {
9139   tree return_type;
9140   tree arg_types;
9141   tree fntype;
9142
9143   /* The TYPE_CONTEXT is not used for function/method types.  */
9144   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9145
9146   /* Substitute the return type.  */
9147   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9148   if (return_type == error_mark_node)
9149     return error_mark_node;
9150   /* The standard does not presently indicate that creation of a
9151      function type with an invalid return type is a deduction failure.
9152      However, that is clearly analogous to creating an array of "void"
9153      or a reference to a reference.  This is core issue #486.  */
9154   if (TREE_CODE (return_type) == ARRAY_TYPE
9155       || TREE_CODE (return_type) == FUNCTION_TYPE)
9156     {
9157       if (complain & tf_error)
9158         {
9159           if (TREE_CODE (return_type) == ARRAY_TYPE)
9160             error ("function returning an array");
9161           else
9162             error ("function returning a function");
9163         }
9164       return error_mark_node;
9165     }
9166
9167   /* Substitute the argument types.  */
9168   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9169                                 complain, in_decl);
9170   if (arg_types == error_mark_node)
9171     return error_mark_node;
9172
9173   /* Construct a new type node and return it.  */
9174   if (TREE_CODE (t) == FUNCTION_TYPE)
9175     fntype = build_function_type (return_type, arg_types);
9176   else
9177     {
9178       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9179       if (! MAYBE_CLASS_TYPE_P (r))
9180         {
9181           /* [temp.deduct]
9182
9183              Type deduction may fail for any of the following
9184              reasons:
9185
9186              -- Attempting to create "pointer to member of T" when T
9187              is not a class type.  */
9188           if (complain & tf_error)
9189             error ("creating pointer to member function of non-class type %qT",
9190                       r);
9191           return error_mark_node;
9192         }
9193
9194       fntype = build_method_type_directly (r, return_type,
9195                                            TREE_CHAIN (arg_types));
9196     }
9197   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9198   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9199
9200   return fntype;
9201 }
9202
9203 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9204    ARGS into that specification, and return the substituted
9205    specification.  If there is no specification, return NULL_TREE.  */
9206
9207 static tree
9208 tsubst_exception_specification (tree fntype,
9209                                 tree args,
9210                                 tsubst_flags_t complain,
9211                                 tree in_decl)
9212 {
9213   tree specs;
9214   tree new_specs;
9215
9216   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9217   new_specs = NULL_TREE;
9218   if (specs)
9219     {
9220       if (! TREE_VALUE (specs))
9221         new_specs = specs;
9222       else
9223         while (specs)
9224           {
9225             tree spec;
9226             int i, len = 1;
9227             tree expanded_specs = NULL_TREE;
9228
9229             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9230               {
9231                 /* Expand the pack expansion type.  */
9232                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9233                                                        args, complain,
9234                                                        in_decl);
9235
9236                 if (expanded_specs == error_mark_node)
9237                   return error_mark_node;
9238                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9239                   len = TREE_VEC_LENGTH (expanded_specs);
9240                 else
9241                   {
9242                     /* We're substituting into a member template, so
9243                        we got a TYPE_PACK_EXPANSION back.  Add that
9244                        expansion and move on.  */
9245                     gcc_assert (TREE_CODE (expanded_specs) 
9246                                 == TYPE_PACK_EXPANSION);
9247                     new_specs = add_exception_specifier (new_specs,
9248                                                          expanded_specs,
9249                                                          complain);
9250                     specs = TREE_CHAIN (specs);
9251                     continue;
9252                   }
9253               }
9254
9255             for (i = 0; i < len; ++i)
9256               {
9257                 if (expanded_specs)
9258                   spec = TREE_VEC_ELT (expanded_specs, i);
9259                 else
9260                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9261                 if (spec == error_mark_node)
9262                   return spec;
9263                 new_specs = add_exception_specifier (new_specs, spec, 
9264                                                      complain);
9265               }
9266
9267             specs = TREE_CHAIN (specs);
9268           }
9269     }
9270   return new_specs;
9271 }
9272
9273 /* Take the tree structure T and replace template parameters used
9274    therein with the argument vector ARGS.  IN_DECL is an associated
9275    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9276    Issue error and warning messages under control of COMPLAIN.  Note
9277    that we must be relatively non-tolerant of extensions here, in
9278    order to preserve conformance; if we allow substitutions that
9279    should not be allowed, we may allow argument deductions that should
9280    not succeed, and therefore report ambiguous overload situations
9281    where there are none.  In theory, we could allow the substitution,
9282    but indicate that it should have failed, and allow our caller to
9283    make sure that the right thing happens, but we don't try to do this
9284    yet.
9285
9286    This function is used for dealing with types, decls and the like;
9287    for expressions, use tsubst_expr or tsubst_copy.  */
9288
9289 tree
9290 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9291 {
9292   tree type, r;
9293
9294   if (t == NULL_TREE || t == error_mark_node
9295       || t == integer_type_node
9296       || t == void_type_node
9297       || t == char_type_node
9298       || t == unknown_type_node
9299       || TREE_CODE (t) == NAMESPACE_DECL)
9300     return t;
9301
9302   if (DECL_P (t))
9303     return tsubst_decl (t, args, complain);
9304
9305   if (args == NULL_TREE)
9306     return t;
9307
9308   if (TREE_CODE (t) == IDENTIFIER_NODE)
9309     type = IDENTIFIER_TYPE_VALUE (t);
9310   else
9311     type = TREE_TYPE (t);
9312
9313   gcc_assert (type != unknown_type_node);
9314
9315   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9316      such as attribute aligned.  */
9317   if (TYPE_P (t)
9318       && TYPE_NAME (t)
9319       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9320     {
9321       tree decl = TYPE_NAME (t);
9322       
9323       if (DECL_CLASS_SCOPE_P (decl)
9324           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9325           && uses_template_parms (DECL_CONTEXT (decl)))
9326         {
9327           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9328           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9329           r = retrieve_specialization (tmpl, gen_args, 0);
9330         }
9331       else if (DECL_FUNCTION_SCOPE_P (decl)
9332                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9333                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9334         r = retrieve_local_specialization (decl);
9335       else
9336         /* The typedef is from a non-template context.  */
9337         return t;
9338
9339       if (r)
9340         {
9341           r = TREE_TYPE (r);
9342           r = cp_build_qualified_type_real
9343             (r, cp_type_quals (t) | cp_type_quals (r),
9344              complain | tf_ignore_bad_quals);
9345           return r;
9346         }
9347       /* Else we must be instantiating the typedef, so fall through.  */
9348     }
9349
9350   if (type
9351       && TREE_CODE (t) != TYPENAME_TYPE
9352       && TREE_CODE (t) != IDENTIFIER_NODE
9353       && TREE_CODE (t) != FUNCTION_TYPE
9354       && TREE_CODE (t) != METHOD_TYPE)
9355     type = tsubst (type, args, complain, in_decl);
9356   if (type == error_mark_node)
9357     return error_mark_node;
9358
9359   switch (TREE_CODE (t))
9360     {
9361     case RECORD_TYPE:
9362     case UNION_TYPE:
9363     case ENUMERAL_TYPE:
9364       return tsubst_aggr_type (t, args, complain, in_decl,
9365                                /*entering_scope=*/0);
9366
9367     case ERROR_MARK:
9368     case IDENTIFIER_NODE:
9369     case VOID_TYPE:
9370     case REAL_TYPE:
9371     case COMPLEX_TYPE:
9372     case VECTOR_TYPE:
9373     case BOOLEAN_TYPE:
9374     case INTEGER_CST:
9375     case REAL_CST:
9376     case STRING_CST:
9377       return t;
9378
9379     case INTEGER_TYPE:
9380       if (t == integer_type_node)
9381         return t;
9382
9383       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9384           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9385         return t;
9386
9387       {
9388         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9389
9390         max = tsubst_expr (omax, args, complain, in_decl,
9391                            /*integral_constant_expression_p=*/false);
9392
9393         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9394            needed.  */
9395         if (TREE_CODE (max) == NOP_EXPR
9396             && TREE_SIDE_EFFECTS (omax)
9397             && !TREE_TYPE (max))
9398           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9399
9400         max = fold_decl_constant_value (max);
9401
9402         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9403            with TREE_SIDE_EFFECTS that indicates this is not an integral
9404            constant expression.  */
9405         if (processing_template_decl
9406             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9407           {
9408             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9409             TREE_SIDE_EFFECTS (max) = 1;
9410           }
9411
9412         if (TREE_CODE (max) != INTEGER_CST
9413             && !at_function_scope_p ()
9414             && !TREE_SIDE_EFFECTS (max)
9415             && !value_dependent_expression_p (max))
9416           {
9417             if (complain & tf_error)
9418               error ("array bound is not an integer constant");
9419             return error_mark_node;
9420           }
9421
9422         /* [temp.deduct]
9423
9424            Type deduction may fail for any of the following
9425            reasons:
9426
9427              Attempting to create an array with a size that is
9428              zero or negative.  */
9429         if (integer_zerop (max) && !(complain & tf_error))
9430           /* We must fail if performing argument deduction (as
9431              indicated by the state of complain), so that
9432              another substitution can be found.  */
9433           return error_mark_node;
9434         else if (TREE_CODE (max) == INTEGER_CST
9435                  && INT_CST_LT (max, integer_zero_node))
9436           {
9437             if (complain & tf_error)
9438               error ("creating array with negative size (%qE)", max);
9439
9440             return error_mark_node;
9441           }
9442
9443         return compute_array_index_type (NULL_TREE, max);
9444       }
9445
9446     case TEMPLATE_TYPE_PARM:
9447     case TEMPLATE_TEMPLATE_PARM:
9448     case BOUND_TEMPLATE_TEMPLATE_PARM:
9449     case TEMPLATE_PARM_INDEX:
9450       {
9451         int idx;
9452         int level;
9453         int levels;
9454         tree arg = NULL_TREE;
9455
9456         r = NULL_TREE;
9457
9458         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9459         template_parm_level_and_index (t, &level, &idx); 
9460
9461         levels = TMPL_ARGS_DEPTH (args);
9462         if (level <= levels)
9463           {
9464             arg = TMPL_ARG (args, level, idx);
9465
9466             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9467               /* See through ARGUMENT_PACK_SELECT arguments. */
9468               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9469           }
9470
9471         if (arg == error_mark_node)
9472           return error_mark_node;
9473         else if (arg != NULL_TREE)
9474           {
9475             if (ARGUMENT_PACK_P (arg))
9476               /* If ARG is an argument pack, we don't actually want to
9477                  perform a substitution here, because substitutions
9478                  for argument packs are only done
9479                  element-by-element. We can get to this point when
9480                  substituting the type of a non-type template
9481                  parameter pack, when that type actually contains
9482                  template parameter packs from an outer template, e.g.,
9483
9484                  template<typename... Types> struct A {
9485                    template<Types... Values> struct B { };
9486                  };  */
9487               return t;
9488
9489             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9490               {
9491                 int quals;
9492                 gcc_assert (TYPE_P (arg));
9493
9494                 /* cv-quals from the template are discarded when
9495                    substituting in a function or reference type.  */
9496                 if (TREE_CODE (arg) == FUNCTION_TYPE
9497                     || TREE_CODE (arg) == METHOD_TYPE
9498                     || TREE_CODE (arg) == REFERENCE_TYPE)
9499                   quals = cp_type_quals (arg);
9500                 else
9501                   quals = cp_type_quals (arg) | cp_type_quals (t);
9502                   
9503                 return cp_build_qualified_type_real
9504                   (arg, quals, complain | tf_ignore_bad_quals);
9505               }
9506             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9507               {
9508                 /* We are processing a type constructed from a
9509                    template template parameter.  */
9510                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9511                                       args, complain, in_decl);
9512                 if (argvec == error_mark_node)
9513                   return error_mark_node;
9514
9515                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9516                    are resolving nested-types in the signature of a
9517                    member function templates.  Otherwise ARG is a
9518                    TEMPLATE_DECL and is the real template to be
9519                    instantiated.  */
9520                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9521                   arg = TYPE_NAME (arg);
9522
9523                 r = lookup_template_class (arg,
9524                                            argvec, in_decl,
9525                                            DECL_CONTEXT (arg),
9526                                             /*entering_scope=*/0,
9527                                            complain);
9528                 return cp_build_qualified_type_real
9529                   (r, TYPE_QUALS (t), complain);
9530               }
9531             else
9532               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9533               return arg;
9534           }
9535
9536         if (level == 1)
9537           /* This can happen during the attempted tsubst'ing in
9538              unify.  This means that we don't yet have any information
9539              about the template parameter in question.  */
9540           return t;
9541
9542         /* If we get here, we must have been looking at a parm for a
9543            more deeply nested template.  Make a new version of this
9544            template parameter, but with a lower level.  */
9545         switch (TREE_CODE (t))
9546           {
9547           case TEMPLATE_TYPE_PARM:
9548           case TEMPLATE_TEMPLATE_PARM:
9549           case BOUND_TEMPLATE_TEMPLATE_PARM:
9550             if (cp_type_quals (t))
9551               {
9552                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9553                 r = cp_build_qualified_type_real
9554                   (r, cp_type_quals (t),
9555                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9556                                ? tf_ignore_bad_quals : 0));
9557               }
9558             else
9559               {
9560                 r = copy_type (t);
9561                 TEMPLATE_TYPE_PARM_INDEX (r)
9562                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9563                                                 r, levels, args, complain);
9564                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9565                 TYPE_MAIN_VARIANT (r) = r;
9566                 TYPE_POINTER_TO (r) = NULL_TREE;
9567                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9568
9569                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9570                   /* We have reduced the level of the template
9571                      template parameter, but not the levels of its
9572                      template parameters, so canonical_type_parameter
9573                      will not be able to find the canonical template
9574                      template parameter for this level. Thus, we
9575                      require structural equality checking to compare
9576                      TEMPLATE_TEMPLATE_PARMs. */
9577                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9578                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9579                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9580                 else
9581                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9582
9583                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9584                   {
9585                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9586                                           complain, in_decl);
9587                     if (argvec == error_mark_node)
9588                       return error_mark_node;
9589
9590                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9591                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9592                   }
9593               }
9594             break;
9595
9596           case TEMPLATE_PARM_INDEX:
9597             r = reduce_template_parm_level (t, type, levels, args, complain);
9598             break;
9599
9600           default:
9601             gcc_unreachable ();
9602           }
9603
9604         return r;
9605       }
9606
9607     case TREE_LIST:
9608       {
9609         tree purpose, value, chain;
9610
9611         if (t == void_list_node)
9612           return t;
9613
9614         purpose = TREE_PURPOSE (t);
9615         if (purpose)
9616           {
9617             purpose = tsubst (purpose, args, complain, in_decl);
9618             if (purpose == error_mark_node)
9619               return error_mark_node;
9620           }
9621         value = TREE_VALUE (t);
9622         if (value)
9623           {
9624             value = tsubst (value, args, complain, in_decl);
9625             if (value == error_mark_node)
9626               return error_mark_node;
9627           }
9628         chain = TREE_CHAIN (t);
9629         if (chain && chain != void_type_node)
9630           {
9631             chain = tsubst (chain, args, complain, in_decl);
9632             if (chain == error_mark_node)
9633               return error_mark_node;
9634           }
9635         if (purpose == TREE_PURPOSE (t)
9636             && value == TREE_VALUE (t)
9637             && chain == TREE_CHAIN (t))
9638           return t;
9639         return hash_tree_cons (purpose, value, chain);
9640       }
9641
9642     case TREE_BINFO:
9643       /* We should never be tsubsting a binfo.  */
9644       gcc_unreachable ();
9645
9646     case TREE_VEC:
9647       /* A vector of template arguments.  */
9648       gcc_assert (!type);
9649       return tsubst_template_args (t, args, complain, in_decl);
9650
9651     case POINTER_TYPE:
9652     case REFERENCE_TYPE:
9653       {
9654         enum tree_code code;
9655
9656         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9657           return t;
9658
9659         code = TREE_CODE (t);
9660
9661
9662         /* [temp.deduct]
9663
9664            Type deduction may fail for any of the following
9665            reasons:
9666
9667            -- Attempting to create a pointer to reference type.
9668            -- Attempting to create a reference to a reference type or
9669               a reference to void.
9670
9671           Core issue 106 says that creating a reference to a reference
9672           during instantiation is no longer a cause for failure. We
9673           only enforce this check in strict C++98 mode.  */
9674         if ((TREE_CODE (type) == REFERENCE_TYPE
9675              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9676             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9677           {
9678             static location_t last_loc;
9679
9680             /* We keep track of the last time we issued this error
9681                message to avoid spewing a ton of messages during a
9682                single bad template instantiation.  */
9683             if (complain & tf_error
9684                 && last_loc != input_location)
9685               {
9686                 if (TREE_CODE (type) == VOID_TYPE)
9687                   error ("forming reference to void");
9688                 else
9689                   error ("forming %s to reference type %qT",
9690                          (code == POINTER_TYPE) ? "pointer" : "reference",
9691                          type);
9692                 last_loc = input_location;
9693               }
9694
9695             return error_mark_node;
9696           }
9697         else if (code == POINTER_TYPE)
9698           {
9699             r = build_pointer_type (type);
9700             if (TREE_CODE (type) == METHOD_TYPE)
9701               r = build_ptrmemfunc_type (r);
9702           }
9703         else if (TREE_CODE (type) == REFERENCE_TYPE)
9704           /* In C++0x, during template argument substitution, when there is an
9705              attempt to create a reference to a reference type, reference
9706              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9707
9708              "If a template-argument for a template-parameter T names a type
9709              that is a reference to a type A, an attempt to create the type
9710              'lvalue reference to cv T' creates the type 'lvalue reference to
9711              A,' while an attempt to create the type type rvalue reference to
9712              cv T' creates the type T"
9713           */
9714           r = cp_build_reference_type
9715               (TREE_TYPE (type),
9716                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9717         else
9718           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9719         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9720
9721         if (r != error_mark_node)
9722           /* Will this ever be needed for TYPE_..._TO values?  */
9723           layout_type (r);
9724
9725         return r;
9726       }
9727     case OFFSET_TYPE:
9728       {
9729         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9730         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9731           {
9732             /* [temp.deduct]
9733
9734                Type deduction may fail for any of the following
9735                reasons:
9736
9737                -- Attempting to create "pointer to member of T" when T
9738                   is not a class type.  */
9739             if (complain & tf_error)
9740               error ("creating pointer to member of non-class type %qT", r);
9741             return error_mark_node;
9742           }
9743         if (TREE_CODE (type) == REFERENCE_TYPE)
9744           {
9745             if (complain & tf_error)
9746               error ("creating pointer to member reference type %qT", type);
9747             return error_mark_node;
9748           }
9749         if (TREE_CODE (type) == VOID_TYPE)
9750           {
9751             if (complain & tf_error)
9752               error ("creating pointer to member of type void");
9753             return error_mark_node;
9754           }
9755         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9756         if (TREE_CODE (type) == FUNCTION_TYPE)
9757           {
9758             /* The type of the implicit object parameter gets its
9759                cv-qualifiers from the FUNCTION_TYPE. */
9760             tree method_type;
9761             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9762                                                       cp_type_quals (type));
9763             tree memptr;
9764             method_type = build_method_type_directly (this_type,
9765                                                       TREE_TYPE (type),
9766                                                       TYPE_ARG_TYPES (type));
9767             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9768             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9769                                                  complain);
9770           }
9771         else
9772           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9773                                                TYPE_QUALS (t),
9774                                                complain);
9775       }
9776     case FUNCTION_TYPE:
9777     case METHOD_TYPE:
9778       {
9779         tree fntype;
9780         tree specs;
9781         fntype = tsubst_function_type (t, args, complain, in_decl);
9782         if (fntype == error_mark_node)
9783           return error_mark_node;
9784
9785         /* Substitute the exception specification.  */
9786         specs = tsubst_exception_specification (t, args, complain,
9787                                                 in_decl);
9788         if (specs == error_mark_node)
9789           return error_mark_node;
9790         if (specs)
9791           fntype = build_exception_variant (fntype, specs);
9792         return fntype;
9793       }
9794     case ARRAY_TYPE:
9795       {
9796         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9797         if (domain == error_mark_node)
9798           return error_mark_node;
9799
9800         /* As an optimization, we avoid regenerating the array type if
9801            it will obviously be the same as T.  */
9802         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9803           return t;
9804
9805         /* These checks should match the ones in grokdeclarator.
9806
9807            [temp.deduct]
9808
9809            The deduction may fail for any of the following reasons:
9810
9811            -- Attempting to create an array with an element type that
9812               is void, a function type, or a reference type, or [DR337]
9813               an abstract class type.  */
9814         if (TREE_CODE (type) == VOID_TYPE
9815             || TREE_CODE (type) == FUNCTION_TYPE
9816             || TREE_CODE (type) == REFERENCE_TYPE)
9817           {
9818             if (complain & tf_error)
9819               error ("creating array of %qT", type);
9820             return error_mark_node;
9821           }
9822         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9823           {
9824             if (complain & tf_error)
9825               error ("creating array of %qT, which is an abstract class type",
9826                      type);
9827             return error_mark_node;
9828           }
9829
9830         r = build_cplus_array_type (type, domain);
9831
9832         if (TYPE_USER_ALIGN (t))
9833           {
9834             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9835             TYPE_USER_ALIGN (r) = 1;
9836           }
9837
9838         return r;
9839       }
9840
9841     case PLUS_EXPR:
9842     case MINUS_EXPR:
9843       {
9844         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9845         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9846
9847         if (e1 == error_mark_node || e2 == error_mark_node)
9848           return error_mark_node;
9849
9850         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9851       }
9852
9853     case NEGATE_EXPR:
9854     case NOP_EXPR:
9855       {
9856         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9857         if (e == error_mark_node)
9858           return error_mark_node;
9859
9860         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9861       }
9862
9863     case TYPENAME_TYPE:
9864       {
9865         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9866                                      in_decl, /*entering_scope=*/1);
9867         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9868                               complain, in_decl);
9869
9870         if (ctx == error_mark_node || f == error_mark_node)
9871           return error_mark_node;
9872
9873         if (!MAYBE_CLASS_TYPE_P (ctx))
9874           {
9875             if (complain & tf_error)
9876               error ("%qT is not a class, struct, or union type", ctx);
9877             return error_mark_node;
9878           }
9879         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9880           {
9881             /* Normally, make_typename_type does not require that the CTX
9882                have complete type in order to allow things like:
9883
9884                  template <class T> struct S { typename S<T>::X Y; };
9885
9886                But, such constructs have already been resolved by this
9887                point, so here CTX really should have complete type, unless
9888                it's a partial instantiation.  */
9889             ctx = complete_type (ctx);
9890             if (!COMPLETE_TYPE_P (ctx))
9891               {
9892                 if (complain & tf_error)
9893                   cxx_incomplete_type_error (NULL_TREE, ctx);
9894                 return error_mark_node;
9895               }
9896           }
9897
9898         f = make_typename_type (ctx, f, typename_type,
9899                                 (complain & tf_error) | tf_keep_type_decl);
9900         if (f == error_mark_node)
9901           return f;
9902         if (TREE_CODE (f) == TYPE_DECL)
9903           {
9904             complain |= tf_ignore_bad_quals;
9905             f = TREE_TYPE (f);
9906           }
9907
9908         if (TREE_CODE (f) != TYPENAME_TYPE)
9909           {
9910             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9911               error ("%qT resolves to %qT, which is not an enumeration type",
9912                      t, f);
9913             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9914               error ("%qT resolves to %qT, which is is not a class type",
9915                      t, f);
9916           }
9917
9918         return cp_build_qualified_type_real
9919           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9920       }
9921
9922     case UNBOUND_CLASS_TEMPLATE:
9923       {
9924         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9925                                      in_decl, /*entering_scope=*/1);
9926         tree name = TYPE_IDENTIFIER (t);
9927         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9928
9929         if (ctx == error_mark_node || name == error_mark_node)
9930           return error_mark_node;
9931
9932         if (parm_list)
9933           parm_list = tsubst_template_parms (parm_list, args, complain);
9934         return make_unbound_class_template (ctx, name, parm_list, complain);
9935       }
9936
9937     case INDIRECT_REF:
9938     case ADDR_EXPR:
9939     case CALL_EXPR:
9940       gcc_unreachable ();
9941
9942     case ARRAY_REF:
9943       {
9944         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9945         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9946                                /*integral_constant_expression_p=*/false);
9947         if (e1 == error_mark_node || e2 == error_mark_node)
9948           return error_mark_node;
9949
9950         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9951       }
9952
9953     case SCOPE_REF:
9954       {
9955         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9956         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9957         if (e1 == error_mark_node || e2 == error_mark_node)
9958           return error_mark_node;
9959
9960         return build_qualified_name (/*type=*/NULL_TREE,
9961                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9962       }
9963
9964     case TYPEOF_TYPE:
9965       {
9966         tree type;
9967
9968         type = finish_typeof (tsubst_expr 
9969                               (TYPEOF_TYPE_EXPR (t), args,
9970                                complain, in_decl,
9971                                /*integral_constant_expression_p=*/false));
9972         return cp_build_qualified_type_real (type,
9973                                              cp_type_quals (t)
9974                                              | cp_type_quals (type),
9975                                              complain);
9976       }
9977
9978     case DECLTYPE_TYPE:
9979       {
9980         tree type;
9981
9982         ++cp_unevaluated_operand;
9983         ++c_inhibit_evaluation_warnings;
9984
9985         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9986                             complain, in_decl,
9987                             /*integral_constant_expression_p=*/false);
9988
9989         --cp_unevaluated_operand;
9990         --c_inhibit_evaluation_warnings;
9991
9992         type =
9993           finish_decltype_type (type,
9994                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9995         return cp_build_qualified_type_real (type,
9996                                              cp_type_quals (t)
9997                                              | cp_type_quals (type),
9998                                              complain);
9999       }
10000
10001     case TYPE_ARGUMENT_PACK:
10002     case NONTYPE_ARGUMENT_PACK:
10003       {
10004         tree r = make_node (TREE_CODE (t));
10005         tree packed_out = 
10006           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10007                                 args,
10008                                 complain,
10009                                 in_decl);
10010         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10011
10012         /* For template nontype argument packs, also substitute into
10013            the type.  */
10014         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10015           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10016
10017         return r;
10018       }
10019       break;
10020
10021     default:
10022       sorry ("use of %qs in template",
10023              tree_code_name [(int) TREE_CODE (t)]);
10024       return error_mark_node;
10025     }
10026 }
10027
10028 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10029    type of the expression on the left-hand side of the "." or "->"
10030    operator.  */
10031
10032 static tree
10033 tsubst_baselink (tree baselink, tree object_type,
10034                  tree args, tsubst_flags_t complain, tree in_decl)
10035 {
10036     tree name;
10037     tree qualifying_scope;
10038     tree fns;
10039     tree optype;
10040     tree template_args = 0;
10041     bool template_id_p = false;
10042
10043     /* A baselink indicates a function from a base class.  Both the
10044        BASELINK_ACCESS_BINFO and the base class referenced may
10045        indicate bases of the template class, rather than the
10046        instantiated class.  In addition, lookups that were not
10047        ambiguous before may be ambiguous now.  Therefore, we perform
10048        the lookup again.  */
10049     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10050     qualifying_scope = tsubst (qualifying_scope, args,
10051                                complain, in_decl);
10052     fns = BASELINK_FUNCTIONS (baselink);
10053     optype = BASELINK_OPTYPE (baselink);
10054     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10055       {
10056         template_id_p = true;
10057         template_args = TREE_OPERAND (fns, 1);
10058         fns = TREE_OPERAND (fns, 0);
10059         if (template_args)
10060           template_args = tsubst_template_args (template_args, args,
10061                                                 complain, in_decl);
10062       }
10063     name = DECL_NAME (get_first_fn (fns));
10064     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10065
10066     /* If lookup found a single function, mark it as used at this
10067        point.  (If it lookup found multiple functions the one selected
10068        later by overload resolution will be marked as used at that
10069        point.)  */
10070     if (BASELINK_P (baselink))
10071       fns = BASELINK_FUNCTIONS (baselink);
10072     if (!template_id_p && !really_overloaded_fn (fns))
10073       mark_used (OVL_CURRENT (fns));
10074
10075     /* Add back the template arguments, if present.  */
10076     if (BASELINK_P (baselink) && template_id_p)
10077       BASELINK_FUNCTIONS (baselink)
10078         = build_nt (TEMPLATE_ID_EXPR,
10079                     BASELINK_FUNCTIONS (baselink),
10080                     template_args);
10081     /* Update the conversion operator type.  */
10082     BASELINK_OPTYPE (baselink) 
10083       = tsubst (optype, args, complain, in_decl);
10084
10085     if (!object_type)
10086       object_type = current_class_type;
10087     return adjust_result_of_qualified_name_lookup (baselink,
10088                                                    qualifying_scope,
10089                                                    object_type);
10090 }
10091
10092 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10093    true if the qualified-id will be a postfix-expression in-and-of
10094    itself; false if more of the postfix-expression follows the
10095    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10096    of "&".  */
10097
10098 static tree
10099 tsubst_qualified_id (tree qualified_id, tree args,
10100                      tsubst_flags_t complain, tree in_decl,
10101                      bool done, bool address_p)
10102 {
10103   tree expr;
10104   tree scope;
10105   tree name;
10106   bool is_template;
10107   tree template_args;
10108
10109   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10110
10111   /* Figure out what name to look up.  */
10112   name = TREE_OPERAND (qualified_id, 1);
10113   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10114     {
10115       is_template = true;
10116       template_args = TREE_OPERAND (name, 1);
10117       if (template_args)
10118         template_args = tsubst_template_args (template_args, args,
10119                                               complain, in_decl);
10120       name = TREE_OPERAND (name, 0);
10121     }
10122   else
10123     {
10124       is_template = false;
10125       template_args = NULL_TREE;
10126     }
10127
10128   /* Substitute into the qualifying scope.  When there are no ARGS, we
10129      are just trying to simplify a non-dependent expression.  In that
10130      case the qualifying scope may be dependent, and, in any case,
10131      substituting will not help.  */
10132   scope = TREE_OPERAND (qualified_id, 0);
10133   if (args)
10134     {
10135       scope = tsubst (scope, args, complain, in_decl);
10136       expr = tsubst_copy (name, args, complain, in_decl);
10137     }
10138   else
10139     expr = name;
10140
10141   if (dependent_type_p (scope))
10142     {
10143       tree type = NULL_TREE;
10144       if (DECL_P (expr) && !dependent_scope_p (scope))
10145         type = TREE_TYPE (expr);
10146       return build_qualified_name (type, scope, expr,
10147                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10148     }
10149
10150   if (!BASELINK_P (name) && !DECL_P (expr))
10151     {
10152       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10153         {
10154           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10155           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10156             {
10157               error ("qualifying type %qT does not match destructor name ~%qT",
10158                      scope, TREE_OPERAND (expr, 0));
10159               expr = error_mark_node;
10160             }
10161           else
10162             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10163                                           /*is_type_p=*/0, false);
10164         }
10165       else
10166         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10167       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10168                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10169         {
10170           if (complain & tf_error)
10171             {
10172               error ("dependent-name %qE is parsed as a non-type, but "
10173                      "instantiation yields a type", qualified_id);
10174               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10175             }
10176           return error_mark_node;
10177         }
10178     }
10179
10180   if (DECL_P (expr))
10181     {
10182       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10183                                            scope);
10184       /* Remember that there was a reference to this entity.  */
10185       mark_used (expr);
10186     }
10187
10188   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10189     {
10190       if (complain & tf_error)
10191         qualified_name_lookup_error (scope,
10192                                      TREE_OPERAND (qualified_id, 1),
10193                                      expr, input_location);
10194       return error_mark_node;
10195     }
10196
10197   if (is_template)
10198     expr = lookup_template_function (expr, template_args);
10199
10200   if (expr == error_mark_node && complain & tf_error)
10201     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10202                                  expr, input_location);
10203   else if (TYPE_P (scope))
10204     {
10205       expr = (adjust_result_of_qualified_name_lookup
10206               (expr, scope, current_class_type));
10207       expr = (finish_qualified_id_expr
10208               (scope, expr, done, address_p,
10209                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10210                /*template_arg_p=*/false));
10211     }
10212
10213   /* Expressions do not generally have reference type.  */
10214   if (TREE_CODE (expr) != SCOPE_REF
10215       /* However, if we're about to form a pointer-to-member, we just
10216          want the referenced member referenced.  */
10217       && TREE_CODE (expr) != OFFSET_REF)
10218     expr = convert_from_reference (expr);
10219
10220   return expr;
10221 }
10222
10223 /* Like tsubst, but deals with expressions.  This function just replaces
10224    template parms; to finish processing the resultant expression, use
10225    tsubst_expr.  */
10226
10227 static tree
10228 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10229 {
10230   enum tree_code code;
10231   tree r;
10232
10233   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10234     return t;
10235
10236   code = TREE_CODE (t);
10237
10238   switch (code)
10239     {
10240     case PARM_DECL:
10241       r = retrieve_local_specialization (t);
10242
10243       if (r == NULL)
10244         {
10245           tree c;
10246           /* This can happen for a parameter name used later in a function
10247              declaration (such as in a late-specified return type).  Just
10248              make a dummy decl, since it's only used for its type.  */
10249           gcc_assert (cp_unevaluated_operand != 0);
10250           /* We copy T because want to tsubst the PARM_DECL only,
10251              not the following PARM_DECLs that are chained to T.  */
10252           c = copy_node (t);
10253           r = tsubst_decl (c, args, complain);
10254           /* Give it the template pattern as its context; its true context
10255              hasn't been instantiated yet and this is good enough for
10256              mangling.  */
10257           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10258         }
10259       
10260       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10261         r = ARGUMENT_PACK_SELECT_ARG (r);
10262       mark_used (r);
10263       return r;
10264
10265     case CONST_DECL:
10266       {
10267         tree enum_type;
10268         tree v;
10269
10270         if (DECL_TEMPLATE_PARM_P (t))
10271           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10272         /* There is no need to substitute into namespace-scope
10273            enumerators.  */
10274         if (DECL_NAMESPACE_SCOPE_P (t))
10275           return t;
10276         /* If ARGS is NULL, then T is known to be non-dependent.  */
10277         if (args == NULL_TREE)
10278           return integral_constant_value (t);
10279
10280         /* Unfortunately, we cannot just call lookup_name here.
10281            Consider:
10282
10283              template <int I> int f() {
10284              enum E { a = I };
10285              struct S { void g() { E e = a; } };
10286              };
10287
10288            When we instantiate f<7>::S::g(), say, lookup_name is not
10289            clever enough to find f<7>::a.  */
10290         enum_type
10291           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10292                               /*entering_scope=*/0);
10293
10294         for (v = TYPE_VALUES (enum_type);
10295              v != NULL_TREE;
10296              v = TREE_CHAIN (v))
10297           if (TREE_PURPOSE (v) == DECL_NAME (t))
10298             return TREE_VALUE (v);
10299
10300           /* We didn't find the name.  That should never happen; if
10301              name-lookup found it during preliminary parsing, we
10302              should find it again here during instantiation.  */
10303         gcc_unreachable ();
10304       }
10305       return t;
10306
10307     case FIELD_DECL:
10308       if (DECL_CONTEXT (t))
10309         {
10310           tree ctx;
10311
10312           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10313                                   /*entering_scope=*/1);
10314           if (ctx != DECL_CONTEXT (t))
10315             {
10316               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10317               if (!r)
10318                 {
10319                   if (complain & tf_error)
10320                     error ("using invalid field %qD", t);
10321                   return error_mark_node;
10322                 }
10323               return r;
10324             }
10325         }
10326
10327       return t;
10328
10329     case VAR_DECL:
10330     case FUNCTION_DECL:
10331       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10332           || local_variable_p (t))
10333         t = tsubst (t, args, complain, in_decl);
10334       mark_used (t);
10335       return t;
10336
10337     case BASELINK:
10338       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10339
10340     case TEMPLATE_DECL:
10341       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10342         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10343                        args, complain, in_decl);
10344       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10345         return tsubst (t, args, complain, in_decl);
10346       else if (DECL_CLASS_SCOPE_P (t)
10347                && uses_template_parms (DECL_CONTEXT (t)))
10348         {
10349           /* Template template argument like the following example need
10350              special treatment:
10351
10352                template <template <class> class TT> struct C {};
10353                template <class T> struct D {
10354                  template <class U> struct E {};
10355                  C<E> c;                                // #1
10356                };
10357                D<int> d;                                // #2
10358
10359              We are processing the template argument `E' in #1 for
10360              the template instantiation #2.  Originally, `E' is a
10361              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10362              have to substitute this with one having context `D<int>'.  */
10363
10364           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10365           return lookup_field (context, DECL_NAME(t), 0, false);
10366         }
10367       else
10368         /* Ordinary template template argument.  */
10369         return t;
10370
10371     case CAST_EXPR:
10372     case REINTERPRET_CAST_EXPR:
10373     case CONST_CAST_EXPR:
10374     case STATIC_CAST_EXPR:
10375     case DYNAMIC_CAST_EXPR:
10376     case NOP_EXPR:
10377       return build1
10378         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10379          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10380
10381     case SIZEOF_EXPR:
10382       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10383         {
10384           /* We only want to compute the number of arguments.  */
10385           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10386                                                 complain, in_decl);
10387           int len = 0;
10388
10389           if (TREE_CODE (expanded) == TREE_VEC)
10390             len = TREE_VEC_LENGTH (expanded);
10391
10392           if (expanded == error_mark_node)
10393             return error_mark_node;
10394           else if (PACK_EXPANSION_P (expanded)
10395                    || (TREE_CODE (expanded) == TREE_VEC
10396                        && len > 0
10397                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10398             {
10399               if (TREE_CODE (expanded) == TREE_VEC)
10400                 expanded = TREE_VEC_ELT (expanded, len - 1);
10401
10402               if (TYPE_P (expanded))
10403                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10404                                                    complain & tf_error);
10405               else
10406                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10407                                                    complain & tf_error);
10408             }
10409           else
10410             return build_int_cst (size_type_node, len);
10411         }
10412       /* Fall through */
10413
10414     case INDIRECT_REF:
10415     case NEGATE_EXPR:
10416     case TRUTH_NOT_EXPR:
10417     case BIT_NOT_EXPR:
10418     case ADDR_EXPR:
10419     case UNARY_PLUS_EXPR:      /* Unary + */
10420     case ALIGNOF_EXPR:
10421     case ARROW_EXPR:
10422     case THROW_EXPR:
10423     case TYPEID_EXPR:
10424     case REALPART_EXPR:
10425     case IMAGPART_EXPR:
10426       return build1
10427         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10428          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10429
10430     case COMPONENT_REF:
10431       {
10432         tree object;
10433         tree name;
10434
10435         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10436         name = TREE_OPERAND (t, 1);
10437         if (TREE_CODE (name) == BIT_NOT_EXPR)
10438           {
10439             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10440                                 complain, in_decl);
10441             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10442           }
10443         else if (TREE_CODE (name) == SCOPE_REF
10444                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10445           {
10446             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10447                                      complain, in_decl);
10448             name = TREE_OPERAND (name, 1);
10449             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10450                                 complain, in_decl);
10451             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10452             name = build_qualified_name (/*type=*/NULL_TREE,
10453                                          base, name,
10454                                          /*template_p=*/false);
10455           }
10456         else if (TREE_CODE (name) == BASELINK)
10457           name = tsubst_baselink (name,
10458                                   non_reference (TREE_TYPE (object)),
10459                                   args, complain,
10460                                   in_decl);
10461         else
10462           name = tsubst_copy (name, args, complain, in_decl);
10463         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10464       }
10465
10466     case PLUS_EXPR:
10467     case MINUS_EXPR:
10468     case MULT_EXPR:
10469     case TRUNC_DIV_EXPR:
10470     case CEIL_DIV_EXPR:
10471     case FLOOR_DIV_EXPR:
10472     case ROUND_DIV_EXPR:
10473     case EXACT_DIV_EXPR:
10474     case BIT_AND_EXPR:
10475     case BIT_IOR_EXPR:
10476     case BIT_XOR_EXPR:
10477     case TRUNC_MOD_EXPR:
10478     case FLOOR_MOD_EXPR:
10479     case TRUTH_ANDIF_EXPR:
10480     case TRUTH_ORIF_EXPR:
10481     case TRUTH_AND_EXPR:
10482     case TRUTH_OR_EXPR:
10483     case RSHIFT_EXPR:
10484     case LSHIFT_EXPR:
10485     case RROTATE_EXPR:
10486     case LROTATE_EXPR:
10487     case EQ_EXPR:
10488     case NE_EXPR:
10489     case MAX_EXPR:
10490     case MIN_EXPR:
10491     case LE_EXPR:
10492     case GE_EXPR:
10493     case LT_EXPR:
10494     case GT_EXPR:
10495     case COMPOUND_EXPR:
10496     case DOTSTAR_EXPR:
10497     case MEMBER_REF:
10498     case PREDECREMENT_EXPR:
10499     case PREINCREMENT_EXPR:
10500     case POSTDECREMENT_EXPR:
10501     case POSTINCREMENT_EXPR:
10502       return build_nt
10503         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10504          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10505
10506     case SCOPE_REF:
10507       return build_qualified_name (/*type=*/NULL_TREE,
10508                                    tsubst_copy (TREE_OPERAND (t, 0),
10509                                                 args, complain, in_decl),
10510                                    tsubst_copy (TREE_OPERAND (t, 1),
10511                                                 args, complain, in_decl),
10512                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10513
10514     case ARRAY_REF:
10515       return build_nt
10516         (ARRAY_REF,
10517          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10518          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10519          NULL_TREE, NULL_TREE);
10520
10521     case CALL_EXPR:
10522       {
10523         int n = VL_EXP_OPERAND_LENGTH (t);
10524         tree result = build_vl_exp (CALL_EXPR, n);
10525         int i;
10526         for (i = 0; i < n; i++)
10527           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10528                                              complain, in_decl);
10529         return result;
10530       }
10531
10532     case COND_EXPR:
10533     case MODOP_EXPR:
10534     case PSEUDO_DTOR_EXPR:
10535       {
10536         r = build_nt
10537           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10538            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10539            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10540         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10541         return r;
10542       }
10543
10544     case NEW_EXPR:
10545       {
10546         r = build_nt
10547         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10548          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10549          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10550         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10551         return r;
10552       }
10553
10554     case DELETE_EXPR:
10555       {
10556         r = build_nt
10557         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10558          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10559         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10560         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10561         return r;
10562       }
10563
10564     case TEMPLATE_ID_EXPR:
10565       {
10566         /* Substituted template arguments */
10567         tree fn = TREE_OPERAND (t, 0);
10568         tree targs = TREE_OPERAND (t, 1);
10569
10570         fn = tsubst_copy (fn, args, complain, in_decl);
10571         if (targs)
10572           targs = tsubst_template_args (targs, args, complain, in_decl);
10573
10574         return lookup_template_function (fn, targs);
10575       }
10576
10577     case TREE_LIST:
10578       {
10579         tree purpose, value, chain;
10580
10581         if (t == void_list_node)
10582           return t;
10583
10584         purpose = TREE_PURPOSE (t);
10585         if (purpose)
10586           purpose = tsubst_copy (purpose, args, complain, in_decl);
10587         value = TREE_VALUE (t);
10588         if (value)
10589           value = tsubst_copy (value, args, complain, in_decl);
10590         chain = TREE_CHAIN (t);
10591         if (chain && chain != void_type_node)
10592           chain = tsubst_copy (chain, args, complain, in_decl);
10593         if (purpose == TREE_PURPOSE (t)
10594             && value == TREE_VALUE (t)
10595             && chain == TREE_CHAIN (t))
10596           return t;
10597         return tree_cons (purpose, value, chain);
10598       }
10599
10600     case RECORD_TYPE:
10601     case UNION_TYPE:
10602     case ENUMERAL_TYPE:
10603     case INTEGER_TYPE:
10604     case TEMPLATE_TYPE_PARM:
10605     case TEMPLATE_TEMPLATE_PARM:
10606     case BOUND_TEMPLATE_TEMPLATE_PARM:
10607     case TEMPLATE_PARM_INDEX:
10608     case POINTER_TYPE:
10609     case REFERENCE_TYPE:
10610     case OFFSET_TYPE:
10611     case FUNCTION_TYPE:
10612     case METHOD_TYPE:
10613     case ARRAY_TYPE:
10614     case TYPENAME_TYPE:
10615     case UNBOUND_CLASS_TEMPLATE:
10616     case TYPEOF_TYPE:
10617     case DECLTYPE_TYPE:
10618     case TYPE_DECL:
10619       return tsubst (t, args, complain, in_decl);
10620
10621     case IDENTIFIER_NODE:
10622       if (IDENTIFIER_TYPENAME_P (t))
10623         {
10624           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10625           return mangle_conv_op_name_for_type (new_type);
10626         }
10627       else
10628         return t;
10629
10630     case CONSTRUCTOR:
10631       /* This is handled by tsubst_copy_and_build.  */
10632       gcc_unreachable ();
10633
10634     case VA_ARG_EXPR:
10635       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10636                                           in_decl),
10637                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10638
10639     case CLEANUP_POINT_EXPR:
10640       /* We shouldn't have built any of these during initial template
10641          generation.  Instead, they should be built during instantiation
10642          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10643       gcc_unreachable ();
10644
10645     case OFFSET_REF:
10646       mark_used (TREE_OPERAND (t, 1));
10647       return t;
10648
10649     case EXPR_PACK_EXPANSION:
10650       error ("invalid use of pack expansion expression");
10651       return error_mark_node;
10652
10653     case NONTYPE_ARGUMENT_PACK:
10654       error ("use %<...%> to expand argument pack");
10655       return error_mark_node;
10656
10657     default:
10658       return t;
10659     }
10660 }
10661
10662 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10663
10664 static tree
10665 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10666                     tree in_decl)
10667 {
10668   tree new_clauses = NULL, nc, oc;
10669
10670   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10671     {
10672       nc = copy_node (oc);
10673       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10674       new_clauses = nc;
10675
10676       switch (OMP_CLAUSE_CODE (nc))
10677         {
10678         case OMP_CLAUSE_LASTPRIVATE:
10679           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10680             {
10681               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10682               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10683                            in_decl, /*integral_constant_expression_p=*/false);
10684               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10685                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10686             }
10687           /* FALLTHRU */
10688         case OMP_CLAUSE_PRIVATE:
10689         case OMP_CLAUSE_SHARED:
10690         case OMP_CLAUSE_FIRSTPRIVATE:
10691         case OMP_CLAUSE_REDUCTION:
10692         case OMP_CLAUSE_COPYIN:
10693         case OMP_CLAUSE_COPYPRIVATE:
10694         case OMP_CLAUSE_IF:
10695         case OMP_CLAUSE_NUM_THREADS:
10696         case OMP_CLAUSE_SCHEDULE:
10697         case OMP_CLAUSE_COLLAPSE:
10698           OMP_CLAUSE_OPERAND (nc, 0)
10699             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10700                            in_decl, /*integral_constant_expression_p=*/false);
10701           break;
10702         case OMP_CLAUSE_NOWAIT:
10703         case OMP_CLAUSE_ORDERED:
10704         case OMP_CLAUSE_DEFAULT:
10705         case OMP_CLAUSE_UNTIED:
10706           break;
10707         default:
10708           gcc_unreachable ();
10709         }
10710     }
10711
10712   return finish_omp_clauses (nreverse (new_clauses));
10713 }
10714
10715 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10716
10717 static tree
10718 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10719                           tree in_decl)
10720 {
10721 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10722
10723   tree purpose, value, chain;
10724
10725   if (t == NULL)
10726     return t;
10727
10728   if (TREE_CODE (t) != TREE_LIST)
10729     return tsubst_copy_and_build (t, args, complain, in_decl,
10730                                   /*function_p=*/false,
10731                                   /*integral_constant_expression_p=*/false);
10732
10733   if (t == void_list_node)
10734     return t;
10735
10736   purpose = TREE_PURPOSE (t);
10737   if (purpose)
10738     purpose = RECUR (purpose);
10739   value = TREE_VALUE (t);
10740   if (value)
10741     value = RECUR (value);
10742   chain = TREE_CHAIN (t);
10743   if (chain && chain != void_type_node)
10744     chain = RECUR (chain);
10745   return tree_cons (purpose, value, chain);
10746 #undef RECUR
10747 }
10748
10749 /* Substitute one OMP_FOR iterator.  */
10750
10751 static void
10752 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10753                          tree condv, tree incrv, tree *clauses,
10754                          tree args, tsubst_flags_t complain, tree in_decl,
10755                          bool integral_constant_expression_p)
10756 {
10757 #define RECUR(NODE)                             \
10758   tsubst_expr ((NODE), args, complain, in_decl, \
10759                integral_constant_expression_p)
10760   tree decl, init, cond, incr, auto_node;
10761
10762   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10763   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10764   decl = RECUR (TREE_OPERAND (init, 0));
10765   init = TREE_OPERAND (init, 1);
10766   auto_node = type_uses_auto (TREE_TYPE (decl));
10767   if (auto_node && init)
10768     {
10769       tree init_expr = init;
10770       if (TREE_CODE (init_expr) == DECL_EXPR)
10771         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10772       init_expr = RECUR (init_expr);
10773       TREE_TYPE (decl)
10774         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10775     }
10776   gcc_assert (!type_dependent_expression_p (decl));
10777
10778   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10779     {
10780       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10781       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10782       if (TREE_CODE (incr) == MODIFY_EXPR)
10783         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10784                                     RECUR (TREE_OPERAND (incr, 1)),
10785                                     complain);
10786       else
10787         incr = RECUR (incr);
10788       TREE_VEC_ELT (declv, i) = decl;
10789       TREE_VEC_ELT (initv, i) = init;
10790       TREE_VEC_ELT (condv, i) = cond;
10791       TREE_VEC_ELT (incrv, i) = incr;
10792       return;
10793     }
10794
10795   if (init && TREE_CODE (init) != DECL_EXPR)
10796     {
10797       tree c;
10798       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10799         {
10800           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10801                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10802               && OMP_CLAUSE_DECL (c) == decl)
10803             break;
10804           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10805                    && OMP_CLAUSE_DECL (c) == decl)
10806             error ("iteration variable %qD should not be firstprivate", decl);
10807           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10808                    && OMP_CLAUSE_DECL (c) == decl)
10809             error ("iteration variable %qD should not be reduction", decl);
10810         }
10811       if (c == NULL)
10812         {
10813           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
10814           OMP_CLAUSE_DECL (c) = decl;
10815           c = finish_omp_clauses (c);
10816           if (c)
10817             {
10818               OMP_CLAUSE_CHAIN (c) = *clauses;
10819               *clauses = c;
10820             }
10821         }
10822     }
10823   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10824   if (COMPARISON_CLASS_P (cond))
10825     cond = build2 (TREE_CODE (cond), boolean_type_node,
10826                    RECUR (TREE_OPERAND (cond, 0)),
10827                    RECUR (TREE_OPERAND (cond, 1)));
10828   else
10829     cond = RECUR (cond);
10830   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10831   switch (TREE_CODE (incr))
10832     {
10833     case PREINCREMENT_EXPR:
10834     case PREDECREMENT_EXPR:
10835     case POSTINCREMENT_EXPR:
10836     case POSTDECREMENT_EXPR:
10837       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10838                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10839       break;
10840     case MODIFY_EXPR:
10841       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10842           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10843         {
10844           tree rhs = TREE_OPERAND (incr, 1);
10845           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10846                          RECUR (TREE_OPERAND (incr, 0)),
10847                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10848                                  RECUR (TREE_OPERAND (rhs, 0)),
10849                                  RECUR (TREE_OPERAND (rhs, 1))));
10850         }
10851       else
10852         incr = RECUR (incr);
10853       break;
10854     case MODOP_EXPR:
10855       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10856           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10857         {
10858           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10859           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10860                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10861                                  TREE_TYPE (decl), lhs,
10862                                  RECUR (TREE_OPERAND (incr, 2))));
10863         }
10864       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10865                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10866                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10867         {
10868           tree rhs = TREE_OPERAND (incr, 2);
10869           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10870                          RECUR (TREE_OPERAND (incr, 0)),
10871                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10872                                  RECUR (TREE_OPERAND (rhs, 0)),
10873                                  RECUR (TREE_OPERAND (rhs, 1))));
10874         }
10875       else
10876         incr = RECUR (incr);
10877       break;
10878     default:
10879       incr = RECUR (incr);
10880       break;
10881     }
10882
10883   TREE_VEC_ELT (declv, i) = decl;
10884   TREE_VEC_ELT (initv, i) = init;
10885   TREE_VEC_ELT (condv, i) = cond;
10886   TREE_VEC_ELT (incrv, i) = incr;
10887 #undef RECUR
10888 }
10889
10890 /* Like tsubst_copy for expressions, etc. but also does semantic
10891    processing.  */
10892
10893 static tree
10894 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10895              bool integral_constant_expression_p)
10896 {
10897 #define RECUR(NODE)                             \
10898   tsubst_expr ((NODE), args, complain, in_decl, \
10899                integral_constant_expression_p)
10900
10901   tree stmt, tmp;
10902
10903   if (t == NULL_TREE || t == error_mark_node)
10904     return t;
10905
10906   if (EXPR_HAS_LOCATION (t))
10907     input_location = EXPR_LOCATION (t);
10908   if (STATEMENT_CODE_P (TREE_CODE (t)))
10909     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10910
10911   switch (TREE_CODE (t))
10912     {
10913     case STATEMENT_LIST:
10914       {
10915         tree_stmt_iterator i;
10916         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10917           RECUR (tsi_stmt (i));
10918         break;
10919       }
10920
10921     case CTOR_INITIALIZER:
10922       finish_mem_initializers (tsubst_initializer_list
10923                                (TREE_OPERAND (t, 0), args));
10924       break;
10925
10926     case RETURN_EXPR:
10927       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10928       break;
10929
10930     case EXPR_STMT:
10931       tmp = RECUR (EXPR_STMT_EXPR (t));
10932       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10933         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10934       else
10935         finish_expr_stmt (tmp);
10936       break;
10937
10938     case USING_STMT:
10939       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10940       break;
10941
10942     case DECL_EXPR:
10943       {
10944         tree decl;
10945         tree init;
10946
10947         decl = DECL_EXPR_DECL (t);
10948         if (TREE_CODE (decl) == LABEL_DECL)
10949           finish_label_decl (DECL_NAME (decl));
10950         else if (TREE_CODE (decl) == USING_DECL)
10951           {
10952             tree scope = USING_DECL_SCOPE (decl);
10953             tree name = DECL_NAME (decl);
10954             tree decl;
10955
10956             scope = RECUR (scope);
10957             decl = lookup_qualified_name (scope, name,
10958                                           /*is_type_p=*/false,
10959                                           /*complain=*/false);
10960             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10961               qualified_name_lookup_error (scope, name, decl, input_location);
10962             else
10963               do_local_using_decl (decl, scope, name);
10964           }
10965         else
10966           {
10967             init = DECL_INITIAL (decl);
10968             decl = tsubst (decl, args, complain, in_decl);
10969             if (decl != error_mark_node)
10970               {
10971                 /* By marking the declaration as instantiated, we avoid
10972                    trying to instantiate it.  Since instantiate_decl can't
10973                    handle local variables, and since we've already done
10974                    all that needs to be done, that's the right thing to
10975                    do.  */
10976                 if (TREE_CODE (decl) == VAR_DECL)
10977                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10978                 if (TREE_CODE (decl) == VAR_DECL
10979                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10980                   /* Anonymous aggregates are a special case.  */
10981                   finish_anon_union (decl);
10982                 else
10983                   {
10984                     maybe_push_decl (decl);
10985                     if (TREE_CODE (decl) == VAR_DECL
10986                         && DECL_PRETTY_FUNCTION_P (decl))
10987                       {
10988                         /* For __PRETTY_FUNCTION__ we have to adjust the
10989                            initializer.  */
10990                         const char *const name
10991                           = cxx_printable_name (current_function_decl, 2);
10992                         init = cp_fname_init (name, &TREE_TYPE (decl));
10993                       }
10994                     else
10995                       {
10996                         tree t = RECUR (init);
10997
10998                         if (init && !t)
10999                           /* If we had an initializer but it
11000                              instantiated to nothing,
11001                              value-initialize the object.  This will
11002                              only occur when the initializer was a
11003                              pack expansion where the parameter packs
11004                              used in that expansion were of length
11005                              zero.  */
11006                           init = build_value_init (TREE_TYPE (decl));
11007                         else
11008                           init = t;
11009                       }
11010
11011                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11012                   }
11013               }
11014           }
11015
11016         /* A DECL_EXPR can also be used as an expression, in the condition
11017            clause of an if/for/while construct.  */
11018         return decl;
11019       }
11020
11021     case FOR_STMT:
11022       stmt = begin_for_stmt ();
11023                           RECUR (FOR_INIT_STMT (t));
11024       finish_for_init_stmt (stmt);
11025       tmp = RECUR (FOR_COND (t));
11026       finish_for_cond (tmp, stmt);
11027       tmp = RECUR (FOR_EXPR (t));
11028       finish_for_expr (tmp, stmt);
11029       RECUR (FOR_BODY (t));
11030       finish_for_stmt (stmt);
11031       break;
11032
11033     case WHILE_STMT:
11034       stmt = begin_while_stmt ();
11035       tmp = RECUR (WHILE_COND (t));
11036       finish_while_stmt_cond (tmp, stmt);
11037       RECUR (WHILE_BODY (t));
11038       finish_while_stmt (stmt);
11039       break;
11040
11041     case DO_STMT:
11042       stmt = begin_do_stmt ();
11043       RECUR (DO_BODY (t));
11044       finish_do_body (stmt);
11045       tmp = RECUR (DO_COND (t));
11046       finish_do_stmt (tmp, stmt);
11047       break;
11048
11049     case IF_STMT:
11050       stmt = begin_if_stmt ();
11051       tmp = RECUR (IF_COND (t));
11052       finish_if_stmt_cond (tmp, stmt);
11053       RECUR (THEN_CLAUSE (t));
11054       finish_then_clause (stmt);
11055
11056       if (ELSE_CLAUSE (t))
11057         {
11058           begin_else_clause (stmt);
11059           RECUR (ELSE_CLAUSE (t));
11060           finish_else_clause (stmt);
11061         }
11062
11063       finish_if_stmt (stmt);
11064       break;
11065
11066     case BIND_EXPR:
11067       if (BIND_EXPR_BODY_BLOCK (t))
11068         stmt = begin_function_body ();
11069       else
11070         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11071                                     ? BCS_TRY_BLOCK : 0);
11072
11073       RECUR (BIND_EXPR_BODY (t));
11074
11075       if (BIND_EXPR_BODY_BLOCK (t))
11076         finish_function_body (stmt);
11077       else
11078         finish_compound_stmt (stmt);
11079       break;
11080
11081     case BREAK_STMT:
11082       finish_break_stmt ();
11083       break;
11084
11085     case CONTINUE_STMT:
11086       finish_continue_stmt ();
11087       break;
11088
11089     case SWITCH_STMT:
11090       stmt = begin_switch_stmt ();
11091       tmp = RECUR (SWITCH_STMT_COND (t));
11092       finish_switch_cond (tmp, stmt);
11093       RECUR (SWITCH_STMT_BODY (t));
11094       finish_switch_stmt (stmt);
11095       break;
11096
11097     case CASE_LABEL_EXPR:
11098       finish_case_label (EXPR_LOCATION (t),
11099                          RECUR (CASE_LOW (t)),
11100                          RECUR (CASE_HIGH (t)));
11101       break;
11102
11103     case LABEL_EXPR:
11104       {
11105         tree decl = LABEL_EXPR_LABEL (t);
11106         tree label;
11107
11108         label = finish_label_stmt (DECL_NAME (decl));
11109         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11110           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11111       }
11112       break;
11113
11114     case GOTO_EXPR:
11115       tmp = GOTO_DESTINATION (t);
11116       if (TREE_CODE (tmp) != LABEL_DECL)
11117         /* Computed goto's must be tsubst'd into.  On the other hand,
11118            non-computed gotos must not be; the identifier in question
11119            will have no binding.  */
11120         tmp = RECUR (tmp);
11121       else
11122         tmp = DECL_NAME (tmp);
11123       finish_goto_stmt (tmp);
11124       break;
11125
11126     case ASM_EXPR:
11127       tmp = finish_asm_stmt
11128         (ASM_VOLATILE_P (t),
11129          RECUR (ASM_STRING (t)),
11130          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11131          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11132          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
11133       {
11134         tree asm_expr = tmp;
11135         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11136           asm_expr = TREE_OPERAND (asm_expr, 0);
11137         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11138       }
11139       break;
11140
11141     case TRY_BLOCK:
11142       if (CLEANUP_P (t))
11143         {
11144           stmt = begin_try_block ();
11145           RECUR (TRY_STMTS (t));
11146           finish_cleanup_try_block (stmt);
11147           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11148         }
11149       else
11150         {
11151           tree compound_stmt = NULL_TREE;
11152
11153           if (FN_TRY_BLOCK_P (t))
11154             stmt = begin_function_try_block (&compound_stmt);
11155           else
11156             stmt = begin_try_block ();
11157
11158           RECUR (TRY_STMTS (t));
11159
11160           if (FN_TRY_BLOCK_P (t))
11161             finish_function_try_block (stmt);
11162           else
11163             finish_try_block (stmt);
11164
11165           RECUR (TRY_HANDLERS (t));
11166           if (FN_TRY_BLOCK_P (t))
11167             finish_function_handler_sequence (stmt, compound_stmt);
11168           else
11169             finish_handler_sequence (stmt);
11170         }
11171       break;
11172
11173     case HANDLER:
11174       {
11175         tree decl = HANDLER_PARMS (t);
11176
11177         if (decl)
11178           {
11179             decl = tsubst (decl, args, complain, in_decl);
11180             /* Prevent instantiate_decl from trying to instantiate
11181                this variable.  We've already done all that needs to be
11182                done.  */
11183             if (decl != error_mark_node)
11184               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11185           }
11186         stmt = begin_handler ();
11187         finish_handler_parms (decl, stmt);
11188         RECUR (HANDLER_BODY (t));
11189         finish_handler (stmt);
11190       }
11191       break;
11192
11193     case TAG_DEFN:
11194       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11195       break;
11196
11197     case STATIC_ASSERT:
11198       {
11199         tree condition = 
11200           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11201                        args,
11202                        complain, in_decl,
11203                        /*integral_constant_expression_p=*/true);
11204         finish_static_assert (condition,
11205                               STATIC_ASSERT_MESSAGE (t),
11206                               STATIC_ASSERT_SOURCE_LOCATION (t),
11207                               /*member_p=*/false);
11208       }
11209       break;
11210
11211     case OMP_PARALLEL:
11212       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11213                                 args, complain, in_decl);
11214       stmt = begin_omp_parallel ();
11215       RECUR (OMP_PARALLEL_BODY (t));
11216       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11217         = OMP_PARALLEL_COMBINED (t);
11218       break;
11219
11220     case OMP_TASK:
11221       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11222                                 args, complain, in_decl);
11223       stmt = begin_omp_task ();
11224       RECUR (OMP_TASK_BODY (t));
11225       finish_omp_task (tmp, stmt);
11226       break;
11227
11228     case OMP_FOR:
11229       {
11230         tree clauses, body, pre_body;
11231         tree declv, initv, condv, incrv;
11232         int i;
11233
11234         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11235                                       args, complain, in_decl);
11236         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11237         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11238         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11239         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11240
11241         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11242           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11243                                    &clauses, args, complain, in_decl,
11244                                    integral_constant_expression_p);
11245
11246         stmt = begin_omp_structured_block ();
11247
11248         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11249           if (TREE_VEC_ELT (initv, i) == NULL
11250               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11251             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11252           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11253             {
11254               tree init = RECUR (TREE_VEC_ELT (initv, i));
11255               gcc_assert (init == TREE_VEC_ELT (declv, i));
11256               TREE_VEC_ELT (initv, i) = NULL_TREE;
11257             }
11258           else
11259             {
11260               tree decl_expr = TREE_VEC_ELT (initv, i);
11261               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11262               gcc_assert (init != NULL);
11263               TREE_VEC_ELT (initv, i) = RECUR (init);
11264               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11265               RECUR (decl_expr);
11266               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11267             }
11268
11269         pre_body = push_stmt_list ();
11270         RECUR (OMP_FOR_PRE_BODY (t));
11271         pre_body = pop_stmt_list (pre_body);
11272
11273         body = push_stmt_list ();
11274         RECUR (OMP_FOR_BODY (t));
11275         body = pop_stmt_list (body);
11276
11277         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11278                             body, pre_body, clauses);
11279
11280         add_stmt (finish_omp_structured_block (stmt));
11281       }
11282       break;
11283
11284     case OMP_SECTIONS:
11285     case OMP_SINGLE:
11286       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11287       stmt = push_stmt_list ();
11288       RECUR (OMP_BODY (t));
11289       stmt = pop_stmt_list (stmt);
11290
11291       t = copy_node (t);
11292       OMP_BODY (t) = stmt;
11293       OMP_CLAUSES (t) = tmp;
11294       add_stmt (t);
11295       break;
11296
11297     case OMP_SECTION:
11298     case OMP_CRITICAL:
11299     case OMP_MASTER:
11300     case OMP_ORDERED:
11301       stmt = push_stmt_list ();
11302       RECUR (OMP_BODY (t));
11303       stmt = pop_stmt_list (stmt);
11304
11305       t = copy_node (t);
11306       OMP_BODY (t) = stmt;
11307       add_stmt (t);
11308       break;
11309
11310     case OMP_ATOMIC:
11311       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11312       {
11313         tree op1 = TREE_OPERAND (t, 1);
11314         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11315         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11316         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11317       }
11318       break;
11319
11320     case EXPR_PACK_EXPANSION:
11321       error ("invalid use of pack expansion expression");
11322       return error_mark_node;
11323
11324     case NONTYPE_ARGUMENT_PACK:
11325       error ("use %<...%> to expand argument pack");
11326       return error_mark_node;
11327
11328     default:
11329       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11330
11331       return tsubst_copy_and_build (t, args, complain, in_decl,
11332                                     /*function_p=*/false,
11333                                     integral_constant_expression_p);
11334     }
11335
11336   return NULL_TREE;
11337 #undef RECUR
11338 }
11339
11340 /* T is a postfix-expression that is not being used in a function
11341    call.  Return the substituted version of T.  */
11342
11343 static tree
11344 tsubst_non_call_postfix_expression (tree t, tree args,
11345                                     tsubst_flags_t complain,
11346                                     tree in_decl)
11347 {
11348   if (TREE_CODE (t) == SCOPE_REF)
11349     t = tsubst_qualified_id (t, args, complain, in_decl,
11350                              /*done=*/false, /*address_p=*/false);
11351   else
11352     t = tsubst_copy_and_build (t, args, complain, in_decl,
11353                                /*function_p=*/false,
11354                                /*integral_constant_expression_p=*/false);
11355
11356   return t;
11357 }
11358
11359 /* Like tsubst but deals with expressions and performs semantic
11360    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11361
11362 tree
11363 tsubst_copy_and_build (tree t,
11364                        tree args,
11365                        tsubst_flags_t complain,
11366                        tree in_decl,
11367                        bool function_p,
11368                        bool integral_constant_expression_p)
11369 {
11370 #define RECUR(NODE)                                             \
11371   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11372                          /*function_p=*/false,                  \
11373                          integral_constant_expression_p)
11374
11375   tree op1;
11376
11377   if (t == NULL_TREE || t == error_mark_node)
11378     return t;
11379
11380   switch (TREE_CODE (t))
11381     {
11382     case USING_DECL:
11383       t = DECL_NAME (t);
11384       /* Fall through.  */
11385     case IDENTIFIER_NODE:
11386       {
11387         tree decl;
11388         cp_id_kind idk;
11389         bool non_integral_constant_expression_p;
11390         const char *error_msg;
11391
11392         if (IDENTIFIER_TYPENAME_P (t))
11393           {
11394             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11395             t = mangle_conv_op_name_for_type (new_type);
11396           }
11397
11398         /* Look up the name.  */
11399         decl = lookup_name (t);
11400
11401         /* By convention, expressions use ERROR_MARK_NODE to indicate
11402            failure, not NULL_TREE.  */
11403         if (decl == NULL_TREE)
11404           decl = error_mark_node;
11405
11406         decl = finish_id_expression (t, decl, NULL_TREE,
11407                                      &idk,
11408                                      integral_constant_expression_p,
11409                                      /*allow_non_integral_constant_expression_p=*/false,
11410                                      &non_integral_constant_expression_p,
11411                                      /*template_p=*/false,
11412                                      /*done=*/true,
11413                                      /*address_p=*/false,
11414                                      /*template_arg_p=*/false,
11415                                      &error_msg,
11416                                      input_location);
11417         if (error_msg)
11418           error (error_msg);
11419         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11420           decl = unqualified_name_lookup_error (decl);
11421         return decl;
11422       }
11423
11424     case TEMPLATE_ID_EXPR:
11425       {
11426         tree object;
11427         tree templ = RECUR (TREE_OPERAND (t, 0));
11428         tree targs = TREE_OPERAND (t, 1);
11429
11430         if (targs)
11431           targs = tsubst_template_args (targs, args, complain, in_decl);
11432
11433         if (TREE_CODE (templ) == COMPONENT_REF)
11434           {
11435             object = TREE_OPERAND (templ, 0);
11436             templ = TREE_OPERAND (templ, 1);
11437           }
11438         else
11439           object = NULL_TREE;
11440         templ = lookup_template_function (templ, targs);
11441
11442         if (object)
11443           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11444                          object, templ, NULL_TREE);
11445         else
11446           return baselink_for_fns (templ);
11447       }
11448
11449     case INDIRECT_REF:
11450       {
11451         tree r = RECUR (TREE_OPERAND (t, 0));
11452
11453         if (REFERENCE_REF_P (t))
11454           {
11455             /* A type conversion to reference type will be enclosed in
11456                such an indirect ref, but the substitution of the cast
11457                will have also added such an indirect ref.  */
11458             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11459               r = convert_from_reference (r);
11460           }
11461         else
11462           r = build_x_indirect_ref (r, "unary *", complain);
11463         return r;
11464       }
11465
11466     case NOP_EXPR:
11467       return build_nop
11468         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11469          RECUR (TREE_OPERAND (t, 0)));
11470
11471     case CAST_EXPR:
11472     case REINTERPRET_CAST_EXPR:
11473     case CONST_CAST_EXPR:
11474     case DYNAMIC_CAST_EXPR:
11475     case STATIC_CAST_EXPR:
11476       {
11477         tree type;
11478         tree op;
11479
11480         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11481         if (integral_constant_expression_p
11482             && !cast_valid_in_integral_constant_expression_p (type))
11483           {
11484             if (complain & tf_error)
11485               error ("a cast to a type other than an integral or "
11486                      "enumeration type cannot appear in a constant-expression");
11487             return error_mark_node; 
11488           }
11489
11490         op = RECUR (TREE_OPERAND (t, 0));
11491
11492         switch (TREE_CODE (t))
11493           {
11494           case CAST_EXPR:
11495             return build_functional_cast (type, op, complain);
11496           case REINTERPRET_CAST_EXPR:
11497             return build_reinterpret_cast (type, op, complain);
11498           case CONST_CAST_EXPR:
11499             return build_const_cast (type, op, complain);
11500           case DYNAMIC_CAST_EXPR:
11501             return build_dynamic_cast (type, op, complain);
11502           case STATIC_CAST_EXPR:
11503             return build_static_cast (type, op, complain);
11504           default:
11505             gcc_unreachable ();
11506           }
11507       }
11508
11509     case POSTDECREMENT_EXPR:
11510     case POSTINCREMENT_EXPR:
11511       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11512                                                 args, complain, in_decl);
11513       return build_x_unary_op (TREE_CODE (t), op1, complain);
11514
11515     case PREDECREMENT_EXPR:
11516     case PREINCREMENT_EXPR:
11517     case NEGATE_EXPR:
11518     case BIT_NOT_EXPR:
11519     case ABS_EXPR:
11520     case TRUTH_NOT_EXPR:
11521     case UNARY_PLUS_EXPR:  /* Unary + */
11522     case REALPART_EXPR:
11523     case IMAGPART_EXPR:
11524       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11525                                complain);
11526
11527     case ADDR_EXPR:
11528       op1 = TREE_OPERAND (t, 0);
11529       if (TREE_CODE (op1) == SCOPE_REF)
11530         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11531                                    /*done=*/true, /*address_p=*/true);
11532       else
11533         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11534                                                   in_decl);
11535       if (TREE_CODE (op1) == LABEL_DECL)
11536         return finish_label_address_expr (DECL_NAME (op1),
11537                                           EXPR_LOCATION (op1));
11538       return build_x_unary_op (ADDR_EXPR, op1, complain);
11539
11540     case PLUS_EXPR:
11541     case MINUS_EXPR:
11542     case MULT_EXPR:
11543     case TRUNC_DIV_EXPR:
11544     case CEIL_DIV_EXPR:
11545     case FLOOR_DIV_EXPR:
11546     case ROUND_DIV_EXPR:
11547     case EXACT_DIV_EXPR:
11548     case BIT_AND_EXPR:
11549     case BIT_IOR_EXPR:
11550     case BIT_XOR_EXPR:
11551     case TRUNC_MOD_EXPR:
11552     case FLOOR_MOD_EXPR:
11553     case TRUTH_ANDIF_EXPR:
11554     case TRUTH_ORIF_EXPR:
11555     case TRUTH_AND_EXPR:
11556     case TRUTH_OR_EXPR:
11557     case RSHIFT_EXPR:
11558     case LSHIFT_EXPR:
11559     case RROTATE_EXPR:
11560     case LROTATE_EXPR:
11561     case EQ_EXPR:
11562     case NE_EXPR:
11563     case MAX_EXPR:
11564     case MIN_EXPR:
11565     case LE_EXPR:
11566     case GE_EXPR:
11567     case LT_EXPR:
11568     case GT_EXPR:
11569     case MEMBER_REF:
11570     case DOTSTAR_EXPR:
11571       return build_x_binary_op
11572         (TREE_CODE (t),
11573          RECUR (TREE_OPERAND (t, 0)),
11574          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11575           ? ERROR_MARK
11576           : TREE_CODE (TREE_OPERAND (t, 0))),
11577          RECUR (TREE_OPERAND (t, 1)),
11578          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11579           ? ERROR_MARK
11580           : TREE_CODE (TREE_OPERAND (t, 1))),
11581          /*overloaded_p=*/NULL,
11582          complain);
11583
11584     case SCOPE_REF:
11585       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11586                                   /*address_p=*/false);
11587     case ARRAY_REF:
11588       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11589                                                 args, complain, in_decl);
11590       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11591
11592     case SIZEOF_EXPR:
11593       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11594         return tsubst_copy (t, args, complain, in_decl);
11595       /* Fall through */
11596       
11597     case ALIGNOF_EXPR:
11598       op1 = TREE_OPERAND (t, 0);
11599       if (!args)
11600         {
11601           /* When there are no ARGS, we are trying to evaluate a
11602              non-dependent expression from the parser.  Trying to do
11603              the substitutions may not work.  */
11604           if (!TYPE_P (op1))
11605             op1 = TREE_TYPE (op1);
11606         }
11607       else
11608         {
11609           ++cp_unevaluated_operand;
11610           ++c_inhibit_evaluation_warnings;
11611           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11612                                        /*function_p=*/false,
11613                                        /*integral_constant_expression_p=*/false);
11614           --cp_unevaluated_operand;
11615           --c_inhibit_evaluation_warnings;
11616         }
11617       if (TYPE_P (op1))
11618         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11619                                            complain & tf_error);
11620       else
11621         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11622                                            complain & tf_error);
11623
11624     case MODOP_EXPR:
11625       {
11626         tree r = build_x_modify_expr
11627           (RECUR (TREE_OPERAND (t, 0)),
11628            TREE_CODE (TREE_OPERAND (t, 1)),
11629            RECUR (TREE_OPERAND (t, 2)),
11630            complain);
11631         /* TREE_NO_WARNING must be set if either the expression was
11632            parenthesized or it uses an operator such as >>= rather
11633            than plain assignment.  In the former case, it was already
11634            set and must be copied.  In the latter case,
11635            build_x_modify_expr sets it and it must not be reset
11636            here.  */
11637         if (TREE_NO_WARNING (t))
11638           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11639         return r;
11640       }
11641
11642     case ARROW_EXPR:
11643       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11644                                                 args, complain, in_decl);
11645       /* Remember that there was a reference to this entity.  */
11646       if (DECL_P (op1))
11647         mark_used (op1);
11648       return build_x_arrow (op1);
11649
11650     case NEW_EXPR:
11651       {
11652         tree placement = RECUR (TREE_OPERAND (t, 0));
11653         tree init = RECUR (TREE_OPERAND (t, 3));
11654         VEC(tree,gc) *placement_vec;
11655         VEC(tree,gc) *init_vec;
11656         tree ret;
11657
11658         if (placement == NULL_TREE)
11659           placement_vec = NULL;
11660         else
11661           {
11662             placement_vec = make_tree_vector ();
11663             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
11664               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
11665           }
11666
11667         /* If there was an initializer in the original tree, but it
11668            instantiated to an empty list, then we should pass a
11669            non-NULL empty vector to tell build_new that it was an
11670            empty initializer() rather than no initializer.  This can
11671            only happen when the initializer is a pack expansion whose
11672            parameter packs are of length zero.  */
11673         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
11674           init_vec = NULL;
11675         else
11676           {
11677             init_vec = make_tree_vector ();
11678             if (init == void_zero_node)
11679               gcc_assert (init_vec != NULL);
11680             else
11681               {
11682                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
11683                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
11684               }
11685           }
11686
11687         ret = build_new (&placement_vec,
11688                          RECUR (TREE_OPERAND (t, 1)),
11689                          RECUR (TREE_OPERAND (t, 2)),
11690                          &init_vec,
11691                          NEW_EXPR_USE_GLOBAL (t),
11692                          complain);
11693
11694         if (placement_vec != NULL)
11695           release_tree_vector (placement_vec);
11696         if (init_vec != NULL)
11697           release_tree_vector (init_vec);
11698
11699         return ret;
11700       }
11701
11702     case DELETE_EXPR:
11703      return delete_sanity
11704        (RECUR (TREE_OPERAND (t, 0)),
11705         RECUR (TREE_OPERAND (t, 1)),
11706         DELETE_EXPR_USE_VEC (t),
11707         DELETE_EXPR_USE_GLOBAL (t));
11708
11709     case COMPOUND_EXPR:
11710       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11711                                     RECUR (TREE_OPERAND (t, 1)),
11712                                     complain);
11713
11714     case CALL_EXPR:
11715       {
11716         tree function;
11717         VEC(tree,gc) *call_args;
11718         unsigned int nargs, i;
11719         bool qualified_p;
11720         bool koenig_p;
11721         tree ret;
11722
11723         function = CALL_EXPR_FN (t);
11724         /* When we parsed the expression,  we determined whether or
11725            not Koenig lookup should be performed.  */
11726         koenig_p = KOENIG_LOOKUP_P (t);
11727         if (TREE_CODE (function) == SCOPE_REF)
11728           {
11729             qualified_p = true;
11730             function = tsubst_qualified_id (function, args, complain, in_decl,
11731                                             /*done=*/false,
11732                                             /*address_p=*/false);
11733           }
11734         else
11735           {
11736             if (TREE_CODE (function) == COMPONENT_REF)
11737               {
11738                 tree op = TREE_OPERAND (function, 1);
11739
11740                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11741                                || (BASELINK_P (op)
11742                                    && BASELINK_QUALIFIED_P (op)));
11743               }
11744             else
11745               qualified_p = false;
11746
11747             function = tsubst_copy_and_build (function, args, complain,
11748                                               in_decl,
11749                                               !qualified_p,
11750                                               integral_constant_expression_p);
11751
11752             if (BASELINK_P (function))
11753               qualified_p = true;
11754           }
11755
11756         nargs = call_expr_nargs (t);
11757         call_args = make_tree_vector ();
11758         for (i = 0; i < nargs; ++i)
11759           {
11760             tree arg = CALL_EXPR_ARG (t, i);
11761
11762             if (!PACK_EXPANSION_P (arg))
11763               VEC_safe_push (tree, gc, call_args,
11764                              RECUR (CALL_EXPR_ARG (t, i)));
11765             else
11766               {
11767                 /* Expand the pack expansion and push each entry onto
11768                    CALL_ARGS.  */
11769                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
11770                 if (TREE_CODE (arg) == TREE_VEC)
11771                   {
11772                     unsigned int len, j;
11773
11774                     len = TREE_VEC_LENGTH (arg);
11775                     for (j = 0; j < len; ++j)
11776                       {
11777                         tree value = TREE_VEC_ELT (arg, j);
11778                         if (value != NULL_TREE)
11779                           value = convert_from_reference (value);
11780                         VEC_safe_push (tree, gc, call_args, value);
11781                       }
11782                   }
11783                 else
11784                   {
11785                     /* A partial substitution.  Add one entry.  */
11786                     VEC_safe_push (tree, gc, call_args, arg);
11787                   }
11788               }
11789           }
11790
11791         /* We do not perform argument-dependent lookup if normal
11792            lookup finds a non-function, in accordance with the
11793            expected resolution of DR 218.  */
11794         if (koenig_p
11795             && ((is_overloaded_fn (function)
11796                  /* If lookup found a member function, the Koenig lookup is
11797                     not appropriate, even if an unqualified-name was used
11798                     to denote the function.  */
11799                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11800                 || TREE_CODE (function) == IDENTIFIER_NODE)
11801             /* Only do this when substitution turns a dependent call
11802                into a non-dependent call.  */
11803             && type_dependent_expression_p_push (t)
11804             && !any_type_dependent_arguments_p (call_args))
11805           function = perform_koenig_lookup (function, call_args);
11806
11807         if (TREE_CODE (function) == IDENTIFIER_NODE)
11808           {
11809             unqualified_name_lookup_error (function);
11810             release_tree_vector (call_args);
11811             return error_mark_node;
11812           }
11813
11814         /* Remember that there was a reference to this entity.  */
11815         if (DECL_P (function))
11816           mark_used (function);
11817
11818         if (TREE_CODE (function) == OFFSET_REF)
11819           ret = build_offset_ref_call_from_tree (function, &call_args);
11820         else if (TREE_CODE (function) == COMPONENT_REF)
11821           {
11822             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11823               ret = finish_call_expr (function, &call_args,
11824                                        /*disallow_virtual=*/false,
11825                                        /*koenig_p=*/false,
11826                                        complain);
11827             else
11828               ret = (build_new_method_call
11829                       (TREE_OPERAND (function, 0),
11830                        TREE_OPERAND (function, 1),
11831                        &call_args, NULL_TREE,
11832                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11833                        /*fn_p=*/NULL,
11834                        complain));
11835           }
11836         else
11837           ret = finish_call_expr (function, &call_args,
11838                                   /*disallow_virtual=*/qualified_p,
11839                                   koenig_p,
11840                                   complain);
11841
11842         release_tree_vector (call_args);
11843
11844         return ret;
11845       }
11846
11847     case COND_EXPR:
11848       return build_x_conditional_expr
11849         (RECUR (TREE_OPERAND (t, 0)),
11850          RECUR (TREE_OPERAND (t, 1)),
11851          RECUR (TREE_OPERAND (t, 2)),
11852          complain);
11853
11854     case PSEUDO_DTOR_EXPR:
11855       return finish_pseudo_destructor_expr
11856         (RECUR (TREE_OPERAND (t, 0)),
11857          RECUR (TREE_OPERAND (t, 1)),
11858          RECUR (TREE_OPERAND (t, 2)));
11859
11860     case TREE_LIST:
11861       {
11862         tree purpose, value, chain;
11863
11864         if (t == void_list_node)
11865           return t;
11866
11867         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11868             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11869           {
11870             /* We have pack expansions, so expand those and
11871                create a new list out of it.  */
11872             tree purposevec = NULL_TREE;
11873             tree valuevec = NULL_TREE;
11874             tree chain;
11875             int i, len = -1;
11876
11877             /* Expand the argument expressions.  */
11878             if (TREE_PURPOSE (t))
11879               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11880                                                  complain, in_decl);
11881             if (TREE_VALUE (t))
11882               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11883                                                complain, in_decl);
11884
11885             /* Build the rest of the list.  */
11886             chain = TREE_CHAIN (t);
11887             if (chain && chain != void_type_node)
11888               chain = RECUR (chain);
11889
11890             /* Determine the number of arguments.  */
11891             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11892               {
11893                 len = TREE_VEC_LENGTH (purposevec);
11894                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11895               }
11896             else if (TREE_CODE (valuevec) == TREE_VEC)
11897               len = TREE_VEC_LENGTH (valuevec);
11898             else
11899               {
11900                 /* Since we only performed a partial substitution into
11901                    the argument pack, we only return a single list
11902                    node.  */
11903                 if (purposevec == TREE_PURPOSE (t)
11904                     && valuevec == TREE_VALUE (t)
11905                     && chain == TREE_CHAIN (t))
11906                   return t;
11907
11908                 return tree_cons (purposevec, valuevec, chain);
11909               }
11910             
11911             /* Convert the argument vectors into a TREE_LIST */
11912             i = len;
11913             while (i > 0)
11914               {
11915                 /* Grab the Ith values.  */
11916                 i--;
11917                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11918                                      : NULL_TREE;
11919                 value 
11920                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11921                              : NULL_TREE;
11922
11923                 /* Build the list (backwards).  */
11924                 chain = tree_cons (purpose, value, chain);
11925               }
11926
11927             return chain;
11928           }
11929
11930         purpose = TREE_PURPOSE (t);
11931         if (purpose)
11932           purpose = RECUR (purpose);
11933         value = TREE_VALUE (t);
11934         if (value)
11935           value = RECUR (value);
11936         chain = TREE_CHAIN (t);
11937         if (chain && chain != void_type_node)
11938           chain = RECUR (chain);
11939         if (purpose == TREE_PURPOSE (t)
11940             && value == TREE_VALUE (t)
11941             && chain == TREE_CHAIN (t))
11942           return t;
11943         return tree_cons (purpose, value, chain);
11944       }
11945
11946     case COMPONENT_REF:
11947       {
11948         tree object;
11949         tree object_type;
11950         tree member;
11951
11952         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11953                                                      args, complain, in_decl);
11954         /* Remember that there was a reference to this entity.  */
11955         if (DECL_P (object))
11956           mark_used (object);
11957         object_type = TREE_TYPE (object);
11958
11959         member = TREE_OPERAND (t, 1);
11960         if (BASELINK_P (member))
11961           member = tsubst_baselink (member,
11962                                     non_reference (TREE_TYPE (object)),
11963                                     args, complain, in_decl);
11964         else
11965           member = tsubst_copy (member, args, complain, in_decl);
11966         if (member == error_mark_node)
11967           return error_mark_node;
11968
11969         if (object_type && !CLASS_TYPE_P (object_type))
11970           {
11971             if (SCALAR_TYPE_P (object_type))
11972               {
11973                 tree s = NULL_TREE;
11974                 tree dtor = member;
11975
11976                 if (TREE_CODE (dtor) == SCOPE_REF)
11977                   {
11978                     s = TREE_OPERAND (dtor, 0);
11979                     dtor = TREE_OPERAND (dtor, 1);
11980                   }
11981                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11982                   {
11983                     dtor = TREE_OPERAND (dtor, 0);
11984                     if (TYPE_P (dtor))
11985                       return finish_pseudo_destructor_expr (object, s, dtor);
11986                   }
11987               }
11988           }
11989         else if (TREE_CODE (member) == SCOPE_REF
11990                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11991           {
11992             tree tmpl;
11993             tree args;
11994
11995             /* Lookup the template functions now that we know what the
11996                scope is.  */
11997             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11998             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11999             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12000                                             /*is_type_p=*/false,
12001                                             /*complain=*/false);
12002             if (BASELINK_P (member))
12003               {
12004                 BASELINK_FUNCTIONS (member)
12005                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12006                               args);
12007                 member = (adjust_result_of_qualified_name_lookup
12008                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12009                            object_type));
12010               }
12011             else
12012               {
12013                 qualified_name_lookup_error (object_type, tmpl, member,
12014                                              input_location);
12015                 return error_mark_node;
12016               }
12017           }
12018         else if (TREE_CODE (member) == SCOPE_REF
12019                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12020                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12021           {
12022             if (complain & tf_error)
12023               {
12024                 if (TYPE_P (TREE_OPERAND (member, 0)))
12025                   error ("%qT is not a class or namespace",
12026                          TREE_OPERAND (member, 0));
12027                 else
12028                   error ("%qD is not a class or namespace",
12029                          TREE_OPERAND (member, 0));
12030               }
12031             return error_mark_node;
12032           }
12033         else if (TREE_CODE (member) == FIELD_DECL)
12034           return finish_non_static_data_member (member, object, NULL_TREE);
12035
12036         return finish_class_member_access_expr (object, member,
12037                                                 /*template_p=*/false,
12038                                                 complain);
12039       }
12040
12041     case THROW_EXPR:
12042       return build_throw
12043         (RECUR (TREE_OPERAND (t, 0)));
12044
12045     case CONSTRUCTOR:
12046       {
12047         VEC(constructor_elt,gc) *n;
12048         constructor_elt *ce;
12049         unsigned HOST_WIDE_INT idx;
12050         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12051         bool process_index_p;
12052         int newlen;
12053         bool need_copy_p = false;
12054         tree r;
12055
12056         if (type == error_mark_node)
12057           return error_mark_node;
12058
12059         /* digest_init will do the wrong thing if we let it.  */
12060         if (type && TYPE_PTRMEMFUNC_P (type))
12061           return t;
12062
12063         /* We do not want to process the index of aggregate
12064            initializers as they are identifier nodes which will be
12065            looked up by digest_init.  */
12066         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12067
12068         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12069         newlen = VEC_length (constructor_elt, n);
12070         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12071           {
12072             if (ce->index && process_index_p)
12073               ce->index = RECUR (ce->index);
12074
12075             if (PACK_EXPANSION_P (ce->value))
12076               {
12077                 /* Substitute into the pack expansion.  */
12078                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12079                                                   in_decl);
12080
12081                 if (ce->value == error_mark_node)
12082                   ;
12083                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12084                   /* Just move the argument into place.  */
12085                   ce->value = TREE_VEC_ELT (ce->value, 0);
12086                 else
12087                   {
12088                     /* Update the length of the final CONSTRUCTOR
12089                        arguments vector, and note that we will need to
12090                        copy.*/
12091                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12092                     need_copy_p = true;
12093                   }
12094               }
12095             else
12096               ce->value = RECUR (ce->value);
12097           }
12098
12099         if (need_copy_p)
12100           {
12101             VEC(constructor_elt,gc) *old_n = n;
12102
12103             n = VEC_alloc (constructor_elt, gc, newlen);
12104             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12105                  idx++)
12106               {
12107                 if (TREE_CODE (ce->value) == TREE_VEC)
12108                   {
12109                     int i, len = TREE_VEC_LENGTH (ce->value);
12110                     for (i = 0; i < len; ++i)
12111                       CONSTRUCTOR_APPEND_ELT (n, 0,
12112                                               TREE_VEC_ELT (ce->value, i));
12113                   }
12114                 else
12115                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12116               }
12117           }
12118
12119         r = build_constructor (init_list_type_node, n);
12120         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12121
12122         if (TREE_HAS_CONSTRUCTOR (t))
12123           return finish_compound_literal (type, r);
12124
12125         return r;
12126       }
12127
12128     case TYPEID_EXPR:
12129       {
12130         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12131         if (TYPE_P (operand_0))
12132           return get_typeid (operand_0);
12133         return build_typeid (operand_0);
12134       }
12135
12136     case VAR_DECL:
12137       if (!args)
12138         return t;
12139       /* Fall through */
12140
12141     case PARM_DECL:
12142       {
12143         tree r = tsubst_copy (t, args, complain, in_decl);
12144
12145         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12146           /* If the original type was a reference, we'll be wrapped in
12147              the appropriate INDIRECT_REF.  */
12148           r = convert_from_reference (r);
12149         return r;
12150       }
12151
12152     case VA_ARG_EXPR:
12153       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12154                              tsubst_copy (TREE_TYPE (t), args, complain,
12155                                           in_decl));
12156
12157     case OFFSETOF_EXPR:
12158       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12159
12160     case TRAIT_EXPR:
12161       {
12162         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12163                                   complain, in_decl);
12164
12165         tree type2 = TRAIT_EXPR_TYPE2 (t);
12166         if (type2)
12167           type2 = tsubst_copy (type2, args, complain, in_decl);
12168         
12169         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12170       }
12171
12172     case STMT_EXPR:
12173       {
12174         tree old_stmt_expr = cur_stmt_expr;
12175         tree stmt_expr = begin_stmt_expr ();
12176
12177         cur_stmt_expr = stmt_expr;
12178         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12179                      integral_constant_expression_p);
12180         stmt_expr = finish_stmt_expr (stmt_expr, false);
12181         cur_stmt_expr = old_stmt_expr;
12182
12183         return stmt_expr;
12184       }
12185
12186     case CONST_DECL:
12187       t = tsubst_copy (t, args, complain, in_decl);
12188       /* As in finish_id_expression, we resolve enumeration constants
12189          to their underlying values.  */
12190       if (TREE_CODE (t) == CONST_DECL)
12191         {
12192           used_types_insert (TREE_TYPE (t));
12193           return DECL_INITIAL (t);
12194         }
12195       return t;
12196
12197     default:
12198       /* Handle Objective-C++ constructs, if appropriate.  */
12199       {
12200         tree subst
12201           = objcp_tsubst_copy_and_build (t, args, complain,
12202                                          in_decl, /*function_p=*/false);
12203         if (subst)
12204           return subst;
12205       }
12206       return tsubst_copy (t, args, complain, in_decl);
12207     }
12208
12209 #undef RECUR
12210 }
12211
12212 /* Verify that the instantiated ARGS are valid. For type arguments,
12213    make sure that the type's linkage is ok. For non-type arguments,
12214    make sure they are constants if they are integral or enumerations.
12215    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12216
12217 static bool
12218 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12219 {
12220   if (ARGUMENT_PACK_P (t))
12221     {
12222       tree vec = ARGUMENT_PACK_ARGS (t);
12223       int len = TREE_VEC_LENGTH (vec);
12224       bool result = false;
12225       int i;
12226
12227       for (i = 0; i < len; ++i)
12228         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12229           result = true;
12230       return result;
12231     }
12232   else if (TYPE_P (t))
12233     {
12234       /* [basic.link]: A name with no linkage (notably, the name
12235          of a class or enumeration declared in a local scope)
12236          shall not be used to declare an entity with linkage.
12237          This implies that names with no linkage cannot be used as
12238          template arguments.  */
12239       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
12240
12241       if (nt)
12242         {
12243           /* DR 488 makes use of a type with no linkage cause
12244              type deduction to fail.  */
12245           if (complain & tf_error)
12246             {
12247               if (TYPE_ANONYMOUS_P (nt))
12248                 error ("%qT is/uses anonymous type", t);
12249               else
12250                 error ("template argument for %qD uses local type %qT",
12251                        tmpl, t);
12252             }
12253           return true;
12254         }
12255       /* In order to avoid all sorts of complications, we do not
12256          allow variably-modified types as template arguments.  */
12257       else if (variably_modified_type_p (t, NULL_TREE))
12258         {
12259           if (complain & tf_error)
12260             error ("%qT is a variably modified type", t);
12261           return true;
12262         }
12263     }
12264   /* A non-type argument of integral or enumerated type must be a
12265      constant.  */
12266   else if (TREE_TYPE (t)
12267            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12268            && !TREE_CONSTANT (t))
12269     {
12270       if (complain & tf_error)
12271         error ("integral expression %qE is not constant", t);
12272       return true;
12273     }
12274   return false;
12275 }
12276
12277 static bool
12278 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12279 {
12280   int ix, len = DECL_NTPARMS (tmpl);
12281   bool result = false;
12282
12283   for (ix = 0; ix != len; ix++)
12284     {
12285       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12286         result = true;
12287     }
12288   if (result && (complain & tf_error))
12289     error ("  trying to instantiate %qD", tmpl);
12290   return result;
12291 }
12292
12293 /* Instantiate the indicated variable or function template TMPL with
12294    the template arguments in TARG_PTR.  */
12295
12296 tree
12297 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12298 {
12299   tree targ_ptr = orig_args;
12300   tree fndecl;
12301   tree gen_tmpl;
12302   tree spec;
12303   HOST_WIDE_INT saved_processing_template_decl;
12304
12305   if (tmpl == error_mark_node)
12306     return error_mark_node;
12307
12308   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12309
12310   /* If this function is a clone, handle it specially.  */
12311   if (DECL_CLONED_FUNCTION_P (tmpl))
12312     {
12313       tree spec;
12314       tree clone;
12315
12316       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12317          DECL_CLONED_FUNCTION.  */
12318       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12319                                    targ_ptr, complain);
12320       if (spec == error_mark_node)
12321         return error_mark_node;
12322
12323       /* Look for the clone.  */
12324       FOR_EACH_CLONE (clone, spec)
12325         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12326           return clone;
12327       /* We should always have found the clone by now.  */
12328       gcc_unreachable ();
12329       return NULL_TREE;
12330     }
12331
12332   /* Check to see if we already have this specialization.  */
12333   gen_tmpl = most_general_template (tmpl);
12334   if (tmpl != gen_tmpl)
12335     /* The TMPL is a partial instantiation.  To get a full set of
12336        arguments we must add the arguments used to perform the
12337        partial instantiation.  */
12338     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12339                                             targ_ptr);
12340
12341   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12342      but it doesn't seem to be on the hot path.  */
12343   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12344
12345   gcc_assert (tmpl == gen_tmpl
12346               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12347                   == spec)
12348               || fndecl == NULL_TREE);
12349
12350   if (spec != NULL_TREE)
12351     return spec;
12352
12353   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12354                                complain))
12355     return error_mark_node;
12356
12357   /* We are building a FUNCTION_DECL, during which the access of its
12358      parameters and return types have to be checked.  However this
12359      FUNCTION_DECL which is the desired context for access checking
12360      is not built yet.  We solve this chicken-and-egg problem by
12361      deferring all checks until we have the FUNCTION_DECL.  */
12362   push_deferring_access_checks (dk_deferred);
12363
12364   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12365      (because, for example, we have encountered a non-dependent
12366      function call in the body of a template function and must now
12367      determine which of several overloaded functions will be called),
12368      within the instantiation itself we are not processing a
12369      template.  */  
12370   saved_processing_template_decl = processing_template_decl;
12371   processing_template_decl = 0;
12372   /* Substitute template parameters to obtain the specialization.  */
12373   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12374                    targ_ptr, complain, gen_tmpl);
12375   processing_template_decl = saved_processing_template_decl;
12376   if (fndecl == error_mark_node)
12377     return error_mark_node;
12378
12379   /* Now we know the specialization, compute access previously
12380      deferred.  */
12381   push_access_scope (fndecl);
12382
12383   /* Some typedefs referenced from within the template code need to be access
12384      checked at template instantiation time, i.e now. These types were
12385      added to the template at parsing time. Let's get those and perfom
12386      the acces checks then.  */
12387   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12388   perform_deferred_access_checks ();
12389   pop_access_scope (fndecl);
12390   pop_deferring_access_checks ();
12391
12392   /* The DECL_TI_TEMPLATE should always be the immediate parent
12393      template, not the most general template.  */
12394   DECL_TI_TEMPLATE (fndecl) = tmpl;
12395
12396   /* If we've just instantiated the main entry point for a function,
12397      instantiate all the alternate entry points as well.  We do this
12398      by cloning the instantiation of the main entry point, not by
12399      instantiating the template clones.  */
12400   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12401     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12402
12403   return fndecl;
12404 }
12405
12406 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12407    NARGS elements of the arguments that are being used when calling
12408    it.  TARGS is a vector into which the deduced template arguments
12409    are placed.
12410
12411    Return zero for success, 2 for an incomplete match that doesn't resolve
12412    all the types, and 1 for complete failure.  An error message will be
12413    printed only for an incomplete match.
12414
12415    If FN is a conversion operator, or we are trying to produce a specific
12416    specialization, RETURN_TYPE is the return type desired.
12417
12418    The EXPLICIT_TARGS are explicit template arguments provided via a
12419    template-id.
12420
12421    The parameter STRICT is one of:
12422
12423    DEDUCE_CALL:
12424      We are deducing arguments for a function call, as in
12425      [temp.deduct.call].
12426
12427    DEDUCE_CONV:
12428      We are deducing arguments for a conversion function, as in
12429      [temp.deduct.conv].
12430
12431    DEDUCE_EXACT:
12432      We are deducing arguments when doing an explicit instantiation
12433      as in [temp.explicit], when determining an explicit specialization
12434      as in [temp.expl.spec], or when taking the address of a function
12435      template, as in [temp.deduct.funcaddr].  */
12436
12437 int
12438 fn_type_unification (tree fn,
12439                      tree explicit_targs,
12440                      tree targs,
12441                      const tree *args,
12442                      unsigned int nargs,
12443                      tree return_type,
12444                      unification_kind_t strict,
12445                      int flags)
12446 {
12447   tree parms;
12448   tree fntype;
12449   int result;
12450   bool incomplete_argument_packs_p = false;
12451
12452   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12453
12454   fntype = TREE_TYPE (fn);
12455   if (explicit_targs)
12456     {
12457       /* [temp.deduct]
12458
12459          The specified template arguments must match the template
12460          parameters in kind (i.e., type, nontype, template), and there
12461          must not be more arguments than there are parameters;
12462          otherwise type deduction fails.
12463
12464          Nontype arguments must match the types of the corresponding
12465          nontype template parameters, or must be convertible to the
12466          types of the corresponding nontype parameters as specified in
12467          _temp.arg.nontype_, otherwise type deduction fails.
12468
12469          All references in the function type of the function template
12470          to the corresponding template parameters are replaced by the
12471          specified template argument values.  If a substitution in a
12472          template parameter or in the function type of the function
12473          template results in an invalid type, type deduction fails.  */
12474       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12475       int i, len = TREE_VEC_LENGTH (tparms);
12476       tree converted_args;
12477       bool incomplete = false;
12478
12479       if (explicit_targs == error_mark_node)
12480         return 1;
12481
12482       converted_args
12483         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12484                                   /*require_all_args=*/false,
12485                                   /*use_default_args=*/false));
12486       if (converted_args == error_mark_node)
12487         return 1;
12488
12489       /* Substitute the explicit args into the function type.  This is
12490          necessary so that, for instance, explicitly declared function
12491          arguments can match null pointed constants.  If we were given
12492          an incomplete set of explicit args, we must not do semantic
12493          processing during substitution as we could create partial
12494          instantiations.  */
12495       for (i = 0; i < len; i++)
12496         {
12497           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12498           bool parameter_pack = false;
12499
12500           /* Dig out the actual parm.  */
12501           if (TREE_CODE (parm) == TYPE_DECL
12502               || TREE_CODE (parm) == TEMPLATE_DECL)
12503             {
12504               parm = TREE_TYPE (parm);
12505               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12506             }
12507           else if (TREE_CODE (parm) == PARM_DECL)
12508             {
12509               parm = DECL_INITIAL (parm);
12510               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12511             }
12512
12513           if (parameter_pack)
12514             {
12515               int level, idx;
12516               tree targ;
12517               template_parm_level_and_index (parm, &level, &idx);
12518
12519               /* Mark the argument pack as "incomplete". We could
12520                  still deduce more arguments during unification.  */
12521               targ = TMPL_ARG (converted_args, level, idx);
12522               if (targ)
12523                 {
12524                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12525                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12526                     = ARGUMENT_PACK_ARGS (targ);
12527                 }
12528
12529               /* We have some incomplete argument packs.  */
12530               incomplete_argument_packs_p = true;
12531             }
12532         }
12533
12534       if (incomplete_argument_packs_p)
12535         /* Any substitution is guaranteed to be incomplete if there
12536            are incomplete argument packs, because we can still deduce
12537            more arguments.  */
12538         incomplete = 1;
12539       else
12540         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12541
12542       processing_template_decl += incomplete;
12543       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12544       processing_template_decl -= incomplete;
12545
12546       if (fntype == error_mark_node)
12547         return 1;
12548
12549       /* Place the explicitly specified arguments in TARGS.  */
12550       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12551         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12552     }
12553
12554   /* Never do unification on the 'this' parameter.  */
12555   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12556
12557   if (return_type)
12558     {
12559       tree *new_args;
12560
12561       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12562       new_args = XALLOCAVEC (tree, nargs + 1);
12563       new_args[0] = return_type;
12564       memcpy (new_args + 1, args, nargs * sizeof (tree));
12565       args = new_args;
12566       ++nargs;
12567     }
12568
12569   /* We allow incomplete unification without an error message here
12570      because the standard doesn't seem to explicitly prohibit it.  Our
12571      callers must be ready to deal with unification failures in any
12572      event.  */
12573   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12574                                   targs, parms, args, nargs, /*subr=*/0,
12575                                   strict, flags);
12576
12577   if (result == 0 && incomplete_argument_packs_p)
12578     {
12579       int i, len = NUM_TMPL_ARGS (targs);
12580
12581       /* Clear the "incomplete" flags on all argument packs.  */
12582       for (i = 0; i < len; i++)
12583         {
12584           tree arg = TREE_VEC_ELT (targs, i);
12585           if (ARGUMENT_PACK_P (arg))
12586             {
12587               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12588               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12589             }
12590         }
12591     }
12592
12593   /* Now that we have bindings for all of the template arguments,
12594      ensure that the arguments deduced for the template template
12595      parameters have compatible template parameter lists.  We cannot
12596      check this property before we have deduced all template
12597      arguments, because the template parameter types of a template
12598      template parameter might depend on prior template parameters
12599      deduced after the template template parameter.  The following
12600      ill-formed example illustrates this issue:
12601
12602        template<typename T, template<T> class C> void f(C<5>, T);
12603
12604        template<int N> struct X {};
12605
12606        void g() {
12607          f(X<5>(), 5l); // error: template argument deduction fails
12608        }
12609
12610      The template parameter list of 'C' depends on the template type
12611      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12612      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12613      time that we deduce 'C'.  */
12614   if (result == 0
12615       && !template_template_parm_bindings_ok_p 
12616            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12617     return 1;
12618
12619   if (result == 0)
12620     /* All is well so far.  Now, check:
12621
12622        [temp.deduct]
12623
12624        When all template arguments have been deduced, all uses of
12625        template parameters in nondeduced contexts are replaced with
12626        the corresponding deduced argument values.  If the
12627        substitution results in an invalid type, as described above,
12628        type deduction fails.  */
12629     {
12630       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12631       if (substed == error_mark_node)
12632         return 1;
12633
12634       /* If we're looking for an exact match, check that what we got
12635          is indeed an exact match.  It might not be if some template
12636          parameters are used in non-deduced contexts.  */
12637       if (strict == DEDUCE_EXACT)
12638         {
12639           unsigned int i;
12640
12641           tree sarg
12642             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12643           if (return_type)
12644             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12645           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
12646             if (!same_type_p (args[i], TREE_VALUE (sarg)))
12647               return 1;
12648         }
12649     }
12650
12651   return result;
12652 }
12653
12654 /* Adjust types before performing type deduction, as described in
12655    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12656    sections are symmetric.  PARM is the type of a function parameter
12657    or the return type of the conversion function.  ARG is the type of
12658    the argument passed to the call, or the type of the value
12659    initialized with the result of the conversion function.
12660    ARG_EXPR is the original argument expression, which may be null.  */
12661
12662 static int
12663 maybe_adjust_types_for_deduction (unification_kind_t strict,
12664                                   tree* parm,
12665                                   tree* arg,
12666                                   tree arg_expr)
12667 {
12668   int result = 0;
12669
12670   switch (strict)
12671     {
12672     case DEDUCE_CALL:
12673       break;
12674
12675     case DEDUCE_CONV:
12676       {
12677         /* Swap PARM and ARG throughout the remainder of this
12678            function; the handling is precisely symmetric since PARM
12679            will initialize ARG rather than vice versa.  */
12680         tree* temp = parm;
12681         parm = arg;
12682         arg = temp;
12683         break;
12684       }
12685
12686     case DEDUCE_EXACT:
12687       /* There is nothing to do in this case.  */
12688       return 0;
12689
12690     default:
12691       gcc_unreachable ();
12692     }
12693
12694   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12695     {
12696       /* [temp.deduct.call]
12697
12698          If P is not a reference type:
12699
12700          --If A is an array type, the pointer type produced by the
12701          array-to-pointer standard conversion (_conv.array_) is
12702          used in place of A for type deduction; otherwise,
12703
12704          --If A is a function type, the pointer type produced by
12705          the function-to-pointer standard conversion
12706          (_conv.func_) is used in place of A for type deduction;
12707          otherwise,
12708
12709          --If A is a cv-qualified type, the top level
12710          cv-qualifiers of A's type are ignored for type
12711          deduction.  */
12712       if (TREE_CODE (*arg) == ARRAY_TYPE)
12713         *arg = build_pointer_type (TREE_TYPE (*arg));
12714       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12715         *arg = build_pointer_type (*arg);
12716       else
12717         *arg = TYPE_MAIN_VARIANT (*arg);
12718     }
12719
12720   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12721      of the form T&&, where T is a template parameter, and the argument
12722      is an lvalue, T is deduced as A& */
12723   if (TREE_CODE (*parm) == REFERENCE_TYPE
12724       && TYPE_REF_IS_RVALUE (*parm)
12725       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12726       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12727       && arg_expr && real_lvalue_p (arg_expr))
12728     *arg = build_reference_type (*arg);
12729
12730   /* [temp.deduct.call]
12731
12732      If P is a cv-qualified type, the top level cv-qualifiers
12733      of P's type are ignored for type deduction.  If P is a
12734      reference type, the type referred to by P is used for
12735      type deduction.  */
12736   *parm = TYPE_MAIN_VARIANT (*parm);
12737   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12738     {
12739       *parm = TREE_TYPE (*parm);
12740       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12741     }
12742
12743   /* DR 322. For conversion deduction, remove a reference type on parm
12744      too (which has been swapped into ARG).  */
12745   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12746     *arg = TREE_TYPE (*arg);
12747
12748   return result;
12749 }
12750
12751 /* Most parms like fn_type_unification.
12752
12753    If SUBR is 1, we're being called recursively (to unify the
12754    arguments of a function or method parameter of a function
12755    template). */
12756
12757 static int
12758 type_unification_real (tree tparms,
12759                        tree targs,
12760                        tree xparms,
12761                        const tree *xargs,
12762                        unsigned int xnargs,
12763                        int subr,
12764                        unification_kind_t strict,
12765                        int flags)
12766 {
12767   tree parm, arg, arg_expr;
12768   int i;
12769   int ntparms = TREE_VEC_LENGTH (tparms);
12770   int sub_strict;
12771   int saw_undeduced = 0;
12772   tree parms;
12773   const tree *args;
12774   unsigned int nargs;
12775   unsigned int ia;
12776
12777   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12778   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12779   gcc_assert (ntparms > 0);
12780
12781   switch (strict)
12782     {
12783     case DEDUCE_CALL:
12784       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12785                     | UNIFY_ALLOW_DERIVED);
12786       break;
12787
12788     case DEDUCE_CONV:
12789       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12790       break;
12791
12792     case DEDUCE_EXACT:
12793       sub_strict = UNIFY_ALLOW_NONE;
12794       break;
12795
12796     default:
12797       gcc_unreachable ();
12798     }
12799
12800  again:
12801   parms = xparms;
12802   args = xargs;
12803   nargs = xnargs;
12804
12805   ia = 0;
12806   while (parms && parms != void_list_node
12807          && ia < nargs)
12808     {
12809       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12810         break;
12811
12812       parm = TREE_VALUE (parms);
12813       parms = TREE_CHAIN (parms);
12814       arg = args[ia];
12815       ++ia;
12816       arg_expr = NULL;
12817
12818       if (arg == error_mark_node)
12819         return 1;
12820       if (arg == unknown_type_node)
12821         /* We can't deduce anything from this, but we might get all the
12822            template args from other function args.  */
12823         continue;
12824
12825       /* Conversions will be performed on a function argument that
12826          corresponds with a function parameter that contains only
12827          non-deducible template parameters and explicitly specified
12828          template parameters.  */
12829       if (!uses_template_parms (parm))
12830         {
12831           tree type;
12832
12833           if (!TYPE_P (arg))
12834             type = TREE_TYPE (arg);
12835           else
12836             type = arg;
12837
12838           if (same_type_p (parm, type))
12839             continue;
12840           if (strict != DEDUCE_EXACT
12841               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12842                                   flags))
12843             continue;
12844
12845           return 1;
12846         }
12847
12848       if (!TYPE_P (arg))
12849         {
12850           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12851           if (type_unknown_p (arg))
12852             {
12853               /* [temp.deduct.type] 
12854
12855                  A template-argument can be deduced from a pointer to
12856                  function or pointer to member function argument if
12857                  the set of overloaded functions does not contain
12858                  function templates and at most one of a set of
12859                  overloaded functions provides a unique match.  */
12860               if (resolve_overloaded_unification
12861                   (tparms, targs, parm, arg, strict, sub_strict))
12862                 continue;
12863
12864               return 1;
12865             }
12866           arg_expr = arg;
12867           arg = unlowered_expr_type (arg);
12868           if (arg == error_mark_node)
12869             return 1;
12870         }
12871
12872       {
12873         int arg_strict = sub_strict;
12874
12875         if (!subr)
12876           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12877                                                           arg_expr);
12878
12879         if (arg == init_list_type_node && arg_expr)
12880           arg = arg_expr;
12881         if (unify (tparms, targs, parm, arg, arg_strict))
12882           return 1;
12883       }
12884     }
12885
12886
12887   if (parms 
12888       && parms != void_list_node
12889       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12890     {
12891       /* Unify the remaining arguments with the pack expansion type.  */
12892       tree argvec;
12893       tree parmvec = make_tree_vec (1);
12894
12895       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12896       argvec = make_tree_vec (nargs - ia);
12897       for (i = 0; ia < nargs; ++ia, ++i)
12898         TREE_VEC_ELT (argvec, i) = args[ia];
12899
12900       /* Copy the parameter into parmvec.  */
12901       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12902       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12903                                 /*call_args_p=*/true, /*subr=*/subr))
12904         return 1;
12905
12906       /* Advance to the end of the list of parameters.  */
12907       parms = TREE_CHAIN (parms);
12908     }
12909
12910   /* Fail if we've reached the end of the parm list, and more args
12911      are present, and the parm list isn't variadic.  */
12912   if (ia < nargs && parms == void_list_node)
12913     return 1;
12914   /* Fail if parms are left and they don't have default values.  */
12915   if (parms && parms != void_list_node
12916       && TREE_PURPOSE (parms) == NULL_TREE)
12917     return 1;
12918
12919   if (!subr)
12920     for (i = 0; i < ntparms; i++)
12921       if (!TREE_VEC_ELT (targs, i))
12922         {
12923           tree tparm;
12924
12925           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12926             continue;
12927
12928           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12929
12930           /* If this is an undeduced nontype parameter that depends on
12931              a type parameter, try another pass; its type may have been
12932              deduced from a later argument than the one from which
12933              this parameter can be deduced.  */
12934           if (TREE_CODE (tparm) == PARM_DECL
12935               && uses_template_parms (TREE_TYPE (tparm))
12936               && !saw_undeduced++)
12937             goto again;
12938
12939           /* Core issue #226 (C++0x) [temp.deduct]:
12940
12941                If a template argument has not been deduced, its
12942                default template argument, if any, is used. 
12943
12944              When we are in C++98 mode, TREE_PURPOSE will either
12945              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12946              to explicitly check cxx_dialect here.  */
12947           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12948             {
12949               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12950                                  targs, tf_none, NULL_TREE);
12951               if (arg == error_mark_node)
12952                 return 1;
12953               else
12954                 {
12955                   TREE_VEC_ELT (targs, i) = arg;
12956                   continue;
12957                 }
12958             }
12959
12960           /* If the type parameter is a parameter pack, then it will
12961              be deduced to an empty parameter pack.  */
12962           if (template_parameter_pack_p (tparm))
12963             {
12964               tree arg;
12965
12966               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12967                 {
12968                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12969                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12970                   TREE_CONSTANT (arg) = 1;
12971                 }
12972               else
12973                 arg = make_node (TYPE_ARGUMENT_PACK);
12974
12975               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12976
12977               TREE_VEC_ELT (targs, i) = arg;
12978               continue;
12979             }
12980
12981           return 2;
12982         }
12983
12984   return 0;
12985 }
12986
12987 /* Subroutine of type_unification_real.  Args are like the variables
12988    at the call site.  ARG is an overloaded function (or template-id);
12989    we try deducing template args from each of the overloads, and if
12990    only one succeeds, we go with that.  Modifies TARGS and returns
12991    true on success.  */
12992
12993 static bool
12994 resolve_overloaded_unification (tree tparms,
12995                                 tree targs,
12996                                 tree parm,
12997                                 tree arg,
12998                                 unification_kind_t strict,
12999                                 int sub_strict)
13000 {
13001   tree tempargs = copy_node (targs);
13002   int good = 0;
13003   tree goodfn = NULL_TREE;
13004   bool addr_p;
13005
13006   if (TREE_CODE (arg) == ADDR_EXPR)
13007     {
13008       arg = TREE_OPERAND (arg, 0);
13009       addr_p = true;
13010     }
13011   else
13012     addr_p = false;
13013
13014   if (TREE_CODE (arg) == COMPONENT_REF)
13015     /* Handle `&x' where `x' is some static or non-static member
13016        function name.  */
13017     arg = TREE_OPERAND (arg, 1);
13018
13019   if (TREE_CODE (arg) == OFFSET_REF)
13020     arg = TREE_OPERAND (arg, 1);
13021
13022   /* Strip baselink information.  */
13023   if (BASELINK_P (arg))
13024     arg = BASELINK_FUNCTIONS (arg);
13025
13026   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13027     {
13028       /* If we got some explicit template args, we need to plug them into
13029          the affected templates before we try to unify, in case the
13030          explicit args will completely resolve the templates in question.  */
13031
13032       tree expl_subargs = TREE_OPERAND (arg, 1);
13033       arg = TREE_OPERAND (arg, 0);
13034
13035       for (; arg; arg = OVL_NEXT (arg))
13036         {
13037           tree fn = OVL_CURRENT (arg);
13038           tree subargs, elem;
13039
13040           if (TREE_CODE (fn) != TEMPLATE_DECL)
13041             continue;
13042
13043           ++processing_template_decl;
13044           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13045                                   expl_subargs, /*check_ret=*/false);
13046           if (subargs)
13047             {
13048               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13049               if (try_one_overload (tparms, targs, tempargs, parm,
13050                                     elem, strict, sub_strict, addr_p)
13051                   && (!goodfn || !decls_match (goodfn, elem)))
13052                 {
13053                   goodfn = elem;
13054                   ++good;
13055                 }
13056             }
13057           --processing_template_decl;
13058         }
13059     }
13060   else if (TREE_CODE (arg) != OVERLOAD
13061            && TREE_CODE (arg) != FUNCTION_DECL)
13062     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13063        -- but the deduction does not succeed because the expression is
13064        not just the function on its own.  */
13065     return false;
13066   else
13067     for (; arg; arg = OVL_NEXT (arg))
13068       if (try_one_overload (tparms, targs, tempargs, parm,
13069                             TREE_TYPE (OVL_CURRENT (arg)),
13070                             strict, sub_strict, addr_p)
13071           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13072         {
13073           goodfn = OVL_CURRENT (arg);
13074           ++good;
13075         }
13076
13077   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13078      to function or pointer to member function argument if the set of
13079      overloaded functions does not contain function templates and at most
13080      one of a set of overloaded functions provides a unique match.
13081
13082      So if we found multiple possibilities, we return success but don't
13083      deduce anything.  */
13084
13085   if (good == 1)
13086     {
13087       int i = TREE_VEC_LENGTH (targs);
13088       for (; i--; )
13089         if (TREE_VEC_ELT (tempargs, i))
13090           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13091     }
13092   if (good)
13093     return true;
13094
13095   return false;
13096 }
13097
13098 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13099    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13100    different overloads deduce different arguments for a given parm.
13101    ADDR_P is true if the expression for which deduction is being
13102    performed was of the form "& fn" rather than simply "fn".
13103
13104    Returns 1 on success.  */
13105
13106 static int
13107 try_one_overload (tree tparms,
13108                   tree orig_targs,
13109                   tree targs,
13110                   tree parm,
13111                   tree arg,
13112                   unification_kind_t strict,
13113                   int sub_strict,
13114                   bool addr_p)
13115 {
13116   int nargs;
13117   tree tempargs;
13118   int i;
13119
13120   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13121      to function or pointer to member function argument if the set of
13122      overloaded functions does not contain function templates and at most
13123      one of a set of overloaded functions provides a unique match.
13124
13125      So if this is a template, just return success.  */
13126
13127   if (uses_template_parms (arg))
13128     return 1;
13129
13130   if (TREE_CODE (arg) == METHOD_TYPE)
13131     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13132   else if (addr_p)
13133     arg = build_pointer_type (arg);
13134
13135   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13136
13137   /* We don't copy orig_targs for this because if we have already deduced
13138      some template args from previous args, unify would complain when we
13139      try to deduce a template parameter for the same argument, even though
13140      there isn't really a conflict.  */
13141   nargs = TREE_VEC_LENGTH (targs);
13142   tempargs = make_tree_vec (nargs);
13143
13144   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13145     return 0;
13146
13147   /* First make sure we didn't deduce anything that conflicts with
13148      explicitly specified args.  */
13149   for (i = nargs; i--; )
13150     {
13151       tree elt = TREE_VEC_ELT (tempargs, i);
13152       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13153
13154       if (!elt)
13155         /*NOP*/;
13156       else if (uses_template_parms (elt))
13157         /* Since we're unifying against ourselves, we will fill in
13158            template args used in the function parm list with our own
13159            template parms.  Discard them.  */
13160         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13161       else if (oldelt && !template_args_equal (oldelt, elt))
13162         return 0;
13163     }
13164
13165   for (i = nargs; i--; )
13166     {
13167       tree elt = TREE_VEC_ELT (tempargs, i);
13168
13169       if (elt)
13170         TREE_VEC_ELT (targs, i) = elt;
13171     }
13172
13173   return 1;
13174 }
13175
13176 /* PARM is a template class (perhaps with unbound template
13177    parameters).  ARG is a fully instantiated type.  If ARG can be
13178    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13179    TARGS are as for unify.  */
13180
13181 static tree
13182 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13183 {
13184   tree copy_of_targs;
13185
13186   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13187       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13188           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13189     return NULL_TREE;
13190
13191   /* We need to make a new template argument vector for the call to
13192      unify.  If we used TARGS, we'd clutter it up with the result of
13193      the attempted unification, even if this class didn't work out.
13194      We also don't want to commit ourselves to all the unifications
13195      we've already done, since unification is supposed to be done on
13196      an argument-by-argument basis.  In other words, consider the
13197      following pathological case:
13198
13199        template <int I, int J, int K>
13200        struct S {};
13201
13202        template <int I, int J>
13203        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13204
13205        template <int I, int J, int K>
13206        void f(S<I, J, K>, S<I, I, I>);
13207
13208        void g() {
13209          S<0, 0, 0> s0;
13210          S<0, 1, 2> s2;
13211
13212          f(s0, s2);
13213        }
13214
13215      Now, by the time we consider the unification involving `s2', we
13216      already know that we must have `f<0, 0, 0>'.  But, even though
13217      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13218      because there are two ways to unify base classes of S<0, 1, 2>
13219      with S<I, I, I>.  If we kept the already deduced knowledge, we
13220      would reject the possibility I=1.  */
13221   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13222
13223   /* If unification failed, we're done.  */
13224   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13225              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13226     return NULL_TREE;
13227
13228   return arg;
13229 }
13230
13231 /* Given a template type PARM and a class type ARG, find the unique
13232    base type in ARG that is an instance of PARM.  We do not examine
13233    ARG itself; only its base-classes.  If there is not exactly one
13234    appropriate base class, return NULL_TREE.  PARM may be the type of
13235    a partial specialization, as well as a plain template type.  Used
13236    by unify.  */
13237
13238 static tree
13239 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13240 {
13241   tree rval = NULL_TREE;
13242   tree binfo;
13243
13244   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13245
13246   binfo = TYPE_BINFO (complete_type (arg));
13247   if (!binfo)
13248     /* The type could not be completed.  */
13249     return NULL_TREE;
13250
13251   /* Walk in inheritance graph order.  The search order is not
13252      important, and this avoids multiple walks of virtual bases.  */
13253   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13254     {
13255       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13256
13257       if (r)
13258         {
13259           /* If there is more than one satisfactory baseclass, then:
13260
13261                [temp.deduct.call]
13262
13263               If they yield more than one possible deduced A, the type
13264               deduction fails.
13265
13266              applies.  */
13267           if (rval && !same_type_p (r, rval))
13268             return NULL_TREE;
13269
13270           rval = r;
13271         }
13272     }
13273
13274   return rval;
13275 }
13276
13277 /* Returns the level of DECL, which declares a template parameter.  */
13278
13279 static int
13280 template_decl_level (tree decl)
13281 {
13282   switch (TREE_CODE (decl))
13283     {
13284     case TYPE_DECL:
13285     case TEMPLATE_DECL:
13286       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13287
13288     case PARM_DECL:
13289       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13290
13291     default:
13292       gcc_unreachable ();
13293     }
13294   return 0;
13295 }
13296
13297 /* Decide whether ARG can be unified with PARM, considering only the
13298    cv-qualifiers of each type, given STRICT as documented for unify.
13299    Returns nonzero iff the unification is OK on that basis.  */
13300
13301 static int
13302 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13303 {
13304   int arg_quals = cp_type_quals (arg);
13305   int parm_quals = cp_type_quals (parm);
13306
13307   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13308       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13309     {
13310       /*  Although a CVR qualifier is ignored when being applied to a
13311           substituted template parameter ([8.3.2]/1 for example), that
13312           does not apply during deduction [14.8.2.4]/1, (even though
13313           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13314           this).  Except when we're allowing additional CV qualifiers
13315           at the outer level [14.8.2.1]/3,1st bullet.  */
13316       if ((TREE_CODE (arg) == REFERENCE_TYPE
13317            || TREE_CODE (arg) == FUNCTION_TYPE
13318            || TREE_CODE (arg) == METHOD_TYPE)
13319           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13320         return 0;
13321
13322       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13323           && (parm_quals & TYPE_QUAL_RESTRICT))
13324         return 0;
13325     }
13326
13327   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13328       && (arg_quals & parm_quals) != parm_quals)
13329     return 0;
13330
13331   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13332       && (parm_quals & arg_quals) != arg_quals)
13333     return 0;
13334
13335   return 1;
13336 }
13337
13338 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13339 void 
13340 template_parm_level_and_index (tree parm, int* level, int* index)
13341 {
13342   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13343       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13344       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13345     {
13346       *index = TEMPLATE_TYPE_IDX (parm);
13347       *level = TEMPLATE_TYPE_LEVEL (parm);
13348     }
13349   else
13350     {
13351       *index = TEMPLATE_PARM_IDX (parm);
13352       *level = TEMPLATE_PARM_LEVEL (parm);
13353     }
13354 }
13355
13356 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13357    expansion at the end of PACKED_PARMS. Returns 0 if the type
13358    deduction succeeds, 1 otherwise. STRICT is the same as in
13359    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13360    call argument list. We'll need to adjust the arguments to make them
13361    types. SUBR tells us if this is from a recursive call to
13362    type_unification_real.  */
13363 int
13364 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13365                       tree packed_args, int strict, bool call_args_p,
13366                       bool subr)
13367 {
13368   tree parm 
13369     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13370   tree pattern = PACK_EXPANSION_PATTERN (parm);
13371   tree pack, packs = NULL_TREE;
13372   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13373   int len = TREE_VEC_LENGTH (packed_args);
13374
13375   /* Determine the parameter packs we will be deducing from the
13376      pattern, and record their current deductions.  */
13377   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13378        pack; pack = TREE_CHAIN (pack))
13379     {
13380       tree parm_pack = TREE_VALUE (pack);
13381       int idx, level;
13382
13383       /* Determine the index and level of this parameter pack.  */
13384       template_parm_level_and_index (parm_pack, &level, &idx);
13385
13386       /* Keep track of the parameter packs and their corresponding
13387          argument packs.  */
13388       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13389       TREE_TYPE (packs) = make_tree_vec (len - start);
13390     }
13391   
13392   /* Loop through all of the arguments that have not yet been
13393      unified and unify each with the pattern.  */
13394   for (i = start; i < len; i++)
13395     {
13396       tree parm = pattern;
13397
13398       /* For each parameter pack, clear out the deduced value so that
13399          we can deduce it again.  */
13400       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13401         {
13402           int idx, level;
13403           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13404
13405           TMPL_ARG (targs, level, idx) = NULL_TREE;
13406         }
13407
13408       /* Unify the pattern with the current argument.  */
13409       {
13410         tree arg = TREE_VEC_ELT (packed_args, i);
13411         tree arg_expr = NULL_TREE;
13412         int arg_strict = strict;
13413         bool skip_arg_p = false;
13414
13415         if (call_args_p)
13416           {
13417             int sub_strict;
13418
13419             /* This mirrors what we do in type_unification_real.  */
13420             switch (strict)
13421               {
13422               case DEDUCE_CALL:
13423                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13424                               | UNIFY_ALLOW_MORE_CV_QUAL
13425                               | UNIFY_ALLOW_DERIVED);
13426                 break;
13427                 
13428               case DEDUCE_CONV:
13429                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13430                 break;
13431                 
13432               case DEDUCE_EXACT:
13433                 sub_strict = UNIFY_ALLOW_NONE;
13434                 break;
13435                 
13436               default:
13437                 gcc_unreachable ();
13438               }
13439
13440             if (!TYPE_P (arg))
13441               {
13442                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13443                 if (type_unknown_p (arg))
13444                   {
13445                     /* [temp.deduct.type] A template-argument can be
13446                        deduced from a pointer to function or pointer
13447                        to member function argument if the set of
13448                        overloaded functions does not contain function
13449                        templates and at most one of a set of
13450                        overloaded functions provides a unique
13451                        match.  */
13452
13453                     if (resolve_overloaded_unification
13454                         (tparms, targs, parm, arg,
13455                          (unification_kind_t) strict,
13456                          sub_strict)
13457                         != 0)
13458                       return 1;
13459                     skip_arg_p = true;
13460                   }
13461
13462                 if (!skip_arg_p)
13463                   {
13464                     arg_expr = arg;
13465                     arg = unlowered_expr_type (arg);
13466                     if (arg == error_mark_node)
13467                       return 1;
13468                   }
13469               }
13470       
13471             arg_strict = sub_strict;
13472
13473             if (!subr)
13474               arg_strict |= 
13475                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13476                                                   &parm, &arg, arg_expr);
13477           }
13478
13479         if (!skip_arg_p)
13480           {
13481             if (unify (tparms, targs, parm, arg, arg_strict))
13482               return 1;
13483           }
13484       }
13485
13486       /* For each parameter pack, collect the deduced value.  */
13487       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13488         {
13489           int idx, level;
13490           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13491
13492           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13493             TMPL_ARG (targs, level, idx);
13494         }
13495     }
13496
13497   /* Verify that the results of unification with the parameter packs
13498      produce results consistent with what we've seen before, and make
13499      the deduced argument packs available.  */
13500   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13501     {
13502       tree old_pack = TREE_VALUE (pack);
13503       tree new_args = TREE_TYPE (pack);
13504       int i, len = TREE_VEC_LENGTH (new_args);
13505       bool nondeduced_p = false;
13506
13507       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13508          actually deduce anything.  */
13509       for (i = 0; i < len && !nondeduced_p; ++i)
13510         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13511           nondeduced_p = true;
13512       if (nondeduced_p)
13513         continue;
13514
13515       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13516         {
13517           /* Prepend the explicit arguments onto NEW_ARGS.  */
13518           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13519           tree old_args = new_args;
13520           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13521           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13522
13523           /* Copy the explicit arguments.  */
13524           new_args = make_tree_vec (len);
13525           for (i = 0; i < explicit_len; i++)
13526             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13527
13528           /* Copy the deduced arguments.  */
13529           for (; i < len; i++)
13530             TREE_VEC_ELT (new_args, i) =
13531               TREE_VEC_ELT (old_args, i - explicit_len);
13532         }
13533
13534       if (!old_pack)
13535         {
13536           tree result;
13537           int idx, level;
13538           
13539           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13540
13541           /* Build the deduced *_ARGUMENT_PACK.  */
13542           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13543             {
13544               result = make_node (NONTYPE_ARGUMENT_PACK);
13545               TREE_TYPE (result) = 
13546                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13547               TREE_CONSTANT (result) = 1;
13548             }
13549           else
13550             result = make_node (TYPE_ARGUMENT_PACK);
13551
13552           SET_ARGUMENT_PACK_ARGS (result, new_args);
13553
13554           /* Note the deduced argument packs for this parameter
13555              pack.  */
13556           TMPL_ARG (targs, level, idx) = result;
13557         }
13558       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13559                && (ARGUMENT_PACK_ARGS (old_pack) 
13560                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13561         {
13562           /* We only had the explicitly-provided arguments before, but
13563              now we have a complete set of arguments.  */
13564           int idx, level;
13565           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13566           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13567
13568           /* Keep the original deduced argument pack.  */
13569           TMPL_ARG (targs, level, idx) = old_pack;
13570
13571           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13572           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13573           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13574         }
13575       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13576                                     new_args))
13577         /* Inconsistent unification of this parameter pack.  */
13578         return 1;
13579       else
13580         {
13581           int idx, level;
13582           
13583           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13584
13585           /* Keep the original deduced argument pack.  */
13586           TMPL_ARG (targs, level, idx) = old_pack;
13587         }
13588     }
13589
13590   return 0;
13591 }
13592
13593 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13594    set of template parameters to a template.  TARGS is the bindings
13595    for those template parameters, as determined thus far; TARGS may
13596    include template arguments for outer levels of template parameters
13597    as well.  PARM is a parameter to a template function, or a
13598    subcomponent of that parameter; ARG is the corresponding argument.
13599    This function attempts to match PARM with ARG in a manner
13600    consistent with the existing assignments in TARGS.  If more values
13601    are deduced, then TARGS is updated.
13602
13603    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13604    parameter STRICT is a bitwise or of the following flags:
13605
13606      UNIFY_ALLOW_NONE:
13607        Require an exact match between PARM and ARG.
13608      UNIFY_ALLOW_MORE_CV_QUAL:
13609        Allow the deduced ARG to be more cv-qualified (by qualification
13610        conversion) than ARG.
13611      UNIFY_ALLOW_LESS_CV_QUAL:
13612        Allow the deduced ARG to be less cv-qualified than ARG.
13613      UNIFY_ALLOW_DERIVED:
13614        Allow the deduced ARG to be a template base class of ARG,
13615        or a pointer to a template base class of the type pointed to by
13616        ARG.
13617      UNIFY_ALLOW_INTEGER:
13618        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13619        case for more information.
13620      UNIFY_ALLOW_OUTER_LEVEL:
13621        This is the outermost level of a deduction. Used to determine validity
13622        of qualification conversions. A valid qualification conversion must
13623        have const qualified pointers leading up to the inner type which
13624        requires additional CV quals, except at the outer level, where const
13625        is not required [conv.qual]. It would be normal to set this flag in
13626        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13627      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13628        This is the outermost level of a deduction, and PARM can be more CV
13629        qualified at this point.
13630      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13631        This is the outermost level of a deduction, and PARM can be less CV
13632        qualified at this point.  */
13633
13634 static int
13635 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13636 {
13637   int idx;
13638   tree targ;
13639   tree tparm;
13640   int strict_in = strict;
13641
13642   /* I don't think this will do the right thing with respect to types.
13643      But the only case I've seen it in so far has been array bounds, where
13644      signedness is the only information lost, and I think that will be
13645      okay.  */
13646   while (TREE_CODE (parm) == NOP_EXPR)
13647     parm = TREE_OPERAND (parm, 0);
13648
13649   if (arg == error_mark_node)
13650     return 1;
13651   if (arg == unknown_type_node
13652       || arg == init_list_type_node)
13653     /* We can't deduce anything from this, but we might get all the
13654        template args from other function args.  */
13655     return 0;
13656
13657   /* If PARM uses template parameters, then we can't bail out here,
13658      even if ARG == PARM, since we won't record unifications for the
13659      template parameters.  We might need them if we're trying to
13660      figure out which of two things is more specialized.  */
13661   if (arg == parm && !uses_template_parms (parm))
13662     return 0;
13663
13664   /* Handle init lists early, so the rest of the function can assume
13665      we're dealing with a type. */
13666   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13667     {
13668       tree elt, elttype;
13669       unsigned i;
13670
13671       if (!is_std_init_list (parm))
13672         /* We can only deduce from an initializer list argument if the
13673            parameter is std::initializer_list; otherwise this is a
13674            non-deduced context. */
13675         return 0;
13676
13677       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13678
13679       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13680         {
13681           int elt_strict = strict;
13682           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13683             {
13684               tree type = TREE_TYPE (elt);
13685               /* It should only be possible to get here for a call.  */
13686               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13687               elt_strict |= maybe_adjust_types_for_deduction
13688                 (DEDUCE_CALL, &elttype, &type, elt);
13689               elt = type;
13690             }
13691
13692           if (unify (tparms, targs, elttype, elt, elt_strict))
13693             return 1;
13694         }
13695       return 0;
13696     }
13697
13698   /* Immediately reject some pairs that won't unify because of
13699      cv-qualification mismatches.  */
13700   if (TREE_CODE (arg) == TREE_CODE (parm)
13701       && TYPE_P (arg)
13702       /* It is the elements of the array which hold the cv quals of an array
13703          type, and the elements might be template type parms. We'll check
13704          when we recurse.  */
13705       && TREE_CODE (arg) != ARRAY_TYPE
13706       /* We check the cv-qualifiers when unifying with template type
13707          parameters below.  We want to allow ARG `const T' to unify with
13708          PARM `T' for example, when computing which of two templates
13709          is more specialized, for example.  */
13710       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13711       && !check_cv_quals_for_unify (strict_in, arg, parm))
13712     return 1;
13713
13714   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13715       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13716     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13717   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13718   strict &= ~UNIFY_ALLOW_DERIVED;
13719   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13720   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13721
13722   switch (TREE_CODE (parm))
13723     {
13724     case TYPENAME_TYPE:
13725     case SCOPE_REF:
13726     case UNBOUND_CLASS_TEMPLATE:
13727       /* In a type which contains a nested-name-specifier, template
13728          argument values cannot be deduced for template parameters used
13729          within the nested-name-specifier.  */
13730       return 0;
13731
13732     case TEMPLATE_TYPE_PARM:
13733     case TEMPLATE_TEMPLATE_PARM:
13734     case BOUND_TEMPLATE_TEMPLATE_PARM:
13735       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13736       if (tparm == error_mark_node)
13737         return 1;
13738
13739       if (TEMPLATE_TYPE_LEVEL (parm)
13740           != template_decl_level (tparm))
13741         /* The PARM is not one we're trying to unify.  Just check
13742            to see if it matches ARG.  */
13743         return (TREE_CODE (arg) == TREE_CODE (parm)
13744                 && same_type_p (parm, arg)) ? 0 : 1;
13745       idx = TEMPLATE_TYPE_IDX (parm);
13746       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13747       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13748
13749       /* Check for mixed types and values.  */
13750       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13751            && TREE_CODE (tparm) != TYPE_DECL)
13752           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13753               && TREE_CODE (tparm) != TEMPLATE_DECL))
13754         return 1;
13755
13756       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13757         {
13758           /* ARG must be constructed from a template class or a template
13759              template parameter.  */
13760           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13761               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13762             return 1;
13763
13764           {
13765             tree parmvec = TYPE_TI_ARGS (parm);
13766             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13767             tree parm_parms 
13768               = DECL_INNERMOST_TEMPLATE_PARMS
13769                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13770             int i, len;
13771             int parm_variadic_p = 0;
13772
13773             /* The resolution to DR150 makes clear that default
13774                arguments for an N-argument may not be used to bind T
13775                to a template template parameter with fewer than N
13776                parameters.  It is not safe to permit the binding of
13777                default arguments as an extension, as that may change
13778                the meaning of a conforming program.  Consider:
13779
13780                   struct Dense { static const unsigned int dim = 1; };
13781
13782                   template <template <typename> class View,
13783                             typename Block>
13784                   void operator+(float, View<Block> const&);
13785
13786                   template <typename Block,
13787                             unsigned int Dim = Block::dim>
13788                   struct Lvalue_proxy { operator float() const; };
13789
13790                   void
13791                   test_1d (void) {
13792                     Lvalue_proxy<Dense> p;
13793                     float b;
13794                     b + p;
13795                   }
13796
13797               Here, if Lvalue_proxy is permitted to bind to View, then
13798               the global operator+ will be used; if they are not, the
13799               Lvalue_proxy will be converted to float.  */
13800             if (coerce_template_parms (parm_parms,
13801                                        argvec,
13802                                        TYPE_TI_TEMPLATE (parm),
13803                                        tf_none,
13804                                        /*require_all_args=*/true,
13805                                        /*use_default_args=*/false)
13806                 == error_mark_node)
13807               return 1;
13808
13809             /* Deduce arguments T, i from TT<T> or TT<i>.
13810                We check each element of PARMVEC and ARGVEC individually
13811                rather than the whole TREE_VEC since they can have
13812                different number of elements.  */
13813
13814             parmvec = expand_template_argument_pack (parmvec);
13815             argvec = expand_template_argument_pack (argvec);
13816
13817             len = TREE_VEC_LENGTH (parmvec);
13818
13819             /* Check if the parameters end in a pack, making them
13820                variadic.  */
13821             if (len > 0
13822                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13823               parm_variadic_p = 1;
13824             
13825             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13826               return 1;
13827
13828              for (i = 0; i < len - parm_variadic_p; ++i)
13829               {
13830                 if (unify (tparms, targs,
13831                            TREE_VEC_ELT (parmvec, i),
13832                            TREE_VEC_ELT (argvec, i),
13833                            UNIFY_ALLOW_NONE))
13834                   return 1;
13835               }
13836
13837             if (parm_variadic_p
13838                 && unify_pack_expansion (tparms, targs,
13839                                          parmvec, argvec,
13840                                          UNIFY_ALLOW_NONE,
13841                                          /*call_args_p=*/false,
13842                                          /*subr=*/false))
13843               return 1;
13844           }
13845           arg = TYPE_TI_TEMPLATE (arg);
13846
13847           /* Fall through to deduce template name.  */
13848         }
13849
13850       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13851           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13852         {
13853           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13854
13855           /* Simple cases: Value already set, does match or doesn't.  */
13856           if (targ != NULL_TREE && template_args_equal (targ, arg))
13857             return 0;
13858           else if (targ)
13859             return 1;
13860         }
13861       else
13862         {
13863           /* If PARM is `const T' and ARG is only `int', we don't have
13864              a match unless we are allowing additional qualification.
13865              If ARG is `const int' and PARM is just `T' that's OK;
13866              that binds `const int' to `T'.  */
13867           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13868                                          arg, parm))
13869             return 1;
13870
13871           /* Consider the case where ARG is `const volatile int' and
13872              PARM is `const T'.  Then, T should be `volatile int'.  */
13873           arg = cp_build_qualified_type_real
13874             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13875           if (arg == error_mark_node)
13876             return 1;
13877
13878           /* Simple cases: Value already set, does match or doesn't.  */
13879           if (targ != NULL_TREE && same_type_p (targ, arg))
13880             return 0;
13881           else if (targ)
13882             return 1;
13883
13884           /* Make sure that ARG is not a variable-sized array.  (Note
13885              that were talking about variable-sized arrays (like
13886              `int[n]'), rather than arrays of unknown size (like
13887              `int[]').)  We'll get very confused by such a type since
13888              the bound of the array will not be computable in an
13889              instantiation.  Besides, such types are not allowed in
13890              ISO C++, so we can do as we please here.  */
13891           if (variably_modified_type_p (arg, NULL_TREE))
13892             return 1;
13893
13894           /* Strip typedefs as in convert_template_argument.  */
13895           arg = strip_typedefs (arg);
13896         }
13897
13898       /* If ARG is a parameter pack or an expansion, we cannot unify
13899          against it unless PARM is also a parameter pack.  */
13900       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13901           && !template_parameter_pack_p (parm))
13902         return 1;
13903
13904       /* If the argument deduction results is a METHOD_TYPE,
13905          then there is a problem.
13906          METHOD_TYPE doesn't map to any real C++ type the result of
13907          the deduction can not be of that type.  */
13908       if (TREE_CODE (arg) == METHOD_TYPE)
13909         return 1;
13910
13911       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13912       return 0;
13913
13914     case TEMPLATE_PARM_INDEX:
13915       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13916       if (tparm == error_mark_node)
13917         return 1;
13918
13919       if (TEMPLATE_PARM_LEVEL (parm)
13920           != template_decl_level (tparm))
13921         /* The PARM is not one we're trying to unify.  Just check
13922            to see if it matches ARG.  */
13923         return !(TREE_CODE (arg) == TREE_CODE (parm)
13924                  && cp_tree_equal (parm, arg));
13925
13926       idx = TEMPLATE_PARM_IDX (parm);
13927       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13928
13929       if (targ)
13930         return !cp_tree_equal (targ, arg);
13931
13932       /* [temp.deduct.type] If, in the declaration of a function template
13933          with a non-type template-parameter, the non-type
13934          template-parameter is used in an expression in the function
13935          parameter-list and, if the corresponding template-argument is
13936          deduced, the template-argument type shall match the type of the
13937          template-parameter exactly, except that a template-argument
13938          deduced from an array bound may be of any integral type.
13939          The non-type parameter might use already deduced type parameters.  */
13940       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13941       if (!TREE_TYPE (arg))
13942         /* Template-parameter dependent expression.  Just accept it for now.
13943            It will later be processed in convert_template_argument.  */
13944         ;
13945       else if (same_type_p (TREE_TYPE (arg), tparm))
13946         /* OK */;
13947       else if ((strict & UNIFY_ALLOW_INTEGER)
13948                && (TREE_CODE (tparm) == INTEGER_TYPE
13949                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13950         /* Convert the ARG to the type of PARM; the deduced non-type
13951            template argument must exactly match the types of the
13952            corresponding parameter.  */
13953         arg = fold (build_nop (tparm, arg));
13954       else if (uses_template_parms (tparm))
13955         /* We haven't deduced the type of this parameter yet.  Try again
13956            later.  */
13957         return 0;
13958       else
13959         return 1;
13960
13961       /* If ARG is a parameter pack or an expansion, we cannot unify
13962          against it unless PARM is also a parameter pack.  */
13963       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13964           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13965         return 1;
13966
13967       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13968       return 0;
13969
13970     case PTRMEM_CST:
13971      {
13972         /* A pointer-to-member constant can be unified only with
13973          another constant.  */
13974       if (TREE_CODE (arg) != PTRMEM_CST)
13975         return 1;
13976
13977       /* Just unify the class member. It would be useless (and possibly
13978          wrong, depending on the strict flags) to unify also
13979          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13980          arg refer to the same variable, even if through different
13981          classes. For instance:
13982
13983          struct A { int x; };
13984          struct B : A { };
13985
13986          Unification of &A::x and &B::x must succeed.  */
13987       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13988                     PTRMEM_CST_MEMBER (arg), strict);
13989      }
13990
13991     case POINTER_TYPE:
13992       {
13993         if (TREE_CODE (arg) != POINTER_TYPE)
13994           return 1;
13995
13996         /* [temp.deduct.call]
13997
13998            A can be another pointer or pointer to member type that can
13999            be converted to the deduced A via a qualification
14000            conversion (_conv.qual_).
14001
14002            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14003            This will allow for additional cv-qualification of the
14004            pointed-to types if appropriate.  */
14005
14006         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14007           /* The derived-to-base conversion only persists through one
14008              level of pointers.  */
14009           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14010
14011         return unify (tparms, targs, TREE_TYPE (parm),
14012                       TREE_TYPE (arg), strict);
14013       }
14014
14015     case REFERENCE_TYPE:
14016       if (TREE_CODE (arg) != REFERENCE_TYPE)
14017         return 1;
14018       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14019                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14020
14021     case ARRAY_TYPE:
14022       if (TREE_CODE (arg) != ARRAY_TYPE)
14023         return 1;
14024       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14025           != (TYPE_DOMAIN (arg) == NULL_TREE))
14026         return 1;
14027       if (TYPE_DOMAIN (parm) != NULL_TREE)
14028         {
14029           tree parm_max;
14030           tree arg_max;
14031           bool parm_cst;
14032           bool arg_cst;
14033
14034           /* Our representation of array types uses "N - 1" as the
14035              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14036              not an integer constant.  We cannot unify arbitrarily
14037              complex expressions, so we eliminate the MINUS_EXPRs
14038              here.  */
14039           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14040           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14041           if (!parm_cst)
14042             {
14043               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14044               parm_max = TREE_OPERAND (parm_max, 0);
14045             }
14046           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14047           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14048           if (!arg_cst)
14049             {
14050               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14051                  trying to unify the type of a variable with the type
14052                  of a template parameter.  For example:
14053
14054                    template <unsigned int N>
14055                    void f (char (&) [N]);
14056                    int g(); 
14057                    void h(int i) {
14058                      char a[g(i)];
14059                      f(a); 
14060                    }
14061
14062                 Here, the type of the ARG will be "int [g(i)]", and
14063                 may be a SAVE_EXPR, etc.  */
14064               if (TREE_CODE (arg_max) != MINUS_EXPR)
14065                 return 1;
14066               arg_max = TREE_OPERAND (arg_max, 0);
14067             }
14068
14069           /* If only one of the bounds used a MINUS_EXPR, compensate
14070              by adding one to the other bound.  */
14071           if (parm_cst && !arg_cst)
14072             parm_max = fold_build2 (PLUS_EXPR,
14073                                     integer_type_node,
14074                                     parm_max,
14075                                     integer_one_node);
14076           else if (arg_cst && !parm_cst)
14077             arg_max = fold_build2 (PLUS_EXPR,
14078                                    integer_type_node,
14079                                    arg_max,
14080                                    integer_one_node);
14081
14082           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14083             return 1;
14084         }
14085       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14086                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14087
14088     case REAL_TYPE:
14089     case COMPLEX_TYPE:
14090     case VECTOR_TYPE:
14091     case INTEGER_TYPE:
14092     case BOOLEAN_TYPE:
14093     case ENUMERAL_TYPE:
14094     case VOID_TYPE:
14095       if (TREE_CODE (arg) != TREE_CODE (parm))
14096         return 1;
14097
14098       /* We have already checked cv-qualification at the top of the
14099          function.  */
14100       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14101         return 1;
14102
14103       /* As far as unification is concerned, this wins.  Later checks
14104          will invalidate it if necessary.  */
14105       return 0;
14106
14107       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14108       /* Type INTEGER_CST can come from ordinary constant template args.  */
14109     case INTEGER_CST:
14110       while (TREE_CODE (arg) == NOP_EXPR)
14111         arg = TREE_OPERAND (arg, 0);
14112
14113       if (TREE_CODE (arg) != INTEGER_CST)
14114         return 1;
14115       return !tree_int_cst_equal (parm, arg);
14116
14117     case TREE_VEC:
14118       {
14119         int i;
14120         if (TREE_CODE (arg) != TREE_VEC)
14121           return 1;
14122         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14123           return 1;
14124         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14125           if (unify (tparms, targs,
14126                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14127                      UNIFY_ALLOW_NONE))
14128             return 1;
14129         return 0;
14130       }
14131
14132     case RECORD_TYPE:
14133     case UNION_TYPE:
14134       if (TREE_CODE (arg) != TREE_CODE (parm))
14135         return 1;
14136
14137       if (TYPE_PTRMEMFUNC_P (parm))
14138         {
14139           if (!TYPE_PTRMEMFUNC_P (arg))
14140             return 1;
14141
14142           return unify (tparms, targs,
14143                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14144                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14145                         strict);
14146         }
14147
14148       if (CLASSTYPE_TEMPLATE_INFO (parm))
14149         {
14150           tree t = NULL_TREE;
14151
14152           if (strict_in & UNIFY_ALLOW_DERIVED)
14153             {
14154               /* First, we try to unify the PARM and ARG directly.  */
14155               t = try_class_unification (tparms, targs,
14156                                          parm, arg);
14157
14158               if (!t)
14159                 {
14160                   /* Fallback to the special case allowed in
14161                      [temp.deduct.call]:
14162
14163                        If P is a class, and P has the form
14164                        template-id, then A can be a derived class of
14165                        the deduced A.  Likewise, if P is a pointer to
14166                        a class of the form template-id, A can be a
14167                        pointer to a derived class pointed to by the
14168                        deduced A.  */
14169                   t = get_template_base (tparms, targs, parm, arg);
14170
14171                   if (!t)
14172                     return 1;
14173                 }
14174             }
14175           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14176                    && (CLASSTYPE_TI_TEMPLATE (parm)
14177                        == CLASSTYPE_TI_TEMPLATE (arg)))
14178             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14179                Then, we should unify `int' and `U'.  */
14180             t = arg;
14181           else
14182             /* There's no chance of unification succeeding.  */
14183             return 1;
14184
14185           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14186                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14187         }
14188       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14189         return 1;
14190       return 0;
14191
14192     case METHOD_TYPE:
14193     case FUNCTION_TYPE:
14194       {
14195         unsigned int nargs;
14196         tree *args;
14197         tree a;
14198         unsigned int i;
14199
14200         if (TREE_CODE (arg) != TREE_CODE (parm))
14201           return 1;
14202
14203         /* CV qualifications for methods can never be deduced, they must
14204            match exactly.  We need to check them explicitly here,
14205            because type_unification_real treats them as any other
14206            cv-qualified parameter.  */
14207         if (TREE_CODE (parm) == METHOD_TYPE
14208             && (!check_cv_quals_for_unify
14209                 (UNIFY_ALLOW_NONE,
14210                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14211                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14212           return 1;
14213
14214         if (unify (tparms, targs, TREE_TYPE (parm),
14215                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14216           return 1;
14217
14218         nargs = list_length (TYPE_ARG_TYPES (arg));
14219         args = XALLOCAVEC (tree, nargs);
14220         for (a = TYPE_ARG_TYPES (arg), i = 0;
14221              a != NULL_TREE && a != void_list_node;
14222              a = TREE_CHAIN (a), ++i)
14223           args[i] = TREE_VALUE (a);
14224         nargs = i;
14225
14226         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14227                                       args, nargs, 1, DEDUCE_EXACT,
14228                                       LOOKUP_NORMAL);
14229       }
14230
14231     case OFFSET_TYPE:
14232       /* Unify a pointer to member with a pointer to member function, which
14233          deduces the type of the member as a function type. */
14234       if (TYPE_PTRMEMFUNC_P (arg))
14235         {
14236           tree method_type;
14237           tree fntype;
14238           cp_cv_quals cv_quals;
14239
14240           /* Check top-level cv qualifiers */
14241           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14242             return 1;
14243
14244           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14245                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14246             return 1;
14247
14248           /* Determine the type of the function we are unifying against. */
14249           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14250           fntype =
14251             build_function_type (TREE_TYPE (method_type),
14252                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14253
14254           /* Extract the cv-qualifiers of the member function from the
14255              implicit object parameter and place them on the function
14256              type to be restored later. */
14257           cv_quals =
14258             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14259           fntype = build_qualified_type (fntype, cv_quals);
14260           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14261         }
14262
14263       if (TREE_CODE (arg) != OFFSET_TYPE)
14264         return 1;
14265       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14266                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14267         return 1;
14268       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14269                     strict);
14270
14271     case CONST_DECL:
14272       if (DECL_TEMPLATE_PARM_P (parm))
14273         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14274       if (arg != integral_constant_value (parm))
14275         return 1;
14276       return 0;
14277
14278     case FIELD_DECL:
14279     case TEMPLATE_DECL:
14280       /* Matched cases are handled by the ARG == PARM test above.  */
14281       return 1;
14282
14283     case TYPE_ARGUMENT_PACK:
14284     case NONTYPE_ARGUMENT_PACK:
14285       {
14286         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14287         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14288         int i, len = TREE_VEC_LENGTH (packed_parms);
14289         int argslen = TREE_VEC_LENGTH (packed_args);
14290         int parm_variadic_p = 0;
14291
14292         for (i = 0; i < len; ++i)
14293           {
14294             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14295               {
14296                 if (i == len - 1)
14297                   /* We can unify against something with a trailing
14298                      parameter pack.  */
14299                   parm_variadic_p = 1;
14300                 else
14301                   /* Since there is something following the pack
14302                      expansion, we cannot unify this template argument
14303                      list.  */
14304                   return 0;
14305               }
14306           }
14307           
14308
14309         /* If we don't have enough arguments to satisfy the parameters
14310            (not counting the pack expression at the end), or we have
14311            too many arguments for a parameter list that doesn't end in
14312            a pack expression, we can't unify.  */
14313         if (argslen < (len - parm_variadic_p)
14314             || (argslen > len && !parm_variadic_p))
14315           return 1;
14316
14317         /* Unify all of the parameters that precede the (optional)
14318            pack expression.  */
14319         for (i = 0; i < len - parm_variadic_p; ++i)
14320           {
14321             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14322                        TREE_VEC_ELT (packed_args, i), strict))
14323               return 1;
14324           }
14325
14326         if (parm_variadic_p)
14327           return unify_pack_expansion (tparms, targs, 
14328                                        packed_parms, packed_args,
14329                                        strict, /*call_args_p=*/false,
14330                                        /*subr=*/false);
14331         return 0;
14332       }
14333
14334       break;
14335
14336     case TYPEOF_TYPE:
14337     case DECLTYPE_TYPE:
14338       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14339          nodes.  */
14340       return 0;
14341
14342     case ERROR_MARK:
14343       /* Unification fails if we hit an error node.  */
14344       return 1;
14345
14346     default:
14347       gcc_assert (EXPR_P (parm));
14348
14349       /* We must be looking at an expression.  This can happen with
14350          something like:
14351
14352            template <int I>
14353            void foo(S<I>, S<I + 2>);
14354
14355          This is a "nondeduced context":
14356
14357            [deduct.type]
14358
14359            The nondeduced contexts are:
14360
14361            --A type that is a template-id in which one or more of
14362              the template-arguments is an expression that references
14363              a template-parameter.
14364
14365          In these cases, we assume deduction succeeded, but don't
14366          actually infer any unifications.  */
14367
14368       if (!uses_template_parms (parm)
14369           && !template_args_equal (parm, arg))
14370         return 1;
14371       else
14372         return 0;
14373     }
14374 }
14375 \f
14376 /* Note that DECL can be defined in this translation unit, if
14377    required.  */
14378
14379 static void
14380 mark_definable (tree decl)
14381 {
14382   tree clone;
14383   DECL_NOT_REALLY_EXTERN (decl) = 1;
14384   FOR_EACH_CLONE (clone, decl)
14385     DECL_NOT_REALLY_EXTERN (clone) = 1;
14386 }
14387
14388 /* Called if RESULT is explicitly instantiated, or is a member of an
14389    explicitly instantiated class.  */
14390
14391 void
14392 mark_decl_instantiated (tree result, int extern_p)
14393 {
14394   SET_DECL_EXPLICIT_INSTANTIATION (result);
14395
14396   /* If this entity has already been written out, it's too late to
14397      make any modifications.  */
14398   if (TREE_ASM_WRITTEN (result))
14399     return;
14400
14401   if (TREE_CODE (result) != FUNCTION_DECL)
14402     /* The TREE_PUBLIC flag for function declarations will have been
14403        set correctly by tsubst.  */
14404     TREE_PUBLIC (result) = 1;
14405
14406   /* This might have been set by an earlier implicit instantiation.  */
14407   DECL_COMDAT (result) = 0;
14408
14409   if (extern_p)
14410     DECL_NOT_REALLY_EXTERN (result) = 0;
14411   else
14412     {
14413       mark_definable (result);
14414       /* Always make artificials weak.  */
14415       if (DECL_ARTIFICIAL (result) && flag_weak)
14416         comdat_linkage (result);
14417       /* For WIN32 we also want to put explicit instantiations in
14418          linkonce sections.  */
14419       else if (TREE_PUBLIC (result))
14420         maybe_make_one_only (result);
14421     }
14422
14423   /* If EXTERN_P, then this function will not be emitted -- unless
14424      followed by an explicit instantiation, at which point its linkage
14425      will be adjusted.  If !EXTERN_P, then this function will be
14426      emitted here.  In neither circumstance do we want
14427      import_export_decl to adjust the linkage.  */
14428   DECL_INTERFACE_KNOWN (result) = 1;
14429 }
14430
14431 /* Given two function templates PAT1 and PAT2, return:
14432
14433    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14434    -1 if PAT2 is more specialized than PAT1.
14435    0 if neither is more specialized.
14436
14437    LEN indicates the number of parameters we should consider
14438    (defaulted parameters should not be considered).
14439
14440    The 1998 std underspecified function template partial ordering, and
14441    DR214 addresses the issue.  We take pairs of arguments, one from
14442    each of the templates, and deduce them against each other.  One of
14443    the templates will be more specialized if all the *other*
14444    template's arguments deduce against its arguments and at least one
14445    of its arguments *does* *not* deduce against the other template's
14446    corresponding argument.  Deduction is done as for class templates.
14447    The arguments used in deduction have reference and top level cv
14448    qualifiers removed.  Iff both arguments were originally reference
14449    types *and* deduction succeeds in both directions, the template
14450    with the more cv-qualified argument wins for that pairing (if
14451    neither is more cv-qualified, they both are equal).  Unlike regular
14452    deduction, after all the arguments have been deduced in this way,
14453    we do *not* verify the deduced template argument values can be
14454    substituted into non-deduced contexts, nor do we have to verify
14455    that all template arguments have been deduced.  */
14456
14457 int
14458 more_specialized_fn (tree pat1, tree pat2, int len)
14459 {
14460   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14461   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14462   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14463   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14464   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14465   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14466   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14467   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14468   int better1 = 0;
14469   int better2 = 0;
14470
14471   /* Remove the this parameter from non-static member functions.  If
14472      one is a non-static member function and the other is not a static
14473      member function, remove the first parameter from that function
14474      also.  This situation occurs for operator functions where we
14475      locate both a member function (with this pointer) and non-member
14476      operator (with explicit first operand).  */
14477   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14478     {
14479       len--; /* LEN is the number of significant arguments for DECL1 */
14480       args1 = TREE_CHAIN (args1);
14481       if (!DECL_STATIC_FUNCTION_P (decl2))
14482         args2 = TREE_CHAIN (args2);
14483     }
14484   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14485     {
14486       args2 = TREE_CHAIN (args2);
14487       if (!DECL_STATIC_FUNCTION_P (decl1))
14488         {
14489           len--;
14490           args1 = TREE_CHAIN (args1);
14491         }
14492     }
14493
14494   /* If only one is a conversion operator, they are unordered.  */
14495   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14496     return 0;
14497
14498   /* Consider the return type for a conversion function */
14499   if (DECL_CONV_FN_P (decl1))
14500     {
14501       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14502       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14503       len++;
14504     }
14505
14506   processing_template_decl++;
14507
14508   while (len--
14509          /* Stop when an ellipsis is seen.  */
14510          && args1 != NULL_TREE && args2 != NULL_TREE)
14511     {
14512       tree arg1 = TREE_VALUE (args1);
14513       tree arg2 = TREE_VALUE (args2);
14514       int deduce1, deduce2;
14515       int quals1 = -1;
14516       int quals2 = -1;
14517
14518       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14519           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14520         {
14521           /* When both arguments are pack expansions, we need only
14522              unify the patterns themselves.  */
14523           arg1 = PACK_EXPANSION_PATTERN (arg1);
14524           arg2 = PACK_EXPANSION_PATTERN (arg2);
14525
14526           /* This is the last comparison we need to do.  */
14527           len = 0;
14528         }
14529
14530       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14531         {
14532           arg1 = TREE_TYPE (arg1);
14533           quals1 = cp_type_quals (arg1);
14534         }
14535
14536       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14537         {
14538           arg2 = TREE_TYPE (arg2);
14539           quals2 = cp_type_quals (arg2);
14540         }
14541
14542       if ((quals1 < 0) != (quals2 < 0))
14543         {
14544           /* Only of the args is a reference, see if we should apply
14545              array/function pointer decay to it.  This is not part of
14546              DR214, but is, IMHO, consistent with the deduction rules
14547              for the function call itself, and with our earlier
14548              implementation of the underspecified partial ordering
14549              rules.  (nathan).  */
14550           if (quals1 >= 0)
14551             {
14552               switch (TREE_CODE (arg1))
14553                 {
14554                 case ARRAY_TYPE:
14555                   arg1 = TREE_TYPE (arg1);
14556                   /* FALLTHROUGH. */
14557                 case FUNCTION_TYPE:
14558                   arg1 = build_pointer_type (arg1);
14559                   break;
14560
14561                 default:
14562                   break;
14563                 }
14564             }
14565           else
14566             {
14567               switch (TREE_CODE (arg2))
14568                 {
14569                 case ARRAY_TYPE:
14570                   arg2 = TREE_TYPE (arg2);
14571                   /* FALLTHROUGH. */
14572                 case FUNCTION_TYPE:
14573                   arg2 = build_pointer_type (arg2);
14574                   break;
14575
14576                 default:
14577                   break;
14578                 }
14579             }
14580         }
14581
14582       arg1 = TYPE_MAIN_VARIANT (arg1);
14583       arg2 = TYPE_MAIN_VARIANT (arg2);
14584
14585       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14586         {
14587           int i, len2 = list_length (args2);
14588           tree parmvec = make_tree_vec (1);
14589           tree argvec = make_tree_vec (len2);
14590           tree ta = args2;
14591
14592           /* Setup the parameter vector, which contains only ARG1.  */
14593           TREE_VEC_ELT (parmvec, 0) = arg1;
14594
14595           /* Setup the argument vector, which contains the remaining
14596              arguments.  */
14597           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14598             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14599
14600           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14601                                            argvec, UNIFY_ALLOW_NONE, 
14602                                            /*call_args_p=*/false, 
14603                                            /*subr=*/0);
14604
14605           /* We cannot deduce in the other direction, because ARG1 is
14606              a pack expansion but ARG2 is not.  */
14607           deduce2 = 0;
14608         }
14609       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14610         {
14611           int i, len1 = list_length (args1);
14612           tree parmvec = make_tree_vec (1);
14613           tree argvec = make_tree_vec (len1);
14614           tree ta = args1;
14615
14616           /* Setup the parameter vector, which contains only ARG1.  */
14617           TREE_VEC_ELT (parmvec, 0) = arg2;
14618
14619           /* Setup the argument vector, which contains the remaining
14620              arguments.  */
14621           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14622             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14623
14624           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14625                                            argvec, UNIFY_ALLOW_NONE, 
14626                                            /*call_args_p=*/false, 
14627                                            /*subr=*/0);
14628
14629           /* We cannot deduce in the other direction, because ARG2 is
14630              a pack expansion but ARG1 is not.*/
14631           deduce1 = 0;
14632         }
14633
14634       else
14635         {
14636           /* The normal case, where neither argument is a pack
14637              expansion.  */
14638           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14639           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14640         }
14641
14642       if (!deduce1)
14643         better2 = -1;
14644       if (!deduce2)
14645         better1 = -1;
14646       if (better1 < 0 && better2 < 0)
14647         /* We've failed to deduce something in either direction.
14648            These must be unordered.  */
14649         break;
14650
14651       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14652         {
14653           /* Deduces in both directions, see if quals can
14654              disambiguate.  Pretend the worse one failed to deduce. */
14655           if ((quals1 & quals2) == quals2)
14656             deduce1 = 0;
14657           if ((quals1 & quals2) == quals1)
14658             deduce2 = 0;
14659         }
14660       if (deduce1 && !deduce2 && !better2)
14661         better2 = 1;
14662       if (deduce2 && !deduce1 && !better1)
14663         better1 = 1;
14664
14665       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14666           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14667         /* We have already processed all of the arguments in our
14668            handing of the pack expansion type.  */
14669         len = 0;
14670
14671       args1 = TREE_CHAIN (args1);
14672       args2 = TREE_CHAIN (args2);
14673     }
14674
14675   processing_template_decl--;
14676
14677   /* All things being equal, if the next argument is a pack expansion
14678      for one function but not for the other, prefer the
14679      non-variadic function.  */
14680   if ((better1 > 0) - (better2 > 0) == 0
14681       && args1 && TREE_VALUE (args1)
14682       && args2 && TREE_VALUE (args2))
14683     {
14684       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14685         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14686       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14687         return 1;
14688     }
14689
14690   return (better1 > 0) - (better2 > 0);
14691 }
14692
14693 /* Determine which of two partial specializations is more specialized.
14694
14695    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14696    to the first partial specialization.  The TREE_VALUE is the
14697    innermost set of template parameters for the partial
14698    specialization.  PAT2 is similar, but for the second template.
14699
14700    Return 1 if the first partial specialization is more specialized;
14701    -1 if the second is more specialized; 0 if neither is more
14702    specialized.
14703
14704    See [temp.class.order] for information about determining which of
14705    two templates is more specialized.  */
14706
14707 static int
14708 more_specialized_class (tree pat1, tree pat2)
14709 {
14710   tree targs;
14711   tree tmpl1, tmpl2;
14712   int winner = 0;
14713   bool any_deductions = false;
14714
14715   tmpl1 = TREE_TYPE (pat1);
14716   tmpl2 = TREE_TYPE (pat2);
14717
14718   /* Just like what happens for functions, if we are ordering between
14719      different class template specializations, we may encounter dependent
14720      types in the arguments, and we need our dependency check functions
14721      to behave correctly.  */
14722   ++processing_template_decl;
14723   targs = get_class_bindings (TREE_VALUE (pat1),
14724                               CLASSTYPE_TI_ARGS (tmpl1),
14725                               CLASSTYPE_TI_ARGS (tmpl2));
14726   if (targs)
14727     {
14728       --winner;
14729       any_deductions = true;
14730     }
14731
14732   targs = get_class_bindings (TREE_VALUE (pat2),
14733                               CLASSTYPE_TI_ARGS (tmpl2),
14734                               CLASSTYPE_TI_ARGS (tmpl1));
14735   if (targs)
14736     {
14737       ++winner;
14738       any_deductions = true;
14739     }
14740   --processing_template_decl;
14741
14742   /* In the case of a tie where at least one of the class templates
14743      has a parameter pack at the end, the template with the most
14744      non-packed parameters wins.  */
14745   if (winner == 0
14746       && any_deductions
14747       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14748           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14749     {
14750       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14751       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14752       int len1 = TREE_VEC_LENGTH (args1);
14753       int len2 = TREE_VEC_LENGTH (args2);
14754
14755       /* We don't count the pack expansion at the end.  */
14756       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14757         --len1;
14758       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14759         --len2;
14760
14761       if (len1 > len2)
14762         return 1;
14763       else if (len1 < len2)
14764         return -1;
14765     }
14766
14767   return winner;
14768 }
14769
14770 /* Return the template arguments that will produce the function signature
14771    DECL from the function template FN, with the explicit template
14772    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14773    also match.  Return NULL_TREE if no satisfactory arguments could be
14774    found.  */
14775
14776 static tree
14777 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14778 {
14779   int ntparms = DECL_NTPARMS (fn);
14780   tree targs = make_tree_vec (ntparms);
14781   tree decl_type;
14782   tree decl_arg_types;
14783   tree *args;
14784   unsigned int nargs, ix;
14785   tree arg;
14786
14787   /* Substitute the explicit template arguments into the type of DECL.
14788      The call to fn_type_unification will handle substitution into the
14789      FN.  */
14790   decl_type = TREE_TYPE (decl);
14791   if (explicit_args && uses_template_parms (decl_type))
14792     {
14793       tree tmpl;
14794       tree converted_args;
14795
14796       if (DECL_TEMPLATE_INFO (decl))
14797         tmpl = DECL_TI_TEMPLATE (decl);
14798       else
14799         /* We can get here for some invalid specializations.  */
14800         return NULL_TREE;
14801
14802       converted_args
14803         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14804                                  explicit_args, NULL_TREE,
14805                                  tf_none,
14806                                  /*require_all_args=*/false,
14807                                  /*use_default_args=*/false);
14808       if (converted_args == error_mark_node)
14809         return NULL_TREE;
14810
14811       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14812       if (decl_type == error_mark_node)
14813         return NULL_TREE;
14814     }
14815
14816   /* Never do unification on the 'this' parameter.  */
14817   decl_arg_types = skip_artificial_parms_for (decl, 
14818                                               TYPE_ARG_TYPES (decl_type));
14819
14820   nargs = list_length (decl_arg_types);
14821   args = XALLOCAVEC (tree, nargs);
14822   for (arg = decl_arg_types, ix = 0;
14823        arg != NULL_TREE && arg != void_list_node;
14824        arg = TREE_CHAIN (arg), ++ix)
14825     args[ix] = TREE_VALUE (arg);
14826
14827   if (fn_type_unification (fn, explicit_args, targs,
14828                            args, ix,
14829                            (check_rettype || DECL_CONV_FN_P (fn)
14830                             ? TREE_TYPE (decl_type) : NULL_TREE),
14831                            DEDUCE_EXACT, LOOKUP_NORMAL))
14832     return NULL_TREE;
14833
14834   return targs;
14835 }
14836
14837 /* Return the innermost template arguments that, when applied to a
14838    template specialization whose innermost template parameters are
14839    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
14840    ARGS.
14841
14842    For example, suppose we have:
14843
14844      template <class T, class U> struct S {};
14845      template <class T> struct S<T*, int> {};
14846
14847    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14848    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14849    int}.  The resulting vector will be {double}, indicating that `T'
14850    is bound to `double'.  */
14851
14852 static tree
14853 get_class_bindings (tree tparms, tree spec_args, tree args)
14854 {
14855   int i, ntparms = TREE_VEC_LENGTH (tparms);
14856   tree deduced_args;
14857   tree innermost_deduced_args;
14858
14859   innermost_deduced_args = make_tree_vec (ntparms);
14860   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14861     {
14862       deduced_args = copy_node (args);
14863       SET_TMPL_ARGS_LEVEL (deduced_args,
14864                            TMPL_ARGS_DEPTH (deduced_args),
14865                            innermost_deduced_args);
14866     }
14867   else
14868     deduced_args = innermost_deduced_args;
14869
14870   if (unify (tparms, deduced_args,
14871              INNERMOST_TEMPLATE_ARGS (spec_args),
14872              INNERMOST_TEMPLATE_ARGS (args),
14873              UNIFY_ALLOW_NONE))
14874     return NULL_TREE;
14875
14876   for (i =  0; i < ntparms; ++i)
14877     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14878       return NULL_TREE;
14879
14880   /* Verify that nondeduced template arguments agree with the type
14881      obtained from argument deduction.
14882
14883      For example:
14884
14885        struct A { typedef int X; };
14886        template <class T, class U> struct C {};
14887        template <class T> struct C<T, typename T::X> {};
14888
14889      Then with the instantiation `C<A, int>', we can deduce that
14890      `T' is `A' but unify () does not check whether `typename T::X'
14891      is `int'.  */
14892   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14893   if (spec_args == error_mark_node
14894       /* We only need to check the innermost arguments; the other
14895          arguments will always agree.  */
14896       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14897                               INNERMOST_TEMPLATE_ARGS (args)))
14898     return NULL_TREE;
14899
14900   /* Now that we have bindings for all of the template arguments,
14901      ensure that the arguments deduced for the template template
14902      parameters have compatible template parameter lists.  See the use
14903      of template_template_parm_bindings_ok_p in fn_type_unification
14904      for more information.  */
14905   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14906     return NULL_TREE;
14907
14908   return deduced_args;
14909 }
14910
14911 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14912    Return the TREE_LIST node with the most specialized template, if
14913    any.  If there is no most specialized template, the error_mark_node
14914    is returned.
14915
14916    Note that this function does not look at, or modify, the
14917    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14918    returned is one of the elements of INSTANTIATIONS, callers may
14919    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14920    and retrieve it from the value returned.  */
14921
14922 tree
14923 most_specialized_instantiation (tree templates)
14924 {
14925   tree fn, champ;
14926
14927   ++processing_template_decl;
14928
14929   champ = templates;
14930   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14931     {
14932       int fate = 0;
14933
14934       if (get_bindings (TREE_VALUE (champ),
14935                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14936                         NULL_TREE, /*check_ret=*/false))
14937         fate--;
14938
14939       if (get_bindings (TREE_VALUE (fn),
14940                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14941                         NULL_TREE, /*check_ret=*/false))
14942         fate++;
14943
14944       if (fate == -1)
14945         champ = fn;
14946       else if (!fate)
14947         {
14948           /* Equally specialized, move to next function.  If there
14949              is no next function, nothing's most specialized.  */
14950           fn = TREE_CHAIN (fn);
14951           champ = fn;
14952           if (!fn)
14953             break;
14954         }
14955     }
14956
14957   if (champ)
14958     /* Now verify that champ is better than everything earlier in the
14959        instantiation list.  */
14960     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14961       if (get_bindings (TREE_VALUE (champ),
14962                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14963                         NULL_TREE, /*check_ret=*/false)
14964           || !get_bindings (TREE_VALUE (fn),
14965                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14966                             NULL_TREE, /*check_ret=*/false))
14967         {
14968           champ = NULL_TREE;
14969           break;
14970         }
14971
14972   processing_template_decl--;
14973
14974   if (!champ)
14975     return error_mark_node;
14976
14977   return champ;
14978 }
14979
14980 /* If DECL is a specialization of some template, return the most
14981    general such template.  Otherwise, returns NULL_TREE.
14982
14983    For example, given:
14984
14985      template <class T> struct S { template <class U> void f(U); };
14986
14987    if TMPL is `template <class U> void S<int>::f(U)' this will return
14988    the full template.  This function will not trace past partial
14989    specializations, however.  For example, given in addition:
14990
14991      template <class T> struct S<T*> { template <class U> void f(U); };
14992
14993    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14994    `template <class T> template <class U> S<T*>::f(U)'.  */
14995
14996 tree
14997 most_general_template (tree decl)
14998 {
14999   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15000      an immediate specialization.  */
15001   if (TREE_CODE (decl) == FUNCTION_DECL)
15002     {
15003       if (DECL_TEMPLATE_INFO (decl)) {
15004         decl = DECL_TI_TEMPLATE (decl);
15005
15006         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15007            template friend.  */
15008         if (TREE_CODE (decl) != TEMPLATE_DECL)
15009           return NULL_TREE;
15010       } else
15011         return NULL_TREE;
15012     }
15013
15014   /* Look for more and more general templates.  */
15015   while (DECL_TEMPLATE_INFO (decl))
15016     {
15017       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15018          (See cp-tree.h for details.)  */
15019       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15020         break;
15021
15022       if (CLASS_TYPE_P (TREE_TYPE (decl))
15023           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15024         break;
15025
15026       /* Stop if we run into an explicitly specialized class template.  */
15027       if (!DECL_NAMESPACE_SCOPE_P (decl)
15028           && DECL_CONTEXT (decl)
15029           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15030         break;
15031
15032       decl = DECL_TI_TEMPLATE (decl);
15033     }
15034
15035   return decl;
15036 }
15037
15038 /* Return the most specialized of the class template partial
15039    specializations of TMPL which can produce TYPE, a specialization of
15040    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15041    a _TYPE node corresponding to the partial specialization, while the
15042    TREE_PURPOSE is the set of template arguments that must be
15043    substituted into the TREE_TYPE in order to generate TYPE.
15044
15045    If the choice of partial specialization is ambiguous, a diagnostic
15046    is issued, and the error_mark_node is returned.  If there are no
15047    partial specializations of TMPL matching TYPE, then NULL_TREE is
15048    returned.  */
15049
15050 static tree
15051 most_specialized_class (tree type, tree tmpl)
15052 {
15053   tree list = NULL_TREE;
15054   tree t;
15055   tree champ;
15056   int fate;
15057   bool ambiguous_p;
15058   tree args;
15059   tree outer_args = NULL_TREE;
15060
15061   tmpl = most_general_template (tmpl);
15062   args = CLASSTYPE_TI_ARGS (type);
15063
15064   /* For determining which partial specialization to use, only the
15065      innermost args are interesting.  */
15066   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15067     {
15068       outer_args = strip_innermost_template_args (args, 1);
15069       args = INNERMOST_TEMPLATE_ARGS (args);
15070     }
15071
15072   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15073     {
15074       tree partial_spec_args;
15075       tree spec_args;
15076       tree parms = TREE_VALUE (t);
15077
15078       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15079       if (outer_args)
15080         {
15081           int i;
15082
15083           ++processing_template_decl;
15084
15085           /* Discard the outer levels of args, and then substitute in the
15086              template args from the enclosing class.  */
15087           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15088           partial_spec_args = tsubst_template_args
15089             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15090
15091           /* PARMS already refers to just the innermost parms, but the
15092              template parms in partial_spec_args had their levels lowered
15093              by tsubst, so we need to do the same for the parm list.  We
15094              can't just tsubst the TREE_VEC itself, as tsubst wants to
15095              treat a TREE_VEC as an argument vector.  */
15096           parms = copy_node (parms);
15097           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15098             TREE_VEC_ELT (parms, i) =
15099               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15100
15101           --processing_template_decl;
15102         }
15103       spec_args = get_class_bindings (parms,
15104                                       partial_spec_args,
15105                                       args);
15106       if (spec_args)
15107         {
15108           if (outer_args)
15109             spec_args = add_to_template_args (outer_args, spec_args);
15110           list = tree_cons (spec_args, TREE_VALUE (t), list);
15111           TREE_TYPE (list) = TREE_TYPE (t);
15112         }
15113     }
15114
15115   if (! list)
15116     return NULL_TREE;
15117
15118   ambiguous_p = false;
15119   t = list;
15120   champ = t;
15121   t = TREE_CHAIN (t);
15122   for (; t; t = TREE_CHAIN (t))
15123     {
15124       fate = more_specialized_class (champ, t);
15125       if (fate == 1)
15126         ;
15127       else
15128         {
15129           if (fate == 0)
15130             {
15131               t = TREE_CHAIN (t);
15132               if (! t)
15133                 {
15134                   ambiguous_p = true;
15135                   break;
15136                 }
15137             }
15138           champ = t;
15139         }
15140     }
15141
15142   if (!ambiguous_p)
15143     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15144       {
15145         fate = more_specialized_class (champ, t);
15146         if (fate != 1)
15147           {
15148             ambiguous_p = true;
15149             break;
15150           }
15151       }
15152
15153   if (ambiguous_p)
15154     {
15155       const char *str = "candidates are:";
15156       error ("ambiguous class template instantiation for %q#T", type);
15157       for (t = list; t; t = TREE_CHAIN (t))
15158         {
15159           error ("%s %+#T", str, TREE_TYPE (t));
15160           str = "               ";
15161         }
15162       return error_mark_node;
15163     }
15164
15165   return champ;
15166 }
15167
15168 /* Explicitly instantiate DECL.  */
15169
15170 void
15171 do_decl_instantiation (tree decl, tree storage)
15172 {
15173   tree result = NULL_TREE;
15174   int extern_p = 0;
15175
15176   if (!decl || decl == error_mark_node)
15177     /* An error occurred, for which grokdeclarator has already issued
15178        an appropriate message.  */
15179     return;
15180   else if (! DECL_LANG_SPECIFIC (decl))
15181     {
15182       error ("explicit instantiation of non-template %q#D", decl);
15183       return;
15184     }
15185   else if (TREE_CODE (decl) == VAR_DECL)
15186     {
15187       /* There is an asymmetry here in the way VAR_DECLs and
15188          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15189          the latter, the DECL we get back will be marked as a
15190          template instantiation, and the appropriate
15191          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15192          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15193          should handle VAR_DECLs as it currently handles
15194          FUNCTION_DECLs.  */
15195       if (!DECL_CLASS_SCOPE_P (decl))
15196         {
15197           error ("%qD is not a static data member of a class template", decl);
15198           return;
15199         }
15200       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15201       if (!result || TREE_CODE (result) != VAR_DECL)
15202         {
15203           error ("no matching template for %qD found", decl);
15204           return;
15205         }
15206       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15207         {
15208           error ("type %qT for explicit instantiation %qD does not match "
15209                  "declared type %qT", TREE_TYPE (result), decl,
15210                  TREE_TYPE (decl));
15211           return;
15212         }
15213     }
15214   else if (TREE_CODE (decl) != FUNCTION_DECL)
15215     {
15216       error ("explicit instantiation of %q#D", decl);
15217       return;
15218     }
15219   else
15220     result = decl;
15221
15222   /* Check for various error cases.  Note that if the explicit
15223      instantiation is valid the RESULT will currently be marked as an
15224      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15225      until we get here.  */
15226
15227   if (DECL_TEMPLATE_SPECIALIZATION (result))
15228     {
15229       /* DR 259 [temp.spec].
15230
15231          Both an explicit instantiation and a declaration of an explicit
15232          specialization shall not appear in a program unless the explicit
15233          instantiation follows a declaration of the explicit specialization.
15234
15235          For a given set of template parameters, if an explicit
15236          instantiation of a template appears after a declaration of an
15237          explicit specialization for that template, the explicit
15238          instantiation has no effect.  */
15239       return;
15240     }
15241   else if (DECL_EXPLICIT_INSTANTIATION (result))
15242     {
15243       /* [temp.spec]
15244
15245          No program shall explicitly instantiate any template more
15246          than once.
15247
15248          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15249          the first instantiation was `extern' and the second is not,
15250          and EXTERN_P for the opposite case.  */
15251       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15252         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15253       /* If an "extern" explicit instantiation follows an ordinary
15254          explicit instantiation, the template is instantiated.  */
15255       if (extern_p)
15256         return;
15257     }
15258   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15259     {
15260       error ("no matching template for %qD found", result);
15261       return;
15262     }
15263   else if (!DECL_TEMPLATE_INFO (result))
15264     {
15265       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15266       return;
15267     }
15268
15269   if (storage == NULL_TREE)
15270     ;
15271   else if (storage == ridpointers[(int) RID_EXTERN])
15272     {
15273       if (!in_system_header && (cxx_dialect == cxx98))
15274         pedwarn (input_location, OPT_pedantic, 
15275                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15276                  "instantiations");
15277       extern_p = 1;
15278     }
15279   else
15280     error ("storage class %qD applied to template instantiation", storage);
15281
15282   check_explicit_instantiation_namespace (result);
15283   mark_decl_instantiated (result, extern_p);
15284   if (! extern_p)
15285     instantiate_decl (result, /*defer_ok=*/1,
15286                       /*expl_inst_class_mem_p=*/false);
15287 }
15288
15289 static void
15290 mark_class_instantiated (tree t, int extern_p)
15291 {
15292   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15293   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15294   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15295   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15296   if (! extern_p)
15297     {
15298       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15299       rest_of_type_compilation (t, 1);
15300     }
15301 }
15302
15303 /* Called from do_type_instantiation through binding_table_foreach to
15304    do recursive instantiation for the type bound in ENTRY.  */
15305 static void
15306 bt_instantiate_type_proc (binding_entry entry, void *data)
15307 {
15308   tree storage = *(tree *) data;
15309
15310   if (MAYBE_CLASS_TYPE_P (entry->type)
15311       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15312     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15313 }
15314
15315 /* Called from do_type_instantiation to instantiate a member
15316    (a member function or a static member variable) of an
15317    explicitly instantiated class template.  */
15318 static void
15319 instantiate_class_member (tree decl, int extern_p)
15320 {
15321   mark_decl_instantiated (decl, extern_p);
15322   if (! extern_p)
15323     instantiate_decl (decl, /*defer_ok=*/1,
15324                       /*expl_inst_class_mem_p=*/true);
15325 }
15326
15327 /* Perform an explicit instantiation of template class T.  STORAGE, if
15328    non-null, is the RID for extern, inline or static.  COMPLAIN is
15329    nonzero if this is called from the parser, zero if called recursively,
15330    since the standard is unclear (as detailed below).  */
15331
15332 void
15333 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15334 {
15335   int extern_p = 0;
15336   int nomem_p = 0;
15337   int static_p = 0;
15338   int previous_instantiation_extern_p = 0;
15339
15340   if (TREE_CODE (t) == TYPE_DECL)
15341     t = TREE_TYPE (t);
15342
15343   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15344     {
15345       error ("explicit instantiation of non-template type %qT", t);
15346       return;
15347     }
15348
15349   complete_type (t);
15350
15351   if (!COMPLETE_TYPE_P (t))
15352     {
15353       if (complain & tf_error)
15354         error ("explicit instantiation of %q#T before definition of template",
15355                t);
15356       return;
15357     }
15358
15359   if (storage != NULL_TREE)
15360     {
15361       if (!in_system_header)
15362         {
15363           if (storage == ridpointers[(int) RID_EXTERN])
15364             {
15365               if (cxx_dialect == cxx98)
15366                 pedwarn (input_location, OPT_pedantic, 
15367                          "ISO C++ 1998 forbids the use of %<extern%> on "
15368                          "explicit instantiations");
15369             }
15370           else
15371             pedwarn (input_location, OPT_pedantic, 
15372                      "ISO C++ forbids the use of %qE"
15373                      " on explicit instantiations", storage);
15374         }
15375
15376       if (storage == ridpointers[(int) RID_INLINE])
15377         nomem_p = 1;
15378       else if (storage == ridpointers[(int) RID_EXTERN])
15379         extern_p = 1;
15380       else if (storage == ridpointers[(int) RID_STATIC])
15381         static_p = 1;
15382       else
15383         {
15384           error ("storage class %qD applied to template instantiation",
15385                  storage);
15386           extern_p = 0;
15387         }
15388     }
15389
15390   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15391     {
15392       /* DR 259 [temp.spec].
15393
15394          Both an explicit instantiation and a declaration of an explicit
15395          specialization shall not appear in a program unless the explicit
15396          instantiation follows a declaration of the explicit specialization.
15397
15398          For a given set of template parameters, if an explicit
15399          instantiation of a template appears after a declaration of an
15400          explicit specialization for that template, the explicit
15401          instantiation has no effect.  */
15402       return;
15403     }
15404   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15405     {
15406       /* [temp.spec]
15407
15408          No program shall explicitly instantiate any template more
15409          than once.
15410
15411          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15412          instantiation was `extern'.  If EXTERN_P then the second is.
15413          These cases are OK.  */
15414       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15415
15416       if (!previous_instantiation_extern_p && !extern_p
15417           && (complain & tf_error))
15418         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15419
15420       /* If we've already instantiated the template, just return now.  */
15421       if (!CLASSTYPE_INTERFACE_ONLY (t))
15422         return;
15423     }
15424
15425   check_explicit_instantiation_namespace (TYPE_NAME (t));
15426   mark_class_instantiated (t, extern_p);
15427
15428   if (nomem_p)
15429     return;
15430
15431   {
15432     tree tmp;
15433
15434     /* In contrast to implicit instantiation, where only the
15435        declarations, and not the definitions, of members are
15436        instantiated, we have here:
15437
15438          [temp.explicit]
15439
15440          The explicit instantiation of a class template specialization
15441          implies the instantiation of all of its members not
15442          previously explicitly specialized in the translation unit
15443          containing the explicit instantiation.
15444
15445        Of course, we can't instantiate member template classes, since
15446        we don't have any arguments for them.  Note that the standard
15447        is unclear on whether the instantiation of the members are
15448        *explicit* instantiations or not.  However, the most natural
15449        interpretation is that it should be an explicit instantiation.  */
15450
15451     if (! static_p)
15452       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15453         if (TREE_CODE (tmp) == FUNCTION_DECL
15454             && DECL_TEMPLATE_INSTANTIATION (tmp))
15455           instantiate_class_member (tmp, extern_p);
15456
15457     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15458       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15459         instantiate_class_member (tmp, extern_p);
15460
15461     if (CLASSTYPE_NESTED_UTDS (t))
15462       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15463                              bt_instantiate_type_proc, &storage);
15464   }
15465 }
15466
15467 /* Given a function DECL, which is a specialization of TMPL, modify
15468    DECL to be a re-instantiation of TMPL with the same template
15469    arguments.  TMPL should be the template into which tsubst'ing
15470    should occur for DECL, not the most general template.
15471
15472    One reason for doing this is a scenario like this:
15473
15474      template <class T>
15475      void f(const T&, int i);
15476
15477      void g() { f(3, 7); }
15478
15479      template <class T>
15480      void f(const T& t, const int i) { }
15481
15482    Note that when the template is first instantiated, with
15483    instantiate_template, the resulting DECL will have no name for the
15484    first parameter, and the wrong type for the second.  So, when we go
15485    to instantiate the DECL, we regenerate it.  */
15486
15487 static void
15488 regenerate_decl_from_template (tree decl, tree tmpl)
15489 {
15490   /* The arguments used to instantiate DECL, from the most general
15491      template.  */
15492   tree args;
15493   tree code_pattern;
15494
15495   args = DECL_TI_ARGS (decl);
15496   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15497
15498   /* Make sure that we can see identifiers, and compute access
15499      correctly.  */
15500   push_access_scope (decl);
15501
15502   if (TREE_CODE (decl) == FUNCTION_DECL)
15503     {
15504       tree decl_parm;
15505       tree pattern_parm;
15506       tree specs;
15507       int args_depth;
15508       int parms_depth;
15509
15510       args_depth = TMPL_ARGS_DEPTH (args);
15511       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15512       if (args_depth > parms_depth)
15513         args = get_innermost_template_args (args, parms_depth);
15514
15515       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15516                                               args, tf_error, NULL_TREE);
15517       if (specs)
15518         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15519                                                     specs);
15520
15521       /* Merge parameter declarations.  */
15522       decl_parm = skip_artificial_parms_for (decl,
15523                                              DECL_ARGUMENTS (decl));
15524       pattern_parm
15525         = skip_artificial_parms_for (code_pattern,
15526                                      DECL_ARGUMENTS (code_pattern));
15527       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15528         {
15529           tree parm_type;
15530           tree attributes;
15531           
15532           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15533             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15534           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15535                               NULL_TREE);
15536           parm_type = type_decays_to (parm_type);
15537           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15538             TREE_TYPE (decl_parm) = parm_type;
15539           attributes = DECL_ATTRIBUTES (pattern_parm);
15540           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15541             {
15542               DECL_ATTRIBUTES (decl_parm) = attributes;
15543               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15544             }
15545           decl_parm = TREE_CHAIN (decl_parm);
15546           pattern_parm = TREE_CHAIN (pattern_parm);
15547         }
15548       /* Merge any parameters that match with the function parameter
15549          pack.  */
15550       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15551         {
15552           int i, len;
15553           tree expanded_types;
15554           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15555              the parameters in this function parameter pack.  */
15556           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15557                                                  args, tf_error, NULL_TREE);
15558           len = TREE_VEC_LENGTH (expanded_types);
15559           for (i = 0; i < len; i++)
15560             {
15561               tree parm_type;
15562               tree attributes;
15563           
15564               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15565                 /* Rename the parameter to include the index.  */
15566                 DECL_NAME (decl_parm) = 
15567                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15568               parm_type = TREE_VEC_ELT (expanded_types, i);
15569               parm_type = type_decays_to (parm_type);
15570               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15571                 TREE_TYPE (decl_parm) = parm_type;
15572               attributes = DECL_ATTRIBUTES (pattern_parm);
15573               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15574                 {
15575                   DECL_ATTRIBUTES (decl_parm) = attributes;
15576                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15577                 }
15578               decl_parm = TREE_CHAIN (decl_parm);
15579             }
15580         }
15581       /* Merge additional specifiers from the CODE_PATTERN.  */
15582       if (DECL_DECLARED_INLINE_P (code_pattern)
15583           && !DECL_DECLARED_INLINE_P (decl))
15584         DECL_DECLARED_INLINE_P (decl) = 1;
15585     }
15586   else if (TREE_CODE (decl) == VAR_DECL)
15587     DECL_INITIAL (decl) =
15588       tsubst_expr (DECL_INITIAL (code_pattern), args,
15589                    tf_error, DECL_TI_TEMPLATE (decl),
15590                    /*integral_constant_expression_p=*/false);
15591   else
15592     gcc_unreachable ();
15593
15594   pop_access_scope (decl);
15595 }
15596
15597 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15598    substituted to get DECL.  */
15599
15600 tree
15601 template_for_substitution (tree decl)
15602 {
15603   tree tmpl = DECL_TI_TEMPLATE (decl);
15604
15605   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15606      for the instantiation.  This is not always the most general
15607      template.  Consider, for example:
15608
15609         template <class T>
15610         struct S { template <class U> void f();
15611                    template <> void f<int>(); };
15612
15613      and an instantiation of S<double>::f<int>.  We want TD to be the
15614      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15615   while (/* An instantiation cannot have a definition, so we need a
15616             more general template.  */
15617          DECL_TEMPLATE_INSTANTIATION (tmpl)
15618            /* We must also deal with friend templates.  Given:
15619
15620                 template <class T> struct S {
15621                   template <class U> friend void f() {};
15622                 };
15623
15624               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15625               so far as the language is concerned, but that's still
15626               where we get the pattern for the instantiation from.  On
15627               other hand, if the definition comes outside the class, say:
15628
15629                 template <class T> struct S {
15630                   template <class U> friend void f();
15631                 };
15632                 template <class U> friend void f() {}
15633
15634               we don't need to look any further.  That's what the check for
15635               DECL_INITIAL is for.  */
15636           || (TREE_CODE (decl) == FUNCTION_DECL
15637               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15638               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15639     {
15640       /* The present template, TD, should not be a definition.  If it
15641          were a definition, we should be using it!  Note that we
15642          cannot restructure the loop to just keep going until we find
15643          a template with a definition, since that might go too far if
15644          a specialization was declared, but not defined.  */
15645       gcc_assert (TREE_CODE (decl) != VAR_DECL
15646                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15647
15648       /* Fetch the more general template.  */
15649       tmpl = DECL_TI_TEMPLATE (tmpl);
15650     }
15651
15652   return tmpl;
15653 }
15654
15655 /* Produce the definition of D, a _DECL generated from a template.  If
15656    DEFER_OK is nonzero, then we don't have to actually do the
15657    instantiation now; we just have to do it sometime.  Normally it is
15658    an error if this is an explicit instantiation but D is undefined.
15659    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15660    explicitly instantiated class template.  */
15661
15662 tree
15663 instantiate_decl (tree d, int defer_ok,
15664                   bool expl_inst_class_mem_p)
15665 {
15666   tree tmpl = DECL_TI_TEMPLATE (d);
15667   tree gen_args;
15668   tree args;
15669   tree td;
15670   tree code_pattern;
15671   tree spec;
15672   tree gen_tmpl;
15673   bool pattern_defined;
15674   int need_push;
15675   location_t saved_loc = input_location;
15676   bool external_p;
15677
15678   /* This function should only be used to instantiate templates for
15679      functions and static member variables.  */
15680   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15681               || TREE_CODE (d) == VAR_DECL);
15682
15683   /* Variables are never deferred; if instantiation is required, they
15684      are instantiated right away.  That allows for better code in the
15685      case that an expression refers to the value of the variable --
15686      if the variable has a constant value the referring expression can
15687      take advantage of that fact.  */
15688   if (TREE_CODE (d) == VAR_DECL)
15689     defer_ok = 0;
15690
15691   /* Don't instantiate cloned functions.  Instead, instantiate the
15692      functions they cloned.  */
15693   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15694     d = DECL_CLONED_FUNCTION (d);
15695
15696   if (DECL_TEMPLATE_INSTANTIATED (d)
15697       || DECL_TEMPLATE_SPECIALIZATION (d))
15698     /* D has already been instantiated or explicitly specialized, so
15699        there's nothing for us to do here.
15700
15701        It might seem reasonable to check whether or not D is an explicit
15702        instantiation, and, if so, stop here.  But when an explicit
15703        instantiation is deferred until the end of the compilation,
15704        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
15705        the instantiation.  */
15706     return d;
15707
15708   gen_tmpl = most_general_template (tmpl);
15709   gen_args = DECL_TI_ARGS (d);
15710
15711   if (tmpl != gen_tmpl)
15712     /* We should already have the extra args.  */
15713     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
15714                 == TMPL_ARGS_DEPTH (gen_args));
15715   /* And what's in the hash table should match D.  */
15716   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
15717               || spec == NULL_TREE);
15718
15719   /* This needs to happen before any tsubsting.  */
15720   if (! push_tinst_level (d))
15721     return d;
15722
15723   timevar_push (TV_PARSE);
15724
15725   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15726      for the instantiation.  */
15727   td = template_for_substitution (d);
15728   code_pattern = DECL_TEMPLATE_RESULT (td);
15729
15730   /* We should never be trying to instantiate a member of a class
15731      template or partial specialization.  */
15732   gcc_assert (d != code_pattern);
15733
15734   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15735       || DECL_TEMPLATE_SPECIALIZATION (td))
15736     /* In the case of a friend template whose definition is provided
15737        outside the class, we may have too many arguments.  Drop the
15738        ones we don't need.  The same is true for specializations.  */
15739     args = get_innermost_template_args
15740       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15741   else
15742     args = gen_args;
15743
15744   if (TREE_CODE (d) == FUNCTION_DECL)
15745     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15746   else
15747     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15748
15749   /* We may be in the middle of deferred access check.  Disable it now.  */
15750   push_deferring_access_checks (dk_no_deferred);
15751
15752   /* Unless an explicit instantiation directive has already determined
15753      the linkage of D, remember that a definition is available for
15754      this entity.  */
15755   if (pattern_defined
15756       && !DECL_INTERFACE_KNOWN (d)
15757       && !DECL_NOT_REALLY_EXTERN (d))
15758     mark_definable (d);
15759
15760   input_location = DECL_SOURCE_LOCATION (d);
15761
15762   /* If D is a member of an explicitly instantiated class template,
15763      and no definition is available, treat it like an implicit
15764      instantiation.  */
15765   if (!pattern_defined && expl_inst_class_mem_p
15766       && DECL_EXPLICIT_INSTANTIATION (d))
15767     {
15768       DECL_NOT_REALLY_EXTERN (d) = 0;
15769       DECL_INTERFACE_KNOWN (d) = 0;
15770       SET_DECL_IMPLICIT_INSTANTIATION (d);
15771     }
15772
15773   if (!defer_ok)
15774     {
15775       /* Recheck the substitutions to obtain any warning messages
15776          about ignoring cv qualifiers.  */
15777       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15778       tree type = TREE_TYPE (gen);
15779
15780       /* Make sure that we can see identifiers, and compute access
15781          correctly.  D is already the target FUNCTION_DECL with the
15782          right context.  */
15783       push_access_scope (d);
15784
15785       if (TREE_CODE (gen) == FUNCTION_DECL)
15786         {
15787           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15788           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15789                                           d);
15790           /* Don't simply tsubst the function type, as that will give
15791              duplicate warnings about poor parameter qualifications.
15792              The function arguments are the same as the decl_arguments
15793              without the top level cv qualifiers.  */
15794           type = TREE_TYPE (type);
15795         }
15796       tsubst (type, gen_args, tf_warning_or_error, d);
15797
15798       pop_access_scope (d);
15799     }
15800
15801   /* Check to see whether we know that this template will be
15802      instantiated in some other file, as with "extern template"
15803      extension.  */
15804   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15805   /* In general, we do not instantiate such templates...  */
15806   if (external_p
15807       /* ... but we instantiate inline functions so that we can inline
15808          them.  An explicit instantiation declaration prohibits implicit
15809          instantiation of non-inline functions.  With high levels of
15810          optimization, we would normally inline non-inline functions
15811          -- but we're not allowed to do that for "extern template" functions.
15812          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15813          possibly_inlined_p.  And ...  */
15814       && ! (TREE_CODE (d) == FUNCTION_DECL
15815             && DECL_DECLARED_INLINE_P (d))
15816       /* ... we instantiate static data members whose values are
15817          needed in integral constant expressions.  */
15818       && ! (TREE_CODE (d) == VAR_DECL
15819             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15820     goto out;
15821   /* Defer all other templates, unless we have been explicitly
15822      forbidden from doing so.  */
15823   if (/* If there is no definition, we cannot instantiate the
15824          template.  */
15825       ! pattern_defined
15826       /* If it's OK to postpone instantiation, do so.  */
15827       || defer_ok
15828       /* If this is a static data member that will be defined
15829          elsewhere, we don't want to instantiate the entire data
15830          member, but we do want to instantiate the initializer so that
15831          we can substitute that elsewhere.  */
15832       || (external_p && TREE_CODE (d) == VAR_DECL))
15833     {
15834       /* The definition of the static data member is now required so
15835          we must substitute the initializer.  */
15836       if (TREE_CODE (d) == VAR_DECL
15837           && !DECL_INITIAL (d)
15838           && DECL_INITIAL (code_pattern))
15839         {
15840           tree ns;
15841           tree init;
15842
15843           ns = decl_namespace_context (d);
15844           push_nested_namespace (ns);
15845           push_nested_class (DECL_CONTEXT (d));
15846           init = tsubst_expr (DECL_INITIAL (code_pattern),
15847                               args,
15848                               tf_warning_or_error, NULL_TREE,
15849                               /*integral_constant_expression_p=*/false);
15850           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15851                           /*asmspec_tree=*/NULL_TREE,
15852                           LOOKUP_ONLYCONVERTING);
15853           pop_nested_class ();
15854           pop_nested_namespace (ns);
15855         }
15856
15857       /* We restore the source position here because it's used by
15858          add_pending_template.  */
15859       input_location = saved_loc;
15860
15861       if (at_eof && !pattern_defined
15862           && DECL_EXPLICIT_INSTANTIATION (d)
15863           && DECL_NOT_REALLY_EXTERN (d))
15864         /* [temp.explicit]
15865
15866            The definition of a non-exported function template, a
15867            non-exported member function template, or a non-exported
15868            member function or static data member of a class template
15869            shall be present in every translation unit in which it is
15870            explicitly instantiated.  */
15871         permerror (input_location,  "explicit instantiation of %qD "
15872                    "but no definition available", d);
15873
15874       /* ??? Historically, we have instantiated inline functions, even
15875          when marked as "extern template".  */
15876       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15877         add_pending_template (d);
15878       goto out;
15879     }
15880   /* Tell the repository that D is available in this translation unit
15881      -- and see if it is supposed to be instantiated here.  */
15882   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15883     {
15884       /* In a PCH file, despite the fact that the repository hasn't
15885          requested instantiation in the PCH it is still possible that
15886          an instantiation will be required in a file that includes the
15887          PCH.  */
15888       if (pch_file)
15889         add_pending_template (d);
15890       /* Instantiate inline functions so that the inliner can do its
15891          job, even though we'll not be emitting a copy of this
15892          function.  */
15893       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15894         goto out;
15895     }
15896
15897   need_push = !cfun || !global_bindings_p ();
15898   if (need_push)
15899     push_to_top_level ();
15900
15901   /* Mark D as instantiated so that recursive calls to
15902      instantiate_decl do not try to instantiate it again.  */
15903   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15904
15905   /* Regenerate the declaration in case the template has been modified
15906      by a subsequent redeclaration.  */
15907   regenerate_decl_from_template (d, td);
15908
15909   /* We already set the file and line above.  Reset them now in case
15910      they changed as a result of calling regenerate_decl_from_template.  */
15911   input_location = DECL_SOURCE_LOCATION (d);
15912
15913   if (TREE_CODE (d) == VAR_DECL)
15914     {
15915       tree init;
15916
15917       /* Clear out DECL_RTL; whatever was there before may not be right
15918          since we've reset the type of the declaration.  */
15919       SET_DECL_RTL (d, NULL_RTX);
15920       DECL_IN_AGGR_P (d) = 0;
15921
15922       /* The initializer is placed in DECL_INITIAL by
15923          regenerate_decl_from_template.  Pull it out so that
15924          cp_finish_decl can process it.  */
15925       init = DECL_INITIAL (d);
15926       DECL_INITIAL (d) = NULL_TREE;
15927       DECL_INITIALIZED_P (d) = 0;
15928
15929       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15930          initializer.  That function will defer actual emission until
15931          we have a chance to determine linkage.  */
15932       DECL_EXTERNAL (d) = 0;
15933
15934       /* Enter the scope of D so that access-checking works correctly.  */
15935       push_nested_class (DECL_CONTEXT (d));
15936       cp_finish_decl (d, init, false, NULL_TREE, 0);
15937       pop_nested_class ();
15938     }
15939   else if (TREE_CODE (d) == FUNCTION_DECL)
15940     {
15941       htab_t saved_local_specializations;
15942       tree subst_decl;
15943       tree tmpl_parm;
15944       tree spec_parm;
15945
15946       /* Save away the current list, in case we are instantiating one
15947          template from within the body of another.  */
15948       saved_local_specializations = local_specializations;
15949
15950       /* Set up the list of local specializations.  */
15951       local_specializations = htab_create (37,
15952                                            hash_local_specialization,
15953                                            eq_local_specializations,
15954                                            NULL);
15955
15956       /* Set up context.  */
15957       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15958
15959       /* Create substitution entries for the parameters.  */
15960       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15961       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15962       spec_parm = DECL_ARGUMENTS (d);
15963       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15964         {
15965           register_local_specialization (spec_parm, tmpl_parm);
15966           spec_parm = skip_artificial_parms_for (d, spec_parm);
15967           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15968         }
15969       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15970         {
15971           register_local_specialization (spec_parm, tmpl_parm);
15972           tmpl_parm = TREE_CHAIN (tmpl_parm);
15973           spec_parm = TREE_CHAIN (spec_parm);
15974         }
15975       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15976         {
15977           /* Register the (value) argument pack as a specialization of
15978              TMPL_PARM, then move on.  */
15979           tree argpack = make_fnparm_pack (spec_parm);
15980           register_local_specialization (argpack, tmpl_parm);
15981           tmpl_parm = TREE_CHAIN (tmpl_parm);
15982           spec_parm = NULL_TREE;
15983         }
15984       gcc_assert (!spec_parm);
15985
15986       /* Substitute into the body of the function.  */
15987       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15988                    tf_warning_or_error, tmpl,
15989                    /*integral_constant_expression_p=*/false);
15990
15991       /* Set the current input_location to the end of the function
15992          so that finish_function knows where we are.  */
15993       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15994
15995       /* We don't need the local specializations any more.  */
15996       htab_delete (local_specializations);
15997       local_specializations = saved_local_specializations;
15998
15999       /* Finish the function.  */
16000       d = finish_function (0);
16001       expand_or_defer_fn (d);
16002     }
16003
16004   /* We're not deferring instantiation any more.  */
16005   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16006
16007   if (need_push)
16008     pop_from_top_level ();
16009
16010 out:
16011   input_location = saved_loc;
16012   pop_deferring_access_checks ();
16013   pop_tinst_level ();
16014
16015   timevar_pop (TV_PARSE);
16016
16017   return d;
16018 }
16019
16020 /* Run through the list of templates that we wish we could
16021    instantiate, and instantiate any we can.  RETRIES is the
16022    number of times we retry pending template instantiation.  */
16023
16024 void
16025 instantiate_pending_templates (int retries)
16026 {
16027   int reconsider;
16028   location_t saved_loc = input_location;
16029
16030   /* Instantiating templates may trigger vtable generation.  This in turn
16031      may require further template instantiations.  We place a limit here
16032      to avoid infinite loop.  */
16033   if (pending_templates && retries >= max_tinst_depth)
16034     {
16035       tree decl = pending_templates->tinst->decl;
16036
16037       error ("template instantiation depth exceeds maximum of %d"
16038              " instantiating %q+D, possibly from virtual table generation"
16039              " (use -ftemplate-depth-NN to increase the maximum)",
16040              max_tinst_depth, decl);
16041       if (TREE_CODE (decl) == FUNCTION_DECL)
16042         /* Pretend that we defined it.  */
16043         DECL_INITIAL (decl) = error_mark_node;
16044       return;
16045     }
16046
16047   do
16048     {
16049       struct pending_template **t = &pending_templates;
16050       struct pending_template *last = NULL;
16051       reconsider = 0;
16052       while (*t)
16053         {
16054           tree instantiation = reopen_tinst_level ((*t)->tinst);
16055           bool complete = false;
16056
16057           if (TYPE_P (instantiation))
16058             {
16059               tree fn;
16060
16061               if (!COMPLETE_TYPE_P (instantiation))
16062                 {
16063                   instantiate_class_template (instantiation);
16064                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16065                     for (fn = TYPE_METHODS (instantiation);
16066                          fn;
16067                          fn = TREE_CHAIN (fn))
16068                       if (! DECL_ARTIFICIAL (fn))
16069                         instantiate_decl (fn,
16070                                           /*defer_ok=*/0,
16071                                           /*expl_inst_class_mem_p=*/false);
16072                   if (COMPLETE_TYPE_P (instantiation))
16073                     reconsider = 1;
16074                 }
16075
16076               complete = COMPLETE_TYPE_P (instantiation);
16077             }
16078           else
16079             {
16080               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16081                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16082                 {
16083                   instantiation
16084                     = instantiate_decl (instantiation,
16085                                         /*defer_ok=*/0,
16086                                         /*expl_inst_class_mem_p=*/false);
16087                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16088                     reconsider = 1;
16089                 }
16090
16091               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16092                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16093             }
16094
16095           if (complete)
16096             /* If INSTANTIATION has been instantiated, then we don't
16097                need to consider it again in the future.  */
16098             *t = (*t)->next;
16099           else
16100             {
16101               last = *t;
16102               t = &(*t)->next;
16103             }
16104           tinst_depth = 0;
16105           current_tinst_level = NULL;
16106         }
16107       last_pending_template = last;
16108     }
16109   while (reconsider);
16110
16111   input_location = saved_loc;
16112 }
16113
16114 /* Substitute ARGVEC into T, which is a list of initializers for
16115    either base class or a non-static data member.  The TREE_PURPOSEs
16116    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16117    instantiate_decl.  */
16118
16119 static tree
16120 tsubst_initializer_list (tree t, tree argvec)
16121 {
16122   tree inits = NULL_TREE;
16123
16124   for (; t; t = TREE_CHAIN (t))
16125     {
16126       tree decl;
16127       tree init;
16128       tree expanded_bases = NULL_TREE;
16129       tree expanded_arguments = NULL_TREE;
16130       int i, len = 1;
16131
16132       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16133         {
16134           tree expr;
16135           tree arg;
16136
16137           /* Expand the base class expansion type into separate base
16138              classes.  */
16139           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16140                                                  tf_warning_or_error,
16141                                                  NULL_TREE);
16142           if (expanded_bases == error_mark_node)
16143             continue;
16144           
16145           /* We'll be building separate TREE_LISTs of arguments for
16146              each base.  */
16147           len = TREE_VEC_LENGTH (expanded_bases);
16148           expanded_arguments = make_tree_vec (len);
16149           for (i = 0; i < len; i++)
16150             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16151
16152           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16153              expand each argument in the TREE_VALUE of t.  */
16154           expr = make_node (EXPR_PACK_EXPANSION);
16155           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16156             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16157
16158           if (TREE_VALUE (t) == void_type_node)
16159             /* VOID_TYPE_NODE is used to indicate
16160                value-initialization.  */
16161             {
16162               for (i = 0; i < len; i++)
16163                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16164             }
16165           else
16166             {
16167               /* Substitute parameter packs into each argument in the
16168                  TREE_LIST.  */
16169               in_base_initializer = 1;
16170               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16171                 {
16172                   tree expanded_exprs;
16173
16174                   /* Expand the argument.  */
16175                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16176                   expanded_exprs 
16177                     = tsubst_pack_expansion (expr, argvec,
16178                                              tf_warning_or_error,
16179                                              NULL_TREE);
16180                   if (expanded_exprs == error_mark_node)
16181                     continue;
16182
16183                   /* Prepend each of the expanded expressions to the
16184                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16185                   for (i = 0; i < len; i++)
16186                     {
16187                       TREE_VEC_ELT (expanded_arguments, i) = 
16188                         tree_cons (NULL_TREE, 
16189                                    TREE_VEC_ELT (expanded_exprs, i),
16190                                    TREE_VEC_ELT (expanded_arguments, i));
16191                     }
16192                 }
16193               in_base_initializer = 0;
16194
16195               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16196                  since we built them backwards.  */
16197               for (i = 0; i < len; i++)
16198                 {
16199                   TREE_VEC_ELT (expanded_arguments, i) = 
16200                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16201                 }
16202             }
16203         }
16204
16205       for (i = 0; i < len; ++i)
16206         {
16207           if (expanded_bases)
16208             {
16209               decl = TREE_VEC_ELT (expanded_bases, i);
16210               decl = expand_member_init (decl);
16211               init = TREE_VEC_ELT (expanded_arguments, i);
16212             }
16213           else
16214             {
16215               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16216                                   tf_warning_or_error, NULL_TREE);
16217
16218               decl = expand_member_init (decl);
16219               if (decl && !DECL_P (decl))
16220                 in_base_initializer = 1;
16221
16222               init = tsubst_expr (TREE_VALUE (t), argvec, 
16223                                   tf_warning_or_error, NULL_TREE,
16224                                   /*integral_constant_expression_p=*/false);
16225               in_base_initializer = 0;
16226             }
16227
16228           if (decl)
16229             {
16230               init = build_tree_list (decl, init);
16231               TREE_CHAIN (init) = inits;
16232               inits = init;
16233             }
16234         }
16235     }
16236   return inits;
16237 }
16238
16239 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16240
16241 static void
16242 set_current_access_from_decl (tree decl)
16243 {
16244   if (TREE_PRIVATE (decl))
16245     current_access_specifier = access_private_node;
16246   else if (TREE_PROTECTED (decl))
16247     current_access_specifier = access_protected_node;
16248   else
16249     current_access_specifier = access_public_node;
16250 }
16251
16252 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16253    is the instantiation (which should have been created with
16254    start_enum) and ARGS are the template arguments to use.  */
16255
16256 static void
16257 tsubst_enum (tree tag, tree newtag, tree args)
16258 {
16259   tree e;
16260
16261   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16262     {
16263       tree value;
16264       tree decl;
16265
16266       decl = TREE_VALUE (e);
16267       /* Note that in a template enum, the TREE_VALUE is the
16268          CONST_DECL, not the corresponding INTEGER_CST.  */
16269       value = tsubst_expr (DECL_INITIAL (decl),
16270                            args, tf_warning_or_error, NULL_TREE,
16271                            /*integral_constant_expression_p=*/true);
16272
16273       /* Give this enumeration constant the correct access.  */
16274       set_current_access_from_decl (decl);
16275
16276       /* Actually build the enumerator itself.  */
16277       build_enumerator (DECL_NAME (decl), value, newtag);
16278     }
16279
16280   finish_enum (newtag);
16281   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16282     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16283 }
16284
16285 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16286    its type -- but without substituting the innermost set of template
16287    arguments.  So, innermost set of template parameters will appear in
16288    the type.  */
16289
16290 tree
16291 get_mostly_instantiated_function_type (tree decl)
16292 {
16293   tree fn_type;
16294   tree tmpl;
16295   tree targs;
16296   tree tparms;
16297   int parm_depth;
16298
16299   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16300   targs = DECL_TI_ARGS (decl);
16301   tparms = DECL_TEMPLATE_PARMS (tmpl);
16302   parm_depth = TMPL_PARMS_DEPTH (tparms);
16303
16304   /* There should be as many levels of arguments as there are levels
16305      of parameters.  */
16306   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16307
16308   fn_type = TREE_TYPE (tmpl);
16309
16310   if (parm_depth == 1)
16311     /* No substitution is necessary.  */
16312     ;
16313   else
16314     {
16315       int i, save_access_control;
16316       tree partial_args;
16317
16318       /* Replace the innermost level of the TARGS with NULL_TREEs to
16319          let tsubst know not to substitute for those parameters.  */
16320       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16321       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16322         SET_TMPL_ARGS_LEVEL (partial_args, i,
16323                              TMPL_ARGS_LEVEL (targs, i));
16324       SET_TMPL_ARGS_LEVEL (partial_args,
16325                            TMPL_ARGS_DEPTH (targs),
16326                            make_tree_vec (DECL_NTPARMS (tmpl)));
16327
16328       /* Disable access control as this function is used only during
16329          name-mangling.  */
16330       save_access_control = flag_access_control;
16331       flag_access_control = 0;
16332
16333       ++processing_template_decl;
16334       /* Now, do the (partial) substitution to figure out the
16335          appropriate function type.  */
16336       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16337       --processing_template_decl;
16338
16339       /* Substitute into the template parameters to obtain the real
16340          innermost set of parameters.  This step is important if the
16341          innermost set of template parameters contains value
16342          parameters whose types depend on outer template parameters.  */
16343       TREE_VEC_LENGTH (partial_args)--;
16344       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16345
16346       flag_access_control = save_access_control;
16347     }
16348
16349   return fn_type;
16350 }
16351
16352 /* Return truthvalue if we're processing a template different from
16353    the last one involved in diagnostics.  */
16354 int
16355 problematic_instantiation_changed (void)
16356 {
16357   return last_template_error_tick != tinst_level_tick;
16358 }
16359
16360 /* Remember current template involved in diagnostics.  */
16361 void
16362 record_last_problematic_instantiation (void)
16363 {
16364   last_template_error_tick = tinst_level_tick;
16365 }
16366
16367 struct tinst_level *
16368 current_instantiation (void)
16369 {
16370   return current_tinst_level;
16371 }
16372
16373 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16374    type. Return zero for ok, nonzero for disallowed. Issue error and
16375    warning messages under control of COMPLAIN.  */
16376
16377 static int
16378 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16379 {
16380   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16381     return 0;
16382   else if (POINTER_TYPE_P (type))
16383     return 0;
16384   else if (TYPE_PTR_TO_MEMBER_P (type))
16385     return 0;
16386   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16387     return 0;
16388   else if (TREE_CODE (type) == TYPENAME_TYPE)
16389     return 0;
16390
16391   if (complain & tf_error)
16392     error ("%q#T is not a valid type for a template constant parameter", type);
16393   return 1;
16394 }
16395
16396 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16397    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16398
16399 static bool
16400 dependent_type_p_r (tree type)
16401 {
16402   tree scope;
16403
16404   /* [temp.dep.type]
16405
16406      A type is dependent if it is:
16407
16408      -- a template parameter. Template template parameters are types
16409         for us (since TYPE_P holds true for them) so we handle
16410         them here.  */
16411   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16412       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16413     return true;
16414   /* -- a qualified-id with a nested-name-specifier which contains a
16415         class-name that names a dependent type or whose unqualified-id
16416         names a dependent type.  */
16417   if (TREE_CODE (type) == TYPENAME_TYPE)
16418     return true;
16419   /* -- a cv-qualified type where the cv-unqualified type is
16420         dependent.  */
16421   type = TYPE_MAIN_VARIANT (type);
16422   /* -- a compound type constructed from any dependent type.  */
16423   if (TYPE_PTR_TO_MEMBER_P (type))
16424     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16425             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16426                                            (type)));
16427   else if (TREE_CODE (type) == POINTER_TYPE
16428            || TREE_CODE (type) == REFERENCE_TYPE)
16429     return dependent_type_p (TREE_TYPE (type));
16430   else if (TREE_CODE (type) == FUNCTION_TYPE
16431            || TREE_CODE (type) == METHOD_TYPE)
16432     {
16433       tree arg_type;
16434
16435       if (dependent_type_p (TREE_TYPE (type)))
16436         return true;
16437       for (arg_type = TYPE_ARG_TYPES (type);
16438            arg_type;
16439            arg_type = TREE_CHAIN (arg_type))
16440         if (dependent_type_p (TREE_VALUE (arg_type)))
16441           return true;
16442       return false;
16443     }
16444   /* -- an array type constructed from any dependent type or whose
16445         size is specified by a constant expression that is
16446         value-dependent.  */
16447   if (TREE_CODE (type) == ARRAY_TYPE)
16448     {
16449       if (TYPE_DOMAIN (type)
16450           && dependent_type_p (TYPE_DOMAIN (type)))
16451         return true;
16452       return dependent_type_p (TREE_TYPE (type));
16453     }
16454   else if (TREE_CODE (type) == INTEGER_TYPE
16455            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16456     {
16457       /* If this is the TYPE_DOMAIN of an array type, consider it
16458          dependent.  We already checked for value-dependence in
16459          compute_array_index_type.  */
16460       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16461     }
16462
16463   /* -- a template-id in which either the template name is a template
16464      parameter ...  */
16465   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16466     return true;
16467   /* ... or any of the template arguments is a dependent type or
16468         an expression that is type-dependent or value-dependent.  */
16469   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16470            && (any_dependent_template_arguments_p
16471                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16472     return true;
16473
16474   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16475      argument of the `typeof' expression is not type-dependent, then
16476      it should already been have resolved.  */
16477   if (TREE_CODE (type) == TYPEOF_TYPE
16478       || TREE_CODE (type) == DECLTYPE_TYPE)
16479     return true;
16480
16481   /* A template argument pack is dependent if any of its packed
16482      arguments are.  */
16483   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16484     {
16485       tree args = ARGUMENT_PACK_ARGS (type);
16486       int i, len = TREE_VEC_LENGTH (args);
16487       for (i = 0; i < len; ++i)
16488         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16489           return true;
16490     }
16491
16492   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16493      be template parameters.  */
16494   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16495     return true;
16496
16497   /* The standard does not specifically mention types that are local
16498      to template functions or local classes, but they should be
16499      considered dependent too.  For example:
16500
16501        template <int I> void f() {
16502          enum E { a = I };
16503          S<sizeof (E)> s;
16504        }
16505
16506      The size of `E' cannot be known until the value of `I' has been
16507      determined.  Therefore, `E' must be considered dependent.  */
16508   scope = TYPE_CONTEXT (type);
16509   if (scope && TYPE_P (scope))
16510     return dependent_type_p (scope);
16511   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16512     return type_dependent_expression_p (scope);
16513
16514   /* Other types are non-dependent.  */
16515   return false;
16516 }
16517
16518 /* Returns TRUE if TYPE is dependent, in the sense of
16519    [temp.dep.type].  */
16520
16521 bool
16522 dependent_type_p (tree type)
16523 {
16524   /* If there are no template parameters in scope, then there can't be
16525      any dependent types.  */
16526   if (!processing_template_decl)
16527     {
16528       /* If we are not processing a template, then nobody should be
16529          providing us with a dependent type.  */
16530       gcc_assert (type);
16531       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16532       return false;
16533     }
16534
16535   /* If the type is NULL, we have not computed a type for the entity
16536      in question; in that case, the type is dependent.  */
16537   if (!type)
16538     return true;
16539
16540   /* Erroneous types can be considered non-dependent.  */
16541   if (type == error_mark_node)
16542     return false;
16543
16544   /* If we have not already computed the appropriate value for TYPE,
16545      do so now.  */
16546   if (!TYPE_DEPENDENT_P_VALID (type))
16547     {
16548       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16549       TYPE_DEPENDENT_P_VALID (type) = 1;
16550     }
16551
16552   return TYPE_DEPENDENT_P (type);
16553 }
16554
16555 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16556    lookup.  In other words, a dependent type that is not the current
16557    instantiation.  */
16558
16559 bool
16560 dependent_scope_p (tree scope)
16561 {
16562   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16563           && !currently_open_class (scope));
16564 }
16565
16566 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16567
16568 static bool
16569 dependent_scope_ref_p (tree expression, bool criterion (tree))
16570 {
16571   tree scope;
16572   tree name;
16573
16574   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16575
16576   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16577     return true;
16578
16579   scope = TREE_OPERAND (expression, 0);
16580   name = TREE_OPERAND (expression, 1);
16581
16582   /* [temp.dep.expr]
16583
16584      An id-expression is type-dependent if it contains a
16585      nested-name-specifier that contains a class-name that names a
16586      dependent type.  */
16587   /* The suggested resolution to Core Issue 224 implies that if the
16588      qualifying type is the current class, then we must peek
16589      inside it.  */
16590   if (DECL_P (name)
16591       && currently_open_class (scope)
16592       && !criterion (name))
16593     return false;
16594   if (dependent_type_p (scope))
16595     return true;
16596
16597   return false;
16598 }
16599
16600 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16601    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16602    expression.  */
16603
16604 bool
16605 value_dependent_expression_p (tree expression)
16606 {
16607   if (!processing_template_decl)
16608     return false;
16609
16610   /* A name declared with a dependent type.  */
16611   if (DECL_P (expression) && type_dependent_expression_p (expression))
16612     return true;
16613
16614   switch (TREE_CODE (expression))
16615     {
16616     case IDENTIFIER_NODE:
16617       /* A name that has not been looked up -- must be dependent.  */
16618       return true;
16619
16620     case TEMPLATE_PARM_INDEX:
16621       /* A non-type template parm.  */
16622       return true;
16623
16624     case CONST_DECL:
16625       /* A non-type template parm.  */
16626       if (DECL_TEMPLATE_PARM_P (expression))
16627         return true;
16628       return value_dependent_expression_p (DECL_INITIAL (expression));
16629
16630     case VAR_DECL:
16631        /* A constant with integral or enumeration type and is initialized
16632           with an expression that is value-dependent.  */
16633       if (DECL_INITIAL (expression)
16634           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16635           && value_dependent_expression_p (DECL_INITIAL (expression)))
16636         return true;
16637       return false;
16638
16639     case DYNAMIC_CAST_EXPR:
16640     case STATIC_CAST_EXPR:
16641     case CONST_CAST_EXPR:
16642     case REINTERPRET_CAST_EXPR:
16643     case CAST_EXPR:
16644       /* These expressions are value-dependent if the type to which
16645          the cast occurs is dependent or the expression being casted
16646          is value-dependent.  */
16647       {
16648         tree type = TREE_TYPE (expression);
16649
16650         if (dependent_type_p (type))
16651           return true;
16652
16653         /* A functional cast has a list of operands.  */
16654         expression = TREE_OPERAND (expression, 0);
16655         if (!expression)
16656           {
16657             /* If there are no operands, it must be an expression such
16658                as "int()". This should not happen for aggregate types
16659                because it would form non-constant expressions.  */
16660             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16661
16662             return false;
16663           }
16664
16665         if (TREE_CODE (expression) == TREE_LIST)
16666           return any_value_dependent_elements_p (expression);
16667
16668         return value_dependent_expression_p (expression);
16669       }
16670
16671     case SIZEOF_EXPR:
16672     case ALIGNOF_EXPR:
16673       /* A `sizeof' expression is value-dependent if the operand is
16674          type-dependent or is a pack expansion.  */
16675       expression = TREE_OPERAND (expression, 0);
16676       if (PACK_EXPANSION_P (expression))
16677         return true;
16678       else if (TYPE_P (expression))
16679         return dependent_type_p (expression);
16680       return type_dependent_expression_p (expression);
16681
16682     case SCOPE_REF:
16683       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16684
16685     case COMPONENT_REF:
16686       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16687               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16688
16689     case CALL_EXPR:
16690       /* A CALL_EXPR may appear in a constant expression if it is a
16691          call to a builtin function, e.g., __builtin_constant_p.  All
16692          such calls are value-dependent.  */
16693       return true;
16694
16695     case NONTYPE_ARGUMENT_PACK:
16696       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16697          is value-dependent.  */
16698       {
16699         tree values = ARGUMENT_PACK_ARGS (expression);
16700         int i, len = TREE_VEC_LENGTH (values);
16701         
16702         for (i = 0; i < len; ++i)
16703           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16704             return true;
16705         
16706         return false;
16707       }
16708
16709     case TRAIT_EXPR:
16710       {
16711         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16712         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16713                 || (type2 ? dependent_type_p (type2) : false));
16714       }
16715
16716     case MODOP_EXPR:
16717       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16718               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16719
16720     default:
16721       /* A constant expression is value-dependent if any subexpression is
16722          value-dependent.  */
16723       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16724         {
16725         case tcc_reference:
16726         case tcc_unary:
16727           return (value_dependent_expression_p
16728                   (TREE_OPERAND (expression, 0)));
16729
16730         case tcc_comparison:
16731         case tcc_binary:
16732           return ((value_dependent_expression_p
16733                    (TREE_OPERAND (expression, 0)))
16734                   || (value_dependent_expression_p
16735                       (TREE_OPERAND (expression, 1))));
16736
16737         case tcc_expression:
16738         case tcc_vl_exp:
16739           {
16740             int i;
16741             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16742               /* In some cases, some of the operands may be missing.
16743                  (For example, in the case of PREDECREMENT_EXPR, the
16744                  amount to increment by may be missing.)  That doesn't
16745                  make the expression dependent.  */
16746               if (TREE_OPERAND (expression, i)
16747                   && (value_dependent_expression_p
16748                       (TREE_OPERAND (expression, i))))
16749                 return true;
16750             return false;
16751           }
16752
16753         default:
16754           break;
16755         }
16756     }
16757
16758   /* The expression is not value-dependent.  */
16759   return false;
16760 }
16761
16762 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16763    [temp.dep.expr].  */
16764
16765 bool
16766 type_dependent_expression_p (tree expression)
16767 {
16768   if (!processing_template_decl)
16769     return false;
16770
16771   if (expression == error_mark_node)
16772     return false;
16773
16774   /* An unresolved name is always dependent.  */
16775   if (TREE_CODE (expression) == IDENTIFIER_NODE
16776       || TREE_CODE (expression) == USING_DECL)
16777     return true;
16778
16779   /* Some expression forms are never type-dependent.  */
16780   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16781       || TREE_CODE (expression) == SIZEOF_EXPR
16782       || TREE_CODE (expression) == ALIGNOF_EXPR
16783       || TREE_CODE (expression) == TRAIT_EXPR
16784       || TREE_CODE (expression) == TYPEID_EXPR
16785       || TREE_CODE (expression) == DELETE_EXPR
16786       || TREE_CODE (expression) == VEC_DELETE_EXPR
16787       || TREE_CODE (expression) == THROW_EXPR)
16788     return false;
16789
16790   /* The types of these expressions depends only on the type to which
16791      the cast occurs.  */
16792   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16793       || TREE_CODE (expression) == STATIC_CAST_EXPR
16794       || TREE_CODE (expression) == CONST_CAST_EXPR
16795       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16796       || TREE_CODE (expression) == CAST_EXPR)
16797     return dependent_type_p (TREE_TYPE (expression));
16798
16799   /* The types of these expressions depends only on the type created
16800      by the expression.  */
16801   if (TREE_CODE (expression) == NEW_EXPR
16802       || TREE_CODE (expression) == VEC_NEW_EXPR)
16803     {
16804       /* For NEW_EXPR tree nodes created inside a template, either
16805          the object type itself or a TREE_LIST may appear as the
16806          operand 1.  */
16807       tree type = TREE_OPERAND (expression, 1);
16808       if (TREE_CODE (type) == TREE_LIST)
16809         /* This is an array type.  We need to check array dimensions
16810            as well.  */
16811         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16812                || value_dependent_expression_p
16813                     (TREE_OPERAND (TREE_VALUE (type), 1));
16814       else
16815         return dependent_type_p (type);
16816     }
16817
16818   if (TREE_CODE (expression) == SCOPE_REF
16819       && dependent_scope_ref_p (expression,
16820                                 type_dependent_expression_p))
16821     return true;
16822
16823   if (TREE_CODE (expression) == FUNCTION_DECL
16824       && DECL_LANG_SPECIFIC (expression)
16825       && DECL_TEMPLATE_INFO (expression)
16826       && (any_dependent_template_arguments_p
16827           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16828     return true;
16829
16830   if (TREE_CODE (expression) == TEMPLATE_DECL
16831       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16832     return false;
16833
16834   if (TREE_CODE (expression) == STMT_EXPR)
16835     expression = stmt_expr_value_expr (expression);
16836
16837   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16838     {
16839       tree elt;
16840       unsigned i;
16841
16842       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16843         {
16844           if (type_dependent_expression_p (elt))
16845             return true;
16846         }
16847       return false;
16848     }
16849
16850   if (TREE_TYPE (expression) == unknown_type_node)
16851     {
16852       if (TREE_CODE (expression) == ADDR_EXPR)
16853         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16854       if (TREE_CODE (expression) == COMPONENT_REF
16855           || TREE_CODE (expression) == OFFSET_REF)
16856         {
16857           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16858             return true;
16859           expression = TREE_OPERAND (expression, 1);
16860           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16861             return false;
16862         }
16863       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16864       if (TREE_CODE (expression) == SCOPE_REF)
16865         return false;
16866
16867       if (TREE_CODE (expression) == BASELINK)
16868         expression = BASELINK_FUNCTIONS (expression);
16869
16870       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16871         {
16872           if (any_dependent_template_arguments_p
16873               (TREE_OPERAND (expression, 1)))
16874             return true;
16875           expression = TREE_OPERAND (expression, 0);
16876         }
16877       gcc_assert (TREE_CODE (expression) == OVERLOAD
16878                   || TREE_CODE (expression) == FUNCTION_DECL);
16879
16880       while (expression)
16881         {
16882           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16883             return true;
16884           expression = OVL_NEXT (expression);
16885         }
16886       return false;
16887     }
16888
16889   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16890
16891   return (dependent_type_p (TREE_TYPE (expression)));
16892 }
16893
16894 /* Like type_dependent_expression_p, but it also works while not processing
16895    a template definition, i.e. during substitution or mangling.  */
16896
16897 bool
16898 type_dependent_expression_p_push (tree expr)
16899 {
16900   bool b;
16901   ++processing_template_decl;
16902   b = type_dependent_expression_p (expr);
16903   --processing_template_decl;
16904   return b;
16905 }
16906
16907 /* Returns TRUE if ARGS contains a type-dependent expression.  */
16908
16909 bool
16910 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
16911 {
16912   unsigned int i;
16913   tree arg;
16914
16915   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
16916     {
16917       if (type_dependent_expression_p (arg))
16918         return true;
16919     }
16920   return false;
16921 }
16922
16923 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16924    expressions) contains any value-dependent expressions.  */
16925
16926 bool
16927 any_value_dependent_elements_p (const_tree list)
16928 {
16929   for (; list; list = TREE_CHAIN (list))
16930     if (value_dependent_expression_p (TREE_VALUE (list)))
16931       return true;
16932
16933   return false;
16934 }
16935
16936 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16937
16938 bool
16939 dependent_template_arg_p (tree arg)
16940 {
16941   if (!processing_template_decl)
16942     return false;
16943
16944   if (TREE_CODE (arg) == TEMPLATE_DECL
16945       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16946     return dependent_template_p (arg);
16947   else if (ARGUMENT_PACK_P (arg))
16948     {
16949       tree args = ARGUMENT_PACK_ARGS (arg);
16950       int i, len = TREE_VEC_LENGTH (args);
16951       for (i = 0; i < len; ++i)
16952         {
16953           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16954             return true;
16955         }
16956
16957       return false;
16958     }
16959   else if (TYPE_P (arg))
16960     return dependent_type_p (arg);
16961   else
16962     return (type_dependent_expression_p (arg)
16963             || value_dependent_expression_p (arg));
16964 }
16965
16966 /* Returns true if ARGS (a collection of template arguments) contains
16967    any types that require structural equality testing.  */
16968
16969 bool
16970 any_template_arguments_need_structural_equality_p (tree args)
16971 {
16972   int i;
16973   int j;
16974
16975   if (!args)
16976     return false;
16977   if (args == error_mark_node)
16978     return true;
16979
16980   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16981     {
16982       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16983       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16984         {
16985           tree arg = TREE_VEC_ELT (level, j);
16986           tree packed_args = NULL_TREE;
16987           int k, len = 1;
16988
16989           if (ARGUMENT_PACK_P (arg))
16990             {
16991               /* Look inside the argument pack.  */
16992               packed_args = ARGUMENT_PACK_ARGS (arg);
16993               len = TREE_VEC_LENGTH (packed_args);
16994             }
16995
16996           for (k = 0; k < len; ++k)
16997             {
16998               if (packed_args)
16999                 arg = TREE_VEC_ELT (packed_args, k);
17000
17001               if (error_operand_p (arg))
17002                 return true;
17003               else if (TREE_CODE (arg) == TEMPLATE_DECL
17004                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17005                 continue;
17006               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17007                 return true;
17008               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17009                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17010                 return true;
17011             }
17012         }
17013     }
17014
17015   return false;
17016 }
17017
17018 /* Returns true if ARGS (a collection of template arguments) contains
17019    any dependent arguments.  */
17020
17021 bool
17022 any_dependent_template_arguments_p (const_tree args)
17023 {
17024   int i;
17025   int j;
17026
17027   if (!args)
17028     return false;
17029   if (args == error_mark_node)
17030     return true;
17031
17032   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17033     {
17034       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17035       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17036         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17037           return true;
17038     }
17039
17040   return false;
17041 }
17042
17043 /* Returns TRUE if the template TMPL is dependent.  */
17044
17045 bool
17046 dependent_template_p (tree tmpl)
17047 {
17048   if (TREE_CODE (tmpl) == OVERLOAD)
17049     {
17050       while (tmpl)
17051         {
17052           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17053             return true;
17054           tmpl = OVL_CHAIN (tmpl);
17055         }
17056       return false;
17057     }
17058
17059   /* Template template parameters are dependent.  */
17060   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17061       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17062     return true;
17063   /* So are names that have not been looked up.  */
17064   if (TREE_CODE (tmpl) == SCOPE_REF
17065       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17066     return true;
17067   /* So are member templates of dependent classes.  */
17068   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17069     return dependent_type_p (DECL_CONTEXT (tmpl));
17070   return false;
17071 }
17072
17073 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17074
17075 bool
17076 dependent_template_id_p (tree tmpl, tree args)
17077 {
17078   return (dependent_template_p (tmpl)
17079           || any_dependent_template_arguments_p (args));
17080 }
17081
17082 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17083    is dependent.  */
17084
17085 bool
17086 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17087 {
17088   int i;
17089
17090   if (!processing_template_decl)
17091     return false;
17092
17093   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17094     {
17095       tree decl = TREE_VEC_ELT (declv, i);
17096       tree init = TREE_VEC_ELT (initv, i);
17097       tree cond = TREE_VEC_ELT (condv, i);
17098       tree incr = TREE_VEC_ELT (incrv, i);
17099
17100       if (type_dependent_expression_p (decl))
17101         return true;
17102
17103       if (init && type_dependent_expression_p (init))
17104         return true;
17105
17106       if (type_dependent_expression_p (cond))
17107         return true;
17108
17109       if (COMPARISON_CLASS_P (cond)
17110           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17111               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17112         return true;
17113
17114       if (TREE_CODE (incr) == MODOP_EXPR)
17115         {
17116           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17117               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17118             return true;
17119         }
17120       else if (type_dependent_expression_p (incr))
17121         return true;
17122       else if (TREE_CODE (incr) == MODIFY_EXPR)
17123         {
17124           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17125             return true;
17126           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17127             {
17128               tree t = TREE_OPERAND (incr, 1);
17129               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17130                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17131                 return true;
17132             }
17133         }
17134     }
17135
17136   return false;
17137 }
17138
17139 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17140    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17141    no such TYPE can be found.  Note that this function peers inside
17142    uninstantiated templates and therefore should be used only in
17143    extremely limited situations.  ONLY_CURRENT_P restricts this
17144    peering to the currently open classes hierarchy (which is required
17145    when comparing types).  */
17146
17147 tree
17148 resolve_typename_type (tree type, bool only_current_p)
17149 {
17150   tree scope;
17151   tree name;
17152   tree decl;
17153   int quals;
17154   tree pushed_scope;
17155   tree result;
17156
17157   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17158
17159   scope = TYPE_CONTEXT (type);
17160   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17161      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17162      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17163      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17164      identifier  of the TYPENAME_TYPE anymore.
17165      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17166      TYPENAME_TYPE instead, we avoid messing up with a possible
17167      typedef variant case.  */
17168   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17169
17170   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17171      it first before we can figure out what NAME refers to.  */
17172   if (TREE_CODE (scope) == TYPENAME_TYPE)
17173     scope = resolve_typename_type (scope, only_current_p);
17174   /* If we don't know what SCOPE refers to, then we cannot resolve the
17175      TYPENAME_TYPE.  */
17176   if (TREE_CODE (scope) == TYPENAME_TYPE)
17177     return type;
17178   /* If the SCOPE is a template type parameter, we have no way of
17179      resolving the name.  */
17180   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17181     return type;
17182   /* If the SCOPE is not the current instantiation, there's no reason
17183      to look inside it.  */
17184   if (only_current_p && !currently_open_class (scope))
17185     return type;
17186   /* If SCOPE isn't the template itself, it will not have a valid
17187      TYPE_FIELDS list.  */
17188   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17189     /* scope is either the template itself or a compatible instantiation
17190        like X<T>, so look up the name in the original template.  */
17191     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17192   else
17193     /* scope is a partial instantiation, so we can't do the lookup or we
17194        will lose the template arguments.  */
17195     return type;
17196   /* Enter the SCOPE so that name lookup will be resolved as if we
17197      were in the class definition.  In particular, SCOPE will no
17198      longer be considered a dependent type.  */
17199   pushed_scope = push_scope (scope);
17200   /* Look up the declaration.  */
17201   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17202
17203   result = NULL_TREE;
17204   
17205   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17206      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17207   if (!decl)
17208     /*nop*/;
17209   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17210            && TREE_CODE (decl) == TYPE_DECL)
17211     {
17212       result = TREE_TYPE (decl);
17213       if (result == error_mark_node)
17214         result = NULL_TREE;
17215     }
17216   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17217            && DECL_CLASS_TEMPLATE_P (decl))
17218     {
17219       tree tmpl;
17220       tree args;
17221       /* Obtain the template and the arguments.  */
17222       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17223       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17224       /* Instantiate the template.  */
17225       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17226                                       /*entering_scope=*/0,
17227                                       tf_error | tf_user);
17228       if (result == error_mark_node)
17229         result = NULL_TREE;
17230     }
17231   
17232   /* Leave the SCOPE.  */
17233   if (pushed_scope)
17234     pop_scope (pushed_scope);
17235
17236   /* If we failed to resolve it, return the original typename.  */
17237   if (!result)
17238     return type;
17239   
17240   /* If lookup found a typename type, resolve that too.  */
17241   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17242     {
17243       /* Ill-formed programs can cause infinite recursion here, so we
17244          must catch that.  */
17245       TYPENAME_IS_RESOLVING_P (type) = 1;
17246       result = resolve_typename_type (result, only_current_p);
17247       TYPENAME_IS_RESOLVING_P (type) = 0;
17248     }
17249   
17250   /* Qualify the resulting type.  */
17251   quals = cp_type_quals (type);
17252   if (quals)
17253     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17254
17255   return result;
17256 }
17257
17258 /* EXPR is an expression which is not type-dependent.  Return a proxy
17259    for EXPR that can be used to compute the types of larger
17260    expressions containing EXPR.  */
17261
17262 tree
17263 build_non_dependent_expr (tree expr)
17264 {
17265   tree inner_expr;
17266
17267   /* Preserve null pointer constants so that the type of things like
17268      "p == 0" where "p" is a pointer can be determined.  */
17269   if (null_ptr_cst_p (expr))
17270     return expr;
17271   /* Preserve OVERLOADs; the functions must be available to resolve
17272      types.  */
17273   inner_expr = expr;
17274   if (TREE_CODE (inner_expr) == STMT_EXPR)
17275     inner_expr = stmt_expr_value_expr (inner_expr);
17276   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17277     inner_expr = TREE_OPERAND (inner_expr, 0);
17278   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17279     inner_expr = TREE_OPERAND (inner_expr, 1);
17280   if (is_overloaded_fn (inner_expr)
17281       || TREE_CODE (inner_expr) == OFFSET_REF)
17282     return expr;
17283   /* There is no need to return a proxy for a variable.  */
17284   if (TREE_CODE (expr) == VAR_DECL)
17285     return expr;
17286   /* Preserve string constants; conversions from string constants to
17287      "char *" are allowed, even though normally a "const char *"
17288      cannot be used to initialize a "char *".  */
17289   if (TREE_CODE (expr) == STRING_CST)
17290     return expr;
17291   /* Preserve arithmetic constants, as an optimization -- there is no
17292      reason to create a new node.  */
17293   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17294     return expr;
17295   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17296      There is at least one place where we want to know that a
17297      particular expression is a throw-expression: when checking a ?:
17298      expression, there are special rules if the second or third
17299      argument is a throw-expression.  */
17300   if (TREE_CODE (expr) == THROW_EXPR)
17301     return expr;
17302
17303   if (TREE_CODE (expr) == COND_EXPR)
17304     return build3 (COND_EXPR,
17305                    TREE_TYPE (expr),
17306                    TREE_OPERAND (expr, 0),
17307                    (TREE_OPERAND (expr, 1)
17308                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17309                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17310                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17311   if (TREE_CODE (expr) == COMPOUND_EXPR
17312       && !COMPOUND_EXPR_OVERLOADED (expr))
17313     return build2 (COMPOUND_EXPR,
17314                    TREE_TYPE (expr),
17315                    TREE_OPERAND (expr, 0),
17316                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17317
17318   /* If the type is unknown, it can't really be non-dependent */
17319   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17320
17321   /* Otherwise, build a NON_DEPENDENT_EXPR.
17322
17323      REFERENCE_TYPEs are not stripped for expressions in templates
17324      because doing so would play havoc with mangling.  Consider, for
17325      example:
17326
17327        template <typename T> void f<T& g>() { g(); }
17328
17329      In the body of "f", the expression for "g" will have
17330      REFERENCE_TYPE, even though the standard says that it should
17331      not.  The reason is that we must preserve the syntactic form of
17332      the expression so that mangling (say) "f<g>" inside the body of
17333      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17334      stripped here.  */
17335   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17336 }
17337
17338 /* ARGS is a vector of expressions as arguments to a function call.
17339    Replace the arguments with equivalent non-dependent expressions.
17340    This modifies ARGS in place.  */
17341
17342 void
17343 make_args_non_dependent (VEC(tree,gc) *args)
17344 {
17345   unsigned int ix;
17346   tree arg;
17347
17348   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17349     {
17350       tree newarg = build_non_dependent_expr (arg);
17351       if (newarg != arg)
17352         VEC_replace (tree, args, ix, newarg);
17353     }
17354 }
17355
17356 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17357    with a level one deeper than the actual template parms.  */
17358
17359 tree
17360 make_auto (void)
17361 {
17362   tree au;
17363
17364   /* ??? Is it worth caching this for multiple autos at the same level?  */
17365   au = cxx_make_type (TEMPLATE_TYPE_PARM);
17366   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17367                                TYPE_DECL, get_identifier ("auto"), au);
17368   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17369   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17370     (0, processing_template_decl + 1, processing_template_decl + 1,
17371      TYPE_NAME (au), NULL_TREE);
17372   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17373   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17374   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17375
17376   return au;
17377 }
17378
17379 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17380
17381 static tree
17382 listify_autos (tree type, tree auto_node)
17383 {
17384   tree std_init_list = namespace_binding
17385     (get_identifier ("initializer_list"), std_node);
17386   tree argvec;
17387   tree init_auto;
17388   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17389     {    
17390       error ("deducing auto from brace-enclosed initializer list requires "
17391              "#include <initializer_list>");
17392       return error_mark_node;
17393     }
17394   argvec = make_tree_vec (1);
17395   TREE_VEC_ELT (argvec, 0) = auto_node;
17396   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
17397                                      NULL_TREE, 0, tf_warning_or_error);
17398
17399   TREE_VEC_ELT (argvec, 0) = init_auto;
17400   if (processing_template_decl)
17401     argvec = add_to_template_args (current_template_args (), argvec);
17402   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17403 }
17404
17405 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17406    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17407
17408 tree
17409 do_auto_deduction (tree type, tree init, tree auto_node)
17410 {
17411   tree parms, tparms, targs;
17412   tree args[1];
17413   int val;
17414
17415   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17416      with either a new invented type template parameter U or, if the
17417      initializer is a braced-init-list (8.5.4), with
17418      std::initializer_list<U>.  */
17419   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17420     type = listify_autos (type, auto_node);
17421
17422   parms = build_tree_list (NULL_TREE, type);
17423   args[0] = init;
17424   tparms = make_tree_vec (1);
17425   targs = make_tree_vec (1);
17426   TREE_VEC_ELT (tparms, 0)
17427     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17428   val = type_unification_real (tparms, targs, parms, args, 1, 0,
17429                                DEDUCE_CALL, LOOKUP_NORMAL);
17430   if (val > 0)
17431     {
17432       error ("unable to deduce %qT from %qE", type, init);
17433       return error_mark_node;
17434     }
17435
17436   if (processing_template_decl)
17437     targs = add_to_template_args (current_template_args (), targs);
17438   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17439 }
17440
17441 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17442    result.  */
17443
17444 tree
17445 splice_late_return_type (tree type, tree late_return_type)
17446 {
17447   tree argvec;
17448
17449   if (late_return_type == NULL_TREE)
17450     return type;
17451   argvec = make_tree_vec (1);
17452   TREE_VEC_ELT (argvec, 0) = late_return_type;
17453   if (processing_template_decl)
17454     argvec = add_to_template_args (current_template_args (), argvec);
17455   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17456 }
17457
17458 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17459
17460 bool
17461 is_auto (const_tree type)
17462 {
17463   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17464       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17465     return true;
17466   else
17467     return false;
17468 }
17469
17470 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17471    appear as a type-specifier for the declaration in question, we don't
17472    have to look through the whole type.  */
17473
17474 tree
17475 type_uses_auto (tree type)
17476 {
17477   enum tree_code code;
17478   if (is_auto (type))
17479     return type;
17480
17481   code = TREE_CODE (type);
17482
17483   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17484       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17485       || code == METHOD_TYPE || code == ARRAY_TYPE)
17486     return type_uses_auto (TREE_TYPE (type));
17487
17488   if (TYPE_PTRMEMFUNC_P (type))
17489     return type_uses_auto (TREE_TYPE (TREE_TYPE
17490                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17491
17492   return NULL_TREE;
17493 }
17494
17495 /* For a given template T, return the list of typedefs referenced
17496    in T for which access check is needed at T instantiation time.
17497    T is either  a FUNCTION_DECL or a RECORD_TYPE.
17498    Those typedefs were added to T by the function
17499    append_type_to_template_for_access_check.  */
17500
17501 tree
17502 get_types_needing_access_check (tree t)
17503 {
17504   tree ti, result = NULL_TREE;
17505
17506   if (!t || t == error_mark_node)
17507     return t;
17508
17509   if (!(ti = get_template_info (t)))
17510     return NULL_TREE;
17511
17512   if (TREE_CODE (t) == RECORD_TYPE || TREE_CODE (t) == FUNCTION_DECL)
17513     {
17514       if (!TI_TEMPLATE (ti))
17515         return NULL_TREE;
17516
17517       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
17518     }
17519
17520   return result;
17521 }
17522
17523 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
17524    tied to T. That list of typedefs will be access checked at
17525    T instantiation time.
17526    T is either a FUNCTION_DECL or a RECORD_TYPE.
17527    TYPE_DECL is a TYPE_DECL node representing a typedef.
17528    SCOPE is the scope through which TYPE_DECL is accessed.
17529
17530    This function is a subroutine of
17531    append_type_to_template_for_access_check.  */
17532
17533 static void
17534 append_type_to_template_for_access_check_1 (tree t,
17535                                             tree type_decl,
17536                                             tree scope)
17537 {
17538   tree ti;
17539
17540   if (!t || t == error_mark_node)
17541     return;
17542
17543   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
17544                || TREE_CODE (t) == RECORD_TYPE)
17545               && type_decl
17546               && TREE_CODE (type_decl) == TYPE_DECL
17547               && scope);
17548
17549   if (!(ti = get_template_info (t)))
17550     return;
17551
17552   gcc_assert (TI_TEMPLATE (ti));
17553
17554   TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti) =
17555     tree_cons (type_decl, scope, TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti));
17556 }
17557
17558 /* Append TYPE_DECL to the template TEMPL.
17559    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
17560    At TEMPL instanciation time, TYPE_DECL will be checked to see
17561    if it can be accessed through SCOPE.
17562
17563    e.g. consider the following code snippet:
17564
17565      class C
17566      {
17567        typedef int myint;
17568      };
17569
17570      template<class U> struct S
17571      {
17572        C::myint mi;
17573      };
17574
17575      S<char> s;
17576
17577    At S<char> instantiation time, we need to check the access of C::myint
17578    In other words, we need to check the access of the myint typedef through
17579    the C scope. For that purpose, this function will add the myint typedef
17580    and the scope C through which its being accessed to a list of typedefs
17581    tied to the template S. That list will be walked at template instantiation
17582    time and access check performed on each typedefs it contains.
17583    Note that this particular code snippet should yield an error because
17584    myint is private to C.  */
17585
17586 void
17587 append_type_to_template_for_access_check (tree templ,
17588                                           tree type_decl,
17589                                           tree scope)
17590 {
17591   tree node;
17592
17593   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
17594
17595   /* Make sure we don't append the type to the template twice.  */
17596   for (node = get_types_needing_access_check (templ);
17597        node;
17598        node = TREE_CHAIN (node))
17599     {
17600       tree decl = TREE_PURPOSE (node);
17601       tree type_scope = TREE_VALUE (node);
17602
17603       if (decl == type_decl && type_scope == scope)
17604         return;
17605     }
17606
17607   append_type_to_template_for_access_check_1 (templ, type_decl, scope);
17608 }
17609
17610 /* Set up the hash tables for template instantiations.  */
17611
17612 void
17613 init_template_processing (void)
17614 {
17615   decl_specializations = htab_create_ggc (37,
17616                                           hash_specialization,
17617                                           eq_specializations,
17618                                           ggc_free);
17619   type_specializations = htab_create_ggc (37,
17620                                           hash_specialization,
17621                                           eq_specializations,
17622                                           ggc_free);
17623 }
17624
17625 #include "gt-cp-pt.h"