OSDN Git Service

PR c++/14912
[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               /* using-declarations can add base methods to the method vec,
979                  and we don't want those here.  */
980               && DECL_CONTEXT (fn) == class_specialization)
981             return fn;
982         }
983       return NULL_TREE;
984     }
985   else
986     {
987       spec_entry *found;
988       spec_entry elt;
989       htab_t specializations;
990
991       elt.tmpl = tmpl;
992       elt.args = args;
993       elt.spec = NULL_TREE;
994
995       if (DECL_CLASS_TEMPLATE_P (tmpl))
996         specializations = type_specializations;
997       else
998         specializations = decl_specializations;
999
1000       if (hash == 0)
1001         hash = hash_specialization (&elt);
1002       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1003       if (found)
1004         return found->spec;
1005     }
1006
1007   return NULL_TREE;
1008 }
1009
1010 /* Like retrieve_specialization, but for local declarations.  */
1011
1012 static tree
1013 retrieve_local_specialization (tree tmpl)
1014 {
1015   tree spec;
1016
1017   if (local_specializations == NULL)
1018     return NULL_TREE;
1019
1020   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1021                                      htab_hash_pointer (tmpl));
1022   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1023 }
1024
1025 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1026
1027 int
1028 is_specialization_of (tree decl, tree tmpl)
1029 {
1030   tree t;
1031
1032   if (TREE_CODE (decl) == FUNCTION_DECL)
1033     {
1034       for (t = decl;
1035            t != NULL_TREE;
1036            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1037         if (t == tmpl)
1038           return 1;
1039     }
1040   else
1041     {
1042       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1043
1044       for (t = TREE_TYPE (decl);
1045            t != NULL_TREE;
1046            t = CLASSTYPE_USE_TEMPLATE (t)
1047              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1048         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1049           return 1;
1050     }
1051
1052   return 0;
1053 }
1054
1055 /* Returns nonzero iff DECL is a specialization of friend declaration
1056    FRIEND_DECL according to [temp.friend].  */
1057
1058 bool
1059 is_specialization_of_friend (tree decl, tree friend_decl)
1060 {
1061   bool need_template = true;
1062   int template_depth;
1063
1064   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1065               || TREE_CODE (decl) == TYPE_DECL);
1066
1067   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1068      of a template class, we want to check if DECL is a specialization
1069      if this.  */
1070   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1071       && DECL_TEMPLATE_INFO (friend_decl)
1072       && !DECL_USE_TEMPLATE (friend_decl))
1073     {
1074       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1075       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1076       need_template = false;
1077     }
1078   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1079            && !PRIMARY_TEMPLATE_P (friend_decl))
1080     need_template = false;
1081
1082   /* There is nothing to do if this is not a template friend.  */
1083   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1084     return false;
1085
1086   if (is_specialization_of (decl, friend_decl))
1087     return true;
1088
1089   /* [temp.friend/6]
1090      A member of a class template may be declared to be a friend of a
1091      non-template class.  In this case, the corresponding member of
1092      every specialization of the class template is a friend of the
1093      class granting friendship.
1094
1095      For example, given a template friend declaration
1096
1097        template <class T> friend void A<T>::f();
1098
1099      the member function below is considered a friend
1100
1101        template <> struct A<int> {
1102          void f();
1103        };
1104
1105      For this type of template friend, TEMPLATE_DEPTH below will be
1106      nonzero.  To determine if DECL is a friend of FRIEND, we first
1107      check if the enclosing class is a specialization of another.  */
1108
1109   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1110   if (template_depth
1111       && DECL_CLASS_SCOPE_P (decl)
1112       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1113                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1114     {
1115       /* Next, we check the members themselves.  In order to handle
1116          a few tricky cases, such as when FRIEND_DECL's are
1117
1118            template <class T> friend void A<T>::g(T t);
1119            template <class T> template <T t> friend void A<T>::h();
1120
1121          and DECL's are
1122
1123            void A<int>::g(int);
1124            template <int> void A<int>::h();
1125
1126          we need to figure out ARGS, the template arguments from
1127          the context of DECL.  This is required for template substitution
1128          of `T' in the function parameter of `g' and template parameter
1129          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1130
1131       tree context = DECL_CONTEXT (decl);
1132       tree args = NULL_TREE;
1133       int current_depth = 0;
1134
1135       while (current_depth < template_depth)
1136         {
1137           if (CLASSTYPE_TEMPLATE_INFO (context))
1138             {
1139               if (current_depth == 0)
1140                 args = TYPE_TI_ARGS (context);
1141               else
1142                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1143               current_depth++;
1144             }
1145           context = TYPE_CONTEXT (context);
1146         }
1147
1148       if (TREE_CODE (decl) == FUNCTION_DECL)
1149         {
1150           bool is_template;
1151           tree friend_type;
1152           tree decl_type;
1153           tree friend_args_type;
1154           tree decl_args_type;
1155
1156           /* Make sure that both DECL and FRIEND_DECL are templates or
1157              non-templates.  */
1158           is_template = DECL_TEMPLATE_INFO (decl)
1159                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1160           if (need_template ^ is_template)
1161             return false;
1162           else if (is_template)
1163             {
1164               /* If both are templates, check template parameter list.  */
1165               tree friend_parms
1166                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1167                                          args, tf_none);
1168               if (!comp_template_parms
1169                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1170                       friend_parms))
1171                 return false;
1172
1173               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1174             }
1175           else
1176             decl_type = TREE_TYPE (decl);
1177
1178           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1179                                               tf_none, NULL_TREE);
1180           if (friend_type == error_mark_node)
1181             return false;
1182
1183           /* Check if return types match.  */
1184           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1185             return false;
1186
1187           /* Check if function parameter types match, ignoring the
1188              `this' parameter.  */
1189           friend_args_type = TYPE_ARG_TYPES (friend_type);
1190           decl_args_type = TYPE_ARG_TYPES (decl_type);
1191           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1192             friend_args_type = TREE_CHAIN (friend_args_type);
1193           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1194             decl_args_type = TREE_CHAIN (decl_args_type);
1195
1196           return compparms (decl_args_type, friend_args_type);
1197         }
1198       else
1199         {
1200           /* DECL is a TYPE_DECL */
1201           bool is_template;
1202           tree decl_type = TREE_TYPE (decl);
1203
1204           /* Make sure that both DECL and FRIEND_DECL are templates or
1205              non-templates.  */
1206           is_template
1207             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1208               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1209
1210           if (need_template ^ is_template)
1211             return false;
1212           else if (is_template)
1213             {
1214               tree friend_parms;
1215               /* If both are templates, check the name of the two
1216                  TEMPLATE_DECL's first because is_friend didn't.  */
1217               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1218                   != DECL_NAME (friend_decl))
1219                 return false;
1220
1221               /* Now check template parameter list.  */
1222               friend_parms
1223                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1224                                          args, tf_none);
1225               return comp_template_parms
1226                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1227                  friend_parms);
1228             }
1229           else
1230             return (DECL_NAME (decl)
1231                     == DECL_NAME (friend_decl));
1232         }
1233     }
1234   return false;
1235 }
1236
1237 /* Register the specialization SPEC as a specialization of TMPL with
1238    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1239    is actually just a friend declaration.  Returns SPEC, or an
1240    equivalent prior declaration, if available.  */
1241
1242 static tree
1243 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1244                          hashval_t hash)
1245 {
1246   tree fn;
1247   spec_entry **slot = NULL;
1248   spec_entry elt;
1249
1250   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1251
1252   if (TREE_CODE (spec) == FUNCTION_DECL
1253       && uses_template_parms (DECL_TI_ARGS (spec)))
1254     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1255        register it; we want the corresponding TEMPLATE_DECL instead.
1256        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1257        the more obvious `uses_template_parms (spec)' to avoid problems
1258        with default function arguments.  In particular, given
1259        something like this:
1260
1261           template <class T> void f(T t1, T t = T())
1262
1263        the default argument expression is not substituted for in an
1264        instantiation unless and until it is actually needed.  */
1265     return spec;
1266
1267   if (optimize_specialization_lookup_p (tmpl))
1268     /* We don't put these specializations in the hash table, but we might
1269        want to give an error about a mismatch.  */
1270     fn = retrieve_specialization (tmpl, args, 0);
1271   else
1272     {
1273       elt.tmpl = tmpl;
1274       elt.args = args;
1275       elt.spec = spec;
1276
1277       if (hash == 0)
1278         hash = hash_specialization (&elt);
1279
1280       slot = (spec_entry **)
1281         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1282       if (*slot)
1283         fn = (*slot)->spec;
1284       else
1285         fn = NULL_TREE;
1286     }
1287
1288   /* We can sometimes try to re-register a specialization that we've
1289      already got.  In particular, regenerate_decl_from_template calls
1290      duplicate_decls which will update the specialization list.  But,
1291      we'll still get called again here anyhow.  It's more convenient
1292      to simply allow this than to try to prevent it.  */
1293   if (fn == spec)
1294     return spec;
1295   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1296     {
1297       if (DECL_TEMPLATE_INSTANTIATION (fn))
1298         {
1299           if (TREE_USED (fn)
1300               || DECL_EXPLICIT_INSTANTIATION (fn))
1301             {
1302               error ("specialization of %qD after instantiation",
1303                      fn);
1304               return error_mark_node;
1305             }
1306           else
1307             {
1308               tree clone;
1309               /* This situation should occur only if the first
1310                  specialization is an implicit instantiation, the
1311                  second is an explicit specialization, and the
1312                  implicit instantiation has not yet been used.  That
1313                  situation can occur if we have implicitly
1314                  instantiated a member function and then specialized
1315                  it later.
1316
1317                  We can also wind up here if a friend declaration that
1318                  looked like an instantiation turns out to be a
1319                  specialization:
1320
1321                    template <class T> void foo(T);
1322                    class S { friend void foo<>(int) };
1323                    template <> void foo(int);
1324
1325                  We transform the existing DECL in place so that any
1326                  pointers to it become pointers to the updated
1327                  declaration.
1328
1329                  If there was a definition for the template, but not
1330                  for the specialization, we want this to look as if
1331                  there were no definition, and vice versa.  */
1332               DECL_INITIAL (fn) = NULL_TREE;
1333               duplicate_decls (spec, fn, is_friend);
1334               /* The call to duplicate_decls will have applied
1335                  [temp.expl.spec]:
1336
1337                    An explicit specialization of a function template
1338                    is inline only if it is explicitly declared to be,
1339                    and independently of whether its function template
1340                    is.
1341
1342                 to the primary function; now copy the inline bits to
1343                 the various clones.  */
1344               FOR_EACH_CLONE (clone, fn)
1345                 DECL_DECLARED_INLINE_P (clone)
1346                   = DECL_DECLARED_INLINE_P (fn);
1347               check_specialization_namespace (fn);
1348
1349               return fn;
1350             }
1351         }
1352       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1353         {
1354           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1355             /* Dup decl failed, but this is a new definition. Set the
1356                line number so any errors match this new
1357                definition.  */
1358             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1359
1360           return fn;
1361         }
1362     }
1363   else if (fn)
1364     return duplicate_decls (spec, fn, is_friend);
1365
1366   /* A specialization must be declared in the same namespace as the
1367      template it is specializing.  */
1368   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1369       && !check_specialization_namespace (tmpl))
1370     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1371
1372   if (!optimize_specialization_lookup_p (tmpl))
1373     {
1374       gcc_assert (tmpl && args && spec);
1375       *slot = GGC_NEW (spec_entry);
1376       **slot = elt;
1377       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1378           && PRIMARY_TEMPLATE_P (tmpl)
1379           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1380         /* TMPL is a forward declaration of a template function; keep a list
1381            of all specializations in case we need to reassign them to a friend
1382            template later in tsubst_friend_function.  */
1383         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1384           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1385     }
1386
1387   return spec;
1388 }
1389
1390 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1391    TMPL and ARGS members, ignores SPEC.  */
1392
1393 static int
1394 eq_specializations (const void *p1, const void *p2)
1395 {
1396   const spec_entry *e1 = (const spec_entry *)p1;
1397   const spec_entry *e2 = (const spec_entry *)p2;
1398
1399   return (e1->tmpl == e2->tmpl
1400           && comp_template_args (e1->args, e2->args));
1401 }
1402
1403 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1404
1405 static hashval_t
1406 hash_tmpl_and_args (tree tmpl, tree args)
1407 {
1408   hashval_t val = DECL_UID (tmpl);
1409   return iterative_hash_template_arg (args, val);
1410 }
1411
1412 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1413    ignoring SPEC.  */
1414
1415 static hashval_t
1416 hash_specialization (const void *p)
1417 {
1418   const spec_entry *e = (const spec_entry *)p;
1419   return hash_tmpl_and_args (e->tmpl, e->args);
1420 }
1421
1422 /* Recursively calculate a hash value for a template argument ARG, for use
1423    in the hash tables of template specializations.  */
1424
1425 static hashval_t
1426 iterative_hash_template_arg (tree arg, hashval_t val)
1427 {
1428   unsigned HOST_WIDE_INT i;
1429   enum tree_code code;
1430   char tclass;
1431
1432   if (arg == NULL_TREE)
1433     return iterative_hash_object (arg, val);
1434
1435   if (!TYPE_P (arg))
1436     STRIP_NOPS (arg);
1437
1438   code = TREE_CODE (arg);
1439   tclass = TREE_CODE_CLASS (code);
1440
1441   val = iterative_hash_object (code, val);
1442
1443   switch (code)
1444     {
1445     case ERROR_MARK:
1446       return val;
1447
1448     case IDENTIFIER_NODE:
1449       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1450
1451     case TREE_VEC:
1452       {
1453         int i, len = TREE_VEC_LENGTH (arg);
1454         for (i = 0; i < len; ++i)
1455           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1456         return val;
1457       }
1458
1459     case TYPE_PACK_EXPANSION:
1460     case EXPR_PACK_EXPANSION:
1461       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1462
1463     case ARGUMENT_PACK_SELECT:
1464       /* We can get one of these when re-hashing a previous entry in the middle
1465          of substituting into a pack expansion.  Just look through it...  */
1466       arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1467       /* ...and fall through.  */
1468     case TYPE_ARGUMENT_PACK:
1469     case NONTYPE_ARGUMENT_PACK:
1470       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1471
1472     case TREE_LIST:
1473       for (; arg; arg = TREE_CHAIN (arg))
1474         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1475       return val;
1476
1477     case OVERLOAD:
1478       for (; arg; arg = OVL_CHAIN (arg))
1479         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1480       return val;
1481
1482     case CONSTRUCTOR:
1483       {
1484         tree field, value;
1485         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1486           {
1487             val = iterative_hash_template_arg (field, val);
1488             val = iterative_hash_template_arg (value, val);
1489           }
1490         return val;
1491       }
1492
1493     case PARM_DECL:
1494       val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1495       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1496
1497     case TARGET_EXPR:
1498       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1499
1500     case PTRMEM_CST:
1501       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1502       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1503
1504     case TEMPLATE_PARM_INDEX:
1505       val = iterative_hash_template_arg
1506         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1507       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1508       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1509
1510     case TRAIT_EXPR:
1511       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1512       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1513       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1514
1515     case BASELINK:
1516       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1517                                          val);
1518       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1519                                           val);
1520
1521     case MODOP_EXPR:
1522       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1523       code = TREE_CODE (TREE_OPERAND (arg, 1));
1524       val = iterative_hash_object (code, val);
1525       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1526
1527     default:
1528       switch (tclass)
1529         {
1530         case tcc_type:
1531           if (TYPE_CANONICAL (arg))
1532             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1533                                           val);
1534           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1535             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1536           /* Otherwise just compare the types during lookup.  */
1537           return val;
1538
1539         case tcc_declaration:
1540         case tcc_constant:
1541           return iterative_hash_expr (arg, val);
1542
1543         default:
1544           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1545           {
1546             unsigned n = TREE_OPERAND_LENGTH (arg);
1547             for (i = 0; i < n; ++i)
1548               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1549             return val;
1550           }
1551         }
1552     }
1553   gcc_unreachable ();
1554   return 0;
1555 }
1556
1557 /* Unregister the specialization SPEC as a specialization of TMPL.
1558    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1559    if the SPEC was listed as a specialization of TMPL.
1560
1561    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1562
1563 bool
1564 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1565 {
1566   spec_entry **slot;
1567   spec_entry elt;
1568
1569   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1570   elt.args = TI_ARGS (tinfo);
1571   elt.spec = NULL_TREE;
1572
1573   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1574   if (*slot)
1575     {
1576       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1577       gcc_assert (new_spec != NULL_TREE);
1578       (*slot)->spec = new_spec;
1579       return 1;
1580     }
1581
1582   return 0;
1583 }
1584
1585 /* Compare an entry in the local specializations hash table P1 (which
1586    is really a pointer to a TREE_LIST) with P2 (which is really a
1587    DECL).  */
1588
1589 static int
1590 eq_local_specializations (const void *p1, const void *p2)
1591 {
1592   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1593 }
1594
1595 /* Hash P1, an entry in the local specializations table.  */
1596
1597 static hashval_t
1598 hash_local_specialization (const void* p1)
1599 {
1600   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1601 }
1602
1603 /* Like register_specialization, but for local declarations.  We are
1604    registering SPEC, an instantiation of TMPL.  */
1605
1606 static void
1607 register_local_specialization (tree spec, tree tmpl)
1608 {
1609   void **slot;
1610
1611   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1612                                    htab_hash_pointer (tmpl), INSERT);
1613   *slot = build_tree_list (spec, tmpl);
1614 }
1615
1616 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1617    specialized class.  */
1618
1619 bool
1620 explicit_class_specialization_p (tree type)
1621 {
1622   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1623     return false;
1624   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1625 }
1626
1627 /* Print the list of candidate FNS in an error message.  */
1628
1629 void
1630 print_candidates (tree fns)
1631 {
1632   tree fn;
1633
1634   const char *str = "candidates are:";
1635
1636   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1637     {
1638       tree f;
1639
1640       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1641         error ("%s %+#D", str, OVL_CURRENT (f));
1642       str = "               ";
1643     }
1644 }
1645
1646 /* Returns the template (one of the functions given by TEMPLATE_ID)
1647    which can be specialized to match the indicated DECL with the
1648    explicit template args given in TEMPLATE_ID.  The DECL may be
1649    NULL_TREE if none is available.  In that case, the functions in
1650    TEMPLATE_ID are non-members.
1651
1652    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1653    specialization of a member template.
1654
1655    The TEMPLATE_COUNT is the number of references to qualifying
1656    template classes that appeared in the name of the function. See
1657    check_explicit_specialization for a more accurate description.
1658
1659    TSK indicates what kind of template declaration (if any) is being
1660    declared.  TSK_TEMPLATE indicates that the declaration given by
1661    DECL, though a FUNCTION_DECL, has template parameters, and is
1662    therefore a template function.
1663
1664    The template args (those explicitly specified and those deduced)
1665    are output in a newly created vector *TARGS_OUT.
1666
1667    If it is impossible to determine the result, an error message is
1668    issued.  The error_mark_node is returned to indicate failure.  */
1669
1670 static tree
1671 determine_specialization (tree template_id,
1672                           tree decl,
1673                           tree* targs_out,
1674                           int need_member_template,
1675                           int template_count,
1676                           tmpl_spec_kind tsk)
1677 {
1678   tree fns;
1679   tree targs;
1680   tree explicit_targs;
1681   tree candidates = NULL_TREE;
1682   /* A TREE_LIST of templates of which DECL may be a specialization.
1683      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1684      corresponding TREE_PURPOSE is the set of template arguments that,
1685      when used to instantiate the template, would produce a function
1686      with the signature of DECL.  */
1687   tree templates = NULL_TREE;
1688   int header_count;
1689   struct cp_binding_level *b;
1690
1691   *targs_out = NULL_TREE;
1692
1693   if (template_id == error_mark_node || decl == error_mark_node)
1694     return error_mark_node;
1695
1696   fns = TREE_OPERAND (template_id, 0);
1697   explicit_targs = TREE_OPERAND (template_id, 1);
1698
1699   if (fns == error_mark_node)
1700     return error_mark_node;
1701
1702   /* Check for baselinks.  */
1703   if (BASELINK_P (fns))
1704     fns = BASELINK_FUNCTIONS (fns);
1705
1706   if (!is_overloaded_fn (fns))
1707     {
1708       error ("%qD is not a function template", fns);
1709       return error_mark_node;
1710     }
1711
1712   /* Count the number of template headers specified for this
1713      specialization.  */
1714   header_count = 0;
1715   for (b = current_binding_level;
1716        b->kind == sk_template_parms;
1717        b = b->level_chain)
1718     ++header_count;
1719
1720   for (; fns; fns = OVL_NEXT (fns))
1721     {
1722       tree fn = OVL_CURRENT (fns);
1723
1724       if (TREE_CODE (fn) == TEMPLATE_DECL)
1725         {
1726           tree decl_arg_types;
1727           tree fn_arg_types;
1728
1729           /* In case of explicit specialization, we need to check if
1730              the number of template headers appearing in the specialization
1731              is correct. This is usually done in check_explicit_specialization,
1732              but the check done there cannot be exhaustive when specializing
1733              member functions. Consider the following code:
1734
1735              template <> void A<int>::f(int);
1736              template <> template <> void A<int>::f(int);
1737
1738              Assuming that A<int> is not itself an explicit specialization
1739              already, the first line specializes "f" which is a non-template
1740              member function, whilst the second line specializes "f" which
1741              is a template member function. So both lines are syntactically
1742              correct, and check_explicit_specialization does not reject
1743              them.
1744
1745              Here, we can do better, as we are matching the specialization
1746              against the declarations. We count the number of template
1747              headers, and we check if they match TEMPLATE_COUNT + 1
1748              (TEMPLATE_COUNT is the number of qualifying template classes,
1749              plus there must be another header for the member template
1750              itself).
1751
1752              Notice that if header_count is zero, this is not a
1753              specialization but rather a template instantiation, so there
1754              is no check we can perform here.  */
1755           if (header_count && header_count != template_count + 1)
1756             continue;
1757
1758           /* Check that the number of template arguments at the
1759              innermost level for DECL is the same as for FN.  */
1760           if (current_binding_level->kind == sk_template_parms
1761               && !current_binding_level->explicit_spec_p
1762               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1763                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1764                                       (current_template_parms))))
1765             continue;
1766
1767           /* DECL might be a specialization of FN.  */
1768           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1769           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1770
1771           /* For a non-static member function, we need to make sure
1772              that the const qualification is the same.  Since
1773              get_bindings does not try to merge the "this" parameter,
1774              we must do the comparison explicitly.  */
1775           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1776               && !same_type_p (TREE_VALUE (fn_arg_types),
1777                                TREE_VALUE (decl_arg_types)))
1778             continue;
1779
1780           /* Skip the "this" parameter and, for constructors of
1781              classes with virtual bases, the VTT parameter.  A
1782              full specialization of a constructor will have a VTT
1783              parameter, but a template never will.  */ 
1784           decl_arg_types 
1785             = skip_artificial_parms_for (decl, decl_arg_types);
1786           fn_arg_types 
1787             = skip_artificial_parms_for (fn, fn_arg_types);
1788
1789           /* Check that the number of function parameters matches.
1790              For example,
1791                template <class T> void f(int i = 0);
1792                template <> void f<int>();
1793              The specialization f<int> is invalid but is not caught
1794              by get_bindings below.  */
1795           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1796             continue;
1797
1798           /* Function templates cannot be specializations; there are
1799              no partial specializations of functions.  Therefore, if
1800              the type of DECL does not match FN, there is no
1801              match.  */
1802           if (tsk == tsk_template)
1803             {
1804               if (compparms (fn_arg_types, decl_arg_types))
1805                 candidates = tree_cons (NULL_TREE, fn, candidates);
1806               continue;
1807             }
1808
1809           /* See whether this function might be a specialization of this
1810              template.  */
1811           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1812
1813           if (!targs)
1814             /* We cannot deduce template arguments that when used to
1815                specialize TMPL will produce DECL.  */
1816             continue;
1817
1818           /* Save this template, and the arguments deduced.  */
1819           templates = tree_cons (targs, fn, templates);
1820         }
1821       else if (need_member_template)
1822         /* FN is an ordinary member function, and we need a
1823            specialization of a member template.  */
1824         ;
1825       else if (TREE_CODE (fn) != FUNCTION_DECL)
1826         /* We can get IDENTIFIER_NODEs here in certain erroneous
1827            cases.  */
1828         ;
1829       else if (!DECL_FUNCTION_MEMBER_P (fn))
1830         /* This is just an ordinary non-member function.  Nothing can
1831            be a specialization of that.  */
1832         ;
1833       else if (DECL_ARTIFICIAL (fn))
1834         /* Cannot specialize functions that are created implicitly.  */
1835         ;
1836       else
1837         {
1838           tree decl_arg_types;
1839
1840           /* This is an ordinary member function.  However, since
1841              we're here, we can assume it's enclosing class is a
1842              template class.  For example,
1843
1844                template <typename T> struct S { void f(); };
1845                template <> void S<int>::f() {}
1846
1847              Here, S<int>::f is a non-template, but S<int> is a
1848              template class.  If FN has the same type as DECL, we
1849              might be in business.  */
1850
1851           if (!DECL_TEMPLATE_INFO (fn))
1852             /* Its enclosing class is an explicit specialization
1853                of a template class.  This is not a candidate.  */
1854             continue;
1855
1856           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1857                             TREE_TYPE (TREE_TYPE (fn))))
1858             /* The return types differ.  */
1859             continue;
1860
1861           /* Adjust the type of DECL in case FN is a static member.  */
1862           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1863           if (DECL_STATIC_FUNCTION_P (fn)
1864               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1865             decl_arg_types = TREE_CHAIN (decl_arg_types);
1866
1867           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1868                          decl_arg_types))
1869             /* They match!  */
1870             candidates = tree_cons (NULL_TREE, fn, candidates);
1871         }
1872     }
1873
1874   if (templates && TREE_CHAIN (templates))
1875     {
1876       /* We have:
1877
1878            [temp.expl.spec]
1879
1880            It is possible for a specialization with a given function
1881            signature to be instantiated from more than one function
1882            template.  In such cases, explicit specification of the
1883            template arguments must be used to uniquely identify the
1884            function template specialization being specialized.
1885
1886          Note that here, there's no suggestion that we're supposed to
1887          determine which of the candidate templates is most
1888          specialized.  However, we, also have:
1889
1890            [temp.func.order]
1891
1892            Partial ordering of overloaded function template
1893            declarations is used in the following contexts to select
1894            the function template to which a function template
1895            specialization refers:
1896
1897            -- when an explicit specialization refers to a function
1898               template.
1899
1900          So, we do use the partial ordering rules, at least for now.
1901          This extension can only serve to make invalid programs valid,
1902          so it's safe.  And, there is strong anecdotal evidence that
1903          the committee intended the partial ordering rules to apply;
1904          the EDG front end has that behavior, and John Spicer claims
1905          that the committee simply forgot to delete the wording in
1906          [temp.expl.spec].  */
1907       tree tmpl = most_specialized_instantiation (templates);
1908       if (tmpl != error_mark_node)
1909         {
1910           templates = tmpl;
1911           TREE_CHAIN (templates) = NULL_TREE;
1912         }
1913     }
1914
1915   if (templates == NULL_TREE && candidates == NULL_TREE)
1916     {
1917       error ("template-id %qD for %q+D does not match any template "
1918              "declaration", template_id, decl);
1919       return error_mark_node;
1920     }
1921   else if ((templates && TREE_CHAIN (templates))
1922            || (candidates && TREE_CHAIN (candidates))
1923            || (templates && candidates))
1924     {
1925       error ("ambiguous template specialization %qD for %q+D",
1926              template_id, decl);
1927       chainon (candidates, templates);
1928       print_candidates (candidates);
1929       return error_mark_node;
1930     }
1931
1932   /* We have one, and exactly one, match.  */
1933   if (candidates)
1934     {
1935       tree fn = TREE_VALUE (candidates);
1936       *targs_out = copy_node (DECL_TI_ARGS (fn));
1937       /* DECL is a re-declaration or partial instantiation of a template
1938          function.  */
1939       if (TREE_CODE (fn) == TEMPLATE_DECL)
1940         return fn;
1941       /* It was a specialization of an ordinary member function in a
1942          template class.  */
1943       return DECL_TI_TEMPLATE (fn);
1944     }
1945
1946   /* It was a specialization of a template.  */
1947   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1948   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1949     {
1950       *targs_out = copy_node (targs);
1951       SET_TMPL_ARGS_LEVEL (*targs_out,
1952                            TMPL_ARGS_DEPTH (*targs_out),
1953                            TREE_PURPOSE (templates));
1954     }
1955   else
1956     *targs_out = TREE_PURPOSE (templates);
1957   return TREE_VALUE (templates);
1958 }
1959
1960 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1961    but with the default argument values filled in from those in the
1962    TMPL_TYPES.  */
1963
1964 static tree
1965 copy_default_args_to_explicit_spec_1 (tree spec_types,
1966                                       tree tmpl_types)
1967 {
1968   tree new_spec_types;
1969
1970   if (!spec_types)
1971     return NULL_TREE;
1972
1973   if (spec_types == void_list_node)
1974     return void_list_node;
1975
1976   /* Substitute into the rest of the list.  */
1977   new_spec_types =
1978     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1979                                           TREE_CHAIN (tmpl_types));
1980
1981   /* Add the default argument for this parameter.  */
1982   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1983                          TREE_VALUE (spec_types),
1984                          new_spec_types);
1985 }
1986
1987 /* DECL is an explicit specialization.  Replicate default arguments
1988    from the template it specializes.  (That way, code like:
1989
1990      template <class T> void f(T = 3);
1991      template <> void f(double);
1992      void g () { f (); }
1993
1994    works, as required.)  An alternative approach would be to look up
1995    the correct default arguments at the call-site, but this approach
1996    is consistent with how implicit instantiations are handled.  */
1997
1998 static void
1999 copy_default_args_to_explicit_spec (tree decl)
2000 {
2001   tree tmpl;
2002   tree spec_types;
2003   tree tmpl_types;
2004   tree new_spec_types;
2005   tree old_type;
2006   tree new_type;
2007   tree t;
2008   tree object_type = NULL_TREE;
2009   tree in_charge = NULL_TREE;
2010   tree vtt = NULL_TREE;
2011
2012   /* See if there's anything we need to do.  */
2013   tmpl = DECL_TI_TEMPLATE (decl);
2014   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2015   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2016     if (TREE_PURPOSE (t))
2017       break;
2018   if (!t)
2019     return;
2020
2021   old_type = TREE_TYPE (decl);
2022   spec_types = TYPE_ARG_TYPES (old_type);
2023
2024   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2025     {
2026       /* Remove the this pointer, but remember the object's type for
2027          CV quals.  */
2028       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2029       spec_types = TREE_CHAIN (spec_types);
2030       tmpl_types = TREE_CHAIN (tmpl_types);
2031
2032       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2033         {
2034           /* DECL may contain more parameters than TMPL due to the extra
2035              in-charge parameter in constructors and destructors.  */
2036           in_charge = spec_types;
2037           spec_types = TREE_CHAIN (spec_types);
2038         }
2039       if (DECL_HAS_VTT_PARM_P (decl))
2040         {
2041           vtt = spec_types;
2042           spec_types = TREE_CHAIN (spec_types);
2043         }
2044     }
2045
2046   /* Compute the merged default arguments.  */
2047   new_spec_types =
2048     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2049
2050   /* Compute the new FUNCTION_TYPE.  */
2051   if (object_type)
2052     {
2053       if (vtt)
2054         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2055                                          TREE_VALUE (vtt),
2056                                          new_spec_types);
2057
2058       if (in_charge)
2059         /* Put the in-charge parameter back.  */
2060         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2061                                          TREE_VALUE (in_charge),
2062                                          new_spec_types);
2063
2064       new_type = build_method_type_directly (object_type,
2065                                              TREE_TYPE (old_type),
2066                                              new_spec_types);
2067     }
2068   else
2069     new_type = build_function_type (TREE_TYPE (old_type),
2070                                     new_spec_types);
2071   new_type = cp_build_type_attribute_variant (new_type,
2072                                               TYPE_ATTRIBUTES (old_type));
2073   new_type = build_exception_variant (new_type,
2074                                       TYPE_RAISES_EXCEPTIONS (old_type));
2075   TREE_TYPE (decl) = new_type;
2076 }
2077
2078 /* Check to see if the function just declared, as indicated in
2079    DECLARATOR, and in DECL, is a specialization of a function
2080    template.  We may also discover that the declaration is an explicit
2081    instantiation at this point.
2082
2083    Returns DECL, or an equivalent declaration that should be used
2084    instead if all goes well.  Issues an error message if something is
2085    amiss.  Returns error_mark_node if the error is not easily
2086    recoverable.
2087
2088    FLAGS is a bitmask consisting of the following flags:
2089
2090    2: The function has a definition.
2091    4: The function is a friend.
2092
2093    The TEMPLATE_COUNT is the number of references to qualifying
2094    template classes that appeared in the name of the function.  For
2095    example, in
2096
2097      template <class T> struct S { void f(); };
2098      void S<int>::f();
2099
2100    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2101    classes are not counted in the TEMPLATE_COUNT, so that in
2102
2103      template <class T> struct S {};
2104      template <> struct S<int> { void f(); }
2105      template <> void S<int>::f();
2106
2107    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2108    invalid; there should be no template <>.)
2109
2110    If the function is a specialization, it is marked as such via
2111    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2112    is set up correctly, and it is added to the list of specializations
2113    for that template.  */
2114
2115 tree
2116 check_explicit_specialization (tree declarator,
2117                                tree decl,
2118                                int template_count,
2119                                int flags)
2120 {
2121   int have_def = flags & 2;
2122   int is_friend = flags & 4;
2123   int specialization = 0;
2124   int explicit_instantiation = 0;
2125   int member_specialization = 0;
2126   tree ctype = DECL_CLASS_CONTEXT (decl);
2127   tree dname = DECL_NAME (decl);
2128   tmpl_spec_kind tsk;
2129
2130   if (is_friend)
2131     {
2132       if (!processing_specialization)
2133         tsk = tsk_none;
2134       else
2135         tsk = tsk_excessive_parms;
2136     }
2137   else
2138     tsk = current_tmpl_spec_kind (template_count);
2139
2140   switch (tsk)
2141     {
2142     case tsk_none:
2143       if (processing_specialization)
2144         {
2145           specialization = 1;
2146           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2147         }
2148       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2149         {
2150           if (is_friend)
2151             /* This could be something like:
2152
2153                template <class T> void f(T);
2154                class S { friend void f<>(int); }  */
2155             specialization = 1;
2156           else
2157             {
2158               /* This case handles bogus declarations like template <>
2159                  template <class T> void f<int>(); */
2160
2161               error ("template-id %qD in declaration of primary template",
2162                      declarator);
2163               return decl;
2164             }
2165         }
2166       break;
2167
2168     case tsk_invalid_member_spec:
2169       /* The error has already been reported in
2170          check_specialization_scope.  */
2171       return error_mark_node;
2172
2173     case tsk_invalid_expl_inst:
2174       error ("template parameter list used in explicit instantiation");
2175
2176       /* Fall through.  */
2177
2178     case tsk_expl_inst:
2179       if (have_def)
2180         error ("definition provided for explicit instantiation");
2181
2182       explicit_instantiation = 1;
2183       break;
2184
2185     case tsk_excessive_parms:
2186     case tsk_insufficient_parms:
2187       if (tsk == tsk_excessive_parms)
2188         error ("too many template parameter lists in declaration of %qD",
2189                decl);
2190       else if (template_header_count)
2191         error("too few template parameter lists in declaration of %qD", decl);
2192       else
2193         error("explicit specialization of %qD must be introduced by "
2194               "%<template <>%>", decl);
2195
2196       /* Fall through.  */
2197     case tsk_expl_spec:
2198       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2199       if (ctype)
2200         member_specialization = 1;
2201       else
2202         specialization = 1;
2203       break;
2204
2205     case tsk_template:
2206       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2207         {
2208           /* This case handles bogus declarations like template <>
2209              template <class T> void f<int>(); */
2210
2211           if (uses_template_parms (declarator))
2212             error ("function template partial specialization %qD "
2213                    "is not allowed", declarator);
2214           else
2215             error ("template-id %qD in declaration of primary template",
2216                    declarator);
2217           return decl;
2218         }
2219
2220       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2221         /* This is a specialization of a member template, without
2222            specialization the containing class.  Something like:
2223
2224              template <class T> struct S {
2225                template <class U> void f (U);
2226              };
2227              template <> template <class U> void S<int>::f(U) {}
2228
2229            That's a specialization -- but of the entire template.  */
2230         specialization = 1;
2231       break;
2232
2233     default:
2234       gcc_unreachable ();
2235     }
2236
2237   if (specialization || member_specialization)
2238     {
2239       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2240       for (; t; t = TREE_CHAIN (t))
2241         if (TREE_PURPOSE (t))
2242           {
2243             permerror (input_location, 
2244                        "default argument specified in explicit specialization");
2245             break;
2246           }
2247     }
2248
2249   if (specialization || member_specialization || explicit_instantiation)
2250     {
2251       tree tmpl = NULL_TREE;
2252       tree targs = NULL_TREE;
2253
2254       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2255       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2256         {
2257           tree fns;
2258
2259           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2260           if (ctype)
2261             fns = dname;
2262           else
2263             {
2264               /* If there is no class context, the explicit instantiation
2265                  must be at namespace scope.  */
2266               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2267
2268               /* Find the namespace binding, using the declaration
2269                  context.  */
2270               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2271                                            false, true);
2272               if (fns == error_mark_node || !is_overloaded_fn (fns))
2273                 {
2274                   error ("%qD is not a template function", dname);
2275                   fns = error_mark_node;
2276                 }
2277               else
2278                 {
2279                   tree fn = OVL_CURRENT (fns);
2280                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2281                                                 CP_DECL_CONTEXT (fn)))
2282                     error ("%qD is not declared in %qD",
2283                            decl, current_namespace);
2284                 }
2285             }
2286
2287           declarator = lookup_template_function (fns, NULL_TREE);
2288         }
2289
2290       if (declarator == error_mark_node)
2291         return error_mark_node;
2292
2293       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2294         {
2295           if (!explicit_instantiation)
2296             /* A specialization in class scope.  This is invalid,
2297                but the error will already have been flagged by
2298                check_specialization_scope.  */
2299             return error_mark_node;
2300           else
2301             {
2302               /* It's not valid to write an explicit instantiation in
2303                  class scope, e.g.:
2304
2305                    class C { template void f(); }
2306
2307                    This case is caught by the parser.  However, on
2308                    something like:
2309
2310                    template class C { void f(); };
2311
2312                    (which is invalid) we can get here.  The error will be
2313                    issued later.  */
2314               ;
2315             }
2316
2317           return decl;
2318         }
2319       else if (ctype != NULL_TREE
2320                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2321                    IDENTIFIER_NODE))
2322         {
2323           /* Find the list of functions in ctype that have the same
2324              name as the declared function.  */
2325           tree name = TREE_OPERAND (declarator, 0);
2326           tree fns = NULL_TREE;
2327           int idx;
2328
2329           if (constructor_name_p (name, ctype))
2330             {
2331               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2332
2333               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2334                   : !CLASSTYPE_DESTRUCTORS (ctype))
2335                 {
2336                   /* From [temp.expl.spec]:
2337
2338                      If such an explicit specialization for the member
2339                      of a class template names an implicitly-declared
2340                      special member function (clause _special_), the
2341                      program is ill-formed.
2342
2343                      Similar language is found in [temp.explicit].  */
2344                   error ("specialization of implicitly-declared special member function");
2345                   return error_mark_node;
2346                 }
2347
2348               name = is_constructor ? ctor_identifier : dtor_identifier;
2349             }
2350
2351           if (!DECL_CONV_FN_P (decl))
2352             {
2353               idx = lookup_fnfields_1 (ctype, name);
2354               if (idx >= 0)
2355                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2356             }
2357           else
2358             {
2359               VEC(tree,gc) *methods;
2360               tree ovl;
2361
2362               /* For a type-conversion operator, we cannot do a
2363                  name-based lookup.  We might be looking for `operator
2364                  int' which will be a specialization of `operator T'.
2365                  So, we find *all* the conversion operators, and then
2366                  select from them.  */
2367               fns = NULL_TREE;
2368
2369               methods = CLASSTYPE_METHOD_VEC (ctype);
2370               if (methods)
2371                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2372                      VEC_iterate (tree, methods, idx, ovl);
2373                      ++idx)
2374                   {
2375                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2376                       /* There are no more conversion functions.  */
2377                       break;
2378
2379                     /* Glue all these conversion functions together
2380                        with those we already have.  */
2381                     for (; ovl; ovl = OVL_NEXT (ovl))
2382                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2383                   }
2384             }
2385
2386           if (fns == NULL_TREE)
2387             {
2388               error ("no member function %qD declared in %qT", name, ctype);
2389               return error_mark_node;
2390             }
2391           else
2392             TREE_OPERAND (declarator, 0) = fns;
2393         }
2394
2395       /* Figure out what exactly is being specialized at this point.
2396          Note that for an explicit instantiation, even one for a
2397          member function, we cannot tell apriori whether the
2398          instantiation is for a member template, or just a member
2399          function of a template class.  Even if a member template is
2400          being instantiated, the member template arguments may be
2401          elided if they can be deduced from the rest of the
2402          declaration.  */
2403       tmpl = determine_specialization (declarator, decl,
2404                                        &targs,
2405                                        member_specialization,
2406                                        template_count,
2407                                        tsk);
2408
2409       if (!tmpl || tmpl == error_mark_node)
2410         /* We couldn't figure out what this declaration was
2411            specializing.  */
2412         return error_mark_node;
2413       else
2414         {
2415           tree gen_tmpl = most_general_template (tmpl);
2416
2417           if (explicit_instantiation)
2418             {
2419               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2420                  is done by do_decl_instantiation later.  */
2421
2422               int arg_depth = TMPL_ARGS_DEPTH (targs);
2423               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2424
2425               if (arg_depth > parm_depth)
2426                 {
2427                   /* If TMPL is not the most general template (for
2428                      example, if TMPL is a friend template that is
2429                      injected into namespace scope), then there will
2430                      be too many levels of TARGS.  Remove some of them
2431                      here.  */
2432                   int i;
2433                   tree new_targs;
2434
2435                   new_targs = make_tree_vec (parm_depth);
2436                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2437                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2438                       = TREE_VEC_ELT (targs, i);
2439                   targs = new_targs;
2440                 }
2441
2442               return instantiate_template (tmpl, targs, tf_error);
2443             }
2444
2445           /* If we thought that the DECL was a member function, but it
2446              turns out to be specializing a static member function,
2447              make DECL a static member function as well.  */
2448           if (DECL_STATIC_FUNCTION_P (tmpl)
2449               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2450             revert_static_member_fn (decl);
2451
2452           /* If this is a specialization of a member template of a
2453              template class, we want to return the TEMPLATE_DECL, not
2454              the specialization of it.  */
2455           if (tsk == tsk_template)
2456             {
2457               tree result = DECL_TEMPLATE_RESULT (tmpl);
2458               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2459               DECL_INITIAL (result) = NULL_TREE;
2460               if (have_def)
2461                 {
2462                   tree parm;
2463                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2464                   DECL_SOURCE_LOCATION (result)
2465                     = DECL_SOURCE_LOCATION (decl);
2466                   /* We want to use the argument list specified in the
2467                      definition, not in the original declaration.  */
2468                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2469                   for (parm = DECL_ARGUMENTS (result); parm;
2470                        parm = TREE_CHAIN (parm))
2471                     DECL_CONTEXT (parm) = result;
2472                 }
2473               return register_specialization (tmpl, gen_tmpl, targs,
2474                                               is_friend, 0);
2475             }
2476
2477           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2478           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2479
2480           /* Inherit default function arguments from the template
2481              DECL is specializing.  */
2482           copy_default_args_to_explicit_spec (decl);
2483
2484           /* This specialization has the same protection as the
2485              template it specializes.  */
2486           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2487           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2488
2489           /* 7.1.1-1 [dcl.stc]
2490
2491              A storage-class-specifier shall not be specified in an
2492              explicit specialization...
2493
2494              The parser rejects these, so unless action is taken here,
2495              explicit function specializations will always appear with
2496              global linkage.
2497
2498              The action recommended by the C++ CWG in response to C++
2499              defect report 605 is to make the storage class and linkage
2500              of the explicit specialization match the templated function:
2501
2502              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2503            */
2504           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2505             {
2506               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2507               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2508
2509               /* This specialization has the same linkage and visibility as
2510                  the function template it specializes.  */
2511               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2512               if (! TREE_PUBLIC (decl))
2513                 {
2514                   DECL_INTERFACE_KNOWN (decl) = 1;
2515                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2516                 }
2517               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2518               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2519                 {
2520                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2521                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2522                 }
2523             }
2524
2525           /* If DECL is a friend declaration, declared using an
2526              unqualified name, the namespace associated with DECL may
2527              have been set incorrectly.  For example, in:
2528
2529                template <typename T> void f(T);
2530                namespace N {
2531                  struct S { friend void f<int>(int); }
2532                }
2533
2534              we will have set the DECL_CONTEXT for the friend
2535              declaration to N, rather than to the global namespace.  */
2536           if (DECL_NAMESPACE_SCOPE_P (decl))
2537             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2538
2539           if (is_friend && !have_def)
2540             /* This is not really a declaration of a specialization.
2541                It's just the name of an instantiation.  But, it's not
2542                a request for an instantiation, either.  */
2543             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2544           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2545             /* This is indeed a specialization.  In case of constructors
2546                and destructors, we need in-charge and not-in-charge
2547                versions in V3 ABI.  */
2548             clone_function_decl (decl, /*update_method_vec_p=*/0);
2549
2550           /* Register this specialization so that we can find it
2551              again.  */
2552           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2553         }
2554     }
2555
2556   return decl;
2557 }
2558
2559 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2560    parameters.  These are represented in the same format used for
2561    DECL_TEMPLATE_PARMS.  */
2562
2563 int
2564 comp_template_parms (const_tree parms1, const_tree parms2)
2565 {
2566   const_tree p1;
2567   const_tree p2;
2568
2569   if (parms1 == parms2)
2570     return 1;
2571
2572   for (p1 = parms1, p2 = parms2;
2573        p1 != NULL_TREE && p2 != NULL_TREE;
2574        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2575     {
2576       tree t1 = TREE_VALUE (p1);
2577       tree t2 = TREE_VALUE (p2);
2578       int i;
2579
2580       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2581       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2582
2583       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2584         return 0;
2585
2586       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2587         {
2588           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2589           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2590
2591           /* If either of the template parameters are invalid, assume
2592              they match for the sake of error recovery. */
2593           if (parm1 == error_mark_node || parm2 == error_mark_node)
2594             return 1;
2595
2596           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2597             return 0;
2598
2599           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2600               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2601                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2602             continue;
2603           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2604             return 0;
2605         }
2606     }
2607
2608   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2609     /* One set of parameters has more parameters lists than the
2610        other.  */
2611     return 0;
2612
2613   return 1;
2614 }
2615
2616 /* Determine whether PARM is a parameter pack.  */
2617 bool 
2618 template_parameter_pack_p (const_tree parm)
2619 {
2620   /* Determine if we have a non-type template parameter pack.  */
2621   if (TREE_CODE (parm) == PARM_DECL)
2622     return (DECL_TEMPLATE_PARM_P (parm) 
2623             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2624
2625   /* If this is a list of template parameters, we could get a
2626      TYPE_DECL or a TEMPLATE_DECL.  */ 
2627   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2628     parm = TREE_TYPE (parm);
2629
2630   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2631            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2632           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2633 }
2634
2635 /* Determine whether ARGS describes a variadic template args list,
2636    i.e., one that is terminated by a template argument pack.  */
2637 static bool 
2638 template_args_variadic_p (tree args)
2639 {
2640   int nargs;
2641   tree last_parm;
2642
2643   if (args == NULL_TREE)
2644     return false;
2645
2646   args = INNERMOST_TEMPLATE_ARGS (args);
2647   nargs = TREE_VEC_LENGTH (args);
2648
2649   if (nargs == 0)
2650     return false;
2651
2652   last_parm = TREE_VEC_ELT (args, nargs - 1);
2653
2654   return ARGUMENT_PACK_P (last_parm);
2655 }
2656
2657 /* Generate a new name for the parameter pack name NAME (an
2658    IDENTIFIER_NODE) that incorporates its */
2659 static tree
2660 make_ith_pack_parameter_name (tree name, int i)
2661 {
2662   /* Munge the name to include the parameter index.  */
2663   char numbuf[128];
2664   char* newname;
2665   
2666   sprintf(numbuf, "%i", i);
2667   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2668   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2669   return get_identifier (newname);
2670 }
2671
2672 /* Structure used to track the progress of find_parameter_packs_r.  */
2673 struct find_parameter_pack_data 
2674 {
2675   /* TREE_LIST that will contain all of the parameter packs found by
2676      the traversal.  */
2677   tree* parameter_packs;
2678
2679   /* Set of AST nodes that have been visited by the traversal.  */
2680   struct pointer_set_t *visited;
2681 };
2682
2683 /* Identifies all of the argument packs that occur in a template
2684    argument and appends them to the TREE_LIST inside DATA, which is a
2685    find_parameter_pack_data structure. This is a subroutine of
2686    make_pack_expansion and uses_parameter_packs.  */
2687 static tree
2688 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2689 {
2690   tree t = *tp;
2691   struct find_parameter_pack_data* ppd = 
2692     (struct find_parameter_pack_data*)data;
2693   bool parameter_pack_p = false;
2694
2695   /* Identify whether this is a parameter pack or not.  */
2696   switch (TREE_CODE (t))
2697     {
2698     case TEMPLATE_PARM_INDEX:
2699       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2700         parameter_pack_p = true;
2701       break;
2702
2703     case TEMPLATE_TYPE_PARM:
2704     case TEMPLATE_TEMPLATE_PARM:
2705       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2706         parameter_pack_p = true;
2707       break;
2708
2709     case PARM_DECL:
2710       if (FUNCTION_PARAMETER_PACK_P (t))
2711         {
2712           /* We don't want to walk into the type of a PARM_DECL,
2713              because we don't want to see the type parameter pack.  */
2714           *walk_subtrees = 0;
2715           parameter_pack_p = true;
2716         }
2717       break;
2718
2719     default:
2720       /* Not a parameter pack.  */
2721       break;
2722     }
2723
2724   if (parameter_pack_p)
2725     {
2726       /* Add this parameter pack to the list.  */
2727       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2728     }
2729
2730   if (TYPE_P (t))
2731     cp_walk_tree (&TYPE_CONTEXT (t), 
2732                   &find_parameter_packs_r, ppd, ppd->visited);
2733
2734   /* This switch statement will return immediately if we don't find a
2735      parameter pack.  */
2736   switch (TREE_CODE (t)) 
2737     {
2738     case TEMPLATE_PARM_INDEX:
2739       return NULL_TREE;
2740
2741     case BOUND_TEMPLATE_TEMPLATE_PARM:
2742       /* Check the template itself.  */
2743       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2744                     &find_parameter_packs_r, ppd, ppd->visited);
2745       /* Check the template arguments.  */
2746       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2747                     ppd->visited);
2748       *walk_subtrees = 0;
2749       return NULL_TREE;
2750
2751     case TEMPLATE_TYPE_PARM:
2752     case TEMPLATE_TEMPLATE_PARM:
2753       return NULL_TREE;
2754
2755     case PARM_DECL:
2756       return NULL_TREE;
2757
2758     case RECORD_TYPE:
2759       if (TYPE_PTRMEMFUNC_P (t))
2760         return NULL_TREE;
2761       /* Fall through.  */
2762
2763     case UNION_TYPE:
2764     case ENUMERAL_TYPE:
2765       if (TYPE_TEMPLATE_INFO (t))
2766         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2767                       &find_parameter_packs_r, ppd, ppd->visited);
2768
2769       *walk_subtrees = 0;
2770       return NULL_TREE;
2771
2772     case TEMPLATE_DECL:
2773       cp_walk_tree (&TREE_TYPE (t),
2774                     &find_parameter_packs_r, ppd, ppd->visited);
2775       return NULL_TREE;
2776  
2777     case TYPENAME_TYPE:
2778       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2779                    ppd, ppd->visited);
2780       *walk_subtrees = 0;
2781       return NULL_TREE;
2782       
2783     case TYPE_PACK_EXPANSION:
2784     case EXPR_PACK_EXPANSION:
2785       *walk_subtrees = 0;
2786       return NULL_TREE;
2787
2788     case INTEGER_TYPE:
2789       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2790                     ppd, ppd->visited);
2791       *walk_subtrees = 0;
2792       return NULL_TREE;
2793
2794     case IDENTIFIER_NODE:
2795       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2796                     ppd->visited);
2797       *walk_subtrees = 0;
2798       return NULL_TREE;
2799
2800     default:
2801       return NULL_TREE;
2802     }
2803
2804   return NULL_TREE;
2805 }
2806
2807 /* Determines if the expression or type T uses any parameter packs.  */
2808 bool
2809 uses_parameter_packs (tree t)
2810 {
2811   tree parameter_packs = NULL_TREE;
2812   struct find_parameter_pack_data ppd;
2813   ppd.parameter_packs = &parameter_packs;
2814   ppd.visited = pointer_set_create ();
2815   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2816   pointer_set_destroy (ppd.visited);
2817   return parameter_packs != NULL_TREE;
2818 }
2819
2820 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2821    representation a base-class initializer into a parameter pack
2822    expansion. If all goes well, the resulting node will be an
2823    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2824    respectively.  */
2825 tree 
2826 make_pack_expansion (tree arg)
2827 {
2828   tree result;
2829   tree parameter_packs = NULL_TREE;
2830   bool for_types = false;
2831   struct find_parameter_pack_data ppd;
2832
2833   if (!arg || arg == error_mark_node)
2834     return arg;
2835
2836   if (TREE_CODE (arg) == TREE_LIST)
2837     {
2838       /* The only time we will see a TREE_LIST here is for a base
2839          class initializer.  In this case, the TREE_PURPOSE will be a
2840          _TYPE node (representing the base class expansion we're
2841          initializing) and the TREE_VALUE will be a TREE_LIST
2842          containing the initialization arguments. 
2843
2844          The resulting expansion looks somewhat different from most
2845          expansions. Rather than returning just one _EXPANSION, we
2846          return a TREE_LIST whose TREE_PURPOSE is a
2847          TYPE_PACK_EXPANSION containing the bases that will be
2848          initialized.  The TREE_VALUE will be identical to the
2849          original TREE_VALUE, which is a list of arguments that will
2850          be passed to each base.  We do not introduce any new pack
2851          expansion nodes into the TREE_VALUE (although it is possible
2852          that some already exist), because the TREE_PURPOSE and
2853          TREE_VALUE all need to be expanded together with the same
2854          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2855          resulting TREE_PURPOSE will mention the parameter packs in
2856          both the bases and the arguments to the bases.  */
2857       tree purpose;
2858       tree value;
2859       tree parameter_packs = NULL_TREE;
2860
2861       /* Determine which parameter packs will be used by the base
2862          class expansion.  */
2863       ppd.visited = pointer_set_create ();
2864       ppd.parameter_packs = &parameter_packs;
2865       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2866                     &ppd, ppd.visited);
2867
2868       if (parameter_packs == NULL_TREE)
2869         {
2870           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2871           pointer_set_destroy (ppd.visited);
2872           return error_mark_node;
2873         }
2874
2875       if (TREE_VALUE (arg) != void_type_node)
2876         {
2877           /* Collect the sets of parameter packs used in each of the
2878              initialization arguments.  */
2879           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2880             {
2881               /* Determine which parameter packs will be expanded in this
2882                  argument.  */
2883               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2884                             &ppd, ppd.visited);
2885             }
2886         }
2887
2888       pointer_set_destroy (ppd.visited);
2889
2890       /* Create the pack expansion type for the base type.  */
2891       purpose = make_node (TYPE_PACK_EXPANSION);
2892       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2893       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2894
2895       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2896          they will rarely be compared to anything.  */
2897       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2898
2899       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2900     }
2901
2902   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2903     for_types = true;
2904
2905   /* Build the PACK_EXPANSION_* node.  */
2906   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2907   SET_PACK_EXPANSION_PATTERN (result, arg);
2908   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2909     {
2910       /* Propagate type and const-expression information.  */
2911       TREE_TYPE (result) = TREE_TYPE (arg);
2912       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2913     }
2914   else
2915     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2916        they will rarely be compared to anything.  */
2917     SET_TYPE_STRUCTURAL_EQUALITY (result);
2918
2919   /* Determine which parameter packs will be expanded.  */
2920   ppd.parameter_packs = &parameter_packs;
2921   ppd.visited = pointer_set_create ();
2922   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2923   pointer_set_destroy (ppd.visited);
2924
2925   /* Make sure we found some parameter packs.  */
2926   if (parameter_packs == NULL_TREE)
2927     {
2928       if (TYPE_P (arg))
2929         error ("expansion pattern %<%T%> contains no argument packs", arg);
2930       else
2931         error ("expansion pattern %<%E%> contains no argument packs", arg);
2932       return error_mark_node;
2933     }
2934   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2935
2936   return result;
2937 }
2938
2939 /* Checks T for any "bare" parameter packs, which have not yet been
2940    expanded, and issues an error if any are found. This operation can
2941    only be done on full expressions or types (e.g., an expression
2942    statement, "if" condition, etc.), because we could have expressions like:
2943
2944      foo(f(g(h(args)))...)
2945
2946    where "args" is a parameter pack. check_for_bare_parameter_packs
2947    should not be called for the subexpressions args, h(args),
2948    g(h(args)), or f(g(h(args))), because we would produce erroneous
2949    error messages. 
2950
2951    Returns TRUE and emits an error if there were bare parameter packs,
2952    returns FALSE otherwise.  */
2953 bool 
2954 check_for_bare_parameter_packs (tree t)
2955 {
2956   tree parameter_packs = NULL_TREE;
2957   struct find_parameter_pack_data ppd;
2958
2959   if (!processing_template_decl || !t || t == error_mark_node)
2960     return false;
2961
2962   if (TREE_CODE (t) == TYPE_DECL)
2963     t = TREE_TYPE (t);
2964
2965   ppd.parameter_packs = &parameter_packs;
2966   ppd.visited = pointer_set_create ();
2967   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2968   pointer_set_destroy (ppd.visited);
2969
2970   if (parameter_packs) 
2971     {
2972       error ("parameter packs not expanded with %<...%>:");
2973       while (parameter_packs)
2974         {
2975           tree pack = TREE_VALUE (parameter_packs);
2976           tree name = NULL_TREE;
2977
2978           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2979               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2980             name = TYPE_NAME (pack);
2981           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2982             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2983           else
2984             name = DECL_NAME (pack);
2985
2986           if (name)
2987             inform (input_location, "        %qD", name);
2988           else
2989             inform (input_location, "        <anonymous>");
2990
2991           parameter_packs = TREE_CHAIN (parameter_packs);
2992         }
2993
2994       return true;
2995     }
2996
2997   return false;
2998 }
2999
3000 /* Expand any parameter packs that occur in the template arguments in
3001    ARGS.  */
3002 tree
3003 expand_template_argument_pack (tree args)
3004 {
3005   tree result_args = NULL_TREE;
3006   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3007   int num_result_args = -1;
3008
3009   /* First, determine if we need to expand anything, and the number of
3010      slots we'll need.  */
3011   for (in_arg = 0; in_arg < nargs; ++in_arg)
3012     {
3013       tree arg = TREE_VEC_ELT (args, in_arg);
3014       if (ARGUMENT_PACK_P (arg))
3015         {
3016           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3017           if (num_result_args < 0)
3018             num_result_args = in_arg + num_packed;
3019           else
3020             num_result_args += num_packed;
3021         }
3022       else
3023         {
3024           if (num_result_args >= 0)
3025             num_result_args++;
3026         }
3027     }
3028
3029   /* If no expansion is necessary, we're done.  */
3030   if (num_result_args < 0)
3031     return args;
3032
3033   /* Expand arguments.  */
3034   result_args = make_tree_vec (num_result_args);
3035   for (in_arg = 0; in_arg < nargs; ++in_arg)
3036     {
3037       tree arg = TREE_VEC_ELT (args, in_arg);
3038       if (ARGUMENT_PACK_P (arg))
3039         {
3040           tree packed = ARGUMENT_PACK_ARGS (arg);
3041           int i, num_packed = TREE_VEC_LENGTH (packed);
3042           for (i = 0; i < num_packed; ++i, ++out_arg)
3043             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3044         }
3045       else
3046         {
3047           TREE_VEC_ELT (result_args, out_arg) = arg;
3048           ++out_arg;
3049         }
3050     }
3051
3052   return result_args;
3053 }
3054
3055 /* Checks if DECL shadows a template parameter.
3056
3057    [temp.local]: A template-parameter shall not be redeclared within its
3058    scope (including nested scopes).
3059
3060    Emits an error and returns TRUE if the DECL shadows a parameter,
3061    returns FALSE otherwise.  */
3062
3063 bool
3064 check_template_shadow (tree decl)
3065 {
3066   tree olddecl;
3067
3068   /* If we're not in a template, we can't possibly shadow a template
3069      parameter.  */
3070   if (!current_template_parms)
3071     return true;
3072
3073   /* Figure out what we're shadowing.  */
3074   if (TREE_CODE (decl) == OVERLOAD)
3075     decl = OVL_CURRENT (decl);
3076   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3077
3078   /* If there's no previous binding for this name, we're not shadowing
3079      anything, let alone a template parameter.  */
3080   if (!olddecl)
3081     return true;
3082
3083   /* If we're not shadowing a template parameter, we're done.  Note
3084      that OLDDECL might be an OVERLOAD (or perhaps even an
3085      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3086      node.  */
3087   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3088     return true;
3089
3090   /* We check for decl != olddecl to avoid bogus errors for using a
3091      name inside a class.  We check TPFI to avoid duplicate errors for
3092      inline member templates.  */
3093   if (decl == olddecl
3094       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3095     return true;
3096
3097   error ("declaration of %q+#D", decl);
3098   error (" shadows template parm %q+#D", olddecl);
3099   return false;
3100 }
3101
3102 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3103    ORIG_LEVEL, DECL, and TYPE.  */
3104
3105 static tree
3106 build_template_parm_index (int index,
3107                            int level,
3108                            int orig_level,
3109                            tree decl,
3110                            tree type)
3111 {
3112   tree t = make_node (TEMPLATE_PARM_INDEX);
3113   TEMPLATE_PARM_IDX (t) = index;
3114   TEMPLATE_PARM_LEVEL (t) = level;
3115   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3116   TEMPLATE_PARM_DECL (t) = decl;
3117   TREE_TYPE (t) = type;
3118   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3119   TREE_READONLY (t) = TREE_READONLY (decl);
3120
3121   return t;
3122 }
3123
3124 /* Find the canonical type parameter for the given template type
3125    parameter.  Returns the canonical type parameter, which may be TYPE
3126    if no such parameter existed.  */
3127 static tree
3128 canonical_type_parameter (tree type)
3129 {
3130   tree list;
3131   int idx = TEMPLATE_TYPE_IDX (type);
3132   if (!canonical_template_parms)
3133     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3134
3135   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3136     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3137
3138   list = VEC_index (tree, canonical_template_parms, idx);
3139   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3140     list = TREE_CHAIN (list);
3141
3142   if (list)
3143     return TREE_VALUE (list);
3144   else
3145     {
3146       VEC_replace(tree, canonical_template_parms, idx,
3147                   tree_cons (NULL_TREE, type, 
3148                              VEC_index (tree, canonical_template_parms, idx)));
3149       return type;
3150     }
3151 }
3152
3153 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3154    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3155    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3156    new one is created.  */
3157
3158 static tree
3159 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3160                             tsubst_flags_t complain)
3161 {
3162   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3163       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3164           != TEMPLATE_PARM_LEVEL (index) - levels))
3165     {
3166       tree orig_decl = TEMPLATE_PARM_DECL (index);
3167       tree decl, t;
3168
3169       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3170                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3171       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3172       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3173       DECL_ARTIFICIAL (decl) = 1;
3174       SET_DECL_TEMPLATE_PARM_P (decl);
3175
3176       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3177                                      TEMPLATE_PARM_LEVEL (index) - levels,
3178                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3179                                      decl, type);
3180       TEMPLATE_PARM_DESCENDANTS (index) = t;
3181       TEMPLATE_PARM_PARAMETER_PACK (t) 
3182         = TEMPLATE_PARM_PARAMETER_PACK (index);
3183
3184         /* Template template parameters need this.  */
3185       if (TREE_CODE (decl) == TEMPLATE_DECL)
3186         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3187           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3188            args, complain);
3189     }
3190
3191   return TEMPLATE_PARM_DESCENDANTS (index);
3192 }
3193
3194 /* Process information from new template parameter PARM and append it to the
3195    LIST being built.  This new parameter is a non-type parameter iff
3196    IS_NON_TYPE is true. This new parameter is a parameter
3197    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3198    PARM_LOC.  */
3199
3200 tree
3201 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3202                        bool is_parameter_pack)
3203 {
3204   tree decl = 0;
3205   tree defval;
3206   tree err_parm_list;
3207   int idx = 0;
3208
3209   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3210   defval = TREE_PURPOSE (parm);
3211
3212   if (list)
3213     {
3214       tree p = tree_last (list);
3215
3216       if (p && TREE_VALUE (p) != error_mark_node)
3217         {
3218           p = TREE_VALUE (p);
3219           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3220             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3221           else
3222             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3223         }
3224
3225       ++idx;
3226     }
3227   else
3228     idx = 0;
3229
3230   if (is_non_type)
3231     {
3232       parm = TREE_VALUE (parm);
3233
3234       SET_DECL_TEMPLATE_PARM_P (parm);
3235
3236       if (TREE_TYPE (parm) == error_mark_node)
3237         {
3238           err_parm_list = build_tree_list (defval, parm);
3239           TREE_VALUE (err_parm_list) = error_mark_node;
3240            return chainon (list, err_parm_list);
3241         }
3242       else
3243       {
3244         /* [temp.param]
3245
3246            The top-level cv-qualifiers on the template-parameter are
3247            ignored when determining its type.  */
3248         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3249         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3250           {
3251             err_parm_list = build_tree_list (defval, parm);
3252             TREE_VALUE (err_parm_list) = error_mark_node;
3253              return chainon (list, err_parm_list);
3254           }
3255
3256         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3257           {
3258             /* This template parameter is not a parameter pack, but it
3259                should be. Complain about "bare" parameter packs.  */
3260             check_for_bare_parameter_packs (TREE_TYPE (parm));
3261             
3262             /* Recover by calling this a parameter pack.  */
3263             is_parameter_pack = true;
3264           }
3265       }
3266
3267       /* A template parameter is not modifiable.  */
3268       TREE_CONSTANT (parm) = 1;
3269       TREE_READONLY (parm) = 1;
3270       decl = build_decl (parm_loc,
3271                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3272       TREE_CONSTANT (decl) = 1;
3273       TREE_READONLY (decl) = 1;
3274       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3275         = build_template_parm_index (idx, processing_template_decl,
3276                                      processing_template_decl,
3277                                      decl, TREE_TYPE (parm));
3278
3279       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3280         = is_parameter_pack;
3281     }
3282   else
3283     {
3284       tree t;
3285       parm = TREE_VALUE (TREE_VALUE (parm));
3286
3287       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3288         {
3289           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3290           /* This is for distinguishing between real templates and template
3291              template parameters */
3292           TREE_TYPE (parm) = t;
3293           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3294           decl = parm;
3295         }
3296       else
3297         {
3298           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3299           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3300           decl = build_decl (parm_loc,
3301                              TYPE_DECL, parm, t);
3302         }
3303
3304       TYPE_NAME (t) = decl;
3305       TYPE_STUB_DECL (t) = decl;
3306       parm = decl;
3307       TEMPLATE_TYPE_PARM_INDEX (t)
3308         = build_template_parm_index (idx, processing_template_decl,
3309                                      processing_template_decl,
3310                                      decl, TREE_TYPE (parm));
3311       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3312       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3313     }
3314   DECL_ARTIFICIAL (decl) = 1;
3315   SET_DECL_TEMPLATE_PARM_P (decl);
3316   pushdecl (decl);
3317   parm = build_tree_list (defval, parm);
3318   return chainon (list, parm);
3319 }
3320
3321 /* The end of a template parameter list has been reached.  Process the
3322    tree list into a parameter vector, converting each parameter into a more
3323    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3324    as PARM_DECLs.  */
3325
3326 tree
3327 end_template_parm_list (tree parms)
3328 {
3329   int nparms;
3330   tree parm, next;
3331   tree saved_parmlist = make_tree_vec (list_length (parms));
3332
3333   current_template_parms
3334     = tree_cons (size_int (processing_template_decl),
3335                  saved_parmlist, current_template_parms);
3336
3337   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3338     {
3339       next = TREE_CHAIN (parm);
3340       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3341       TREE_CHAIN (parm) = NULL_TREE;
3342     }
3343
3344   --processing_template_parmlist;
3345
3346   return saved_parmlist;
3347 }
3348
3349 /* end_template_decl is called after a template declaration is seen.  */
3350
3351 void
3352 end_template_decl (void)
3353 {
3354   reset_specialization ();
3355
3356   if (! processing_template_decl)
3357     return;
3358
3359   /* This matches the pushlevel in begin_template_parm_list.  */
3360   finish_scope ();
3361
3362   --processing_template_decl;
3363   current_template_parms = TREE_CHAIN (current_template_parms);
3364 }
3365
3366 /* Within the declaration of a template, return all levels of template
3367    parameters that apply.  The template parameters are represented as
3368    a TREE_VEC, in the form documented in cp-tree.h for template
3369    arguments.  */
3370
3371 static tree
3372 current_template_args (void)
3373 {
3374   tree header;
3375   tree args = NULL_TREE;
3376   int length = TMPL_PARMS_DEPTH (current_template_parms);
3377   int l = length;
3378
3379   /* If there is only one level of template parameters, we do not
3380      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3381      TREE_VEC containing the arguments.  */
3382   if (length > 1)
3383     args = make_tree_vec (length);
3384
3385   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3386     {
3387       tree a = copy_node (TREE_VALUE (header));
3388       int i;
3389
3390       TREE_TYPE (a) = NULL_TREE;
3391       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3392         {
3393           tree t = TREE_VEC_ELT (a, i);
3394
3395           /* T will be a list if we are called from within a
3396              begin/end_template_parm_list pair, but a vector directly
3397              if within a begin/end_member_template_processing pair.  */
3398           if (TREE_CODE (t) == TREE_LIST)
3399             {
3400               t = TREE_VALUE (t);
3401
3402               if (!error_operand_p (t))
3403                 {
3404                   if (TREE_CODE (t) == TYPE_DECL
3405                       || TREE_CODE (t) == TEMPLATE_DECL)
3406                     {
3407                       t = TREE_TYPE (t);
3408                       
3409                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3410                         {
3411                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3412                              with a single element, which expands T.  */
3413                           tree vec = make_tree_vec (1);
3414                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3415                           
3416                           t = make_node (TYPE_ARGUMENT_PACK);
3417                           SET_ARGUMENT_PACK_ARGS (t, vec);
3418                         }
3419                     }
3420                   else
3421                     {
3422                       t = DECL_INITIAL (t);
3423                       
3424                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3425                         {
3426                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3427                              with a single element, which expands T.  */
3428                           tree vec = make_tree_vec (1);
3429                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3430                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3431                           
3432                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3433                           SET_ARGUMENT_PACK_ARGS (t, vec);
3434                           TREE_TYPE (t) = type;
3435                         }
3436                     }
3437                   TREE_VEC_ELT (a, i) = t;
3438                 }
3439             }
3440         }
3441
3442       if (length > 1)
3443         TREE_VEC_ELT (args, --l) = a;
3444       else
3445         args = a;
3446     }
3447
3448   return args;
3449 }
3450
3451 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3452    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3453    a member template.  Used by push_template_decl below.  */
3454
3455 static tree
3456 build_template_decl (tree decl, tree parms, bool member_template_p)
3457 {
3458   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3459   DECL_TEMPLATE_PARMS (tmpl) = parms;
3460   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3461   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3462
3463   return tmpl;
3464 }
3465
3466 struct template_parm_data
3467 {
3468   /* The level of the template parameters we are currently
3469      processing.  */
3470   int level;
3471
3472   /* The index of the specialization argument we are currently
3473      processing.  */
3474   int current_arg;
3475
3476   /* An array whose size is the number of template parameters.  The
3477      elements are nonzero if the parameter has been used in any one
3478      of the arguments processed so far.  */
3479   int* parms;
3480
3481   /* An array whose size is the number of template arguments.  The
3482      elements are nonzero if the argument makes use of template
3483      parameters of this level.  */
3484   int* arg_uses_template_parms;
3485 };
3486
3487 /* Subroutine of push_template_decl used to see if each template
3488    parameter in a partial specialization is used in the explicit
3489    argument list.  If T is of the LEVEL given in DATA (which is
3490    treated as a template_parm_data*), then DATA->PARMS is marked
3491    appropriately.  */
3492
3493 static int
3494 mark_template_parm (tree t, void* data)
3495 {
3496   int level;
3497   int idx;
3498   struct template_parm_data* tpd = (struct template_parm_data*) data;
3499
3500   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3501     {
3502       level = TEMPLATE_PARM_LEVEL (t);
3503       idx = TEMPLATE_PARM_IDX (t);
3504     }
3505   else
3506     {
3507       level = TEMPLATE_TYPE_LEVEL (t);
3508       idx = TEMPLATE_TYPE_IDX (t);
3509     }
3510
3511   if (level == tpd->level)
3512     {
3513       tpd->parms[idx] = 1;
3514       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3515     }
3516
3517   /* Return zero so that for_each_template_parm will continue the
3518      traversal of the tree; we want to mark *every* template parm.  */
3519   return 0;
3520 }
3521
3522 /* Process the partial specialization DECL.  */
3523
3524 static tree
3525 process_partial_specialization (tree decl)
3526 {
3527   tree type = TREE_TYPE (decl);
3528   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3529   tree specargs = CLASSTYPE_TI_ARGS (type);
3530   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3531   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3532   tree inner_parms;
3533   int nargs = TREE_VEC_LENGTH (inner_args);
3534   int ntparms;
3535   int  i;
3536   int did_error_intro = 0;
3537   struct template_parm_data tpd;
3538   struct template_parm_data tpd2;
3539
3540   gcc_assert (current_template_parms);
3541
3542   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3543   ntparms = TREE_VEC_LENGTH (inner_parms);
3544
3545   /* We check that each of the template parameters given in the
3546      partial specialization is used in the argument list to the
3547      specialization.  For example:
3548
3549        template <class T> struct S;
3550        template <class T> struct S<T*>;
3551
3552      The second declaration is OK because `T*' uses the template
3553      parameter T, whereas
3554
3555        template <class T> struct S<int>;
3556
3557      is no good.  Even trickier is:
3558
3559        template <class T>
3560        struct S1
3561        {
3562           template <class U>
3563           struct S2;
3564           template <class U>
3565           struct S2<T>;
3566        };
3567
3568      The S2<T> declaration is actually invalid; it is a
3569      full-specialization.  Of course,
3570
3571           template <class U>
3572           struct S2<T (*)(U)>;
3573
3574      or some such would have been OK.  */
3575   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3576   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3577   memset (tpd.parms, 0, sizeof (int) * ntparms);
3578
3579   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3580   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3581   for (i = 0; i < nargs; ++i)
3582     {
3583       tpd.current_arg = i;
3584       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3585                               &mark_template_parm,
3586                               &tpd,
3587                               NULL,
3588                               /*include_nondeduced_p=*/false);
3589     }
3590   for (i = 0; i < ntparms; ++i)
3591     if (tpd.parms[i] == 0)
3592       {
3593         /* One of the template parms was not used in the
3594            specialization.  */
3595         if (!did_error_intro)
3596           {
3597             error ("template parameters not used in partial specialization:");
3598             did_error_intro = 1;
3599           }
3600
3601         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3602       }
3603
3604   /* [temp.class.spec]
3605
3606      The argument list of the specialization shall not be identical to
3607      the implicit argument list of the primary template.  */
3608   if (comp_template_args
3609       (inner_args,
3610        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3611                                                    (maintmpl)))))
3612     error ("partial specialization %qT does not specialize any template arguments", type);
3613
3614   /* [temp.class.spec]
3615
3616      A partially specialized non-type argument expression shall not
3617      involve template parameters of the partial specialization except
3618      when the argument expression is a simple identifier.
3619
3620      The type of a template parameter corresponding to a specialized
3621      non-type argument shall not be dependent on a parameter of the
3622      specialization. 
3623
3624      Also, we verify that pack expansions only occur at the
3625      end of the argument list.  */
3626   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3627   tpd2.parms = 0;
3628   for (i = 0; i < nargs; ++i)
3629     {
3630       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3631       tree arg = TREE_VEC_ELT (inner_args, i);
3632       tree packed_args = NULL_TREE;
3633       int j, len = 1;
3634
3635       if (ARGUMENT_PACK_P (arg))
3636         {
3637           /* Extract the arguments from the argument pack. We'll be
3638              iterating over these in the following loop.  */
3639           packed_args = ARGUMENT_PACK_ARGS (arg);
3640           len = TREE_VEC_LENGTH (packed_args);
3641         }
3642
3643       for (j = 0; j < len; j++)
3644         {
3645           if (packed_args)
3646             /* Get the Jth argument in the parameter pack.  */
3647             arg = TREE_VEC_ELT (packed_args, j);
3648
3649           if (PACK_EXPANSION_P (arg))
3650             {
3651               /* Pack expansions must come at the end of the
3652                  argument list.  */
3653               if ((packed_args && j < len - 1)
3654                   || (!packed_args && i < nargs - 1))
3655                 {
3656                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3657                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3658                   else
3659                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3660
3661                   if (packed_args)
3662                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3663                 }
3664             }
3665
3666           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3667             /* We only care about the pattern.  */
3668             arg = PACK_EXPANSION_PATTERN (arg);
3669
3670           if (/* These first two lines are the `non-type' bit.  */
3671               !TYPE_P (arg)
3672               && TREE_CODE (arg) != TEMPLATE_DECL
3673               /* This next line is the `argument expression is not just a
3674                  simple identifier' condition and also the `specialized
3675                  non-type argument' bit.  */
3676               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3677             {
3678               if ((!packed_args && tpd.arg_uses_template_parms[i])
3679                   || (packed_args && uses_template_parms (arg)))
3680                 error ("template argument %qE involves template parameter(s)",
3681                        arg);
3682               else 
3683                 {
3684                   /* Look at the corresponding template parameter,
3685                      marking which template parameters its type depends
3686                      upon.  */
3687                   tree type = TREE_TYPE (parm);
3688
3689                   if (!tpd2.parms)
3690                     {
3691                       /* We haven't yet initialized TPD2.  Do so now.  */
3692                       tpd2.arg_uses_template_parms 
3693                         = (int *) alloca (sizeof (int) * nargs);
3694                       /* The number of parameters here is the number in the
3695                          main template, which, as checked in the assertion
3696                          above, is NARGS.  */
3697                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3698                       tpd2.level = 
3699                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3700                     }
3701
3702                   /* Mark the template parameters.  But this time, we're
3703                      looking for the template parameters of the main
3704                      template, not in the specialization.  */
3705                   tpd2.current_arg = i;
3706                   tpd2.arg_uses_template_parms[i] = 0;
3707                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3708                   for_each_template_parm (type,
3709                                           &mark_template_parm,
3710                                           &tpd2,
3711                                           NULL,
3712                                           /*include_nondeduced_p=*/false);
3713
3714                   if (tpd2.arg_uses_template_parms [i])
3715                     {
3716                       /* The type depended on some template parameters.
3717                          If they are fully specialized in the
3718                          specialization, that's OK.  */
3719                       int j;
3720                       for (j = 0; j < nargs; ++j)
3721                         if (tpd2.parms[j] != 0
3722                             && tpd.arg_uses_template_parms [j])
3723                           {
3724                             error ("type %qT of template argument %qE depends "
3725                                    "on template parameter(s)", 
3726                                    type,
3727                                    arg);
3728                             break;
3729                           }
3730                     }
3731                 }
3732             }
3733         }
3734     }
3735
3736   /* We should only get here once.  */
3737   gcc_assert (!COMPLETE_TYPE_P (type));
3738
3739   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3740     = tree_cons (specargs, inner_parms,
3741                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3742   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3743   return decl;
3744 }
3745
3746 /* Check that a template declaration's use of default arguments and
3747    parameter packs is not invalid.  Here, PARMS are the template
3748    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3749    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3750    specialization.
3751    
3752
3753    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3754    declaration (but not a definition); 1 indicates a declaration, 2
3755    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3756    emitted for extraneous default arguments.
3757
3758    Returns TRUE if there were no errors found, FALSE otherwise. */
3759
3760 bool
3761 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3762                          int is_partial, int is_friend_decl)
3763 {
3764   const char *msg;
3765   int last_level_to_check;
3766   tree parm_level;
3767   bool no_errors = true;
3768
3769   /* [temp.param]
3770
3771      A default template-argument shall not be specified in a
3772      function template declaration or a function template definition, nor
3773      in the template-parameter-list of the definition of a member of a
3774      class template.  */
3775
3776   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3777     /* You can't have a function template declaration in a local
3778        scope, nor you can you define a member of a class template in a
3779        local scope.  */
3780     return true;
3781
3782   if (current_class_type
3783       && !TYPE_BEING_DEFINED (current_class_type)
3784       && DECL_LANG_SPECIFIC (decl)
3785       && DECL_DECLARES_FUNCTION_P (decl)
3786       /* If this is either a friend defined in the scope of the class
3787          or a member function.  */
3788       && (DECL_FUNCTION_MEMBER_P (decl)
3789           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3790           : DECL_FRIEND_CONTEXT (decl)
3791           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3792           : false)
3793       /* And, if it was a member function, it really was defined in
3794          the scope of the class.  */
3795       && (!DECL_FUNCTION_MEMBER_P (decl)
3796           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3797     /* We already checked these parameters when the template was
3798        declared, so there's no need to do it again now.  This function
3799        was defined in class scope, but we're processing it's body now
3800        that the class is complete.  */
3801     return true;
3802
3803   /* Core issue 226 (C++0x only): the following only applies to class
3804      templates.  */
3805   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3806     {
3807       /* [temp.param]
3808
3809          If a template-parameter has a default template-argument, all
3810          subsequent template-parameters shall have a default
3811          template-argument supplied.  */
3812       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3813         {
3814           tree inner_parms = TREE_VALUE (parm_level);
3815           int ntparms = TREE_VEC_LENGTH (inner_parms);
3816           int seen_def_arg_p = 0;
3817           int i;
3818
3819           for (i = 0; i < ntparms; ++i)
3820             {
3821               tree parm = TREE_VEC_ELT (inner_parms, i);
3822
3823               if (parm == error_mark_node)
3824                 continue;
3825
3826               if (TREE_PURPOSE (parm))
3827                 seen_def_arg_p = 1;
3828               else if (seen_def_arg_p
3829                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3830                 {
3831                   error ("no default argument for %qD", TREE_VALUE (parm));
3832                   /* For better subsequent error-recovery, we indicate that
3833                      there should have been a default argument.  */
3834                   TREE_PURPOSE (parm) = error_mark_node;
3835                   no_errors = false;
3836                 }
3837               else if (is_primary
3838                        && !is_partial
3839                        && !is_friend_decl
3840                        /* Don't complain about an enclosing partial
3841                           specialization.  */
3842                        && parm_level == parms
3843                        && TREE_CODE (decl) == TYPE_DECL
3844                        && i < ntparms - 1
3845                        && template_parameter_pack_p (TREE_VALUE (parm)))
3846                 {
3847                   /* A primary class template can only have one
3848                      parameter pack, at the end of the template
3849                      parameter list.  */
3850
3851                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3852                     error ("parameter pack %qE must be at the end of the"
3853                            " template parameter list", TREE_VALUE (parm));
3854                   else
3855                     error ("parameter pack %qT must be at the end of the"
3856                            " template parameter list", 
3857                            TREE_TYPE (TREE_VALUE (parm)));
3858
3859                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3860                     = error_mark_node;
3861                   no_errors = false;
3862                 }
3863             }
3864         }
3865     }
3866
3867   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3868       || is_partial 
3869       || !is_primary
3870       || is_friend_decl)
3871     /* For an ordinary class template, default template arguments are
3872        allowed at the innermost level, e.g.:
3873          template <class T = int>
3874          struct S {};
3875        but, in a partial specialization, they're not allowed even
3876        there, as we have in [temp.class.spec]:
3877
3878          The template parameter list of a specialization shall not
3879          contain default template argument values.
3880
3881        So, for a partial specialization, or for a function template
3882        (in C++98/C++03), we look at all of them.  */
3883     ;
3884   else
3885     /* But, for a primary class template that is not a partial
3886        specialization we look at all template parameters except the
3887        innermost ones.  */
3888     parms = TREE_CHAIN (parms);
3889
3890   /* Figure out what error message to issue.  */
3891   if (is_friend_decl == 2)
3892     msg = "default template arguments may not be used in function template friend re-declaration";
3893   else if (is_friend_decl)
3894     msg = "default template arguments may not be used in function template friend declarations";
3895   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3896     msg = "default template arguments may not be used in function templates";
3897   else if (is_partial)
3898     msg = "default template arguments may not be used in partial specializations";
3899   else
3900     msg = "default argument for template parameter for class enclosing %qD";
3901
3902   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3903     /* If we're inside a class definition, there's no need to
3904        examine the parameters to the class itself.  On the one
3905        hand, they will be checked when the class is defined, and,
3906        on the other, default arguments are valid in things like:
3907          template <class T = double>
3908          struct S { template <class U> void f(U); };
3909        Here the default argument for `S' has no bearing on the
3910        declaration of `f'.  */
3911     last_level_to_check = template_class_depth (current_class_type) + 1;
3912   else
3913     /* Check everything.  */
3914     last_level_to_check = 0;
3915
3916   for (parm_level = parms;
3917        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3918        parm_level = TREE_CHAIN (parm_level))
3919     {
3920       tree inner_parms = TREE_VALUE (parm_level);
3921       int i;
3922       int ntparms;
3923
3924       ntparms = TREE_VEC_LENGTH (inner_parms);
3925       for (i = 0; i < ntparms; ++i)
3926         {
3927           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3928             continue;
3929
3930           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3931             {
3932               if (msg)
3933                 {
3934                   no_errors = false;
3935                   if (is_friend_decl == 2)
3936                     return no_errors;
3937
3938                   error (msg, decl);
3939                   msg = 0;
3940                 }
3941
3942               /* Clear out the default argument so that we are not
3943                  confused later.  */
3944               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3945             }
3946         }
3947
3948       /* At this point, if we're still interested in issuing messages,
3949          they must apply to classes surrounding the object declared.  */
3950       if (msg)
3951         msg = "default argument for template parameter for class enclosing %qD";
3952     }
3953
3954   return no_errors;
3955 }
3956
3957 /* Worker for push_template_decl_real, called via
3958    for_each_template_parm.  DATA is really an int, indicating the
3959    level of the parameters we are interested in.  If T is a template
3960    parameter of that level, return nonzero.  */
3961
3962 static int
3963 template_parm_this_level_p (tree t, void* data)
3964 {
3965   int this_level = *(int *)data;
3966   int level;
3967
3968   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3969     level = TEMPLATE_PARM_LEVEL (t);
3970   else
3971     level = TEMPLATE_TYPE_LEVEL (t);
3972   return level == this_level;
3973 }
3974
3975 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3976    parameters given by current_template_args, or reuses a
3977    previously existing one, if appropriate.  Returns the DECL, or an
3978    equivalent one, if it is replaced via a call to duplicate_decls.
3979
3980    If IS_FRIEND is true, DECL is a friend declaration.  */
3981
3982 tree
3983 push_template_decl_real (tree decl, bool is_friend)
3984 {
3985   tree tmpl;
3986   tree args;
3987   tree info;
3988   tree ctx;
3989   int primary;
3990   int is_partial;
3991   int new_template_p = 0;
3992   /* True if the template is a member template, in the sense of
3993      [temp.mem].  */
3994   bool member_template_p = false;
3995
3996   if (decl == error_mark_node || !current_template_parms)
3997     return error_mark_node;
3998
3999   /* See if this is a partial specialization.  */
4000   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4001                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4002                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4003
4004   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4005     is_friend = true;
4006
4007   if (is_friend)
4008     /* For a friend, we want the context of the friend function, not
4009        the type of which it is a friend.  */
4010     ctx = DECL_CONTEXT (decl);
4011   else if (CP_DECL_CONTEXT (decl)
4012            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4013     /* In the case of a virtual function, we want the class in which
4014        it is defined.  */
4015     ctx = CP_DECL_CONTEXT (decl);
4016   else
4017     /* Otherwise, if we're currently defining some class, the DECL
4018        is assumed to be a member of the class.  */
4019     ctx = current_scope ();
4020
4021   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4022     ctx = NULL_TREE;
4023
4024   if (!DECL_CONTEXT (decl))
4025     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4026
4027   /* See if this is a primary template.  */
4028   if (is_friend && ctx)
4029     /* A friend template that specifies a class context, i.e.
4030          template <typename T> friend void A<T>::f();
4031        is not primary.  */
4032     primary = 0;
4033   else
4034     primary = template_parm_scope_p ();
4035
4036   if (primary)
4037     {
4038       if (DECL_CLASS_SCOPE_P (decl))
4039         member_template_p = true;
4040       if (TREE_CODE (decl) == TYPE_DECL
4041           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4042         {
4043           error ("template class without a name");
4044           return error_mark_node;
4045         }
4046       else if (TREE_CODE (decl) == FUNCTION_DECL)
4047         {
4048           if (DECL_DESTRUCTOR_P (decl))
4049             {
4050               /* [temp.mem]
4051
4052                  A destructor shall not be a member template.  */
4053               error ("destructor %qD declared as member template", decl);
4054               return error_mark_node;
4055             }
4056           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4057               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4058                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4059                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4060                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4061                       == void_list_node)))
4062             {
4063               /* [basic.stc.dynamic.allocation]
4064
4065                  An allocation function can be a function
4066                  template. ... Template allocation functions shall
4067                  have two or more parameters.  */
4068               error ("invalid template declaration of %qD", decl);
4069               return error_mark_node;
4070             }
4071         }
4072       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4073                && CLASS_TYPE_P (TREE_TYPE (decl)))
4074         /* OK */;
4075       else
4076         {
4077           error ("template declaration of %q#D", decl);
4078           return error_mark_node;
4079         }
4080     }
4081
4082   /* Check to see that the rules regarding the use of default
4083      arguments are not being violated.  */
4084   check_default_tmpl_args (decl, current_template_parms,
4085                            primary, is_partial, /*is_friend_decl=*/0);
4086
4087   /* Ensure that there are no parameter packs in the type of this
4088      declaration that have not been expanded.  */
4089   if (TREE_CODE (decl) == FUNCTION_DECL)
4090     {
4091       /* Check each of the arguments individually to see if there are
4092          any bare parameter packs.  */
4093       tree type = TREE_TYPE (decl);
4094       tree arg = DECL_ARGUMENTS (decl);
4095       tree argtype = TYPE_ARG_TYPES (type);
4096
4097       while (arg && argtype)
4098         {
4099           if (!FUNCTION_PARAMETER_PACK_P (arg)
4100               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4101             {
4102             /* This is a PARM_DECL that contains unexpanded parameter
4103                packs. We have already complained about this in the
4104                check_for_bare_parameter_packs call, so just replace
4105                these types with ERROR_MARK_NODE.  */
4106               TREE_TYPE (arg) = error_mark_node;
4107               TREE_VALUE (argtype) = error_mark_node;
4108             }
4109
4110           arg = TREE_CHAIN (arg);
4111           argtype = TREE_CHAIN (argtype);
4112         }
4113
4114       /* Check for bare parameter packs in the return type and the
4115          exception specifiers.  */
4116       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4117         /* Errors were already issued, set return type to int
4118            as the frontend doesn't expect error_mark_node as
4119            the return type.  */
4120         TREE_TYPE (type) = integer_type_node;
4121       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4122         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4123     }
4124   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4125     {
4126       TREE_TYPE (decl) = error_mark_node;
4127       return error_mark_node;
4128     }
4129
4130   if (is_partial)
4131     return process_partial_specialization (decl);
4132
4133   args = current_template_args ();
4134
4135   if (!ctx
4136       || TREE_CODE (ctx) == FUNCTION_DECL
4137       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4138       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4139     {
4140       if (DECL_LANG_SPECIFIC (decl)
4141           && DECL_TEMPLATE_INFO (decl)
4142           && DECL_TI_TEMPLATE (decl))
4143         tmpl = DECL_TI_TEMPLATE (decl);
4144       /* If DECL is a TYPE_DECL for a class-template, then there won't
4145          be DECL_LANG_SPECIFIC.  The information equivalent to
4146          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4147       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4148                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4149                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4150         {
4151           /* Since a template declaration already existed for this
4152              class-type, we must be redeclaring it here.  Make sure
4153              that the redeclaration is valid.  */
4154           redeclare_class_template (TREE_TYPE (decl),
4155                                     current_template_parms);
4156           /* We don't need to create a new TEMPLATE_DECL; just use the
4157              one we already had.  */
4158           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4159         }
4160       else
4161         {
4162           tmpl = build_template_decl (decl, current_template_parms,
4163                                       member_template_p);
4164           new_template_p = 1;
4165
4166           if (DECL_LANG_SPECIFIC (decl)
4167               && DECL_TEMPLATE_SPECIALIZATION (decl))
4168             {
4169               /* A specialization of a member template of a template
4170                  class.  */
4171               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4172               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4173               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4174             }
4175         }
4176     }
4177   else
4178     {
4179       tree a, t, current, parms;
4180       int i;
4181       tree tinfo = get_template_info (decl);
4182
4183       if (!tinfo)
4184         {
4185           error ("template definition of non-template %q#D", decl);
4186           return error_mark_node;
4187         }
4188
4189       tmpl = TI_TEMPLATE (tinfo);
4190
4191       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4192           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4193           && DECL_TEMPLATE_SPECIALIZATION (decl)
4194           && DECL_MEMBER_TEMPLATE_P (tmpl))
4195         {
4196           tree new_tmpl;
4197
4198           /* The declaration is a specialization of a member
4199              template, declared outside the class.  Therefore, the
4200              innermost template arguments will be NULL, so we
4201              replace them with the arguments determined by the
4202              earlier call to check_explicit_specialization.  */
4203           args = DECL_TI_ARGS (decl);
4204
4205           new_tmpl
4206             = build_template_decl (decl, current_template_parms,
4207                                    member_template_p);
4208           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4209           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4210           DECL_TI_TEMPLATE (decl) = new_tmpl;
4211           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4212           DECL_TEMPLATE_INFO (new_tmpl)
4213             = tree_cons (tmpl, args, NULL_TREE);
4214
4215           register_specialization (new_tmpl,
4216                                    most_general_template (tmpl),
4217                                    args,
4218                                    is_friend, 0);
4219           return decl;
4220         }
4221
4222       /* Make sure the template headers we got make sense.  */
4223
4224       parms = DECL_TEMPLATE_PARMS (tmpl);
4225       i = TMPL_PARMS_DEPTH (parms);
4226       if (TMPL_ARGS_DEPTH (args) != i)
4227         {
4228           error ("expected %d levels of template parms for %q#D, got %d",
4229                  i, decl, TMPL_ARGS_DEPTH (args));
4230         }
4231       else
4232         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4233           {
4234             a = TMPL_ARGS_LEVEL (args, i);
4235             t = INNERMOST_TEMPLATE_PARMS (parms);
4236
4237             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4238               {
4239                 if (current == decl)
4240                   error ("got %d template parameters for %q#D",
4241                          TREE_VEC_LENGTH (a), decl);
4242                 else
4243                   error ("got %d template parameters for %q#T",
4244                          TREE_VEC_LENGTH (a), current);
4245                 error ("  but %d required", TREE_VEC_LENGTH (t));
4246                 return error_mark_node;
4247               }
4248
4249             if (current == decl)
4250               current = ctx;
4251             else
4252               current = (TYPE_P (current)
4253                          ? TYPE_CONTEXT (current)
4254                          : DECL_CONTEXT (current));
4255           }
4256
4257       /* Check that the parms are used in the appropriate qualifying scopes
4258          in the declarator.  */
4259       if (!comp_template_args
4260           (TI_ARGS (tinfo),
4261            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4262         {
4263           error ("\
4264 template arguments to %qD do not match original template %qD",
4265                  decl, DECL_TEMPLATE_RESULT (tmpl));
4266           if (!uses_template_parms (TI_ARGS (tinfo)))
4267             inform (input_location, "use template<> for an explicit specialization");
4268           /* Avoid crash in import_export_decl.  */
4269           DECL_INTERFACE_KNOWN (decl) = 1;
4270           return error_mark_node;
4271         }
4272     }
4273
4274   DECL_TEMPLATE_RESULT (tmpl) = decl;
4275   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4276
4277   /* Push template declarations for global functions and types.  Note
4278      that we do not try to push a global template friend declared in a
4279      template class; such a thing may well depend on the template
4280      parameters of the class.  */
4281   if (new_template_p && !ctx
4282       && !(is_friend && template_class_depth (current_class_type) > 0))
4283     {
4284       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4285       if (tmpl == error_mark_node)
4286         return error_mark_node;
4287
4288       /* Hide template friend classes that haven't been declared yet.  */
4289       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4290         {
4291           DECL_ANTICIPATED (tmpl) = 1;
4292           DECL_FRIEND_P (tmpl) = 1;
4293         }
4294     }
4295
4296   if (primary)
4297     {
4298       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4299       int i;
4300
4301       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4302       if (DECL_CONV_FN_P (tmpl))
4303         {
4304           int depth = TMPL_PARMS_DEPTH (parms);
4305
4306           /* It is a conversion operator. See if the type converted to
4307              depends on innermost template operands.  */
4308
4309           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4310                                          depth))
4311             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4312         }
4313
4314       /* Give template template parms a DECL_CONTEXT of the template
4315          for which they are a parameter.  */
4316       parms = INNERMOST_TEMPLATE_PARMS (parms);
4317       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4318         {
4319           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4320           if (TREE_CODE (parm) == TEMPLATE_DECL)
4321             DECL_CONTEXT (parm) = tmpl;
4322         }
4323     }
4324
4325   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4326      back to its most general template.  If TMPL is a specialization,
4327      ARGS may only have the innermost set of arguments.  Add the missing
4328      argument levels if necessary.  */
4329   if (DECL_TEMPLATE_INFO (tmpl))
4330     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4331
4332   info = tree_cons (tmpl, args, NULL_TREE);
4333
4334   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4335     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4336   else if (DECL_LANG_SPECIFIC (decl))
4337     DECL_TEMPLATE_INFO (decl) = info;
4338
4339   return DECL_TEMPLATE_RESULT (tmpl);
4340 }
4341
4342 tree
4343 push_template_decl (tree decl)
4344 {
4345   return push_template_decl_real (decl, false);
4346 }
4347
4348 /* Called when a class template TYPE is redeclared with the indicated
4349    template PARMS, e.g.:
4350
4351      template <class T> struct S;
4352      template <class T> struct S {};  */
4353
4354 bool
4355 redeclare_class_template (tree type, tree parms)
4356 {
4357   tree tmpl;
4358   tree tmpl_parms;
4359   int i;
4360
4361   if (!TYPE_TEMPLATE_INFO (type))
4362     {
4363       error ("%qT is not a template type", type);
4364       return false;
4365     }
4366
4367   tmpl = TYPE_TI_TEMPLATE (type);
4368   if (!PRIMARY_TEMPLATE_P (tmpl))
4369     /* The type is nested in some template class.  Nothing to worry
4370        about here; there are no new template parameters for the nested
4371        type.  */
4372     return true;
4373
4374   if (!parms)
4375     {
4376       error ("template specifiers not specified in declaration of %qD",
4377              tmpl);
4378       return false;
4379     }
4380
4381   parms = INNERMOST_TEMPLATE_PARMS (parms);
4382   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4383
4384   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4385     {
4386       error ("redeclared with %d template parameter(s)", 
4387              TREE_VEC_LENGTH (parms));
4388       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4389              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4390       return false;
4391     }
4392
4393   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4394     {
4395       tree tmpl_parm;
4396       tree parm;
4397       tree tmpl_default;
4398       tree parm_default;
4399
4400       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4401           || TREE_VEC_ELT (parms, i) == error_mark_node)
4402         continue;
4403
4404       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4405       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4406       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4407       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4408
4409       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4410          TEMPLATE_DECL.  */
4411       if (tmpl_parm != error_mark_node
4412           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4413               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4414                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4415               || (TREE_CODE (tmpl_parm) != PARM_DECL
4416                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4417                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4418               || (TREE_CODE (tmpl_parm) == PARM_DECL
4419                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4420                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4421         {
4422           error ("template parameter %q+#D", tmpl_parm);
4423           error ("redeclared here as %q#D", parm);
4424           return false;
4425         }
4426
4427       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4428         {
4429           /* We have in [temp.param]:
4430
4431              A template-parameter may not be given default arguments
4432              by two different declarations in the same scope.  */
4433           error_at (input_location, "redefinition of default argument for %q#D", parm);
4434           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4435                   "original definition appeared here");
4436           return false;
4437         }
4438
4439       if (parm_default != NULL_TREE)
4440         /* Update the previous template parameters (which are the ones
4441            that will really count) with the new default value.  */
4442         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4443       else if (tmpl_default != NULL_TREE)
4444         /* Update the new parameters, too; they'll be used as the
4445            parameters for any members.  */
4446         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4447     }
4448
4449     return true;
4450 }
4451
4452 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4453    (possibly simplified) expression.  */
4454
4455 tree
4456 fold_non_dependent_expr (tree expr)
4457 {
4458   if (expr == NULL_TREE)
4459     return NULL_TREE;
4460
4461   /* If we're in a template, but EXPR isn't value dependent, simplify
4462      it.  We're supposed to treat:
4463
4464        template <typename T> void f(T[1 + 1]);
4465        template <typename T> void f(T[2]);
4466
4467      as two declarations of the same function, for example.  */
4468   if (processing_template_decl
4469       && !type_dependent_expression_p (expr)
4470       && !value_dependent_expression_p (expr))
4471     {
4472       HOST_WIDE_INT saved_processing_template_decl;
4473
4474       saved_processing_template_decl = processing_template_decl;
4475       processing_template_decl = 0;
4476       expr = tsubst_copy_and_build (expr,
4477                                     /*args=*/NULL_TREE,
4478                                     tf_error,
4479                                     /*in_decl=*/NULL_TREE,
4480                                     /*function_p=*/false,
4481                                     /*integral_constant_expression_p=*/true);
4482       processing_template_decl = saved_processing_template_decl;
4483     }
4484   return expr;
4485 }
4486
4487 /* EXPR is an expression which is used in a constant-expression context.
4488    For instance, it could be a VAR_DECL with a constant initializer.
4489    Extract the innermost constant expression.
4490
4491    This is basically a more powerful version of
4492    integral_constant_value, which can be used also in templates where
4493    initializers can maintain a syntactic rather than semantic form
4494    (even if they are non-dependent, for access-checking purposes).  */
4495
4496 static tree
4497 fold_decl_constant_value (tree expr)
4498 {
4499   tree const_expr = expr;
4500   do
4501     {
4502       expr = fold_non_dependent_expr (const_expr);
4503       const_expr = integral_constant_value (expr);
4504     }
4505   while (expr != const_expr);
4506
4507   return expr;
4508 }
4509
4510 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4511    must be a function or a pointer-to-function type, as specified
4512    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4513    and check that the resulting function has external linkage.  */
4514
4515 static tree
4516 convert_nontype_argument_function (tree type, tree expr)
4517 {
4518   tree fns = expr;
4519   tree fn, fn_no_ptr;
4520
4521   fn = instantiate_type (type, fns, tf_none);
4522   if (fn == error_mark_node)
4523     return error_mark_node;
4524
4525   fn_no_ptr = fn;
4526   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4527     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4528   if (TREE_CODE (fn_no_ptr) == BASELINK)
4529     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4530  
4531   /* [temp.arg.nontype]/1
4532
4533      A template-argument for a non-type, non-template template-parameter
4534      shall be one of:
4535      [...]
4536      -- the address of an object or function with external linkage.  */
4537   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4538     {
4539       error ("%qE is not a valid template argument for type %qT "
4540              "because function %qD has not external linkage",
4541              expr, type, fn_no_ptr);
4542       return NULL_TREE;
4543     }
4544
4545   return fn;
4546 }
4547
4548 /* Attempt to convert the non-type template parameter EXPR to the
4549    indicated TYPE.  If the conversion is successful, return the
4550    converted value.  If the conversion is unsuccessful, return
4551    NULL_TREE if we issued an error message, or error_mark_node if we
4552    did not.  We issue error messages for out-and-out bad template
4553    parameters, but not simply because the conversion failed, since we
4554    might be just trying to do argument deduction.  Both TYPE and EXPR
4555    must be non-dependent.
4556
4557    The conversion follows the special rules described in
4558    [temp.arg.nontype], and it is much more strict than an implicit
4559    conversion.
4560
4561    This function is called twice for each template argument (see
4562    lookup_template_class for a more accurate description of this
4563    problem). This means that we need to handle expressions which
4564    are not valid in a C++ source, but can be created from the
4565    first call (for instance, casts to perform conversions). These
4566    hacks can go away after we fix the double coercion problem.  */
4567
4568 static tree
4569 convert_nontype_argument (tree type, tree expr)
4570 {
4571   tree expr_type;
4572
4573   /* Detect immediately string literals as invalid non-type argument.
4574      This special-case is not needed for correctness (we would easily
4575      catch this later), but only to provide better diagnostic for this
4576      common user mistake. As suggested by DR 100, we do not mention
4577      linkage issues in the diagnostic as this is not the point.  */
4578   if (TREE_CODE (expr) == STRING_CST)
4579     {
4580       error ("%qE is not a valid template argument for type %qT "
4581              "because string literals can never be used in this context",
4582              expr, type);
4583       return NULL_TREE;
4584     }
4585
4586   /* If we are in a template, EXPR may be non-dependent, but still
4587      have a syntactic, rather than semantic, form.  For example, EXPR
4588      might be a SCOPE_REF, rather than the VAR_DECL to which the
4589      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4590      so that access checking can be performed when the template is
4591      instantiated -- but here we need the resolved form so that we can
4592      convert the argument.  */
4593   expr = fold_non_dependent_expr (expr);
4594   if (error_operand_p (expr))
4595     return error_mark_node;
4596   expr_type = TREE_TYPE (expr);
4597
4598   /* HACK: Due to double coercion, we can get a
4599      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4600      which is the tree that we built on the first call (see
4601      below when coercing to reference to object or to reference to
4602      function). We just strip everything and get to the arg.
4603      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4604      for examples.  */
4605   if (TREE_CODE (expr) == NOP_EXPR)
4606     {
4607       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4608         {
4609           /* ??? Maybe we could use convert_from_reference here, but we
4610              would need to relax its constraints because the NOP_EXPR
4611              could actually change the type to something more cv-qualified,
4612              and this is not folded by convert_from_reference.  */
4613           tree addr = TREE_OPERAND (expr, 0);
4614           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4615           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4616           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4617           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4618                       (TREE_TYPE (expr_type),
4619                        TREE_TYPE (TREE_TYPE (addr))));
4620
4621           expr = TREE_OPERAND (addr, 0);
4622           expr_type = TREE_TYPE (expr);
4623         }
4624
4625       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4626          parameter is a pointer to object, through decay and
4627          qualification conversion. Let's strip everything.  */
4628       else if (TYPE_PTROBV_P (type))
4629         {
4630           STRIP_NOPS (expr);
4631           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4632           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4633           /* Skip the ADDR_EXPR only if it is part of the decay for
4634              an array. Otherwise, it is part of the original argument
4635              in the source code.  */
4636           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4637             expr = TREE_OPERAND (expr, 0);
4638           expr_type = TREE_TYPE (expr);
4639         }
4640     }
4641
4642   /* [temp.arg.nontype]/5, bullet 1
4643
4644      For a non-type template-parameter of integral or enumeration type,
4645      integral promotions (_conv.prom_) and integral conversions
4646      (_conv.integral_) are applied.  */
4647   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4648     {
4649       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4650         return error_mark_node;
4651
4652       expr = fold_decl_constant_value (expr);
4653       /* Notice that there are constant expressions like '4 % 0' which
4654          do not fold into integer constants.  */
4655       if (TREE_CODE (expr) != INTEGER_CST)
4656         {
4657           error ("%qE is not a valid template argument for type %qT "
4658                  "because it is a non-constant expression", expr, type);
4659           return NULL_TREE;
4660         }
4661
4662       /* At this point, an implicit conversion does what we want,
4663          because we already know that the expression is of integral
4664          type.  */
4665       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4666       if (expr == error_mark_node)
4667         return error_mark_node;
4668
4669       /* Conversion was allowed: fold it to a bare integer constant.  */
4670       expr = fold (expr);
4671     }
4672   /* [temp.arg.nontype]/5, bullet 2
4673
4674      For a non-type template-parameter of type pointer to object,
4675      qualification conversions (_conv.qual_) and the array-to-pointer
4676      conversion (_conv.array_) are applied.  */
4677   else if (TYPE_PTROBV_P (type))
4678     {
4679       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4680
4681          A template-argument for a non-type, non-template template-parameter
4682          shall be one of: [...]
4683
4684          -- the name of a non-type template-parameter;
4685          -- the address of an object or function with external linkage, [...]
4686             expressed as "& id-expression" where the & is optional if the name
4687             refers to a function or array, or if the corresponding
4688             template-parameter is a reference.
4689
4690         Here, we do not care about functions, as they are invalid anyway
4691         for a parameter of type pointer-to-object.  */
4692
4693       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4694         /* Non-type template parameters are OK.  */
4695         ;
4696       else if (TREE_CODE (expr) != ADDR_EXPR
4697                && TREE_CODE (expr_type) != ARRAY_TYPE)
4698         {
4699           if (TREE_CODE (expr) == VAR_DECL)
4700             {
4701               error ("%qD is not a valid template argument "
4702                      "because %qD is a variable, not the address of "
4703                      "a variable",
4704                      expr, expr);
4705               return NULL_TREE;
4706             }
4707           /* Other values, like integer constants, might be valid
4708              non-type arguments of some other type.  */
4709           return error_mark_node;
4710         }
4711       else
4712         {
4713           tree decl;
4714
4715           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4716                   ? TREE_OPERAND (expr, 0) : expr);
4717           if (TREE_CODE (decl) != VAR_DECL)
4718             {
4719               error ("%qE is not a valid template argument of type %qT "
4720                      "because %qE is not a variable",
4721                      expr, type, decl);
4722               return NULL_TREE;
4723             }
4724           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4725             {
4726               error ("%qE is not a valid template argument of type %qT "
4727                      "because %qD does not have external linkage",
4728                      expr, type, decl);
4729               return NULL_TREE;
4730             }
4731         }
4732
4733       expr = decay_conversion (expr);
4734       if (expr == error_mark_node)
4735         return error_mark_node;
4736
4737       expr = perform_qualification_conversions (type, expr);
4738       if (expr == error_mark_node)
4739         return error_mark_node;
4740     }
4741   /* [temp.arg.nontype]/5, bullet 3
4742
4743      For a non-type template-parameter of type reference to object, no
4744      conversions apply. The type referred to by the reference may be more
4745      cv-qualified than the (otherwise identical) type of the
4746      template-argument. The template-parameter is bound directly to the
4747      template-argument, which must be an lvalue.  */
4748   else if (TYPE_REF_OBJ_P (type))
4749     {
4750       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4751                                                       expr_type))
4752         return error_mark_node;
4753
4754       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4755         {
4756           error ("%qE is not a valid template argument for type %qT "
4757                  "because of conflicts in cv-qualification", expr, type);
4758           return NULL_TREE;
4759         }
4760
4761       if (!real_lvalue_p (expr))
4762         {
4763           error ("%qE is not a valid template argument for type %qT "
4764                  "because it is not an lvalue", expr, type);
4765           return NULL_TREE;
4766         }
4767
4768       /* [temp.arg.nontype]/1
4769
4770          A template-argument for a non-type, non-template template-parameter
4771          shall be one of: [...]
4772
4773          -- the address of an object or function with external linkage.  */
4774       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4775         {
4776           error ("%qE is not a valid template argument for type %qT "
4777                  "because object %qD has not external linkage",
4778                  expr, type, expr);
4779           return NULL_TREE;
4780         }
4781
4782       expr = build_nop (type, build_address (expr));
4783     }
4784   /* [temp.arg.nontype]/5, bullet 4
4785
4786      For a non-type template-parameter of type pointer to function, only
4787      the function-to-pointer conversion (_conv.func_) is applied. If the
4788      template-argument represents a set of overloaded functions (or a
4789      pointer to such), the matching function is selected from the set
4790      (_over.over_).  */
4791   else if (TYPE_PTRFN_P (type))
4792     {
4793       /* If the argument is a template-id, we might not have enough
4794          context information to decay the pointer.  */
4795       if (!type_unknown_p (expr_type))
4796         {
4797           expr = decay_conversion (expr);
4798           if (expr == error_mark_node)
4799             return error_mark_node;
4800         }
4801
4802       expr = convert_nontype_argument_function (type, expr);
4803       if (!expr || expr == error_mark_node)
4804         return expr;
4805
4806       if (TREE_CODE (expr) != ADDR_EXPR)
4807         {
4808           error ("%qE is not a valid template argument for type %qT", expr, type);
4809           error ("it must be the address of a function with external linkage");
4810           return NULL_TREE;
4811         }
4812     }
4813   /* [temp.arg.nontype]/5, bullet 5
4814
4815      For a non-type template-parameter of type reference to function, no
4816      conversions apply. If the template-argument represents a set of
4817      overloaded functions, the matching function is selected from the set
4818      (_over.over_).  */
4819   else if (TYPE_REFFN_P (type))
4820     {
4821       if (TREE_CODE (expr) == ADDR_EXPR)
4822         {
4823           error ("%qE is not a valid template argument for type %qT "
4824                  "because it is a pointer", expr, type);
4825           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4826           return NULL_TREE;
4827         }
4828
4829       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4830       if (!expr || expr == error_mark_node)
4831         return expr;
4832
4833       expr = build_nop (type, build_address (expr));
4834     }
4835   /* [temp.arg.nontype]/5, bullet 6
4836
4837      For a non-type template-parameter of type pointer to member function,
4838      no conversions apply. If the template-argument represents a set of
4839      overloaded member functions, the matching member function is selected
4840      from the set (_over.over_).  */
4841   else if (TYPE_PTRMEMFUNC_P (type))
4842     {
4843       expr = instantiate_type (type, expr, tf_none);
4844       if (expr == error_mark_node)
4845         return error_mark_node;
4846
4847       /* There is no way to disable standard conversions in
4848          resolve_address_of_overloaded_function (called by
4849          instantiate_type). It is possible that the call succeeded by
4850          converting &B::I to &D::I (where B is a base of D), so we need
4851          to reject this conversion here.
4852
4853          Actually, even if there was a way to disable standard conversions,
4854          it would still be better to reject them here so that we can
4855          provide a superior diagnostic.  */
4856       if (!same_type_p (TREE_TYPE (expr), type))
4857         {
4858           /* Make sure we are just one standard conversion off.  */
4859           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4860           error ("%qE is not a valid template argument for type %qT "
4861                  "because it is of type %qT", expr, type,
4862                  TREE_TYPE (expr));
4863           inform (input_location, "standard conversions are not allowed in this context");
4864           return NULL_TREE;
4865         }
4866     }
4867   /* [temp.arg.nontype]/5, bullet 7
4868
4869      For a non-type template-parameter of type pointer to data member,
4870      qualification conversions (_conv.qual_) are applied.  */
4871   else if (TYPE_PTRMEM_P (type))
4872     {
4873       expr = perform_qualification_conversions (type, expr);
4874       if (expr == error_mark_node)
4875         return expr;
4876     }
4877   /* A template non-type parameter must be one of the above.  */
4878   else
4879     gcc_unreachable ();
4880
4881   /* Sanity check: did we actually convert the argument to the
4882      right type?  */
4883   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4884   return expr;
4885 }
4886
4887 /* Subroutine of coerce_template_template_parms, which returns 1 if
4888    PARM_PARM and ARG_PARM match using the rule for the template
4889    parameters of template template parameters. Both PARM and ARG are
4890    template parameters; the rest of the arguments are the same as for
4891    coerce_template_template_parms.
4892  */
4893 static int
4894 coerce_template_template_parm (tree parm,
4895                               tree arg,
4896                               tsubst_flags_t complain,
4897                               tree in_decl,
4898                               tree outer_args)
4899 {
4900   if (arg == NULL_TREE || arg == error_mark_node
4901       || parm == NULL_TREE || parm == error_mark_node)
4902     return 0;
4903   
4904   if (TREE_CODE (arg) != TREE_CODE (parm))
4905     return 0;
4906   
4907   switch (TREE_CODE (parm))
4908     {
4909     case TEMPLATE_DECL:
4910       /* We encounter instantiations of templates like
4911          template <template <template <class> class> class TT>
4912          class C;  */
4913       {
4914         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4915         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4916         
4917         if (!coerce_template_template_parms
4918             (parmparm, argparm, complain, in_decl, outer_args))
4919           return 0;
4920       }
4921       /* Fall through.  */
4922       
4923     case TYPE_DECL:
4924       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4925           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4926         /* Argument is a parameter pack but parameter is not.  */
4927         return 0;
4928       break;
4929       
4930     case PARM_DECL:
4931       /* The tsubst call is used to handle cases such as
4932          
4933            template <int> class C {};
4934            template <class T, template <T> class TT> class D {};
4935            D<int, C> d;
4936
4937          i.e. the parameter list of TT depends on earlier parameters.  */
4938       if (!uses_template_parms (TREE_TYPE (arg))
4939           && !same_type_p
4940                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4941                  TREE_TYPE (arg)))
4942         return 0;
4943       
4944       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4945           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4946         /* Argument is a parameter pack but parameter is not.  */
4947         return 0;
4948       
4949       break;
4950
4951     default:
4952       gcc_unreachable ();
4953     }
4954
4955   return 1;
4956 }
4957
4958
4959 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4960    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4961    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4962    or PARM_DECL.
4963
4964    Consider the example:
4965      template <class T> class A;
4966      template<template <class U> class TT> class B;
4967
4968    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4969    the parameters to A, and OUTER_ARGS contains A.  */
4970
4971 static int
4972 coerce_template_template_parms (tree parm_parms,
4973                                 tree arg_parms,
4974                                 tsubst_flags_t complain,
4975                                 tree in_decl,
4976                                 tree outer_args)
4977 {
4978   int nparms, nargs, i;
4979   tree parm, arg;
4980   int variadic_p = 0;
4981
4982   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4983   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4984
4985   nparms = TREE_VEC_LENGTH (parm_parms);
4986   nargs = TREE_VEC_LENGTH (arg_parms);
4987
4988   /* Determine whether we have a parameter pack at the end of the
4989      template template parameter's template parameter list.  */
4990   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4991     {
4992       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4993       
4994       if (parm == error_mark_node)
4995         return 0;
4996
4997       switch (TREE_CODE (parm))
4998         {
4999         case TEMPLATE_DECL:
5000         case TYPE_DECL:
5001           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5002             variadic_p = 1;
5003           break;
5004           
5005         case PARM_DECL:
5006           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5007             variadic_p = 1;
5008           break;
5009           
5010         default:
5011           gcc_unreachable ();
5012         }
5013     }
5014  
5015   if (nargs != nparms
5016       && !(variadic_p && nargs >= nparms - 1))
5017     return 0;
5018
5019   /* Check all of the template parameters except the parameter pack at
5020      the end (if any).  */
5021   for (i = 0; i < nparms - variadic_p; ++i)
5022     {
5023       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5024           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5025         continue;
5026
5027       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5028       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5029
5030       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5031                                           outer_args))
5032         return 0;
5033
5034     }
5035
5036   if (variadic_p)
5037     {
5038       /* Check each of the template parameters in the template
5039          argument against the template parameter pack at the end of
5040          the template template parameter.  */
5041       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5042         return 0;
5043
5044       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5045
5046       for (; i < nargs; ++i)
5047         {
5048           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5049             continue;
5050  
5051           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5052  
5053           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5054                                               outer_args))
5055             return 0;
5056         }
5057     }
5058
5059   return 1;
5060 }
5061
5062 /* Verifies that the deduced template arguments (in TARGS) for the
5063    template template parameters (in TPARMS) represent valid bindings,
5064    by comparing the template parameter list of each template argument
5065    to the template parameter list of its corresponding template
5066    template parameter, in accordance with DR150. This
5067    routine can only be called after all template arguments have been
5068    deduced. It will return TRUE if all of the template template
5069    parameter bindings are okay, FALSE otherwise.  */
5070 bool 
5071 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5072 {
5073   int i, ntparms = TREE_VEC_LENGTH (tparms);
5074   bool ret = true;
5075
5076   /* We're dealing with template parms in this process.  */
5077   ++processing_template_decl;
5078
5079   targs = INNERMOST_TEMPLATE_ARGS (targs);
5080
5081   for (i = 0; i < ntparms; ++i)
5082     {
5083       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5084       tree targ = TREE_VEC_ELT (targs, i);
5085
5086       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5087         {
5088           tree packed_args = NULL_TREE;
5089           int idx, len = 1;
5090
5091           if (ARGUMENT_PACK_P (targ))
5092             {
5093               /* Look inside the argument pack.  */
5094               packed_args = ARGUMENT_PACK_ARGS (targ);
5095               len = TREE_VEC_LENGTH (packed_args);
5096             }
5097
5098           for (idx = 0; idx < len; ++idx)
5099             {
5100               tree targ_parms = NULL_TREE;
5101
5102               if (packed_args)
5103                 /* Extract the next argument from the argument
5104                    pack.  */
5105                 targ = TREE_VEC_ELT (packed_args, idx);
5106
5107               if (PACK_EXPANSION_P (targ))
5108                 /* Look at the pattern of the pack expansion.  */
5109                 targ = PACK_EXPANSION_PATTERN (targ);
5110
5111               /* Extract the template parameters from the template
5112                  argument.  */
5113               if (TREE_CODE (targ) == TEMPLATE_DECL)
5114                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5115               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5116                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5117
5118               /* Verify that we can coerce the template template
5119                  parameters from the template argument to the template
5120                  parameter.  This requires an exact match.  */
5121               if (targ_parms
5122                   && !coerce_template_template_parms
5123                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5124                         targ_parms,
5125                         tf_none,
5126                         tparm,
5127                         targs))
5128                 {
5129                   ret = false;
5130                   goto out;
5131                 }
5132             }
5133         }
5134     }
5135
5136  out:
5137
5138   --processing_template_decl;
5139   return ret;
5140 }
5141
5142 /* Convert the indicated template ARG as necessary to match the
5143    indicated template PARM.  Returns the converted ARG, or
5144    error_mark_node if the conversion was unsuccessful.  Error and
5145    warning messages are issued under control of COMPLAIN.  This
5146    conversion is for the Ith parameter in the parameter list.  ARGS is
5147    the full set of template arguments deduced so far.  */
5148
5149 static tree
5150 convert_template_argument (tree parm,
5151                            tree arg,
5152                            tree args,
5153                            tsubst_flags_t complain,
5154                            int i,
5155                            tree in_decl)
5156 {
5157   tree orig_arg;
5158   tree val;
5159   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5160
5161   if (TREE_CODE (arg) == TREE_LIST
5162       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5163     {
5164       /* The template argument was the name of some
5165          member function.  That's usually
5166          invalid, but static members are OK.  In any
5167          case, grab the underlying fields/functions
5168          and issue an error later if required.  */
5169       orig_arg = TREE_VALUE (arg);
5170       TREE_TYPE (arg) = unknown_type_node;
5171     }
5172
5173   orig_arg = arg;
5174
5175   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5176   requires_type = (TREE_CODE (parm) == TYPE_DECL
5177                    || requires_tmpl_type);
5178
5179   /* When determining whether an argument pack expansion is a template,
5180      look at the pattern.  */
5181   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5182     arg = PACK_EXPANSION_PATTERN (arg);
5183
5184   is_tmpl_type = 
5185     ((TREE_CODE (arg) == TEMPLATE_DECL
5186       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5187      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5188      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5189
5190   if (is_tmpl_type
5191       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5192           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5193     arg = TYPE_STUB_DECL (arg);
5194
5195   is_type = TYPE_P (arg) || is_tmpl_type;
5196
5197   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5198       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5199     {
5200       permerror (input_location, "to refer to a type member of a template parameter, "
5201                  "use %<typename %E%>", orig_arg);
5202
5203       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5204                                      TREE_OPERAND (arg, 1),
5205                                      typename_type,
5206                                      complain & tf_error);
5207       arg = orig_arg;
5208       is_type = 1;
5209     }
5210   if (is_type != requires_type)
5211     {
5212       if (in_decl)
5213         {
5214           if (complain & tf_error)
5215             {
5216               error ("type/value mismatch at argument %d in template "
5217                      "parameter list for %qD",
5218                      i + 1, in_decl);
5219               if (is_type)
5220                 error ("  expected a constant of type %qT, got %qT",
5221                        TREE_TYPE (parm),
5222                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5223               else if (requires_tmpl_type)
5224                 error ("  expected a class template, got %qE", orig_arg);
5225               else
5226                 error ("  expected a type, got %qE", orig_arg);
5227             }
5228         }
5229       return error_mark_node;
5230     }
5231   if (is_tmpl_type ^ requires_tmpl_type)
5232     {
5233       if (in_decl && (complain & tf_error))
5234         {
5235           error ("type/value mismatch at argument %d in template "
5236                  "parameter list for %qD",
5237                  i + 1, in_decl);
5238           if (is_tmpl_type)
5239             error ("  expected a type, got %qT", DECL_NAME (arg));
5240           else
5241             error ("  expected a class template, got %qT", orig_arg);
5242         }
5243       return error_mark_node;
5244     }
5245
5246   if (is_type)
5247     {
5248       if (requires_tmpl_type)
5249         {
5250           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5251             /* The number of argument required is not known yet.
5252                Just accept it for now.  */
5253             val = TREE_TYPE (arg);
5254           else
5255             {
5256               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5257               tree argparm;
5258
5259               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5260
5261               if (coerce_template_template_parms (parmparm, argparm,
5262                                                   complain, in_decl,
5263                                                   args))
5264                 {
5265                   val = orig_arg;
5266
5267                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5268                      TEMPLATE_DECL.  */
5269                   if (val != error_mark_node)
5270                     {
5271                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5272                         val = TREE_TYPE (val);
5273                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5274                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5275                         {
5276                           val = TREE_TYPE (arg);
5277                           val = make_pack_expansion (val);
5278                         }
5279                     }
5280                 }
5281               else
5282                 {
5283                   if (in_decl && (complain & tf_error))
5284                     {
5285                       error ("type/value mismatch at argument %d in "
5286                              "template parameter list for %qD",
5287                              i + 1, in_decl);
5288                       error ("  expected a template of type %qD, got %qD",
5289                              parm, orig_arg);
5290                     }
5291
5292                   val = error_mark_node;
5293                 }
5294             }
5295         }
5296       else
5297         val = orig_arg;
5298       /* We only form one instance of each template specialization.
5299          Therefore, if we use a non-canonical variant (i.e., a
5300          typedef), any future messages referring to the type will use
5301          the typedef, which is confusing if those future uses do not
5302          themselves also use the typedef.  */
5303       if (TYPE_P (val))
5304         val = strip_typedefs (val);
5305     }
5306   else
5307     {
5308       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5309
5310       if (invalid_nontype_parm_type_p (t, complain))
5311         return error_mark_node;
5312
5313       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5314         {
5315           if (same_type_p (t, TREE_TYPE (orig_arg)))
5316             val = orig_arg;
5317           else
5318             {
5319               /* Not sure if this is reachable, but it doesn't hurt
5320                  to be robust.  */
5321               error ("type mismatch in nontype parameter pack");
5322               val = error_mark_node;
5323             }
5324         }
5325       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5326         /* We used to call digest_init here.  However, digest_init
5327            will report errors, which we don't want when complain
5328            is zero.  More importantly, digest_init will try too
5329            hard to convert things: for example, `0' should not be
5330            converted to pointer type at this point according to
5331            the standard.  Accepting this is not merely an
5332            extension, since deciding whether or not these
5333            conversions can occur is part of determining which
5334            function template to call, or whether a given explicit
5335            argument specification is valid.  */
5336         val = convert_nontype_argument (t, orig_arg);
5337       else
5338         val = orig_arg;
5339
5340       if (val == NULL_TREE)
5341         val = error_mark_node;
5342       else if (val == error_mark_node && (complain & tf_error))
5343         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5344     }
5345
5346   return val;
5347 }
5348
5349 /* Coerces the remaining template arguments in INNER_ARGS (from
5350    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5351    Returns the coerced argument pack. PARM_IDX is the position of this
5352    parameter in the template parameter list. ARGS is the original
5353    template argument list.  */
5354 static tree
5355 coerce_template_parameter_pack (tree parms,
5356                                 int parm_idx,
5357                                 tree args,
5358                                 tree inner_args,
5359                                 int arg_idx,
5360                                 tree new_args,
5361                                 int* lost,
5362                                 tree in_decl,
5363                                 tsubst_flags_t complain)
5364 {
5365   tree parm = TREE_VEC_ELT (parms, parm_idx);
5366   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5367   tree packed_args;
5368   tree argument_pack;
5369   tree packed_types = NULL_TREE;
5370
5371   if (arg_idx > nargs)
5372     arg_idx = nargs;
5373
5374   packed_args = make_tree_vec (nargs - arg_idx);
5375
5376   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5377       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5378     {
5379       /* When the template parameter is a non-type template
5380          parameter pack whose type uses parameter packs, we need
5381          to look at each of the template arguments
5382          separately. Build a vector of the types for these
5383          non-type template parameters in PACKED_TYPES.  */
5384       tree expansion 
5385         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5386       packed_types = tsubst_pack_expansion (expansion, args,
5387                                             complain, in_decl);
5388
5389       if (packed_types == error_mark_node)
5390         return error_mark_node;
5391
5392       /* Check that we have the right number of arguments.  */
5393       if (arg_idx < nargs
5394           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5395           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5396         {
5397           int needed_parms 
5398             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5399           error ("wrong number of template arguments (%d, should be %d)",
5400                  nargs, needed_parms);
5401           return error_mark_node;
5402         }
5403
5404       /* If we aren't able to check the actual arguments now
5405          (because they haven't been expanded yet), we can at least
5406          verify that all of the types used for the non-type
5407          template parameter pack are, in fact, valid for non-type
5408          template parameters.  */
5409       if (arg_idx < nargs 
5410           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5411         {
5412           int j, len = TREE_VEC_LENGTH (packed_types);
5413           for (j = 0; j < len; ++j)
5414             {
5415               tree t = TREE_VEC_ELT (packed_types, j);
5416               if (invalid_nontype_parm_type_p (t, complain))
5417                 return error_mark_node;
5418             }
5419         }
5420     }
5421
5422   /* Convert the remaining arguments, which will be a part of the
5423      parameter pack "parm".  */
5424   for (; arg_idx < nargs; ++arg_idx)
5425     {
5426       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5427       tree actual_parm = TREE_VALUE (parm);
5428
5429       if (packed_types && !PACK_EXPANSION_P (arg))
5430         {
5431           /* When we have a vector of types (corresponding to the
5432              non-type template parameter pack that uses parameter
5433              packs in its type, as mention above), and the
5434              argument is not an expansion (which expands to a
5435              currently unknown number of arguments), clone the
5436              parm and give it the next type in PACKED_TYPES.  */
5437           actual_parm = copy_node (actual_parm);
5438           TREE_TYPE (actual_parm) = 
5439             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5440         }
5441
5442       if (arg != error_mark_node)
5443         arg = convert_template_argument (actual_parm, 
5444                                          arg, new_args, complain, parm_idx,
5445                                          in_decl);
5446       if (arg == error_mark_node)
5447         (*lost)++;
5448       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5449     }
5450
5451   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5452       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5453     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5454   else
5455     {
5456       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5457       TREE_TYPE (argument_pack) 
5458         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5459       TREE_CONSTANT (argument_pack) = 1;
5460     }
5461
5462   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5463   return argument_pack;
5464 }
5465
5466 /* Convert all template arguments to their appropriate types, and
5467    return a vector containing the innermost resulting template
5468    arguments.  If any error occurs, return error_mark_node. Error and
5469    warning messages are issued under control of COMPLAIN.
5470
5471    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5472    for arguments not specified in ARGS.  Otherwise, if
5473    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5474    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5475    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5476    ARGS.  */
5477
5478 static tree
5479 coerce_template_parms (tree parms,
5480                        tree args,
5481                        tree in_decl,
5482                        tsubst_flags_t complain,
5483                        bool require_all_args,
5484                        bool use_default_args)
5485 {
5486   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5487   tree inner_args;
5488   tree new_args;
5489   tree new_inner_args;
5490   int saved_unevaluated_operand;
5491   int saved_inhibit_evaluation_warnings;
5492
5493   /* When used as a boolean value, indicates whether this is a
5494      variadic template parameter list. Since it's an int, we can also
5495      subtract it from nparms to get the number of non-variadic
5496      parameters.  */
5497   int variadic_p = 0;
5498
5499   nparms = TREE_VEC_LENGTH (parms);
5500
5501   /* Determine if there are any parameter packs.  */
5502   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5503     {
5504       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5505       if (template_parameter_pack_p (tparm))
5506         ++variadic_p;
5507     }
5508
5509   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5510   /* If there are 0 or 1 parameter packs, we need to expand any argument
5511      packs so that we can deduce a parameter pack from some non-packed args
5512      followed by an argument pack, as in variadic85.C.  If there are more
5513      than that, we need to leave argument packs intact so the arguments are
5514      assigned to the right parameter packs.  This should only happen when
5515      dealing with a nested class inside a partial specialization of a class
5516      template, as in variadic92.C.  */
5517   if (variadic_p <= 1)
5518     inner_args = expand_template_argument_pack (inner_args);
5519
5520   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5521   if ((nargs > nparms && !variadic_p)
5522       || (nargs < nparms - variadic_p
5523           && require_all_args
5524           && (!use_default_args
5525               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5526                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5527     {
5528       if (complain & tf_error)
5529         {
5530           const char *or_more = "";
5531           if (variadic_p)
5532             {
5533               or_more = " or more";
5534               --nparms;
5535             }
5536
5537           error ("wrong number of template arguments (%d, should be %d%s)",
5538                  nargs, nparms, or_more);
5539
5540           if (in_decl)
5541             error ("provided for %q+D", in_decl);
5542         }
5543
5544       return error_mark_node;
5545     }
5546
5547   /* We need to evaluate the template arguments, even though this
5548      template-id may be nested within a "sizeof".  */
5549   saved_unevaluated_operand = cp_unevaluated_operand;
5550   cp_unevaluated_operand = 0;
5551   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5552   c_inhibit_evaluation_warnings = 0;
5553   new_inner_args = make_tree_vec (nparms);
5554   new_args = add_outermost_template_args (args, new_inner_args);
5555   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5556     {
5557       tree arg;
5558       tree parm;
5559
5560       /* Get the Ith template parameter.  */
5561       parm = TREE_VEC_ELT (parms, parm_idx);
5562  
5563       if (parm == error_mark_node)
5564       {
5565         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5566         continue;
5567       }
5568
5569       /* Calculate the next argument.  */
5570       if (arg_idx < nargs)
5571         arg = TREE_VEC_ELT (inner_args, arg_idx);
5572       else
5573         arg = NULL_TREE;
5574
5575       if (template_parameter_pack_p (TREE_VALUE (parm))
5576           && !(arg && ARGUMENT_PACK_P (arg)))
5577         {
5578           /* All remaining arguments will be placed in the
5579              template parameter pack PARM.  */
5580           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5581                                                 inner_args, arg_idx,
5582                                                 new_args, &lost,
5583                                                 in_decl, complain);
5584
5585           /* Store this argument.  */
5586           if (arg == error_mark_node)
5587             lost++;
5588           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5589
5590           /* We are done with all of the arguments.  */
5591           arg_idx = nargs;
5592           
5593           continue;
5594         }
5595       else if (arg)
5596         {
5597           if (PACK_EXPANSION_P (arg))
5598             {
5599               if (complain & tf_error)
5600                 {
5601                   /* FIXME this restriction was removed by N2555; see
5602                      bug 35722.  */
5603                   /* If ARG is a pack expansion, but PARM is not a
5604                      template parameter pack (if it were, we would have
5605                      handled it above), we're trying to expand into a
5606                      fixed-length argument list.  */
5607                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5608                     sorry ("cannot expand %<%E%> into a fixed-length "
5609                            "argument list", arg);
5610                   else
5611                     sorry ("cannot expand %<%T%> into a fixed-length "
5612                            "argument list", arg);
5613                 }
5614               return error_mark_node;
5615             }
5616         }
5617       else if (require_all_args)
5618         /* There must be a default arg in this case.  */
5619         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5620                                    complain, in_decl);
5621       else
5622         break;
5623
5624       if (arg == error_mark_node)
5625         {
5626           if (complain & tf_error)
5627             error ("template argument %d is invalid", arg_idx + 1);
5628         }
5629       else if (!arg)
5630         /* This only occurs if there was an error in the template
5631            parameter list itself (which we would already have
5632            reported) that we are trying to recover from, e.g., a class
5633            template with a parameter list such as
5634            template<typename..., typename>.  */
5635         return error_mark_node;
5636       else
5637         arg = convert_template_argument (TREE_VALUE (parm),
5638                                          arg, new_args, complain, 
5639                                          parm_idx, in_decl);
5640
5641       if (arg == error_mark_node)
5642         lost++;
5643       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5644     }
5645   cp_unevaluated_operand = saved_unevaluated_operand;
5646   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5647
5648   if (lost)
5649     return error_mark_node;
5650
5651   return new_inner_args;
5652 }
5653
5654 /* Returns 1 if template args OT and NT are equivalent.  */
5655
5656 static int
5657 template_args_equal (tree ot, tree nt)
5658 {
5659   if (nt == ot)
5660     return 1;
5661
5662   if (TREE_CODE (nt) == TREE_VEC)
5663     /* For member templates */
5664     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5665   else if (PACK_EXPANSION_P (ot))
5666     return PACK_EXPANSION_P (nt) 
5667       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5668                               PACK_EXPANSION_PATTERN (nt));
5669   else if (ARGUMENT_PACK_P (ot))
5670     {
5671       int i, len;
5672       tree opack, npack;
5673
5674       if (!ARGUMENT_PACK_P (nt))
5675         return 0;
5676
5677       opack = ARGUMENT_PACK_ARGS (ot);
5678       npack = ARGUMENT_PACK_ARGS (nt);
5679       len = TREE_VEC_LENGTH (opack);
5680       if (TREE_VEC_LENGTH (npack) != len)
5681         return 0;
5682       for (i = 0; i < len; ++i)
5683         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5684                                   TREE_VEC_ELT (npack, i)))
5685           return 0;
5686       return 1;
5687     }
5688   else if (TYPE_P (nt))
5689     return TYPE_P (ot) && same_type_p (ot, nt);
5690   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5691     return 0;
5692   else
5693     return cp_tree_equal (ot, nt);
5694 }
5695
5696 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5697    of template arguments.  Returns 0 otherwise.  */
5698
5699 int
5700 comp_template_args (tree oldargs, tree newargs)
5701 {
5702   int i;
5703
5704   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5705     return 0;
5706
5707   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5708     {
5709       tree nt = TREE_VEC_ELT (newargs, i);
5710       tree ot = TREE_VEC_ELT (oldargs, i);
5711
5712       if (! template_args_equal (ot, nt))
5713         return 0;
5714     }
5715   return 1;
5716 }
5717
5718 static void
5719 add_pending_template (tree d)
5720 {
5721   tree ti = (TYPE_P (d)
5722              ? CLASSTYPE_TEMPLATE_INFO (d)
5723              : DECL_TEMPLATE_INFO (d));
5724   struct pending_template *pt;
5725   int level;
5726
5727   if (TI_PENDING_TEMPLATE_FLAG (ti))
5728     return;
5729
5730   /* We are called both from instantiate_decl, where we've already had a
5731      tinst_level pushed, and instantiate_template, where we haven't.
5732      Compensate.  */
5733   level = !current_tinst_level || current_tinst_level->decl != d;
5734
5735   if (level)
5736     push_tinst_level (d);
5737
5738   pt = GGC_NEW (struct pending_template);
5739   pt->next = NULL;
5740   pt->tinst = current_tinst_level;
5741   if (last_pending_template)
5742     last_pending_template->next = pt;
5743   else
5744     pending_templates = pt;
5745
5746   last_pending_template = pt;
5747
5748   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5749
5750   if (level)
5751     pop_tinst_level ();
5752 }
5753
5754
5755 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5756    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5757    documentation for TEMPLATE_ID_EXPR.  */
5758
5759 tree
5760 lookup_template_function (tree fns, tree arglist)
5761 {
5762   tree type;
5763
5764   if (fns == error_mark_node || arglist == error_mark_node)
5765     return error_mark_node;
5766
5767   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5768   gcc_assert (fns && (is_overloaded_fn (fns)
5769                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5770
5771   if (BASELINK_P (fns))
5772     {
5773       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5774                                          unknown_type_node,
5775                                          BASELINK_FUNCTIONS (fns),
5776                                          arglist);
5777       return fns;
5778     }
5779
5780   type = TREE_TYPE (fns);
5781   if (TREE_CODE (fns) == OVERLOAD || !type)
5782     type = unknown_type_node;
5783
5784   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5785 }
5786
5787 /* Within the scope of a template class S<T>, the name S gets bound
5788    (in build_self_reference) to a TYPE_DECL for the class, not a
5789    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5790    or one of its enclosing classes, and that type is a template,
5791    return the associated TEMPLATE_DECL.  Otherwise, the original
5792    DECL is returned.  */
5793
5794 tree
5795 maybe_get_template_decl_from_type_decl (tree decl)
5796 {
5797   return (decl != NULL_TREE
5798           && TREE_CODE (decl) == TYPE_DECL
5799           && DECL_ARTIFICIAL (decl)
5800           && CLASS_TYPE_P (TREE_TYPE (decl))
5801           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5802     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5803 }
5804
5805 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5806    parameters, find the desired type.
5807
5808    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5809
5810    IN_DECL, if non-NULL, is the template declaration we are trying to
5811    instantiate.
5812
5813    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5814    the class we are looking up.
5815
5816    Issue error and warning messages under control of COMPLAIN.
5817
5818    If the template class is really a local class in a template
5819    function, then the FUNCTION_CONTEXT is the function in which it is
5820    being instantiated.
5821
5822    ??? Note that this function is currently called *twice* for each
5823    template-id: the first time from the parser, while creating the
5824    incomplete type (finish_template_type), and the second type during the
5825    real instantiation (instantiate_template_class). This is surely something
5826    that we want to avoid. It also causes some problems with argument
5827    coercion (see convert_nontype_argument for more information on this).  */
5828
5829 tree
5830 lookup_template_class (tree d1,
5831                        tree arglist,
5832                        tree in_decl,
5833                        tree context,
5834                        int entering_scope,
5835                        tsubst_flags_t complain)
5836 {
5837   tree templ = NULL_TREE, parmlist;
5838   tree t;
5839   spec_entry **slot;
5840   spec_entry *entry;
5841   spec_entry elt;
5842   hashval_t hash;
5843
5844   timevar_push (TV_NAME_LOOKUP);
5845
5846   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5847     {
5848       tree value = innermost_non_namespace_value (d1);
5849       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5850         templ = value;
5851       else
5852         {
5853           if (context)
5854             push_decl_namespace (context);
5855           templ = lookup_name (d1);
5856           templ = maybe_get_template_decl_from_type_decl (templ);
5857           if (context)
5858             pop_decl_namespace ();
5859         }
5860       if (templ)
5861         context = DECL_CONTEXT (templ);
5862     }
5863   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5864     {
5865       tree type = TREE_TYPE (d1);
5866
5867       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5868          an implicit typename for the second A.  Deal with it.  */
5869       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5870         type = TREE_TYPE (type);
5871
5872       if (CLASSTYPE_TEMPLATE_INFO (type))
5873         {
5874           templ = CLASSTYPE_TI_TEMPLATE (type);
5875           d1 = DECL_NAME (templ);
5876         }
5877     }
5878   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5879            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5880     {
5881       templ = TYPE_TI_TEMPLATE (d1);
5882       d1 = DECL_NAME (templ);
5883     }
5884   else if (TREE_CODE (d1) == TEMPLATE_DECL
5885            && DECL_TEMPLATE_RESULT (d1)
5886            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5887     {
5888       templ = d1;
5889       d1 = DECL_NAME (templ);
5890       context = DECL_CONTEXT (templ);
5891     }
5892
5893   /* Issue an error message if we didn't find a template.  */
5894   if (! templ)
5895     {
5896       if (complain & tf_error)
5897         error ("%qT is not a template", d1);
5898       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5899     }
5900
5901   if (TREE_CODE (templ) != TEMPLATE_DECL
5902          /* Make sure it's a user visible template, if it was named by
5903             the user.  */
5904       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5905           && !PRIMARY_TEMPLATE_P (templ)))
5906     {
5907       if (complain & tf_error)
5908         {
5909           error ("non-template type %qT used as a template", d1);
5910           if (in_decl)
5911             error ("for template declaration %q+D", in_decl);
5912         }
5913       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5914     }
5915
5916   complain &= ~tf_user;
5917
5918   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5919     {
5920       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5921          template arguments */
5922
5923       tree parm;
5924       tree arglist2;
5925       tree outer;
5926
5927       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5928
5929       /* Consider an example where a template template parameter declared as
5930
5931            template <class T, class U = std::allocator<T> > class TT
5932
5933          The template parameter level of T and U are one level larger than
5934          of TT.  To proper process the default argument of U, say when an
5935          instantiation `TT<int>' is seen, we need to build the full
5936          arguments containing {int} as the innermost level.  Outer levels,
5937          available when not appearing as default template argument, can be
5938          obtained from the arguments of the enclosing template.
5939
5940          Suppose that TT is later substituted with std::vector.  The above
5941          instantiation is `TT<int, std::allocator<T> >' with TT at
5942          level 1, and T at level 2, while the template arguments at level 1
5943          becomes {std::vector} and the inner level 2 is {int}.  */
5944
5945       outer = DECL_CONTEXT (templ);
5946       if (outer)
5947         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5948       else if (current_template_parms)
5949         /* This is an argument of the current template, so we haven't set
5950            DECL_CONTEXT yet.  */
5951         outer = current_template_args ();
5952
5953       if (outer)
5954         arglist = add_to_template_args (outer, arglist);
5955
5956       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5957                                         complain,
5958                                         /*require_all_args=*/true,
5959                                         /*use_default_args=*/true);
5960       if (arglist2 == error_mark_node
5961           || (!uses_template_parms (arglist2)
5962               && check_instantiated_args (templ, arglist2, complain)))
5963         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5964
5965       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5966       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5967     }
5968   else
5969     {
5970       tree template_type = TREE_TYPE (templ);
5971       tree gen_tmpl;
5972       tree type_decl;
5973       tree found = NULL_TREE;
5974       int arg_depth;
5975       int parm_depth;
5976       int is_partial_instantiation;
5977
5978       gen_tmpl = most_general_template (templ);
5979       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5980       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5981       arg_depth = TMPL_ARGS_DEPTH (arglist);
5982
5983       if (arg_depth == 1 && parm_depth > 1)
5984         {
5985           /* We've been given an incomplete set of template arguments.
5986              For example, given:
5987
5988                template <class T> struct S1 {
5989                  template <class U> struct S2 {};
5990                  template <class U> struct S2<U*> {};
5991                 };
5992
5993              we will be called with an ARGLIST of `U*', but the
5994              TEMPLATE will be `template <class T> template
5995              <class U> struct S1<T>::S2'.  We must fill in the missing
5996              arguments.  */
5997           arglist
5998             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5999                                            arglist);
6000           arg_depth = TMPL_ARGS_DEPTH (arglist);
6001         }
6002
6003       /* Now we should have enough arguments.  */
6004       gcc_assert (parm_depth == arg_depth);
6005
6006       /* From here on, we're only interested in the most general
6007          template.  */
6008
6009       /* Calculate the BOUND_ARGS.  These will be the args that are
6010          actually tsubst'd into the definition to create the
6011          instantiation.  */
6012       if (parm_depth > 1)
6013         {
6014           /* We have multiple levels of arguments to coerce, at once.  */
6015           int i;
6016           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6017
6018           tree bound_args = make_tree_vec (parm_depth);
6019
6020           for (i = saved_depth,
6021                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6022                i > 0 && t != NULL_TREE;
6023                --i, t = TREE_CHAIN (t))
6024             {
6025               tree a = coerce_template_parms (TREE_VALUE (t),
6026                                               arglist, gen_tmpl,
6027                                               complain,
6028                                               /*require_all_args=*/true,
6029                                               /*use_default_args=*/true);
6030
6031               /* Don't process further if one of the levels fails.  */
6032               if (a == error_mark_node)
6033                 {
6034                   /* Restore the ARGLIST to its full size.  */
6035                   TREE_VEC_LENGTH (arglist) = saved_depth;
6036                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6037                 }
6038
6039               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6040
6041               /* We temporarily reduce the length of the ARGLIST so
6042                  that coerce_template_parms will see only the arguments
6043                  corresponding to the template parameters it is
6044                  examining.  */
6045               TREE_VEC_LENGTH (arglist)--;
6046             }
6047
6048           /* Restore the ARGLIST to its full size.  */
6049           TREE_VEC_LENGTH (arglist) = saved_depth;
6050
6051           arglist = bound_args;
6052         }
6053       else
6054         arglist
6055           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6056                                    INNERMOST_TEMPLATE_ARGS (arglist),
6057                                    gen_tmpl,
6058                                    complain,
6059                                    /*require_all_args=*/true,
6060                                    /*use_default_args=*/true);
6061
6062       if (arglist == error_mark_node)
6063         /* We were unable to bind the arguments.  */
6064         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6065
6066       /* In the scope of a template class, explicit references to the
6067          template class refer to the type of the template, not any
6068          instantiation of it.  For example, in:
6069
6070            template <class T> class C { void f(C<T>); }
6071
6072          the `C<T>' is just the same as `C'.  Outside of the
6073          class, however, such a reference is an instantiation.  */
6074       if ((entering_scope
6075            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6076            || currently_open_class (template_type))
6077           /* comp_template_args is expensive, check it last.  */
6078           && comp_template_args (TYPE_TI_ARGS (template_type),
6079                                  arglist))
6080         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6081
6082       /* If we already have this specialization, return it.  */
6083       elt.tmpl = gen_tmpl;
6084       elt.args = arglist;
6085       hash = hash_specialization (&elt);
6086       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6087                                                   &elt, hash);
6088
6089       if (entry)
6090         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6091
6092       /* This type is a "partial instantiation" if any of the template
6093          arguments still involve template parameters.  Note that we set
6094          IS_PARTIAL_INSTANTIATION for partial specializations as
6095          well.  */
6096       is_partial_instantiation = uses_template_parms (arglist);
6097
6098       /* If the deduced arguments are invalid, then the binding
6099          failed.  */
6100       if (!is_partial_instantiation
6101           && check_instantiated_args (gen_tmpl,
6102                                       INNERMOST_TEMPLATE_ARGS (arglist),
6103                                       complain))
6104         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6105
6106       if (!is_partial_instantiation
6107           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6108           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6109         {
6110           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6111                                       DECL_NAME (gen_tmpl),
6112                                       /*tag_scope=*/ts_global);
6113           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6114         }
6115
6116       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6117                         complain, in_decl);
6118       if (!context)
6119         context = global_namespace;
6120
6121       /* Create the type.  */
6122       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6123         {
6124           if (!is_partial_instantiation)
6125             {
6126               set_current_access_from_decl (TYPE_NAME (template_type));
6127               t = start_enum (TYPE_IDENTIFIER (template_type),
6128                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6129                                       arglist, complain, in_decl),
6130                               SCOPED_ENUM_P (template_type));
6131             }
6132           else
6133             {
6134               /* We don't want to call start_enum for this type, since
6135                  the values for the enumeration constants may involve
6136                  template parameters.  And, no one should be interested
6137                  in the enumeration constants for such a type.  */
6138               t = make_node (ENUMERAL_TYPE);
6139               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6140             }
6141         }
6142       else
6143         {
6144           t = make_class_type (TREE_CODE (template_type));
6145           CLASSTYPE_DECLARED_CLASS (t)
6146             = CLASSTYPE_DECLARED_CLASS (template_type);
6147           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6148           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6149
6150           /* A local class.  Make sure the decl gets registered properly.  */
6151           if (context == current_function_decl)
6152             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6153
6154           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6155             /* This instantiation is another name for the primary
6156                template type. Set the TYPE_CANONICAL field
6157                appropriately. */
6158             TYPE_CANONICAL (t) = template_type;
6159           else if (any_template_arguments_need_structural_equality_p (arglist))
6160             /* Some of the template arguments require structural
6161                equality testing, so this template class requires
6162                structural equality testing. */
6163             SET_TYPE_STRUCTURAL_EQUALITY (t);
6164         }
6165
6166       /* If we called start_enum or pushtag above, this information
6167          will already be set up.  */
6168       if (!TYPE_NAME (t))
6169         {
6170           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6171
6172           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6173           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6174           TYPE_STUB_DECL (t) = type_decl;
6175           DECL_SOURCE_LOCATION (type_decl)
6176             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6177         }
6178       else
6179         type_decl = TYPE_NAME (t);
6180
6181       TREE_PRIVATE (type_decl)
6182         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6183       TREE_PROTECTED (type_decl)
6184         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6185       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6186         {
6187           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6188           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6189         }
6190
6191       /* Set up the template information.  We have to figure out which
6192          template is the immediate parent if this is a full
6193          instantiation.  */
6194       if (parm_depth == 1 || is_partial_instantiation
6195           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6196         /* This case is easy; there are no member templates involved.  */
6197         found = gen_tmpl;
6198       else
6199         {
6200           /* This is a full instantiation of a member template.  Find
6201              the partial instantiation of which this is an instance.  */
6202
6203           /* Temporarily reduce by one the number of levels in the ARGLIST
6204              so as to avoid comparing the last set of arguments.  */
6205           TREE_VEC_LENGTH (arglist)--;
6206           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6207           TREE_VEC_LENGTH (arglist)++;
6208           found = CLASSTYPE_TI_TEMPLATE (found);
6209         }
6210
6211       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6212
6213       elt.spec = t;
6214       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6215                                                        &elt, hash, INSERT);
6216       *slot = GGC_NEW (spec_entry);
6217       **slot = elt;
6218
6219       /* Note this use of the partial instantiation so we can check it
6220          later in maybe_process_partial_specialization.  */
6221       DECL_TEMPLATE_INSTANTIATIONS (templ)
6222         = tree_cons (arglist, t,
6223                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6224
6225       if (TREE_CODE (t) == ENUMERAL_TYPE
6226           && !is_partial_instantiation)
6227         /* Now that the type has been registered on the instantiations
6228            list, we set up the enumerators.  Because the enumeration
6229            constants may involve the enumeration type itself, we make
6230            sure to register the type first, and then create the
6231            constants.  That way, doing tsubst_expr for the enumeration
6232            constants won't result in recursive calls here; we'll find
6233            the instantiation and exit above.  */
6234         tsubst_enum (template_type, t, arglist);
6235
6236       if (is_partial_instantiation)
6237         /* If the type makes use of template parameters, the
6238            code that generates debugging information will crash.  */
6239         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6240
6241       /* Possibly limit visibility based on template args.  */
6242       TREE_PUBLIC (type_decl) = 1;
6243       determine_visibility (type_decl);
6244
6245       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6246     }
6247   timevar_pop (TV_NAME_LOOKUP);
6248 }
6249 \f
6250 struct pair_fn_data
6251 {
6252   tree_fn_t fn;
6253   void *data;
6254   /* True when we should also visit template parameters that occur in
6255      non-deduced contexts.  */
6256   bool include_nondeduced_p;
6257   struct pointer_set_t *visited;
6258 };
6259
6260 /* Called from for_each_template_parm via walk_tree.  */
6261
6262 static tree
6263 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6264 {
6265   tree t = *tp;
6266   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6267   tree_fn_t fn = pfd->fn;
6268   void *data = pfd->data;
6269
6270   if (TYPE_P (t)
6271       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6272       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6273                                  pfd->include_nondeduced_p))
6274     return error_mark_node;
6275
6276   switch (TREE_CODE (t))
6277     {
6278     case RECORD_TYPE:
6279       if (TYPE_PTRMEMFUNC_P (t))
6280         break;
6281       /* Fall through.  */
6282
6283     case UNION_TYPE:
6284     case ENUMERAL_TYPE:
6285       if (!TYPE_TEMPLATE_INFO (t))
6286         *walk_subtrees = 0;
6287       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6288                                        fn, data, pfd->visited, 
6289                                        pfd->include_nondeduced_p))
6290         return error_mark_node;
6291       break;
6292
6293     case INTEGER_TYPE:
6294       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6295                                   fn, data, pfd->visited, 
6296                                   pfd->include_nondeduced_p)
6297           || for_each_template_parm (TYPE_MAX_VALUE (t),
6298                                      fn, data, pfd->visited,
6299                                      pfd->include_nondeduced_p))
6300         return error_mark_node;
6301       break;
6302
6303     case METHOD_TYPE:
6304       /* Since we're not going to walk subtrees, we have to do this
6305          explicitly here.  */
6306       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6307                                   pfd->visited, pfd->include_nondeduced_p))
6308         return error_mark_node;
6309       /* Fall through.  */
6310
6311     case FUNCTION_TYPE:
6312       /* Check the return type.  */
6313       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6314                                   pfd->include_nondeduced_p))
6315         return error_mark_node;
6316
6317       /* Check the parameter types.  Since default arguments are not
6318          instantiated until they are needed, the TYPE_ARG_TYPES may
6319          contain expressions that involve template parameters.  But,
6320          no-one should be looking at them yet.  And, once they're
6321          instantiated, they don't contain template parameters, so
6322          there's no point in looking at them then, either.  */
6323       {
6324         tree parm;
6325
6326         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6327           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6328                                       pfd->visited, pfd->include_nondeduced_p))
6329             return error_mark_node;
6330
6331         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6332            want walk_tree walking into them itself.  */
6333         *walk_subtrees = 0;
6334       }
6335       break;
6336
6337     case TYPEOF_TYPE:
6338       if (pfd->include_nondeduced_p
6339           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6340                                      pfd->visited, 
6341                                      pfd->include_nondeduced_p))
6342         return error_mark_node;
6343       break;
6344
6345     case FUNCTION_DECL:
6346     case VAR_DECL:
6347       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6348           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6349                                      pfd->visited, pfd->include_nondeduced_p))
6350         return error_mark_node;
6351       /* Fall through.  */
6352
6353     case PARM_DECL:
6354     case CONST_DECL:
6355       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6356           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6357                                      pfd->visited, pfd->include_nondeduced_p))
6358         return error_mark_node;
6359       if (DECL_CONTEXT (t)
6360           && pfd->include_nondeduced_p
6361           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6362                                      pfd->visited, pfd->include_nondeduced_p))
6363         return error_mark_node;
6364       break;
6365
6366     case BOUND_TEMPLATE_TEMPLATE_PARM:
6367       /* Record template parameters such as `T' inside `TT<T>'.  */
6368       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6369                                   pfd->include_nondeduced_p))
6370         return error_mark_node;
6371       /* Fall through.  */
6372
6373     case TEMPLATE_TEMPLATE_PARM:
6374     case TEMPLATE_TYPE_PARM:
6375     case TEMPLATE_PARM_INDEX:
6376       if (fn && (*fn)(t, data))
6377         return error_mark_node;
6378       else if (!fn)
6379         return error_mark_node;
6380       break;
6381
6382     case TEMPLATE_DECL:
6383       /* A template template parameter is encountered.  */
6384       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6385           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6386                                      pfd->include_nondeduced_p))
6387         return error_mark_node;
6388
6389       /* Already substituted template template parameter */
6390       *walk_subtrees = 0;
6391       break;
6392
6393     case TYPENAME_TYPE:
6394       if (!fn
6395           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6396                                      data, pfd->visited, 
6397                                      pfd->include_nondeduced_p))
6398         return error_mark_node;
6399       break;
6400
6401     case CONSTRUCTOR:
6402       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6403           && pfd->include_nondeduced_p
6404           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6405                                      (TREE_TYPE (t)), fn, data,
6406                                      pfd->visited, pfd->include_nondeduced_p))
6407         return error_mark_node;
6408       break;
6409
6410     case INDIRECT_REF:
6411     case COMPONENT_REF:
6412       /* If there's no type, then this thing must be some expression
6413          involving template parameters.  */
6414       if (!fn && !TREE_TYPE (t))
6415         return error_mark_node;
6416       break;
6417
6418     case MODOP_EXPR:
6419     case CAST_EXPR:
6420     case REINTERPRET_CAST_EXPR:
6421     case CONST_CAST_EXPR:
6422     case STATIC_CAST_EXPR:
6423     case DYNAMIC_CAST_EXPR:
6424     case ARROW_EXPR:
6425     case DOTSTAR_EXPR:
6426     case TYPEID_EXPR:
6427     case PSEUDO_DTOR_EXPR:
6428       if (!fn)
6429         return error_mark_node;
6430       break;
6431
6432     default:
6433       break;
6434     }
6435
6436   /* We didn't find any template parameters we liked.  */
6437   return NULL_TREE;
6438 }
6439
6440 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6441    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6442    call FN with the parameter and the DATA.
6443    If FN returns nonzero, the iteration is terminated, and
6444    for_each_template_parm returns 1.  Otherwise, the iteration
6445    continues.  If FN never returns a nonzero value, the value
6446    returned by for_each_template_parm is 0.  If FN is NULL, it is
6447    considered to be the function which always returns 1.
6448
6449    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6450    parameters that occur in non-deduced contexts.  When false, only
6451    visits those template parameters that can be deduced.  */
6452
6453 static int
6454 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6455                         struct pointer_set_t *visited,
6456                         bool include_nondeduced_p)
6457 {
6458   struct pair_fn_data pfd;
6459   int result;
6460
6461   /* Set up.  */
6462   pfd.fn = fn;
6463   pfd.data = data;
6464   pfd.include_nondeduced_p = include_nondeduced_p;
6465
6466   /* Walk the tree.  (Conceptually, we would like to walk without
6467      duplicates, but for_each_template_parm_r recursively calls
6468      for_each_template_parm, so we would need to reorganize a fair
6469      bit to use walk_tree_without_duplicates, so we keep our own
6470      visited list.)  */
6471   if (visited)
6472     pfd.visited = visited;
6473   else
6474     pfd.visited = pointer_set_create ();
6475   result = cp_walk_tree (&t,
6476                          for_each_template_parm_r,
6477                          &pfd,
6478                          pfd.visited) != NULL_TREE;
6479
6480   /* Clean up.  */
6481   if (!visited)
6482     {
6483       pointer_set_destroy (pfd.visited);
6484       pfd.visited = 0;
6485     }
6486
6487   return result;
6488 }
6489
6490 /* Returns true if T depends on any template parameter.  */
6491
6492 int
6493 uses_template_parms (tree t)
6494 {
6495   bool dependent_p;
6496   int saved_processing_template_decl;
6497
6498   saved_processing_template_decl = processing_template_decl;
6499   if (!saved_processing_template_decl)
6500     processing_template_decl = 1;
6501   if (TYPE_P (t))
6502     dependent_p = dependent_type_p (t);
6503   else if (TREE_CODE (t) == TREE_VEC)
6504     dependent_p = any_dependent_template_arguments_p (t);
6505   else if (TREE_CODE (t) == TREE_LIST)
6506     dependent_p = (uses_template_parms (TREE_VALUE (t))
6507                    || uses_template_parms (TREE_CHAIN (t)));
6508   else if (TREE_CODE (t) == TYPE_DECL)
6509     dependent_p = dependent_type_p (TREE_TYPE (t));
6510   else if (DECL_P (t)
6511            || EXPR_P (t)
6512            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6513            || TREE_CODE (t) == OVERLOAD
6514            || TREE_CODE (t) == BASELINK
6515            || TREE_CODE (t) == IDENTIFIER_NODE
6516            || TREE_CODE (t) == TRAIT_EXPR
6517            || TREE_CODE (t) == CONSTRUCTOR
6518            || CONSTANT_CLASS_P (t))
6519     dependent_p = (type_dependent_expression_p (t)
6520                    || value_dependent_expression_p (t));
6521   else
6522     {
6523       gcc_assert (t == error_mark_node);
6524       dependent_p = false;
6525     }
6526
6527   processing_template_decl = saved_processing_template_decl;
6528
6529   return dependent_p;
6530 }
6531
6532 /* Returns true if T depends on any template parameter with level LEVEL.  */
6533
6534 int
6535 uses_template_parms_level (tree t, int level)
6536 {
6537   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6538                                  /*include_nondeduced_p=*/true);
6539 }
6540
6541 static int tinst_depth;
6542 extern int max_tinst_depth;
6543 #ifdef GATHER_STATISTICS
6544 int depth_reached;
6545 #endif
6546 static int tinst_level_tick;
6547 static int last_template_error_tick;
6548
6549 /* We're starting to instantiate D; record the template instantiation context
6550    for diagnostics and to restore it later.  */
6551
6552 static int
6553 push_tinst_level (tree d)
6554 {
6555   struct tinst_level *new_level;
6556
6557   if (tinst_depth >= max_tinst_depth)
6558     {
6559       /* If the instantiation in question still has unbound template parms,
6560          we don't really care if we can't instantiate it, so just return.
6561          This happens with base instantiation for implicit `typename'.  */
6562       if (uses_template_parms (d))
6563         return 0;
6564
6565       last_template_error_tick = tinst_level_tick;
6566       error ("template instantiation depth exceeds maximum of %d (use "
6567              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6568              max_tinst_depth, d);
6569
6570       print_instantiation_context ();
6571
6572       return 0;
6573     }
6574
6575   new_level = GGC_NEW (struct tinst_level);
6576   new_level->decl = d;
6577   new_level->locus = input_location;
6578   new_level->in_system_header_p = in_system_header;
6579   new_level->next = current_tinst_level;
6580   current_tinst_level = new_level;
6581
6582   ++tinst_depth;
6583 #ifdef GATHER_STATISTICS
6584   if (tinst_depth > depth_reached)
6585     depth_reached = tinst_depth;
6586 #endif
6587
6588   ++tinst_level_tick;
6589   return 1;
6590 }
6591
6592 /* We're done instantiating this template; return to the instantiation
6593    context.  */
6594
6595 static void
6596 pop_tinst_level (void)
6597 {
6598   /* Restore the filename and line number stashed away when we started
6599      this instantiation.  */
6600   input_location = current_tinst_level->locus;
6601   current_tinst_level = current_tinst_level->next;
6602   --tinst_depth;
6603   ++tinst_level_tick;
6604 }
6605
6606 /* We're instantiating a deferred template; restore the template
6607    instantiation context in which the instantiation was requested, which
6608    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6609
6610 static tree
6611 reopen_tinst_level (struct tinst_level *level)
6612 {
6613   struct tinst_level *t;
6614
6615   tinst_depth = 0;
6616   for (t = level; t; t = t->next)
6617     ++tinst_depth;
6618
6619   current_tinst_level = level;
6620   pop_tinst_level ();
6621   return level->decl;
6622 }
6623
6624 /* Returns the TINST_LEVEL which gives the original instantiation
6625    context.  */
6626
6627 struct tinst_level *
6628 outermost_tinst_level (void)
6629 {
6630   struct tinst_level *level = current_tinst_level;
6631   if (level)
6632     while (level->next)
6633       level = level->next;
6634   return level;
6635 }
6636
6637 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6638
6639 bool
6640 parameter_of_template_p (tree parm, tree templ)
6641 {
6642   tree parms;
6643   int i;
6644
6645   if (!parm || !templ)
6646     return false;
6647
6648   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6649   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6650
6651   parms = DECL_TEMPLATE_PARMS (templ);
6652   parms = INNERMOST_TEMPLATE_PARMS (parms);
6653
6654   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6655     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6656       return true;
6657
6658   return false;
6659 }
6660
6661 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6662    vector of template arguments, as for tsubst.
6663
6664    Returns an appropriate tsubst'd friend declaration.  */
6665
6666 static tree
6667 tsubst_friend_function (tree decl, tree args)
6668 {
6669   tree new_friend;
6670
6671   if (TREE_CODE (decl) == FUNCTION_DECL
6672       && DECL_TEMPLATE_INSTANTIATION (decl)
6673       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6674     /* This was a friend declared with an explicit template
6675        argument list, e.g.:
6676
6677        friend void f<>(T);
6678
6679        to indicate that f was a template instantiation, not a new
6680        function declaration.  Now, we have to figure out what
6681        instantiation of what template.  */
6682     {
6683       tree template_id, arglist, fns;
6684       tree new_args;
6685       tree tmpl;
6686       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6687
6688       /* Friend functions are looked up in the containing namespace scope.
6689          We must enter that scope, to avoid finding member functions of the
6690          current class with same name.  */
6691       push_nested_namespace (ns);
6692       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6693                          tf_warning_or_error, NULL_TREE,
6694                          /*integral_constant_expression_p=*/false);
6695       pop_nested_namespace (ns);
6696       arglist = tsubst (DECL_TI_ARGS (decl), args,
6697                         tf_warning_or_error, NULL_TREE);
6698       template_id = lookup_template_function (fns, arglist);
6699
6700       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6701       tmpl = determine_specialization (template_id, new_friend,
6702                                        &new_args,
6703                                        /*need_member_template=*/0,
6704                                        TREE_VEC_LENGTH (args),
6705                                        tsk_none);
6706       return instantiate_template (tmpl, new_args, tf_error);
6707     }
6708
6709   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6710
6711   /* The NEW_FRIEND will look like an instantiation, to the
6712      compiler, but is not an instantiation from the point of view of
6713      the language.  For example, we might have had:
6714
6715      template <class T> struct S {
6716        template <class U> friend void f(T, U);
6717      };
6718
6719      Then, in S<int>, template <class U> void f(int, U) is not an
6720      instantiation of anything.  */
6721   if (new_friend == error_mark_node)
6722     return error_mark_node;
6723
6724   DECL_USE_TEMPLATE (new_friend) = 0;
6725   if (TREE_CODE (decl) == TEMPLATE_DECL)
6726     {
6727       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6728       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6729         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6730     }
6731
6732   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6733      is not a template instantiation and should not be mangled like
6734      one.  Therefore, we forget the mangling here; we'll recompute it
6735      later if we need it.  */
6736   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6737     {
6738       SET_DECL_RTL (new_friend, NULL_RTX);
6739       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6740     }
6741
6742   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6743     {
6744       tree old_decl;
6745       tree new_friend_template_info;
6746       tree new_friend_result_template_info;
6747       tree ns;
6748       int  new_friend_is_defn;
6749
6750       /* We must save some information from NEW_FRIEND before calling
6751          duplicate decls since that function will free NEW_FRIEND if
6752          possible.  */
6753       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6754       new_friend_is_defn =
6755             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6756                            (template_for_substitution (new_friend)))
6757              != NULL_TREE);
6758       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6759         {
6760           /* This declaration is a `primary' template.  */
6761           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6762
6763           new_friend_result_template_info
6764             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6765         }
6766       else
6767         new_friend_result_template_info = NULL_TREE;
6768
6769       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6770       if (new_friend_is_defn)
6771         DECL_INITIAL (new_friend) = error_mark_node;
6772
6773       /* Inside pushdecl_namespace_level, we will push into the
6774          current namespace. However, the friend function should go
6775          into the namespace of the template.  */
6776       ns = decl_namespace_context (new_friend);
6777       push_nested_namespace (ns);
6778       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6779       pop_nested_namespace (ns);
6780
6781       if (old_decl == error_mark_node)
6782         return error_mark_node;
6783
6784       if (old_decl != new_friend)
6785         {
6786           /* This new friend declaration matched an existing
6787              declaration.  For example, given:
6788
6789                template <class T> void f(T);
6790                template <class U> class C {
6791                  template <class T> friend void f(T) {}
6792                };
6793
6794              the friend declaration actually provides the definition
6795              of `f', once C has been instantiated for some type.  So,
6796              old_decl will be the out-of-class template declaration,
6797              while new_friend is the in-class definition.
6798
6799              But, if `f' was called before this point, the
6800              instantiation of `f' will have DECL_TI_ARGS corresponding
6801              to `T' but not to `U', references to which might appear
6802              in the definition of `f'.  Previously, the most general
6803              template for an instantiation of `f' was the out-of-class
6804              version; now it is the in-class version.  Therefore, we
6805              run through all specialization of `f', adding to their
6806              DECL_TI_ARGS appropriately.  In particular, they need a
6807              new set of outer arguments, corresponding to the
6808              arguments for this class instantiation.
6809
6810              The same situation can arise with something like this:
6811
6812                friend void f(int);
6813                template <class T> class C {
6814                  friend void f(T) {}
6815                };
6816
6817              when `C<int>' is instantiated.  Now, `f(int)' is defined
6818              in the class.  */
6819
6820           if (!new_friend_is_defn)
6821             /* On the other hand, if the in-class declaration does
6822                *not* provide a definition, then we don't want to alter
6823                existing definitions.  We can just leave everything
6824                alone.  */
6825             ;
6826           else
6827             {
6828               tree new_template = TI_TEMPLATE (new_friend_template_info);
6829               tree new_args = TI_ARGS (new_friend_template_info);
6830
6831               /* Overwrite whatever template info was there before, if
6832                  any, with the new template information pertaining to
6833                  the declaration.  */
6834               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6835
6836               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6837                 /* We should have called reregister_specialization in
6838                    duplicate_decls.  */
6839                 gcc_assert (retrieve_specialization (new_template,
6840                                                      new_args, 0)
6841                             == old_decl);
6842               else
6843                 {
6844                   tree t;
6845
6846                   /* Indicate that the old function template is a partial
6847                      instantiation.  */
6848                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6849                     = new_friend_result_template_info;
6850
6851                   gcc_assert (new_template
6852                               == most_general_template (new_template));
6853                   gcc_assert (new_template != old_decl);
6854
6855                   /* Reassign any specializations already in the hash table
6856                      to the new more general template, and add the
6857                      additional template args.  */
6858                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
6859                        t != NULL_TREE;
6860                        t = TREE_CHAIN (t))
6861                     {
6862                       tree spec = TREE_VALUE (t);
6863                       spec_entry elt;
6864
6865                       elt.tmpl = old_decl;
6866                       elt.args = DECL_TI_ARGS (spec);
6867                       elt.spec = NULL_TREE;
6868
6869                       htab_remove_elt (decl_specializations, &elt);
6870
6871                       DECL_TI_ARGS (spec)
6872                         = add_outermost_template_args (new_args,
6873                                                        DECL_TI_ARGS (spec));
6874
6875                       register_specialization
6876                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
6877
6878                     }
6879                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
6880                 }
6881             }
6882
6883           /* The information from NEW_FRIEND has been merged into OLD_DECL
6884              by duplicate_decls.  */
6885           new_friend = old_decl;
6886         }
6887     }
6888   else
6889     {
6890       tree context = DECL_CONTEXT (new_friend);
6891       bool dependent_p;
6892
6893       /* In the code
6894            template <class T> class C {
6895              template <class U> friend void C1<U>::f (); // case 1
6896              friend void C2<T>::f ();                    // case 2
6897            };
6898          we only need to make sure CONTEXT is a complete type for
6899          case 2.  To distinguish between the two cases, we note that
6900          CONTEXT of case 1 remains dependent type after tsubst while
6901          this isn't true for case 2.  */
6902       ++processing_template_decl;
6903       dependent_p = dependent_type_p (context);
6904       --processing_template_decl;
6905
6906       if (!dependent_p
6907           && !complete_type_or_else (context, NULL_TREE))
6908         return error_mark_node;
6909
6910       if (COMPLETE_TYPE_P (context))
6911         {
6912           /* Check to see that the declaration is really present, and,
6913              possibly obtain an improved declaration.  */
6914           tree fn = check_classfn (context,
6915                                    new_friend, NULL_TREE);
6916
6917           if (fn)
6918             new_friend = fn;
6919         }
6920     }
6921
6922   return new_friend;
6923 }
6924
6925 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6926    template arguments, as for tsubst.
6927
6928    Returns an appropriate tsubst'd friend type or error_mark_node on
6929    failure.  */
6930
6931 static tree
6932 tsubst_friend_class (tree friend_tmpl, tree args)
6933 {
6934   tree friend_type;
6935   tree tmpl;
6936   tree context;
6937
6938   context = DECL_CONTEXT (friend_tmpl);
6939
6940   if (context)
6941     {
6942       if (TREE_CODE (context) == NAMESPACE_DECL)
6943         push_nested_namespace (context);
6944       else
6945         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6946     }
6947
6948   /* Look for a class template declaration.  We look for hidden names
6949      because two friend declarations of the same template are the
6950      same.  For example, in:
6951
6952        struct A { 
6953          template <typename> friend class F;
6954        };
6955        template <typename> struct B { 
6956          template <typename> friend class F;
6957        };
6958
6959      both F templates are the same.  */
6960   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6961                            /*block_p=*/true, 0, 
6962                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6963
6964   /* But, if we don't find one, it might be because we're in a
6965      situation like this:
6966
6967        template <class T>
6968        struct S {
6969          template <class U>
6970          friend struct S;
6971        };
6972
6973      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6974      for `S<int>', not the TEMPLATE_DECL.  */
6975   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6976     {
6977       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6978       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6979     }
6980
6981   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6982     {
6983       /* The friend template has already been declared.  Just
6984          check to see that the declarations match, and install any new
6985          default parameters.  We must tsubst the default parameters,
6986          of course.  We only need the innermost template parameters
6987          because that is all that redeclare_class_template will look
6988          at.  */
6989       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6990           > TMPL_ARGS_DEPTH (args))
6991         {
6992           tree parms;
6993           location_t saved_input_location;
6994           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6995                                          args, tf_warning_or_error);
6996
6997           saved_input_location = input_location;
6998           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6999           redeclare_class_template (TREE_TYPE (tmpl), parms);
7000           input_location = saved_input_location;
7001           
7002         }
7003
7004       friend_type = TREE_TYPE (tmpl);
7005     }
7006   else
7007     {
7008       /* The friend template has not already been declared.  In this
7009          case, the instantiation of the template class will cause the
7010          injection of this template into the global scope.  */
7011       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7012       if (tmpl == error_mark_node)
7013         return error_mark_node;
7014
7015       /* The new TMPL is not an instantiation of anything, so we
7016          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7017          the new type because that is supposed to be the corresponding
7018          template decl, i.e., TMPL.  */
7019       DECL_USE_TEMPLATE (tmpl) = 0;
7020       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7021       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7022       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7023         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7024
7025       /* Inject this template into the global scope.  */
7026       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7027     }
7028
7029   if (context)
7030     {
7031       if (TREE_CODE (context) == NAMESPACE_DECL)
7032         pop_nested_namespace (context);
7033       else
7034         pop_nested_class ();
7035     }
7036
7037   return friend_type;
7038 }
7039
7040 /* Returns zero if TYPE cannot be completed later due to circularity.
7041    Otherwise returns one.  */
7042
7043 static int
7044 can_complete_type_without_circularity (tree type)
7045 {
7046   if (type == NULL_TREE || type == error_mark_node)
7047     return 0;
7048   else if (COMPLETE_TYPE_P (type))
7049     return 1;
7050   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7051     return can_complete_type_without_circularity (TREE_TYPE (type));
7052   else if (CLASS_TYPE_P (type)
7053            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7054     return 0;
7055   else
7056     return 1;
7057 }
7058
7059 /* Apply any attributes which had to be deferred until instantiation
7060    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7061    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7062
7063 static void
7064 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7065                                 tree args, tsubst_flags_t complain, tree in_decl)
7066 {
7067   tree last_dep = NULL_TREE;
7068   tree t;
7069   tree *p;
7070
7071   for (t = attributes; t; t = TREE_CHAIN (t))
7072     if (ATTR_IS_DEPENDENT (t))
7073       {
7074         last_dep = t;
7075         attributes = copy_list (attributes);
7076         break;
7077       }
7078
7079   if (DECL_P (*decl_p))
7080     {
7081       if (TREE_TYPE (*decl_p) == error_mark_node)
7082         return;
7083       p = &DECL_ATTRIBUTES (*decl_p);
7084     }
7085   else
7086     p = &TYPE_ATTRIBUTES (*decl_p);
7087
7088   if (last_dep)
7089     {
7090       tree late_attrs = NULL_TREE;
7091       tree *q = &late_attrs;
7092
7093       for (*p = attributes; *p; )
7094         {
7095           t = *p;
7096           if (ATTR_IS_DEPENDENT (t))
7097             {
7098               *p = TREE_CHAIN (t);
7099               TREE_CHAIN (t) = NULL_TREE;
7100               /* If the first attribute argument is an identifier, don't
7101                  pass it through tsubst.  Attributes like mode, format,
7102                  cleanup and several target specific attributes expect it
7103                  unmodified.  */
7104               if (TREE_VALUE (t)
7105                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7106                   && TREE_VALUE (TREE_VALUE (t))
7107                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7108                       == IDENTIFIER_NODE))
7109                 {
7110                   tree chain
7111                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7112                                    in_decl,
7113                                    /*integral_constant_expression_p=*/false);
7114                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7115                     TREE_VALUE (t)
7116                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7117                                    chain);
7118                 }
7119               else
7120                 TREE_VALUE (t)
7121                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7122                                  /*integral_constant_expression_p=*/false);
7123               *q = t;
7124               q = &TREE_CHAIN (t);
7125             }
7126           else
7127             p = &TREE_CHAIN (t);
7128         }
7129
7130       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7131     }
7132 }
7133
7134 /* Perform (or defer) access check for typedefs that were referenced
7135    from within the template TMPL code.
7136    This is a subroutine of instantiate_template and instantiate_class_template.
7137    TMPL is the template to consider and TARGS is the list of arguments of
7138    that template.  */
7139
7140 static void
7141 perform_typedefs_access_check (tree tmpl, tree targs)
7142 {
7143   tree t;
7144
7145   if (!tmpl
7146       || (!CLASS_TYPE_P (tmpl)
7147           && TREE_CODE (tmpl) != FUNCTION_DECL))
7148     return;
7149
7150   for (t = get_types_needing_access_check (tmpl); t; t = TREE_CHAIN (t))
7151     {
7152       tree type_decl = TREE_PURPOSE (t);
7153       tree type_scope = TREE_VALUE (t);
7154
7155       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7156         continue;
7157
7158       if (uses_template_parms (type_decl))
7159         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7160       if (uses_template_parms (type_scope))
7161         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7162
7163       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7164                                      type_decl, type_decl);
7165     }
7166 }
7167
7168 tree
7169 instantiate_class_template (tree type)
7170 {
7171   tree templ, args, pattern, t, member;
7172   tree typedecl;
7173   tree pbinfo;
7174   tree base_list;
7175
7176   if (type == error_mark_node)
7177     return error_mark_node;
7178
7179   if (TYPE_BEING_DEFINED (type)
7180       || COMPLETE_TYPE_P (type)
7181       || dependent_type_p (type))
7182     return type;
7183
7184   /* Figure out which template is being instantiated.  */
7185   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7186   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7187
7188   /* Determine what specialization of the original template to
7189      instantiate.  */
7190   t = most_specialized_class (type, templ);
7191   if (t == error_mark_node)
7192     {
7193       TYPE_BEING_DEFINED (type) = 1;
7194       return error_mark_node;
7195     }
7196   else if (t)
7197     {
7198       /* This TYPE is actually an instantiation of a partial
7199          specialization.  We replace the innermost set of ARGS with
7200          the arguments appropriate for substitution.  For example,
7201          given:
7202
7203            template <class T> struct S {};
7204            template <class T> struct S<T*> {};
7205
7206          and supposing that we are instantiating S<int*>, ARGS will
7207          presently be {int*} -- but we need {int}.  */
7208       pattern = TREE_TYPE (t);
7209       args = TREE_PURPOSE (t);
7210     }
7211   else
7212     {
7213       pattern = TREE_TYPE (templ);
7214       args = CLASSTYPE_TI_ARGS (type);
7215     }
7216
7217   /* If the template we're instantiating is incomplete, then clearly
7218      there's nothing we can do.  */
7219   if (!COMPLETE_TYPE_P (pattern))
7220     return type;
7221
7222   /* If we've recursively instantiated too many templates, stop.  */
7223   if (! push_tinst_level (type))
7224     return type;
7225
7226   /* Now we're really doing the instantiation.  Mark the type as in
7227      the process of being defined.  */
7228   TYPE_BEING_DEFINED (type) = 1;
7229
7230   /* We may be in the middle of deferred access check.  Disable
7231      it now.  */
7232   push_deferring_access_checks (dk_no_deferred);
7233
7234   push_to_top_level ();
7235
7236   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7237
7238   /* Set the input location to the most specialized template definition.
7239      This is needed if tsubsting causes an error.  */
7240   typedecl = TYPE_MAIN_DECL (pattern);
7241   input_location = DECL_SOURCE_LOCATION (typedecl);
7242
7243   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7244   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7245   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7246   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7247   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7248   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7249   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7250   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7251   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7252   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7253   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7254   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7255   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7256   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7257   if (ANON_AGGR_TYPE_P (pattern))
7258     SET_ANON_AGGR_TYPE_P (type);
7259   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7260     {
7261       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7262       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7263     }
7264
7265   pbinfo = TYPE_BINFO (pattern);
7266
7267   /* We should never instantiate a nested class before its enclosing
7268      class; we need to look up the nested class by name before we can
7269      instantiate it, and that lookup should instantiate the enclosing
7270      class.  */
7271   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7272               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7273               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7274
7275   base_list = NULL_TREE;
7276   if (BINFO_N_BASE_BINFOS (pbinfo))
7277     {
7278       tree pbase_binfo;
7279       tree context = TYPE_CONTEXT (type);
7280       tree pushed_scope;
7281       int i;
7282
7283       /* We must enter the scope containing the type, as that is where
7284          the accessibility of types named in dependent bases are
7285          looked up from.  */
7286       pushed_scope = push_scope (context ? context : global_namespace);
7287
7288       /* Substitute into each of the bases to determine the actual
7289          basetypes.  */
7290       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7291         {
7292           tree base;
7293           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7294           tree expanded_bases = NULL_TREE;
7295           int idx, len = 1;
7296
7297           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7298             {
7299               expanded_bases = 
7300                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7301                                        args, tf_error, NULL_TREE);
7302               if (expanded_bases == error_mark_node)
7303                 continue;
7304
7305               len = TREE_VEC_LENGTH (expanded_bases);
7306             }
7307
7308           for (idx = 0; idx < len; idx++)
7309             {
7310               if (expanded_bases)
7311                 /* Extract the already-expanded base class.  */
7312                 base = TREE_VEC_ELT (expanded_bases, idx);
7313               else
7314                 /* Substitute to figure out the base class.  */
7315                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7316                                NULL_TREE);
7317
7318               if (base == error_mark_node)
7319                 continue;
7320
7321               base_list = tree_cons (access, base, base_list);
7322               if (BINFO_VIRTUAL_P (pbase_binfo))
7323                 TREE_TYPE (base_list) = integer_type_node;
7324             }
7325         }
7326
7327       /* The list is now in reverse order; correct that.  */
7328       base_list = nreverse (base_list);
7329
7330       if (pushed_scope)
7331         pop_scope (pushed_scope);
7332     }
7333   /* Now call xref_basetypes to set up all the base-class
7334      information.  */
7335   xref_basetypes (type, base_list);
7336
7337   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7338                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7339                                   args, tf_error, NULL_TREE);
7340
7341   /* Now that our base classes are set up, enter the scope of the
7342      class, so that name lookups into base classes, etc. will work
7343      correctly.  This is precisely analogous to what we do in
7344      begin_class_definition when defining an ordinary non-template
7345      class, except we also need to push the enclosing classes.  */
7346   push_nested_class (type);
7347
7348   /* Now members are processed in the order of declaration.  */
7349   for (member = CLASSTYPE_DECL_LIST (pattern);
7350        member; member = TREE_CHAIN (member))
7351     {
7352       tree t = TREE_VALUE (member);
7353
7354       if (TREE_PURPOSE (member))
7355         {
7356           if (TYPE_P (t))
7357             {
7358               /* Build new CLASSTYPE_NESTED_UTDS.  */
7359
7360               tree newtag;
7361               bool class_template_p;
7362
7363               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7364                                   && TYPE_LANG_SPECIFIC (t)
7365                                   && CLASSTYPE_IS_TEMPLATE (t));
7366               /* If the member is a class template, then -- even after
7367                  substitution -- there may be dependent types in the
7368                  template argument list for the class.  We increment
7369                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7370                  that function will assume that no types are dependent
7371                  when outside of a template.  */
7372               if (class_template_p)
7373                 ++processing_template_decl;
7374               newtag = tsubst (t, args, tf_error, NULL_TREE);
7375               if (class_template_p)
7376                 --processing_template_decl;
7377               if (newtag == error_mark_node)
7378                 continue;
7379
7380               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7381                 {
7382                   tree name = TYPE_IDENTIFIER (t);
7383
7384                   if (class_template_p)
7385                     /* Unfortunately, lookup_template_class sets
7386                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7387                        instantiation (i.e., for the type of a member
7388                        template class nested within a template class.)
7389                        This behavior is required for
7390                        maybe_process_partial_specialization to work
7391                        correctly, but is not accurate in this case;
7392                        the TAG is not an instantiation of anything.
7393                        (The corresponding TEMPLATE_DECL is an
7394                        instantiation, but the TYPE is not.) */
7395                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7396
7397                   /* Now, we call pushtag to put this NEWTAG into the scope of
7398                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7399                      pushtag calling push_template_decl.  We don't have to do
7400                      this for enums because it will already have been done in
7401                      tsubst_enum.  */
7402                   if (name)
7403                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7404                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7405                 }
7406             }
7407           else if (TREE_CODE (t) == FUNCTION_DECL
7408                    || DECL_FUNCTION_TEMPLATE_P (t))
7409             {
7410               /* Build new TYPE_METHODS.  */
7411               tree r;
7412
7413               if (TREE_CODE (t) == TEMPLATE_DECL)
7414                 ++processing_template_decl;
7415               r = tsubst (t, args, tf_error, NULL_TREE);
7416               if (TREE_CODE (t) == TEMPLATE_DECL)
7417                 --processing_template_decl;
7418               set_current_access_from_decl (r);
7419               finish_member_declaration (r);
7420             }
7421           else
7422             {
7423               /* Build new TYPE_FIELDS.  */
7424               if (TREE_CODE (t) == STATIC_ASSERT)
7425                 {
7426                   tree condition = 
7427                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7428                                  tf_warning_or_error, NULL_TREE,
7429                                  /*integral_constant_expression_p=*/true);
7430                   finish_static_assert (condition,
7431                                         STATIC_ASSERT_MESSAGE (t), 
7432                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7433                                         /*member_p=*/true);
7434                 }
7435               else if (TREE_CODE (t) != CONST_DECL)
7436                 {
7437                   tree r;
7438
7439                   /* The file and line for this declaration, to
7440                      assist in error message reporting.  Since we
7441                      called push_tinst_level above, we don't need to
7442                      restore these.  */
7443                   input_location = DECL_SOURCE_LOCATION (t);
7444
7445                   if (TREE_CODE (t) == TEMPLATE_DECL)
7446                     ++processing_template_decl;
7447                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7448                   if (TREE_CODE (t) == TEMPLATE_DECL)
7449                     --processing_template_decl;
7450                   if (TREE_CODE (r) == VAR_DECL)
7451                     {
7452                       /* In [temp.inst]:
7453
7454                            [t]he initialization (and any associated
7455                            side-effects) of a static data member does
7456                            not occur unless the static data member is
7457                            itself used in a way that requires the
7458                            definition of the static data member to
7459                            exist.
7460
7461                          Therefore, we do not substitute into the
7462                          initialized for the static data member here.  */
7463                       finish_static_data_member_decl
7464                         (r,
7465                          /*init=*/NULL_TREE,
7466                          /*init_const_expr_p=*/false,
7467                          /*asmspec_tree=*/NULL_TREE,
7468                          /*flags=*/0);
7469                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7470                         check_static_variable_definition (r, TREE_TYPE (r));
7471                     }
7472                   else if (TREE_CODE (r) == FIELD_DECL)
7473                     {
7474                       /* Determine whether R has a valid type and can be
7475                          completed later.  If R is invalid, then it is
7476                          replaced by error_mark_node so that it will not be
7477                          added to TYPE_FIELDS.  */
7478                       tree rtype = TREE_TYPE (r);
7479                       if (can_complete_type_without_circularity (rtype))
7480                         complete_type (rtype);
7481
7482                       if (!COMPLETE_TYPE_P (rtype))
7483                         {
7484                           cxx_incomplete_type_error (r, rtype);
7485                           r = error_mark_node;
7486                         }
7487                     }
7488
7489                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7490                      such a thing will already have been added to the field
7491                      list by tsubst_enum in finish_member_declaration in the
7492                      CLASSTYPE_NESTED_UTDS case above.  */
7493                   if (!(TREE_CODE (r) == TYPE_DECL
7494                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7495                         && DECL_ARTIFICIAL (r)))
7496                     {
7497                       set_current_access_from_decl (r);
7498                       finish_member_declaration (r);
7499                     }
7500                 }
7501             }
7502         }
7503       else
7504         {
7505           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7506             {
7507               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7508
7509               tree friend_type = t;
7510               bool adjust_processing_template_decl = false;
7511
7512               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7513                 {
7514                   /* template <class T> friend class C;  */
7515                   friend_type = tsubst_friend_class (friend_type, args);
7516                   adjust_processing_template_decl = true;
7517                 }
7518               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7519                 {
7520                   /* template <class T> friend class C::D;  */
7521                   friend_type = tsubst (friend_type, args,
7522                                         tf_warning_or_error, NULL_TREE);
7523                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7524                     friend_type = TREE_TYPE (friend_type);
7525                   adjust_processing_template_decl = true;
7526                 }
7527               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7528                 {
7529                   /* This could be either
7530
7531                        friend class T::C;
7532
7533                      when dependent_type_p is false or
7534
7535                        template <class U> friend class T::C;
7536
7537                      otherwise.  */
7538                   friend_type = tsubst (friend_type, args,
7539                                         tf_warning_or_error, NULL_TREE);
7540                   /* Bump processing_template_decl for correct
7541                      dependent_type_p calculation.  */
7542                   ++processing_template_decl;
7543                   if (dependent_type_p (friend_type))
7544                     adjust_processing_template_decl = true;
7545                   --processing_template_decl;
7546                 }
7547               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7548                        && hidden_name_p (TYPE_NAME (friend_type)))
7549                 {
7550                   /* friend class C;
7551
7552                      where C hasn't been declared yet.  Let's lookup name
7553                      from namespace scope directly, bypassing any name that
7554                      come from dependent base class.  */
7555                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7556
7557                   /* The call to xref_tag_from_type does injection for friend
7558                      classes.  */
7559                   push_nested_namespace (ns);
7560                   friend_type =
7561                     xref_tag_from_type (friend_type, NULL_TREE,
7562                                         /*tag_scope=*/ts_current);
7563                   pop_nested_namespace (ns);
7564                 }
7565               else if (uses_template_parms (friend_type))
7566                 /* friend class C<T>;  */
7567                 friend_type = tsubst (friend_type, args,
7568                                       tf_warning_or_error, NULL_TREE);
7569               /* Otherwise it's
7570
7571                    friend class C;
7572
7573                  where C is already declared or
7574
7575                    friend class C<int>;
7576
7577                  We don't have to do anything in these cases.  */
7578
7579               if (adjust_processing_template_decl)
7580                 /* Trick make_friend_class into realizing that the friend
7581                    we're adding is a template, not an ordinary class.  It's
7582                    important that we use make_friend_class since it will
7583                    perform some error-checking and output cross-reference
7584                    information.  */
7585                 ++processing_template_decl;
7586
7587               if (friend_type != error_mark_node)
7588                 make_friend_class (type, friend_type, /*complain=*/false);
7589
7590               if (adjust_processing_template_decl)
7591                 --processing_template_decl;
7592             }
7593           else
7594             {
7595               /* Build new DECL_FRIENDLIST.  */
7596               tree r;
7597
7598               /* The file and line for this declaration, to
7599                  assist in error message reporting.  Since we
7600                  called push_tinst_level above, we don't need to
7601                  restore these.  */
7602               input_location = DECL_SOURCE_LOCATION (t);
7603
7604               if (TREE_CODE (t) == TEMPLATE_DECL)
7605                 {
7606                   ++processing_template_decl;
7607                   push_deferring_access_checks (dk_no_check);
7608                 }
7609
7610               r = tsubst_friend_function (t, args);
7611               add_friend (type, r, /*complain=*/false);
7612               if (TREE_CODE (t) == TEMPLATE_DECL)
7613                 {
7614                   pop_deferring_access_checks ();
7615                   --processing_template_decl;
7616                 }
7617             }
7618         }
7619     }
7620
7621   /* Set the file and line number information to whatever is given for
7622      the class itself.  This puts error messages involving generated
7623      implicit functions at a predictable point, and the same point
7624      that would be used for non-template classes.  */
7625   input_location = DECL_SOURCE_LOCATION (typedecl);
7626
7627   unreverse_member_declarations (type);
7628   finish_struct_1 (type);
7629   TYPE_BEING_DEFINED (type) = 0;
7630
7631   /* Now that the class is complete, instantiate default arguments for
7632      any member functions.  We don't do this earlier because the
7633      default arguments may reference members of the class.  */
7634   if (!PRIMARY_TEMPLATE_P (templ))
7635     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7636       if (TREE_CODE (t) == FUNCTION_DECL
7637           /* Implicitly generated member functions will not have template
7638              information; they are not instantiations, but instead are
7639              created "fresh" for each instantiation.  */
7640           && DECL_TEMPLATE_INFO (t))
7641         tsubst_default_arguments (t);
7642
7643   /* Some typedefs referenced from within the template code need to be access
7644      checked at template instantiation time, i.e now. These types were
7645      added to the template at parsing time. Let's get those and perform
7646      the access checks then.  */
7647   perform_typedefs_access_check (pattern, args);
7648   perform_deferred_access_checks ();
7649   pop_nested_class ();
7650   pop_from_top_level ();
7651   pop_deferring_access_checks ();
7652   pop_tinst_level ();
7653
7654   /* The vtable for a template class can be emitted in any translation
7655      unit in which the class is instantiated.  When there is no key
7656      method, however, finish_struct_1 will already have added TYPE to
7657      the keyed_classes list.  */
7658   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7659     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7660
7661   return type;
7662 }
7663
7664 static tree
7665 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7666 {
7667   tree r;
7668
7669   if (!t)
7670     r = t;
7671   else if (TYPE_P (t))
7672     r = tsubst (t, args, complain, in_decl);
7673   else
7674     {
7675       r = tsubst_expr (t, args, complain, in_decl,
7676                        /*integral_constant_expression_p=*/true);
7677       r = fold_non_dependent_expr (r);
7678     }
7679   return r;
7680 }
7681
7682 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7683    NONTYPE_ARGUMENT_PACK.  */
7684
7685 static tree
7686 make_fnparm_pack (tree spec_parm)
7687 {
7688   /* Collect all of the extra "packed" parameters into an
7689      argument pack.  */
7690   tree parmvec;
7691   tree parmtypevec;
7692   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7693   tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
7694   int i, len = list_length (spec_parm);
7695
7696   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7697   parmvec = make_tree_vec (len);
7698   parmtypevec = make_tree_vec (len);
7699   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7700     {
7701       TREE_VEC_ELT (parmvec, i) = spec_parm;
7702       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7703     }
7704
7705   /* Build the argument packs.  */
7706   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7707   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7708   TREE_TYPE (argpack) = argtypepack;
7709
7710   return argpack;
7711 }        
7712
7713 /* Substitute ARGS into T, which is an pack expansion
7714    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7715    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7716    (if only a partial substitution could be performed) or
7717    ERROR_MARK_NODE if there was an error.  */
7718 tree
7719 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7720                        tree in_decl)
7721 {
7722   tree pattern;
7723   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7724   tree first_arg_pack; int i, len = -1;
7725   tree result;
7726   int incomplete = 0;
7727   bool very_local_specializations = false;
7728
7729   gcc_assert (PACK_EXPANSION_P (t));
7730   pattern = PACK_EXPANSION_PATTERN (t);
7731
7732   /* Determine the argument packs that will instantiate the parameter
7733      packs used in the expansion expression. While we're at it,
7734      compute the number of arguments to be expanded and make sure it
7735      is consistent.  */
7736   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7737        pack = TREE_CHAIN (pack))
7738     {
7739       tree parm_pack = TREE_VALUE (pack);
7740       tree arg_pack = NULL_TREE;
7741       tree orig_arg = NULL_TREE;
7742
7743       if (TREE_CODE (parm_pack) == PARM_DECL)
7744         {
7745           arg_pack = retrieve_local_specialization (parm_pack);
7746           if (arg_pack == NULL_TREE)
7747             {
7748               /* This can happen for a parameter name used later in a function
7749                  declaration (such as in a late-specified return type).  Just
7750                  make a dummy decl, since it's only used for its type.  */
7751               gcc_assert (cp_unevaluated_operand != 0);
7752               arg_pack = tsubst_decl (parm_pack, args, complain);
7753               arg_pack = make_fnparm_pack (arg_pack);
7754             }
7755         }
7756       else
7757         {
7758           int level, idx, levels;
7759           template_parm_level_and_index (parm_pack, &level, &idx);
7760
7761           levels = TMPL_ARGS_DEPTH (args);
7762           if (level <= levels)
7763             arg_pack = TMPL_ARG (args, level, idx);
7764         }
7765
7766       orig_arg = arg_pack;
7767       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7768         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7769       
7770       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7771         /* This can only happen if we forget to expand an argument
7772            pack somewhere else. Just return an error, silently.  */
7773         {
7774           result = make_tree_vec (1);
7775           TREE_VEC_ELT (result, 0) = error_mark_node;
7776           return result;
7777         }
7778
7779       if (arg_pack
7780           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7781           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7782         {
7783           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7784           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7785           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7786               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7787             /* The argument pack that the parameter maps to is just an
7788                expansion of the parameter itself, such as one would
7789                find in the implicit typedef of a class inside the
7790                class itself.  Consider this parameter "unsubstituted",
7791                so that we will maintain the outer pack expansion.  */
7792             arg_pack = NULL_TREE;
7793         }
7794           
7795       if (arg_pack)
7796         {
7797           int my_len = 
7798             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7799
7800           /* It's all-or-nothing with incomplete argument packs.  */
7801           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7802             return error_mark_node;
7803           
7804           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7805             incomplete = 1;
7806
7807           if (len < 0)
7808             {
7809               len = my_len;
7810               first_arg_pack = arg_pack;
7811             }
7812           else if (len != my_len)
7813             {
7814               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7815                 error ("mismatched argument pack lengths while expanding "
7816                        "%<%T%>",
7817                        pattern);
7818               else
7819                 error ("mismatched argument pack lengths while expanding "
7820                        "%<%E%>",
7821                        pattern);
7822               return error_mark_node;
7823             }
7824
7825           /* Keep track of the parameter packs and their corresponding
7826              argument packs.  */
7827           packs = tree_cons (parm_pack, arg_pack, packs);
7828           TREE_TYPE (packs) = orig_arg;
7829         }
7830       else
7831         /* We can't substitute for this parameter pack.  */
7832         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7833                                          TREE_VALUE (pack),
7834                                          unsubstituted_packs);
7835     }
7836
7837   /* We cannot expand this expansion expression, because we don't have
7838      all of the argument packs we need. Substitute into the pattern
7839      and return a PACK_EXPANSION_*. The caller will need to deal with
7840      that.  */
7841   if (unsubstituted_packs)
7842     {
7843       tree new_pat;
7844       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7845         new_pat = tsubst_expr (pattern, args, complain, in_decl,
7846                                /*integral_constant_expression_p=*/false);
7847       else
7848         new_pat = tsubst (pattern, args, complain, in_decl);
7849       return make_pack_expansion (new_pat);
7850     }
7851
7852   /* We could not find any argument packs that work.  */
7853   if (len < 0)
7854     return error_mark_node;
7855
7856   if (!local_specializations)
7857     {
7858       /* We're in a late-specified return type, so we don't have a local
7859          specializations table.  Create one for doing this expansion.  */
7860       very_local_specializations = true;
7861       local_specializations = htab_create (37,
7862                                            hash_local_specialization,
7863                                            eq_local_specializations,
7864                                            NULL);
7865     }
7866
7867   /* For each argument in each argument pack, substitute into the
7868      pattern.  */
7869   result = make_tree_vec (len + incomplete);
7870   for (i = 0; i < len + incomplete; ++i)
7871     {
7872       /* For parameter pack, change the substitution of the parameter
7873          pack to the ith argument in its argument pack, then expand
7874          the pattern.  */
7875       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7876         {
7877           tree parm = TREE_PURPOSE (pack);
7878
7879           if (TREE_CODE (parm) == PARM_DECL)
7880             {
7881               /* Select the Ith argument from the pack.  */
7882               tree arg = make_node (ARGUMENT_PACK_SELECT);
7883               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7884               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7885               mark_used (parm);
7886               register_local_specialization (arg, parm);
7887             }
7888           else
7889             {
7890               tree value = parm;
7891               int idx, level;
7892               template_parm_level_and_index (parm, &level, &idx);
7893               
7894               if (i < len) 
7895                 {
7896                   /* Select the Ith argument from the pack. */
7897                   value = make_node (ARGUMENT_PACK_SELECT);
7898                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7899                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7900                 }
7901
7902               /* Update the corresponding argument.  */
7903               TMPL_ARG (args, level, idx) = value;
7904             }
7905         }
7906
7907       /* Substitute into the PATTERN with the altered arguments.  */
7908       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7909         TREE_VEC_ELT (result, i) = 
7910           tsubst_expr (pattern, args, complain, in_decl,
7911                        /*integral_constant_expression_p=*/false);
7912       else
7913         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7914
7915       if (i == len)
7916         /* When we have incomplete argument packs, the last "expanded"
7917            result is itself a pack expansion, which allows us
7918            to deduce more arguments.  */
7919         TREE_VEC_ELT (result, i) = 
7920           make_pack_expansion (TREE_VEC_ELT (result, i));
7921
7922       if (TREE_VEC_ELT (result, i) == error_mark_node)
7923         {
7924           result = error_mark_node;
7925           break;
7926         }
7927     }
7928
7929   /* Update ARGS to restore the substitution from parameter packs to
7930      their argument packs.  */
7931   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7932     {
7933       tree parm = TREE_PURPOSE (pack);
7934
7935       if (TREE_CODE (parm) == PARM_DECL)
7936         register_local_specialization (TREE_TYPE (pack), parm);
7937       else
7938         {
7939           int idx, level;
7940           template_parm_level_and_index (parm, &level, &idx);
7941           
7942           /* Update the corresponding argument.  */
7943           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7944             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7945               TREE_TYPE (pack);
7946           else
7947             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7948         }
7949     }
7950
7951   if (very_local_specializations)
7952     {
7953       htab_delete (local_specializations);
7954       local_specializations = NULL;
7955     }
7956   
7957   return result;
7958 }
7959
7960 /* Substitute ARGS into the vector or list of template arguments T.  */
7961
7962 static tree
7963 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7964 {
7965   tree orig_t = t;
7966   int len = TREE_VEC_LENGTH (t);
7967   int need_new = 0, i, expanded_len_adjust = 0, out;
7968   tree *elts = (tree *) alloca (len * sizeof (tree));
7969
7970   for (i = 0; i < len; i++)
7971     {
7972       tree orig_arg = TREE_VEC_ELT (t, i);
7973       tree new_arg;
7974
7975       if (TREE_CODE (orig_arg) == TREE_VEC)
7976         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7977       else if (PACK_EXPANSION_P (orig_arg))
7978         {
7979           /* Substitute into an expansion expression.  */
7980           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7981
7982           if (TREE_CODE (new_arg) == TREE_VEC)
7983             /* Add to the expanded length adjustment the number of
7984                expanded arguments. We subtract one from this
7985                measurement, because the argument pack expression
7986                itself is already counted as 1 in
7987                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7988                the argument pack is empty.  */
7989             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7990         }
7991       else if (ARGUMENT_PACK_P (orig_arg))
7992         {
7993           /* Substitute into each of the arguments.  */
7994           new_arg = make_node (TREE_CODE (orig_arg));
7995           
7996           SET_ARGUMENT_PACK_ARGS (
7997             new_arg,
7998             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7999                                   args, complain, in_decl));
8000
8001           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8002             new_arg = error_mark_node;
8003
8004           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8005             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8006                                           complain, in_decl);
8007             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8008
8009             if (TREE_TYPE (new_arg) == error_mark_node)
8010               new_arg = error_mark_node;
8011           }
8012         }
8013       else
8014         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8015
8016       if (new_arg == error_mark_node)
8017         return error_mark_node;
8018
8019       elts[i] = new_arg;
8020       if (new_arg != orig_arg)
8021         need_new = 1;
8022     }
8023
8024   if (!need_new)
8025     return t;
8026
8027   /* Make space for the expanded arguments coming from template
8028      argument packs.  */
8029   t = make_tree_vec (len + expanded_len_adjust);
8030   for (i = 0, out = 0; i < len; i++)
8031     {
8032       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8033            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8034           && TREE_CODE (elts[i]) == TREE_VEC)
8035         {
8036           int idx;
8037
8038           /* Now expand the template argument pack "in place".  */
8039           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8040             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8041         }
8042       else
8043         {
8044           TREE_VEC_ELT (t, out) = elts[i];
8045           out++;
8046         }
8047     }
8048
8049   return t;
8050 }
8051
8052 /* Return the result of substituting ARGS into the template parameters
8053    given by PARMS.  If there are m levels of ARGS and m + n levels of
8054    PARMS, then the result will contain n levels of PARMS.  For
8055    example, if PARMS is `template <class T> template <class U>
8056    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8057    result will be `template <int*, double, class V>'.  */
8058
8059 static tree
8060 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8061 {
8062   tree r = NULL_TREE;
8063   tree* new_parms;
8064
8065   /* When substituting into a template, we must set
8066      PROCESSING_TEMPLATE_DECL as the template parameters may be
8067      dependent if they are based on one-another, and the dependency
8068      predicates are short-circuit outside of templates.  */
8069   ++processing_template_decl;
8070
8071   for (new_parms = &r;
8072        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8073        new_parms = &(TREE_CHAIN (*new_parms)),
8074          parms = TREE_CHAIN (parms))
8075     {
8076       tree new_vec =
8077         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8078       int i;
8079
8080       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8081         {
8082           tree tuple;
8083           tree default_value;
8084           tree parm_decl;
8085
8086           if (parms == error_mark_node)
8087             continue;
8088
8089           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8090
8091           if (tuple == error_mark_node)
8092             continue;
8093
8094           default_value = TREE_PURPOSE (tuple);
8095           parm_decl = TREE_VALUE (tuple);
8096
8097           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8098           if (TREE_CODE (parm_decl) == PARM_DECL
8099               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8100             parm_decl = error_mark_node;
8101           default_value = tsubst_template_arg (default_value, args,
8102                                                complain, NULL_TREE);
8103
8104           tuple = build_tree_list (default_value, parm_decl);
8105           TREE_VEC_ELT (new_vec, i) = tuple;
8106         }
8107
8108       *new_parms =
8109         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8110                              - TMPL_ARGS_DEPTH (args)),
8111                    new_vec, NULL_TREE);
8112     }
8113
8114   --processing_template_decl;
8115
8116   return r;
8117 }
8118
8119 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8120    type T.  If T is not an aggregate or enumeration type, it is
8121    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8122    ENTERING_SCOPE is nonzero, T is the context for a template which
8123    we are presently tsubst'ing.  Return the substituted value.  */
8124
8125 static tree
8126 tsubst_aggr_type (tree t,
8127                   tree args,
8128                   tsubst_flags_t complain,
8129                   tree in_decl,
8130                   int entering_scope)
8131 {
8132   if (t == NULL_TREE)
8133     return NULL_TREE;
8134
8135   switch (TREE_CODE (t))
8136     {
8137     case RECORD_TYPE:
8138       if (TYPE_PTRMEMFUNC_P (t))
8139         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8140
8141       /* Else fall through.  */
8142     case ENUMERAL_TYPE:
8143     case UNION_TYPE:
8144       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8145         {
8146           tree argvec;
8147           tree context;
8148           tree r;
8149           int saved_unevaluated_operand;
8150           int saved_inhibit_evaluation_warnings;
8151
8152           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8153           saved_unevaluated_operand = cp_unevaluated_operand;
8154           cp_unevaluated_operand = 0;
8155           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8156           c_inhibit_evaluation_warnings = 0;
8157
8158           /* First, determine the context for the type we are looking
8159              up.  */
8160           context = TYPE_CONTEXT (t);
8161           if (context)
8162             {
8163               context = tsubst_aggr_type (context, args, complain,
8164                                           in_decl, /*entering_scope=*/1);
8165               /* If context is a nested class inside a class template,
8166                  it may still need to be instantiated (c++/33959).  */
8167               if (TYPE_P (context))
8168                 context = complete_type (context);
8169             }
8170
8171           /* Then, figure out what arguments are appropriate for the
8172              type we are trying to find.  For example, given:
8173
8174                template <class T> struct S;
8175                template <class T, class U> void f(T, U) { S<U> su; }
8176
8177              and supposing that we are instantiating f<int, double>,
8178              then our ARGS will be {int, double}, but, when looking up
8179              S we only want {double}.  */
8180           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8181                                          complain, in_decl);
8182           if (argvec == error_mark_node)
8183             r = error_mark_node;
8184           else
8185             {
8186               r = lookup_template_class (t, argvec, in_decl, context,
8187                                          entering_scope, complain);
8188               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8189             }
8190
8191           cp_unevaluated_operand = saved_unevaluated_operand;
8192           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8193
8194           return r;
8195         }
8196       else
8197         /* This is not a template type, so there's nothing to do.  */
8198         return t;
8199
8200     default:
8201       return tsubst (t, args, complain, in_decl);
8202     }
8203 }
8204
8205 /* Substitute into the default argument ARG (a default argument for
8206    FN), which has the indicated TYPE.  */
8207
8208 tree
8209 tsubst_default_argument (tree fn, tree type, tree arg)
8210 {
8211   tree saved_class_ptr = NULL_TREE;
8212   tree saved_class_ref = NULL_TREE;
8213
8214   /* This default argument came from a template.  Instantiate the
8215      default argument here, not in tsubst.  In the case of
8216      something like:
8217
8218        template <class T>
8219        struct S {
8220          static T t();
8221          void f(T = t());
8222        };
8223
8224      we must be careful to do name lookup in the scope of S<T>,
8225      rather than in the current class.  */
8226   push_access_scope (fn);
8227   /* The "this" pointer is not valid in a default argument.  */
8228   if (cfun)
8229     {
8230       saved_class_ptr = current_class_ptr;
8231       cp_function_chain->x_current_class_ptr = NULL_TREE;
8232       saved_class_ref = current_class_ref;
8233       cp_function_chain->x_current_class_ref = NULL_TREE;
8234     }
8235
8236   push_deferring_access_checks(dk_no_deferred);
8237   /* The default argument expression may cause implicitly defined
8238      member functions to be synthesized, which will result in garbage
8239      collection.  We must treat this situation as if we were within
8240      the body of function so as to avoid collecting live data on the
8241      stack.  */
8242   ++function_depth;
8243   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8244                      tf_warning_or_error, NULL_TREE,
8245                      /*integral_constant_expression_p=*/false);
8246   --function_depth;
8247   pop_deferring_access_checks();
8248
8249   /* Restore the "this" pointer.  */
8250   if (cfun)
8251     {
8252       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8253       cp_function_chain->x_current_class_ref = saved_class_ref;
8254     }
8255
8256   pop_access_scope (fn);
8257
8258   /* Make sure the default argument is reasonable.  */
8259   arg = check_default_argument (type, arg);
8260
8261   return arg;
8262 }
8263
8264 /* Substitute into all the default arguments for FN.  */
8265
8266 static void
8267 tsubst_default_arguments (tree fn)
8268 {
8269   tree arg;
8270   tree tmpl_args;
8271
8272   tmpl_args = DECL_TI_ARGS (fn);
8273
8274   /* If this function is not yet instantiated, we certainly don't need
8275      its default arguments.  */
8276   if (uses_template_parms (tmpl_args))
8277     return;
8278
8279   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8280        arg;
8281        arg = TREE_CHAIN (arg))
8282     if (TREE_PURPOSE (arg))
8283       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8284                                                     TREE_VALUE (arg),
8285                                                     TREE_PURPOSE (arg));
8286 }
8287
8288 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8289    result of the substitution.  Issue error and warning messages under
8290    control of COMPLAIN.  */
8291
8292 static tree
8293 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8294 {
8295   location_t saved_loc;
8296   tree r = NULL_TREE;
8297   tree in_decl = t;
8298   hashval_t hash = 0;
8299
8300   /* Set the filename and linenumber to improve error-reporting.  */
8301   saved_loc = input_location;
8302   input_location = DECL_SOURCE_LOCATION (t);
8303
8304   switch (TREE_CODE (t))
8305     {
8306     case TEMPLATE_DECL:
8307       {
8308         /* We can get here when processing a member function template,
8309            member class template, or template template parameter.  */
8310         tree decl = DECL_TEMPLATE_RESULT (t);
8311         tree spec;
8312         tree tmpl_args;
8313         tree full_args;
8314
8315         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8316           {
8317             /* Template template parameter is treated here.  */
8318             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8319             if (new_type == error_mark_node)
8320               return error_mark_node;
8321
8322             r = copy_decl (t);
8323             TREE_CHAIN (r) = NULL_TREE;
8324             TREE_TYPE (r) = new_type;
8325             DECL_TEMPLATE_RESULT (r)
8326               = build_decl (DECL_SOURCE_LOCATION (decl),
8327                             TYPE_DECL, DECL_NAME (decl), new_type);
8328             DECL_TEMPLATE_PARMS (r)
8329               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8330                                        complain);
8331             TYPE_NAME (new_type) = r;
8332             break;
8333           }
8334
8335         /* We might already have an instance of this template.
8336            The ARGS are for the surrounding class type, so the
8337            full args contain the tsubst'd args for the context,
8338            plus the innermost args from the template decl.  */
8339         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8340           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8341           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8342         /* Because this is a template, the arguments will still be
8343            dependent, even after substitution.  If
8344            PROCESSING_TEMPLATE_DECL is not set, the dependency
8345            predicates will short-circuit.  */
8346         ++processing_template_decl;
8347         full_args = tsubst_template_args (tmpl_args, args,
8348                                           complain, in_decl);
8349         --processing_template_decl;
8350         if (full_args == error_mark_node)
8351           return error_mark_node;
8352
8353         /* If this is a default template template argument,
8354            tsubst might not have changed anything.  */
8355         if (full_args == tmpl_args)
8356           return t;
8357
8358         hash = hash_tmpl_and_args (t, full_args);
8359         spec = retrieve_specialization (t, full_args, hash);
8360         if (spec != NULL_TREE)
8361           {
8362             r = spec;
8363             break;
8364           }
8365
8366         /* Make a new template decl.  It will be similar to the
8367            original, but will record the current template arguments.
8368            We also create a new function declaration, which is just
8369            like the old one, but points to this new template, rather
8370            than the old one.  */
8371         r = copy_decl (t);
8372         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8373         TREE_CHAIN (r) = NULL_TREE;
8374
8375         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8376
8377         if (TREE_CODE (decl) == TYPE_DECL)
8378           {
8379             tree new_type;
8380             ++processing_template_decl;
8381             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8382             --processing_template_decl;
8383             if (new_type == error_mark_node)
8384               return error_mark_node;
8385
8386             TREE_TYPE (r) = new_type;
8387             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8388             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8389             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8390             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8391           }
8392         else
8393           {
8394             tree new_decl;
8395             ++processing_template_decl;
8396             new_decl = tsubst (decl, args, complain, in_decl);
8397             --processing_template_decl;
8398             if (new_decl == error_mark_node)
8399               return error_mark_node;
8400
8401             DECL_TEMPLATE_RESULT (r) = new_decl;
8402             DECL_TI_TEMPLATE (new_decl) = r;
8403             TREE_TYPE (r) = TREE_TYPE (new_decl);
8404             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8405             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8406           }
8407
8408         SET_DECL_IMPLICIT_INSTANTIATION (r);
8409         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8410         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8411
8412         /* The template parameters for this new template are all the
8413            template parameters for the old template, except the
8414            outermost level of parameters.  */
8415         DECL_TEMPLATE_PARMS (r)
8416           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8417                                    complain);
8418
8419         if (PRIMARY_TEMPLATE_P (t))
8420           DECL_PRIMARY_TEMPLATE (r) = r;
8421
8422         if (TREE_CODE (decl) != TYPE_DECL)
8423           /* Record this non-type partial instantiation.  */
8424           register_specialization (r, t,
8425                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8426                                    false, hash);
8427       }
8428       break;
8429
8430     case FUNCTION_DECL:
8431       {
8432         tree ctx;
8433         tree argvec = NULL_TREE;
8434         tree *friends;
8435         tree gen_tmpl;
8436         tree type;
8437         int member;
8438         int args_depth;
8439         int parms_depth;
8440
8441         /* Nobody should be tsubst'ing into non-template functions.  */
8442         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8443
8444         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8445           {
8446             tree spec;
8447             bool dependent_p;
8448
8449             /* If T is not dependent, just return it.  We have to
8450                increment PROCESSING_TEMPLATE_DECL because
8451                value_dependent_expression_p assumes that nothing is
8452                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8453             ++processing_template_decl;
8454             dependent_p = value_dependent_expression_p (t);
8455             --processing_template_decl;
8456             if (!dependent_p)
8457               return t;
8458
8459             /* Calculate the most general template of which R is a
8460                specialization, and the complete set of arguments used to
8461                specialize R.  */
8462             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8463             argvec = tsubst_template_args (DECL_TI_ARGS
8464                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8465                                            args, complain, in_decl);
8466
8467             /* Check to see if we already have this specialization.  */
8468             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8469             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8470
8471             if (spec)
8472               {
8473                 r = spec;
8474                 break;
8475               }
8476
8477             /* We can see more levels of arguments than parameters if
8478                there was a specialization of a member template, like
8479                this:
8480
8481                  template <class T> struct S { template <class U> void f(); }
8482                  template <> template <class U> void S<int>::f(U);
8483
8484                Here, we'll be substituting into the specialization,
8485                because that's where we can find the code we actually
8486                want to generate, but we'll have enough arguments for
8487                the most general template.
8488
8489                We also deal with the peculiar case:
8490
8491                  template <class T> struct S {
8492                    template <class U> friend void f();
8493                  };
8494                  template <class U> void f() {}
8495                  template S<int>;
8496                  template void f<double>();
8497
8498                Here, the ARGS for the instantiation of will be {int,
8499                double}.  But, we only need as many ARGS as there are
8500                levels of template parameters in CODE_PATTERN.  We are
8501                careful not to get fooled into reducing the ARGS in
8502                situations like:
8503
8504                  template <class T> struct S { template <class U> void f(U); }
8505                  template <class T> template <> void S<T>::f(int) {}
8506
8507                which we can spot because the pattern will be a
8508                specialization in this case.  */
8509             args_depth = TMPL_ARGS_DEPTH (args);
8510             parms_depth =
8511               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8512             if (args_depth > parms_depth
8513                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8514               args = get_innermost_template_args (args, parms_depth);
8515           }
8516         else
8517           {
8518             /* This special case arises when we have something like this:
8519
8520                  template <class T> struct S {
8521                    friend void f<int>(int, double);
8522                  };
8523
8524                Here, the DECL_TI_TEMPLATE for the friend declaration
8525                will be an IDENTIFIER_NODE.  We are being called from
8526                tsubst_friend_function, and we want only to create a
8527                new decl (R) with appropriate types so that we can call
8528                determine_specialization.  */
8529             gen_tmpl = NULL_TREE;
8530           }
8531
8532         if (DECL_CLASS_SCOPE_P (t))
8533           {
8534             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8535               member = 2;
8536             else
8537               member = 1;
8538             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8539                                     complain, t, /*entering_scope=*/1);
8540           }
8541         else
8542           {
8543             member = 0;
8544             ctx = DECL_CONTEXT (t);
8545           }
8546         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8547         if (type == error_mark_node)
8548           return error_mark_node;
8549
8550         /* We do NOT check for matching decls pushed separately at this
8551            point, as they may not represent instantiations of this
8552            template, and in any case are considered separate under the
8553            discrete model.  */
8554         r = copy_decl (t);
8555         DECL_USE_TEMPLATE (r) = 0;
8556         TREE_TYPE (r) = type;
8557         /* Clear out the mangled name and RTL for the instantiation.  */
8558         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8559         SET_DECL_RTL (r, NULL_RTX);
8560         /* Leave DECL_INITIAL set on deleted instantiations.  */
8561         if (!DECL_DELETED_FN (r))
8562           DECL_INITIAL (r) = NULL_TREE;
8563         DECL_CONTEXT (r) = ctx;
8564
8565         if (member && DECL_CONV_FN_P (r))
8566           /* Type-conversion operator.  Reconstruct the name, in
8567              case it's the name of one of the template's parameters.  */
8568           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8569
8570         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8571                                      complain, t);
8572         DECL_RESULT (r) = NULL_TREE;
8573
8574         TREE_STATIC (r) = 0;
8575         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8576         DECL_EXTERNAL (r) = 1;
8577         /* If this is an instantiation of a function with internal
8578            linkage, we already know what object file linkage will be
8579            assigned to the instantiation.  */
8580         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8581         DECL_DEFER_OUTPUT (r) = 0;
8582         TREE_CHAIN (r) = NULL_TREE;
8583         DECL_PENDING_INLINE_INFO (r) = 0;
8584         DECL_PENDING_INLINE_P (r) = 0;
8585         DECL_SAVED_TREE (r) = NULL_TREE;
8586         DECL_STRUCT_FUNCTION (r) = NULL;
8587         TREE_USED (r) = 0;
8588         /* We'll re-clone as appropriate in instantiate_template.  */
8589         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8590
8591         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8592            this in the special friend case mentioned above where
8593            GEN_TMPL is NULL.  */
8594         if (gen_tmpl)
8595           {
8596             DECL_TEMPLATE_INFO (r)
8597               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8598             SET_DECL_IMPLICIT_INSTANTIATION (r);
8599             register_specialization (r, gen_tmpl, argvec, false, hash);
8600
8601             /* We're not supposed to instantiate default arguments
8602                until they are called, for a template.  But, for a
8603                declaration like:
8604
8605                  template <class T> void f ()
8606                  { extern void g(int i = T()); }
8607
8608                we should do the substitution when the template is
8609                instantiated.  We handle the member function case in
8610                instantiate_class_template since the default arguments
8611                might refer to other members of the class.  */
8612             if (!member
8613                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8614                 && !uses_template_parms (argvec))
8615               tsubst_default_arguments (r);
8616           }
8617         else
8618           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8619
8620         /* Copy the list of befriending classes.  */
8621         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8622              *friends;
8623              friends = &TREE_CHAIN (*friends))
8624           {
8625             *friends = copy_node (*friends);
8626             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8627                                             args, complain,
8628                                             in_decl);
8629           }
8630
8631         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8632           {
8633             maybe_retrofit_in_chrg (r);
8634             if (DECL_CONSTRUCTOR_P (r))
8635               grok_ctor_properties (ctx, r);
8636             /* If this is an instantiation of a member template, clone it.
8637                If it isn't, that'll be handled by
8638                clone_constructors_and_destructors.  */
8639             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8640               clone_function_decl (r, /*update_method_vec_p=*/0);
8641           }
8642         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8643                  && !grok_op_properties (r, (complain & tf_error) != 0))
8644           return error_mark_node;
8645
8646         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8647           SET_DECL_FRIEND_CONTEXT (r,
8648                                    tsubst (DECL_FRIEND_CONTEXT (t),
8649                                             args, complain, in_decl));
8650
8651         /* Possibly limit visibility based on template args.  */
8652         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8653         if (DECL_VISIBILITY_SPECIFIED (t))
8654           {
8655             DECL_VISIBILITY_SPECIFIED (r) = 0;
8656             DECL_ATTRIBUTES (r)
8657               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8658           }
8659         determine_visibility (r);
8660
8661         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8662                                         args, complain, in_decl);
8663       }
8664       break;
8665
8666     case PARM_DECL:
8667       {
8668         tree type = NULL_TREE;
8669         int i, len = 1;
8670         tree expanded_types = NULL_TREE;
8671         tree prev_r = NULL_TREE;
8672         tree first_r = NULL_TREE;
8673
8674         if (FUNCTION_PARAMETER_PACK_P (t))
8675           {
8676             /* If there is a local specialization that isn't a
8677                parameter pack, it means that we're doing a "simple"
8678                substitution from inside tsubst_pack_expansion. Just
8679                return the local specialization (which will be a single
8680                parm).  */
8681             tree spec = retrieve_local_specialization (t);
8682             if (spec 
8683                 && TREE_CODE (spec) == PARM_DECL
8684                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8685               return spec;
8686
8687             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8688                the parameters in this function parameter pack.  */
8689             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8690                                                     complain, in_decl);
8691             if (TREE_CODE (expanded_types) == TREE_VEC)
8692               {
8693                 len = TREE_VEC_LENGTH (expanded_types);
8694
8695                 /* Zero-length parameter packs are boring. Just substitute
8696                    into the chain.  */
8697                 if (len == 0)
8698                   return tsubst (TREE_CHAIN (t), args, complain, 
8699                                  TREE_CHAIN (t));
8700               }
8701             else
8702               {
8703                 /* All we did was update the type. Make a note of that.  */
8704                 type = expanded_types;
8705                 expanded_types = NULL_TREE;
8706               }
8707           }
8708
8709         /* Loop through all of the parameter's we'll build. When T is
8710            a function parameter pack, LEN is the number of expanded
8711            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8712         r = NULL_TREE;
8713         for (i = 0; i < len; ++i)
8714           {
8715             prev_r = r;
8716             r = copy_node (t);
8717             if (DECL_TEMPLATE_PARM_P (t))
8718               SET_DECL_TEMPLATE_PARM_P (r);
8719
8720             if (expanded_types)
8721               /* We're on the Ith parameter of the function parameter
8722                  pack.  */
8723               {
8724                 /* Get the Ith type.  */
8725                 type = TREE_VEC_ELT (expanded_types, i);
8726
8727                 if (DECL_NAME (r))
8728                   /* Rename the parameter to include the index.  */
8729                   DECL_NAME (r) =
8730                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8731               }
8732             else if (!type)
8733               /* We're dealing with a normal parameter.  */
8734               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8735
8736             type = type_decays_to (type);
8737             TREE_TYPE (r) = type;
8738             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8739
8740             if (DECL_INITIAL (r))
8741               {
8742                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8743                   DECL_INITIAL (r) = TREE_TYPE (r);
8744                 else
8745                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8746                                              complain, in_decl);
8747               }
8748
8749             DECL_CONTEXT (r) = NULL_TREE;
8750
8751             if (!DECL_TEMPLATE_PARM_P (r))
8752               DECL_ARG_TYPE (r) = type_passed_as (type);
8753
8754             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8755                                             args, complain, in_decl);
8756
8757             /* Keep track of the first new parameter we
8758                generate. That's what will be returned to the
8759                caller.  */
8760             if (!first_r)
8761               first_r = r;
8762
8763             /* Build a proper chain of parameters when substituting
8764                into a function parameter pack.  */
8765             if (prev_r)
8766               TREE_CHAIN (prev_r) = r;
8767           }
8768
8769         if (TREE_CHAIN (t))
8770           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8771                                    complain, TREE_CHAIN (t));
8772
8773         /* FIRST_R contains the start of the chain we've built.  */
8774         r = first_r;
8775       }
8776       break;
8777
8778     case FIELD_DECL:
8779       {
8780         tree type;
8781
8782         r = copy_decl (t);
8783         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8784         if (type == error_mark_node)
8785           return error_mark_node;
8786         TREE_TYPE (r) = type;
8787         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8788
8789         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8790         DECL_INITIAL (r)
8791           = tsubst_expr (DECL_INITIAL (t), args,
8792                          complain, in_decl,
8793                          /*integral_constant_expression_p=*/true);
8794         /* We don't have to set DECL_CONTEXT here; it is set by
8795            finish_member_declaration.  */
8796         TREE_CHAIN (r) = NULL_TREE;
8797         if (VOID_TYPE_P (type))
8798           error ("instantiation of %q+D as type %qT", r, type);
8799
8800         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8801                                         args, complain, in_decl);
8802       }
8803       break;
8804
8805     case USING_DECL:
8806       /* We reach here only for member using decls.  */
8807       if (DECL_DEPENDENT_P (t))
8808         {
8809           r = do_class_using_decl
8810             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8811              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8812           if (!r)
8813             r = error_mark_node;
8814           else
8815             {
8816               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8817               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8818             }
8819         }
8820       else
8821         {
8822           r = copy_node (t);
8823           TREE_CHAIN (r) = NULL_TREE;
8824         }
8825       break;
8826
8827     case TYPE_DECL:
8828     case VAR_DECL:
8829       {
8830         tree argvec = NULL_TREE;
8831         tree gen_tmpl = NULL_TREE;
8832         tree spec;
8833         tree tmpl = NULL_TREE;
8834         tree ctx;
8835         tree type = NULL_TREE;
8836         bool local_p;
8837
8838         if (TREE_CODE (t) == TYPE_DECL
8839             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8840           {
8841             /* If this is the canonical decl, we don't have to
8842                mess with instantiations, and often we can't (for
8843                typename, template type parms and such).  Note that
8844                TYPE_NAME is not correct for the above test if
8845                we've copied the type for a typedef.  */
8846             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8847             if (type == error_mark_node)
8848               return error_mark_node;
8849             r = TYPE_NAME (type);
8850             break;
8851           }
8852
8853         /* Check to see if we already have the specialization we
8854            need.  */
8855         spec = NULL_TREE;
8856         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8857           {
8858             /* T is a static data member or namespace-scope entity.
8859                We have to substitute into namespace-scope variables
8860                (even though such entities are never templates) because
8861                of cases like:
8862                
8863                  template <class T> void f() { extern T t; }
8864
8865                where the entity referenced is not known until
8866                instantiation time.  */
8867             local_p = false;
8868             ctx = DECL_CONTEXT (t);
8869             if (DECL_CLASS_SCOPE_P (t))
8870               {
8871                 ctx = tsubst_aggr_type (ctx, args,
8872                                         complain,
8873                                         in_decl, /*entering_scope=*/1);
8874                 /* If CTX is unchanged, then T is in fact the
8875                    specialization we want.  That situation occurs when
8876                    referencing a static data member within in its own
8877                    class.  We can use pointer equality, rather than
8878                    same_type_p, because DECL_CONTEXT is always
8879                    canonical.  */
8880                 if (ctx == DECL_CONTEXT (t))
8881                   spec = t;
8882               }
8883
8884             if (!spec)
8885               {
8886                 tmpl = DECL_TI_TEMPLATE (t);
8887                 gen_tmpl = most_general_template (tmpl);
8888                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8889                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
8890                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
8891               }
8892           }
8893         else
8894           {
8895             /* A local variable.  */
8896             local_p = true;
8897             /* Subsequent calls to pushdecl will fill this in.  */
8898             ctx = NULL_TREE;
8899             spec = retrieve_local_specialization (t);
8900           }
8901         /* If we already have the specialization we need, there is
8902            nothing more to do.  */ 
8903         if (spec)
8904           {
8905             r = spec;
8906             break;
8907           }
8908
8909         /* Create a new node for the specialization we need.  */
8910         r = copy_decl (t);
8911         if (type == NULL_TREE)
8912           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8913         if (TREE_CODE (r) == VAR_DECL)
8914           {
8915             /* Even if the original location is out of scope, the
8916                newly substituted one is not.  */
8917             DECL_DEAD_FOR_LOCAL (r) = 0;
8918             DECL_INITIALIZED_P (r) = 0;
8919             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8920             if (type == error_mark_node)
8921               return error_mark_node;
8922             if (TREE_CODE (type) == FUNCTION_TYPE)
8923               {
8924                 /* It may seem that this case cannot occur, since:
8925
8926                      typedef void f();
8927                      void g() { f x; }
8928
8929                    declares a function, not a variable.  However:
8930       
8931                      typedef void f();
8932                      template <typename T> void g() { T t; }
8933                      template void g<f>();
8934
8935                    is an attempt to declare a variable with function
8936                    type.  */
8937                 error ("variable %qD has function type",
8938                        /* R is not yet sufficiently initialized, so we
8939                           just use its name.  */
8940                        DECL_NAME (r));
8941                 return error_mark_node;
8942               }
8943             type = complete_type (type);
8944             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8945               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8946             type = check_var_type (DECL_NAME (r), type);
8947
8948             if (DECL_HAS_VALUE_EXPR_P (t))
8949               {
8950                 tree ve = DECL_VALUE_EXPR (t);
8951                 ve = tsubst_expr (ve, args, complain, in_decl,
8952                                   /*constant_expression_p=*/false);
8953                 SET_DECL_VALUE_EXPR (r, ve);
8954               }
8955           }
8956         else if (DECL_SELF_REFERENCE_P (t))
8957           SET_DECL_SELF_REFERENCE_P (r);
8958         TREE_TYPE (r) = type;
8959         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8960         DECL_CONTEXT (r) = ctx;
8961         /* Clear out the mangled name and RTL for the instantiation.  */
8962         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8963         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8964           SET_DECL_RTL (r, NULL_RTX);
8965         /* The initializer must not be expanded until it is required;
8966            see [temp.inst].  */
8967         DECL_INITIAL (r) = NULL_TREE;
8968         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8969           SET_DECL_RTL (r, NULL_RTX);
8970         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8971         if (TREE_CODE (r) == VAR_DECL)
8972           {
8973             /* Possibly limit visibility based on template args.  */
8974             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8975             if (DECL_VISIBILITY_SPECIFIED (t))
8976               {
8977                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8978                 DECL_ATTRIBUTES (r)
8979                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8980               }
8981             determine_visibility (r);
8982           }
8983         /* Preserve a typedef that names a type.  */
8984         else if (TREE_CODE (r) == TYPE_DECL
8985                  && DECL_ORIGINAL_TYPE (t)
8986                  && type != error_mark_node)
8987           {
8988             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8989                                              args, complain, in_decl);
8990             TREE_TYPE (r) = type = build_variant_type_copy (type);
8991             TYPE_NAME (type) = r;
8992           }
8993
8994         if (!local_p)
8995           {
8996             /* A static data member declaration is always marked
8997                external when it is declared in-class, even if an
8998                initializer is present.  We mimic the non-template
8999                processing here.  */
9000             DECL_EXTERNAL (r) = 1;
9001
9002             register_specialization (r, gen_tmpl, argvec, false, hash);
9003             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
9004             SET_DECL_IMPLICIT_INSTANTIATION (r);
9005           }
9006         else
9007           register_local_specialization (r, t);
9008
9009         TREE_CHAIN (r) = NULL_TREE;
9010
9011         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9012                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9013                                         args, complain, in_decl);
9014         layout_decl (r, 0);
9015       }
9016       break;
9017
9018     default:
9019       gcc_unreachable ();
9020     }
9021
9022   /* Restore the file and line information.  */
9023   input_location = saved_loc;
9024
9025   return r;
9026 }
9027
9028 /* Substitute into the ARG_TYPES of a function type.  */
9029
9030 static tree
9031 tsubst_arg_types (tree arg_types,
9032                   tree args,
9033                   tsubst_flags_t complain,
9034                   tree in_decl)
9035 {
9036   tree remaining_arg_types;
9037   tree type = NULL_TREE;
9038   int i = 1;
9039   tree expanded_args = NULL_TREE;
9040   tree default_arg;
9041
9042   if (!arg_types || arg_types == void_list_node)
9043     return arg_types;
9044
9045   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9046                                           args, complain, in_decl);
9047   if (remaining_arg_types == error_mark_node)
9048     return error_mark_node;
9049
9050   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9051     {
9052       /* For a pack expansion, perform substitution on the
9053          entire expression. Later on, we'll handle the arguments
9054          one-by-one.  */
9055       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9056                                             args, complain, in_decl);
9057
9058       if (TREE_CODE (expanded_args) == TREE_VEC)
9059         /* So that we'll spin through the parameters, one by one.  */
9060         i = TREE_VEC_LENGTH (expanded_args);
9061       else
9062         {
9063           /* We only partially substituted into the parameter
9064              pack. Our type is TYPE_PACK_EXPANSION.  */
9065           type = expanded_args;
9066           expanded_args = NULL_TREE;
9067         }
9068     }
9069
9070   while (i > 0) {
9071     --i;
9072     
9073     if (expanded_args)
9074       type = TREE_VEC_ELT (expanded_args, i);
9075     else if (!type)
9076       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9077
9078     if (type == error_mark_node)
9079       return error_mark_node;
9080     if (VOID_TYPE_P (type))
9081       {
9082         if (complain & tf_error)
9083           {
9084             error ("invalid parameter type %qT", type);
9085             if (in_decl)
9086               error ("in declaration %q+D", in_decl);
9087           }
9088         return error_mark_node;
9089     }
9090     
9091     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9092        top-level qualifiers as required.  */
9093     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9094
9095     /* We do not substitute into default arguments here.  The standard
9096        mandates that they be instantiated only when needed, which is
9097        done in build_over_call.  */
9098     default_arg = TREE_PURPOSE (arg_types);
9099
9100     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9101       {
9102         /* We've instantiated a template before its default arguments
9103            have been parsed.  This can happen for a nested template
9104            class, and is not an error unless we require the default
9105            argument in a call of this function.  */
9106         remaining_arg_types = 
9107           tree_cons (default_arg, type, remaining_arg_types);
9108         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9109                        remaining_arg_types);
9110       }
9111     else
9112       remaining_arg_types = 
9113         hash_tree_cons (default_arg, type, remaining_arg_types);
9114   }
9115         
9116   return remaining_arg_types;
9117 }
9118
9119 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9120    *not* handle the exception-specification for FNTYPE, because the
9121    initial substitution of explicitly provided template parameters
9122    during argument deduction forbids substitution into the
9123    exception-specification:
9124
9125      [temp.deduct]
9126
9127      All references in the function type of the function template to  the
9128      corresponding template parameters are replaced by the specified tem-
9129      plate argument values.  If a substitution in a template parameter or
9130      in  the function type of the function template results in an invalid
9131      type, type deduction fails.  [Note: The equivalent  substitution  in
9132      exception specifications is done only when the function is instanti-
9133      ated, at which point a program is  ill-formed  if  the  substitution
9134      results in an invalid type.]  */
9135
9136 static tree
9137 tsubst_function_type (tree t,
9138                       tree args,
9139                       tsubst_flags_t complain,
9140                       tree in_decl)
9141 {
9142   tree return_type;
9143   tree arg_types;
9144   tree fntype;
9145
9146   /* The TYPE_CONTEXT is not used for function/method types.  */
9147   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9148
9149   /* Substitute the return type.  */
9150   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9151   if (return_type == error_mark_node)
9152     return error_mark_node;
9153   /* The standard does not presently indicate that creation of a
9154      function type with an invalid return type is a deduction failure.
9155      However, that is clearly analogous to creating an array of "void"
9156      or a reference to a reference.  This is core issue #486.  */
9157   if (TREE_CODE (return_type) == ARRAY_TYPE
9158       || TREE_CODE (return_type) == FUNCTION_TYPE)
9159     {
9160       if (complain & tf_error)
9161         {
9162           if (TREE_CODE (return_type) == ARRAY_TYPE)
9163             error ("function returning an array");
9164           else
9165             error ("function returning a function");
9166         }
9167       return error_mark_node;
9168     }
9169
9170   /* Substitute the argument types.  */
9171   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9172                                 complain, in_decl);
9173   if (arg_types == error_mark_node)
9174     return error_mark_node;
9175
9176   /* Construct a new type node and return it.  */
9177   if (TREE_CODE (t) == FUNCTION_TYPE)
9178     fntype = build_function_type (return_type, arg_types);
9179   else
9180     {
9181       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9182       if (! MAYBE_CLASS_TYPE_P (r))
9183         {
9184           /* [temp.deduct]
9185
9186              Type deduction may fail for any of the following
9187              reasons:
9188
9189              -- Attempting to create "pointer to member of T" when T
9190              is not a class type.  */
9191           if (complain & tf_error)
9192             error ("creating pointer to member function of non-class type %qT",
9193                       r);
9194           return error_mark_node;
9195         }
9196
9197       fntype = build_method_type_directly (r, return_type,
9198                                            TREE_CHAIN (arg_types));
9199     }
9200   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9201   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9202
9203   return fntype;
9204 }
9205
9206 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9207    ARGS into that specification, and return the substituted
9208    specification.  If there is no specification, return NULL_TREE.  */
9209
9210 static tree
9211 tsubst_exception_specification (tree fntype,
9212                                 tree args,
9213                                 tsubst_flags_t complain,
9214                                 tree in_decl)
9215 {
9216   tree specs;
9217   tree new_specs;
9218
9219   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9220   new_specs = NULL_TREE;
9221   if (specs)
9222     {
9223       if (! TREE_VALUE (specs))
9224         new_specs = specs;
9225       else
9226         while (specs)
9227           {
9228             tree spec;
9229             int i, len = 1;
9230             tree expanded_specs = NULL_TREE;
9231
9232             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9233               {
9234                 /* Expand the pack expansion type.  */
9235                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9236                                                        args, complain,
9237                                                        in_decl);
9238
9239                 if (expanded_specs == error_mark_node)
9240                   return error_mark_node;
9241                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9242                   len = TREE_VEC_LENGTH (expanded_specs);
9243                 else
9244                   {
9245                     /* We're substituting into a member template, so
9246                        we got a TYPE_PACK_EXPANSION back.  Add that
9247                        expansion and move on.  */
9248                     gcc_assert (TREE_CODE (expanded_specs) 
9249                                 == TYPE_PACK_EXPANSION);
9250                     new_specs = add_exception_specifier (new_specs,
9251                                                          expanded_specs,
9252                                                          complain);
9253                     specs = TREE_CHAIN (specs);
9254                     continue;
9255                   }
9256               }
9257
9258             for (i = 0; i < len; ++i)
9259               {
9260                 if (expanded_specs)
9261                   spec = TREE_VEC_ELT (expanded_specs, i);
9262                 else
9263                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9264                 if (spec == error_mark_node)
9265                   return spec;
9266                 new_specs = add_exception_specifier (new_specs, spec, 
9267                                                      complain);
9268               }
9269
9270             specs = TREE_CHAIN (specs);
9271           }
9272     }
9273   return new_specs;
9274 }
9275
9276 /* Take the tree structure T and replace template parameters used
9277    therein with the argument vector ARGS.  IN_DECL is an associated
9278    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9279    Issue error and warning messages under control of COMPLAIN.  Note
9280    that we must be relatively non-tolerant of extensions here, in
9281    order to preserve conformance; if we allow substitutions that
9282    should not be allowed, we may allow argument deductions that should
9283    not succeed, and therefore report ambiguous overload situations
9284    where there are none.  In theory, we could allow the substitution,
9285    but indicate that it should have failed, and allow our caller to
9286    make sure that the right thing happens, but we don't try to do this
9287    yet.
9288
9289    This function is used for dealing with types, decls and the like;
9290    for expressions, use tsubst_expr or tsubst_copy.  */
9291
9292 tree
9293 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9294 {
9295   tree type, r;
9296
9297   if (t == NULL_TREE || t == error_mark_node
9298       || t == integer_type_node
9299       || t == void_type_node
9300       || t == char_type_node
9301       || t == unknown_type_node
9302       || TREE_CODE (t) == NAMESPACE_DECL)
9303     return t;
9304
9305   if (DECL_P (t))
9306     return tsubst_decl (t, args, complain);
9307
9308   if (args == NULL_TREE)
9309     return t;
9310
9311   if (TREE_CODE (t) == IDENTIFIER_NODE)
9312     type = IDENTIFIER_TYPE_VALUE (t);
9313   else
9314     type = TREE_TYPE (t);
9315
9316   gcc_assert (type != unknown_type_node);
9317
9318   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9319      such as attribute aligned.  */
9320   if (TYPE_P (t)
9321       && TYPE_NAME (t)
9322       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9323     {
9324       tree decl = TYPE_NAME (t);
9325       
9326       if (DECL_CLASS_SCOPE_P (decl)
9327           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9328           && uses_template_parms (DECL_CONTEXT (decl)))
9329         {
9330           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9331           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9332           r = retrieve_specialization (tmpl, gen_args, 0);
9333         }
9334       else if (DECL_FUNCTION_SCOPE_P (decl)
9335                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9336                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9337         r = retrieve_local_specialization (decl);
9338       else
9339         /* The typedef is from a non-template context.  */
9340         return t;
9341
9342       if (r)
9343         {
9344           r = TREE_TYPE (r);
9345           r = cp_build_qualified_type_real
9346             (r, cp_type_quals (t) | cp_type_quals (r),
9347              complain | tf_ignore_bad_quals);
9348           return r;
9349         }
9350       /* Else we must be instantiating the typedef, so fall through.  */
9351     }
9352
9353   if (type
9354       && TREE_CODE (t) != TYPENAME_TYPE
9355       && TREE_CODE (t) != IDENTIFIER_NODE
9356       && TREE_CODE (t) != FUNCTION_TYPE
9357       && TREE_CODE (t) != METHOD_TYPE)
9358     type = tsubst (type, args, complain, in_decl);
9359   if (type == error_mark_node)
9360     return error_mark_node;
9361
9362   switch (TREE_CODE (t))
9363     {
9364     case RECORD_TYPE:
9365     case UNION_TYPE:
9366     case ENUMERAL_TYPE:
9367       return tsubst_aggr_type (t, args, complain, in_decl,
9368                                /*entering_scope=*/0);
9369
9370     case ERROR_MARK:
9371     case IDENTIFIER_NODE:
9372     case VOID_TYPE:
9373     case REAL_TYPE:
9374     case COMPLEX_TYPE:
9375     case VECTOR_TYPE:
9376     case BOOLEAN_TYPE:
9377     case INTEGER_CST:
9378     case REAL_CST:
9379     case STRING_CST:
9380       return t;
9381
9382     case INTEGER_TYPE:
9383       if (t == integer_type_node)
9384         return t;
9385
9386       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9387           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9388         return t;
9389
9390       {
9391         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9392
9393         max = tsubst_expr (omax, args, complain, in_decl,
9394                            /*integral_constant_expression_p=*/false);
9395
9396         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9397            needed.  */
9398         if (TREE_CODE (max) == NOP_EXPR
9399             && TREE_SIDE_EFFECTS (omax)
9400             && !TREE_TYPE (max))
9401           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9402
9403         max = fold_decl_constant_value (max);
9404
9405         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9406            with TREE_SIDE_EFFECTS that indicates this is not an integral
9407            constant expression.  */
9408         if (processing_template_decl
9409             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9410           {
9411             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9412             TREE_SIDE_EFFECTS (max) = 1;
9413           }
9414
9415         if (TREE_CODE (max) != INTEGER_CST
9416             && !at_function_scope_p ()
9417             && !TREE_SIDE_EFFECTS (max)
9418             && !value_dependent_expression_p (max))
9419           {
9420             if (complain & tf_error)
9421               error ("array bound is not an integer constant");
9422             return error_mark_node;
9423           }
9424
9425         /* [temp.deduct]
9426
9427            Type deduction may fail for any of the following
9428            reasons:
9429
9430              Attempting to create an array with a size that is
9431              zero or negative.  */
9432         if (integer_zerop (max) && !(complain & tf_error))
9433           /* We must fail if performing argument deduction (as
9434              indicated by the state of complain), so that
9435              another substitution can be found.  */
9436           return error_mark_node;
9437         else if (TREE_CODE (max) == INTEGER_CST
9438                  && INT_CST_LT (max, integer_zero_node))
9439           {
9440             if (complain & tf_error)
9441               error ("creating array with negative size (%qE)", max);
9442
9443             return error_mark_node;
9444           }
9445
9446         return compute_array_index_type (NULL_TREE, max);
9447       }
9448
9449     case TEMPLATE_TYPE_PARM:
9450     case TEMPLATE_TEMPLATE_PARM:
9451     case BOUND_TEMPLATE_TEMPLATE_PARM:
9452     case TEMPLATE_PARM_INDEX:
9453       {
9454         int idx;
9455         int level;
9456         int levels;
9457         tree arg = NULL_TREE;
9458
9459         r = NULL_TREE;
9460
9461         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9462         template_parm_level_and_index (t, &level, &idx); 
9463
9464         levels = TMPL_ARGS_DEPTH (args);
9465         if (level <= levels)
9466           {
9467             arg = TMPL_ARG (args, level, idx);
9468
9469             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9470               /* See through ARGUMENT_PACK_SELECT arguments. */
9471               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9472           }
9473
9474         if (arg == error_mark_node)
9475           return error_mark_node;
9476         else if (arg != NULL_TREE)
9477           {
9478             if (ARGUMENT_PACK_P (arg))
9479               /* If ARG is an argument pack, we don't actually want to
9480                  perform a substitution here, because substitutions
9481                  for argument packs are only done
9482                  element-by-element. We can get to this point when
9483                  substituting the type of a non-type template
9484                  parameter pack, when that type actually contains
9485                  template parameter packs from an outer template, e.g.,
9486
9487                  template<typename... Types> struct A {
9488                    template<Types... Values> struct B { };
9489                  };  */
9490               return t;
9491
9492             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9493               {
9494                 int quals;
9495                 gcc_assert (TYPE_P (arg));
9496
9497                 /* cv-quals from the template are discarded when
9498                    substituting in a function or reference type.  */
9499                 if (TREE_CODE (arg) == FUNCTION_TYPE
9500                     || TREE_CODE (arg) == METHOD_TYPE
9501                     || TREE_CODE (arg) == REFERENCE_TYPE)
9502                   quals = cp_type_quals (arg);
9503                 else
9504                   quals = cp_type_quals (arg) | cp_type_quals (t);
9505                   
9506                 return cp_build_qualified_type_real
9507                   (arg, quals, complain | tf_ignore_bad_quals);
9508               }
9509             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9510               {
9511                 /* We are processing a type constructed from a
9512                    template template parameter.  */
9513                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9514                                       args, complain, in_decl);
9515                 if (argvec == error_mark_node)
9516                   return error_mark_node;
9517
9518                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9519                    are resolving nested-types in the signature of a
9520                    member function templates.  Otherwise ARG is a
9521                    TEMPLATE_DECL and is the real template to be
9522                    instantiated.  */
9523                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9524                   arg = TYPE_NAME (arg);
9525
9526                 r = lookup_template_class (arg,
9527                                            argvec, in_decl,
9528                                            DECL_CONTEXT (arg),
9529                                             /*entering_scope=*/0,
9530                                            complain);
9531                 return cp_build_qualified_type_real
9532                   (r, TYPE_QUALS (t), complain);
9533               }
9534             else
9535               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9536               return arg;
9537           }
9538
9539         if (level == 1)
9540           /* This can happen during the attempted tsubst'ing in
9541              unify.  This means that we don't yet have any information
9542              about the template parameter in question.  */
9543           return t;
9544
9545         /* If we get here, we must have been looking at a parm for a
9546            more deeply nested template.  Make a new version of this
9547            template parameter, but with a lower level.  */
9548         switch (TREE_CODE (t))
9549           {
9550           case TEMPLATE_TYPE_PARM:
9551           case TEMPLATE_TEMPLATE_PARM:
9552           case BOUND_TEMPLATE_TEMPLATE_PARM:
9553             if (cp_type_quals (t))
9554               {
9555                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9556                 r = cp_build_qualified_type_real
9557                   (r, cp_type_quals (t),
9558                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9559                                ? tf_ignore_bad_quals : 0));
9560               }
9561             else
9562               {
9563                 r = copy_type (t);
9564                 TEMPLATE_TYPE_PARM_INDEX (r)
9565                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9566                                                 r, levels, args, complain);
9567                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9568                 TYPE_MAIN_VARIANT (r) = r;
9569                 TYPE_POINTER_TO (r) = NULL_TREE;
9570                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9571
9572                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9573                   /* We have reduced the level of the template
9574                      template parameter, but not the levels of its
9575                      template parameters, so canonical_type_parameter
9576                      will not be able to find the canonical template
9577                      template parameter for this level. Thus, we
9578                      require structural equality checking to compare
9579                      TEMPLATE_TEMPLATE_PARMs. */
9580                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9581                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9582                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9583                 else
9584                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9585
9586                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9587                   {
9588                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9589                                           complain, in_decl);
9590                     if (argvec == error_mark_node)
9591                       return error_mark_node;
9592
9593                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9594                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9595                   }
9596               }
9597             break;
9598
9599           case TEMPLATE_PARM_INDEX:
9600             r = reduce_template_parm_level (t, type, levels, args, complain);
9601             break;
9602
9603           default:
9604             gcc_unreachable ();
9605           }
9606
9607         return r;
9608       }
9609
9610     case TREE_LIST:
9611       {
9612         tree purpose, value, chain;
9613
9614         if (t == void_list_node)
9615           return t;
9616
9617         purpose = TREE_PURPOSE (t);
9618         if (purpose)
9619           {
9620             purpose = tsubst (purpose, args, complain, in_decl);
9621             if (purpose == error_mark_node)
9622               return error_mark_node;
9623           }
9624         value = TREE_VALUE (t);
9625         if (value)
9626           {
9627             value = tsubst (value, args, complain, in_decl);
9628             if (value == error_mark_node)
9629               return error_mark_node;
9630           }
9631         chain = TREE_CHAIN (t);
9632         if (chain && chain != void_type_node)
9633           {
9634             chain = tsubst (chain, args, complain, in_decl);
9635             if (chain == error_mark_node)
9636               return error_mark_node;
9637           }
9638         if (purpose == TREE_PURPOSE (t)
9639             && value == TREE_VALUE (t)
9640             && chain == TREE_CHAIN (t))
9641           return t;
9642         return hash_tree_cons (purpose, value, chain);
9643       }
9644
9645     case TREE_BINFO:
9646       /* We should never be tsubsting a binfo.  */
9647       gcc_unreachable ();
9648
9649     case TREE_VEC:
9650       /* A vector of template arguments.  */
9651       gcc_assert (!type);
9652       return tsubst_template_args (t, args, complain, in_decl);
9653
9654     case POINTER_TYPE:
9655     case REFERENCE_TYPE:
9656       {
9657         enum tree_code code;
9658
9659         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9660           return t;
9661
9662         code = TREE_CODE (t);
9663
9664
9665         /* [temp.deduct]
9666
9667            Type deduction may fail for any of the following
9668            reasons:
9669
9670            -- Attempting to create a pointer to reference type.
9671            -- Attempting to create a reference to a reference type or
9672               a reference to void.
9673
9674           Core issue 106 says that creating a reference to a reference
9675           during instantiation is no longer a cause for failure. We
9676           only enforce this check in strict C++98 mode.  */
9677         if ((TREE_CODE (type) == REFERENCE_TYPE
9678              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9679             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9680           {
9681             static location_t last_loc;
9682
9683             /* We keep track of the last time we issued this error
9684                message to avoid spewing a ton of messages during a
9685                single bad template instantiation.  */
9686             if (complain & tf_error
9687                 && last_loc != input_location)
9688               {
9689                 if (TREE_CODE (type) == VOID_TYPE)
9690                   error ("forming reference to void");
9691                 else
9692                   error ("forming %s to reference type %qT",
9693                          (code == POINTER_TYPE) ? "pointer" : "reference",
9694                          type);
9695                 last_loc = input_location;
9696               }
9697
9698             return error_mark_node;
9699           }
9700         else if (code == POINTER_TYPE)
9701           {
9702             r = build_pointer_type (type);
9703             if (TREE_CODE (type) == METHOD_TYPE)
9704               r = build_ptrmemfunc_type (r);
9705           }
9706         else if (TREE_CODE (type) == REFERENCE_TYPE)
9707           /* In C++0x, during template argument substitution, when there is an
9708              attempt to create a reference to a reference type, reference
9709              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9710
9711              "If a template-argument for a template-parameter T names a type
9712              that is a reference to a type A, an attempt to create the type
9713              'lvalue reference to cv T' creates the type 'lvalue reference to
9714              A,' while an attempt to create the type type rvalue reference to
9715              cv T' creates the type T"
9716           */
9717           r = cp_build_reference_type
9718               (TREE_TYPE (type),
9719                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9720         else
9721           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9722         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9723
9724         if (r != error_mark_node)
9725           /* Will this ever be needed for TYPE_..._TO values?  */
9726           layout_type (r);
9727
9728         return r;
9729       }
9730     case OFFSET_TYPE:
9731       {
9732         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9733         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9734           {
9735             /* [temp.deduct]
9736
9737                Type deduction may fail for any of the following
9738                reasons:
9739
9740                -- Attempting to create "pointer to member of T" when T
9741                   is not a class type.  */
9742             if (complain & tf_error)
9743               error ("creating pointer to member of non-class type %qT", r);
9744             return error_mark_node;
9745           }
9746         if (TREE_CODE (type) == REFERENCE_TYPE)
9747           {
9748             if (complain & tf_error)
9749               error ("creating pointer to member reference type %qT", type);
9750             return error_mark_node;
9751           }
9752         if (TREE_CODE (type) == VOID_TYPE)
9753           {
9754             if (complain & tf_error)
9755               error ("creating pointer to member of type void");
9756             return error_mark_node;
9757           }
9758         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9759         if (TREE_CODE (type) == FUNCTION_TYPE)
9760           {
9761             /* The type of the implicit object parameter gets its
9762                cv-qualifiers from the FUNCTION_TYPE. */
9763             tree method_type;
9764             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9765                                                       cp_type_quals (type));
9766             tree memptr;
9767             method_type = build_method_type_directly (this_type,
9768                                                       TREE_TYPE (type),
9769                                                       TYPE_ARG_TYPES (type));
9770             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9771             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9772                                                  complain);
9773           }
9774         else
9775           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9776                                                TYPE_QUALS (t),
9777                                                complain);
9778       }
9779     case FUNCTION_TYPE:
9780     case METHOD_TYPE:
9781       {
9782         tree fntype;
9783         tree specs;
9784         fntype = tsubst_function_type (t, args, complain, in_decl);
9785         if (fntype == error_mark_node)
9786           return error_mark_node;
9787
9788         /* Substitute the exception specification.  */
9789         specs = tsubst_exception_specification (t, args, complain,
9790                                                 in_decl);
9791         if (specs == error_mark_node)
9792           return error_mark_node;
9793         if (specs)
9794           fntype = build_exception_variant (fntype, specs);
9795         return fntype;
9796       }
9797     case ARRAY_TYPE:
9798       {
9799         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9800         if (domain == error_mark_node)
9801           return error_mark_node;
9802
9803         /* As an optimization, we avoid regenerating the array type if
9804            it will obviously be the same as T.  */
9805         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9806           return t;
9807
9808         /* These checks should match the ones in grokdeclarator.
9809
9810            [temp.deduct]
9811
9812            The deduction may fail for any of the following reasons:
9813
9814            -- Attempting to create an array with an element type that
9815               is void, a function type, or a reference type, or [DR337]
9816               an abstract class type.  */
9817         if (TREE_CODE (type) == VOID_TYPE
9818             || TREE_CODE (type) == FUNCTION_TYPE
9819             || TREE_CODE (type) == REFERENCE_TYPE)
9820           {
9821             if (complain & tf_error)
9822               error ("creating array of %qT", type);
9823             return error_mark_node;
9824           }
9825         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9826           {
9827             if (complain & tf_error)
9828               error ("creating array of %qT, which is an abstract class type",
9829                      type);
9830             return error_mark_node;
9831           }
9832
9833         r = build_cplus_array_type (type, domain);
9834
9835         if (TYPE_USER_ALIGN (t))
9836           {
9837             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9838             TYPE_USER_ALIGN (r) = 1;
9839           }
9840
9841         return r;
9842       }
9843
9844     case PLUS_EXPR:
9845     case MINUS_EXPR:
9846       {
9847         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9848         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9849
9850         if (e1 == error_mark_node || e2 == error_mark_node)
9851           return error_mark_node;
9852
9853         return fold_build2_loc (input_location,
9854                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
9855       }
9856
9857     case NEGATE_EXPR:
9858     case NOP_EXPR:
9859       {
9860         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9861         if (e == error_mark_node)
9862           return error_mark_node;
9863
9864         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
9865       }
9866
9867     case TYPENAME_TYPE:
9868       {
9869         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9870                                      in_decl, /*entering_scope=*/1);
9871         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9872                               complain, in_decl);
9873
9874         if (ctx == error_mark_node || f == error_mark_node)
9875           return error_mark_node;
9876
9877         if (!MAYBE_CLASS_TYPE_P (ctx))
9878           {
9879             if (complain & tf_error)
9880               error ("%qT is not a class, struct, or union type", ctx);
9881             return error_mark_node;
9882           }
9883         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9884           {
9885             /* Normally, make_typename_type does not require that the CTX
9886                have complete type in order to allow things like:
9887
9888                  template <class T> struct S { typename S<T>::X Y; };
9889
9890                But, such constructs have already been resolved by this
9891                point, so here CTX really should have complete type, unless
9892                it's a partial instantiation.  */
9893             if (!(complain & tf_no_class_instantiations))
9894               ctx = complete_type (ctx);
9895             if (!COMPLETE_TYPE_P (ctx))
9896               {
9897                 if (complain & tf_error)
9898                   cxx_incomplete_type_error (NULL_TREE, ctx);
9899                 return error_mark_node;
9900               }
9901           }
9902
9903         f = make_typename_type (ctx, f, typename_type,
9904                                 (complain & tf_error) | tf_keep_type_decl);
9905         if (f == error_mark_node)
9906           return f;
9907         if (TREE_CODE (f) == TYPE_DECL)
9908           {
9909             complain |= tf_ignore_bad_quals;
9910             f = TREE_TYPE (f);
9911           }
9912
9913         if (TREE_CODE (f) != TYPENAME_TYPE)
9914           {
9915             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9916               error ("%qT resolves to %qT, which is not an enumeration type",
9917                      t, f);
9918             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9919               error ("%qT resolves to %qT, which is is not a class type",
9920                      t, f);
9921           }
9922
9923         return cp_build_qualified_type_real
9924           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9925       }
9926
9927     case UNBOUND_CLASS_TEMPLATE:
9928       {
9929         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9930                                      in_decl, /*entering_scope=*/1);
9931         tree name = TYPE_IDENTIFIER (t);
9932         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9933
9934         if (ctx == error_mark_node || name == error_mark_node)
9935           return error_mark_node;
9936
9937         if (parm_list)
9938           parm_list = tsubst_template_parms (parm_list, args, complain);
9939         return make_unbound_class_template (ctx, name, parm_list, complain);
9940       }
9941
9942     case INDIRECT_REF:
9943     case ADDR_EXPR:
9944     case CALL_EXPR:
9945       gcc_unreachable ();
9946
9947     case ARRAY_REF:
9948       {
9949         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9950         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9951                                /*integral_constant_expression_p=*/false);
9952         if (e1 == error_mark_node || e2 == error_mark_node)
9953           return error_mark_node;
9954
9955         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9956       }
9957
9958     case SCOPE_REF:
9959       {
9960         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9961         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9962         if (e1 == error_mark_node || e2 == error_mark_node)
9963           return error_mark_node;
9964
9965         return build_qualified_name (/*type=*/NULL_TREE,
9966                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9967       }
9968
9969     case TYPEOF_TYPE:
9970       {
9971         tree type;
9972
9973         type = finish_typeof (tsubst_expr 
9974                               (TYPEOF_TYPE_EXPR (t), args,
9975                                complain, in_decl,
9976                                /*integral_constant_expression_p=*/false));
9977         return cp_build_qualified_type_real (type,
9978                                              cp_type_quals (t)
9979                                              | cp_type_quals (type),
9980                                              complain);
9981       }
9982
9983     case DECLTYPE_TYPE:
9984       {
9985         tree type;
9986
9987         ++cp_unevaluated_operand;
9988         ++c_inhibit_evaluation_warnings;
9989
9990         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9991                             complain, in_decl,
9992                             /*integral_constant_expression_p=*/false);
9993
9994         --cp_unevaluated_operand;
9995         --c_inhibit_evaluation_warnings;
9996
9997         type =
9998           finish_decltype_type (type,
9999                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10000         return cp_build_qualified_type_real (type,
10001                                              cp_type_quals (t)
10002                                              | cp_type_quals (type),
10003                                              complain);
10004       }
10005
10006     case TYPE_ARGUMENT_PACK:
10007     case NONTYPE_ARGUMENT_PACK:
10008       {
10009         tree r = make_node (TREE_CODE (t));
10010         tree packed_out = 
10011           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10012                                 args,
10013                                 complain,
10014                                 in_decl);
10015         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10016
10017         /* For template nontype argument packs, also substitute into
10018            the type.  */
10019         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10020           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10021
10022         return r;
10023       }
10024       break;
10025
10026     default:
10027       sorry ("use of %qs in template",
10028              tree_code_name [(int) TREE_CODE (t)]);
10029       return error_mark_node;
10030     }
10031 }
10032
10033 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10034    type of the expression on the left-hand side of the "." or "->"
10035    operator.  */
10036
10037 static tree
10038 tsubst_baselink (tree baselink, tree object_type,
10039                  tree args, tsubst_flags_t complain, tree in_decl)
10040 {
10041     tree name;
10042     tree qualifying_scope;
10043     tree fns;
10044     tree optype;
10045     tree template_args = 0;
10046     bool template_id_p = false;
10047
10048     /* A baselink indicates a function from a base class.  Both the
10049        BASELINK_ACCESS_BINFO and the base class referenced may
10050        indicate bases of the template class, rather than the
10051        instantiated class.  In addition, lookups that were not
10052        ambiguous before may be ambiguous now.  Therefore, we perform
10053        the lookup again.  */
10054     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10055     qualifying_scope = tsubst (qualifying_scope, args,
10056                                complain, in_decl);
10057     fns = BASELINK_FUNCTIONS (baselink);
10058     optype = BASELINK_OPTYPE (baselink);
10059     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10060       {
10061         template_id_p = true;
10062         template_args = TREE_OPERAND (fns, 1);
10063         fns = TREE_OPERAND (fns, 0);
10064         if (template_args)
10065           template_args = tsubst_template_args (template_args, args,
10066                                                 complain, in_decl);
10067       }
10068     name = DECL_NAME (get_first_fn (fns));
10069     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10070
10071     /* If lookup found a single function, mark it as used at this
10072        point.  (If it lookup found multiple functions the one selected
10073        later by overload resolution will be marked as used at that
10074        point.)  */
10075     if (BASELINK_P (baselink))
10076       fns = BASELINK_FUNCTIONS (baselink);
10077     if (!template_id_p && !really_overloaded_fn (fns))
10078       mark_used (OVL_CURRENT (fns));
10079
10080     /* Add back the template arguments, if present.  */
10081     if (BASELINK_P (baselink) && template_id_p)
10082       BASELINK_FUNCTIONS (baselink)
10083         = build_nt (TEMPLATE_ID_EXPR,
10084                     BASELINK_FUNCTIONS (baselink),
10085                     template_args);
10086     /* Update the conversion operator type.  */
10087     BASELINK_OPTYPE (baselink) 
10088       = tsubst (optype, args, complain, in_decl);
10089
10090     if (!object_type)
10091       object_type = current_class_type;
10092     return adjust_result_of_qualified_name_lookup (baselink,
10093                                                    qualifying_scope,
10094                                                    object_type);
10095 }
10096
10097 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10098    true if the qualified-id will be a postfix-expression in-and-of
10099    itself; false if more of the postfix-expression follows the
10100    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10101    of "&".  */
10102
10103 static tree
10104 tsubst_qualified_id (tree qualified_id, tree args,
10105                      tsubst_flags_t complain, tree in_decl,
10106                      bool done, bool address_p)
10107 {
10108   tree expr;
10109   tree scope;
10110   tree name;
10111   bool is_template;
10112   tree template_args;
10113
10114   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10115
10116   /* Figure out what name to look up.  */
10117   name = TREE_OPERAND (qualified_id, 1);
10118   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10119     {
10120       is_template = true;
10121       template_args = TREE_OPERAND (name, 1);
10122       if (template_args)
10123         template_args = tsubst_template_args (template_args, args,
10124                                               complain, in_decl);
10125       name = TREE_OPERAND (name, 0);
10126     }
10127   else
10128     {
10129       is_template = false;
10130       template_args = NULL_TREE;
10131     }
10132
10133   /* Substitute into the qualifying scope.  When there are no ARGS, we
10134      are just trying to simplify a non-dependent expression.  In that
10135      case the qualifying scope may be dependent, and, in any case,
10136      substituting will not help.  */
10137   scope = TREE_OPERAND (qualified_id, 0);
10138   if (args)
10139     {
10140       scope = tsubst (scope, args, complain, in_decl);
10141       expr = tsubst_copy (name, args, complain, in_decl);
10142     }
10143   else
10144     expr = name;
10145
10146   if (dependent_type_p (scope))
10147     {
10148       tree type = NULL_TREE;
10149       if (DECL_P (expr) && !dependent_scope_p (scope))
10150         type = TREE_TYPE (expr);
10151       return build_qualified_name (type, scope, expr,
10152                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10153     }
10154
10155   if (!BASELINK_P (name) && !DECL_P (expr))
10156     {
10157       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10158         {
10159           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10160           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10161             {
10162               error ("qualifying type %qT does not match destructor name ~%qT",
10163                      scope, TREE_OPERAND (expr, 0));
10164               expr = error_mark_node;
10165             }
10166           else
10167             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10168                                           /*is_type_p=*/0, false);
10169         }
10170       else
10171         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10172       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10173                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10174         {
10175           if (complain & tf_error)
10176             {
10177               error ("dependent-name %qE is parsed as a non-type, but "
10178                      "instantiation yields a type", qualified_id);
10179               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10180             }
10181           return error_mark_node;
10182         }
10183     }
10184
10185   if (DECL_P (expr))
10186     {
10187       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10188                                            scope);
10189       /* Remember that there was a reference to this entity.  */
10190       mark_used (expr);
10191     }
10192
10193   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10194     {
10195       if (complain & tf_error)
10196         qualified_name_lookup_error (scope,
10197                                      TREE_OPERAND (qualified_id, 1),
10198                                      expr, input_location);
10199       return error_mark_node;
10200     }
10201
10202   if (is_template)
10203     expr = lookup_template_function (expr, template_args);
10204
10205   if (expr == error_mark_node && complain & tf_error)
10206     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10207                                  expr, input_location);
10208   else if (TYPE_P (scope))
10209     {
10210       expr = (adjust_result_of_qualified_name_lookup
10211               (expr, scope, current_class_type));
10212       expr = (finish_qualified_id_expr
10213               (scope, expr, done, address_p,
10214                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10215                /*template_arg_p=*/false));
10216     }
10217
10218   /* Expressions do not generally have reference type.  */
10219   if (TREE_CODE (expr) != SCOPE_REF
10220       /* However, if we're about to form a pointer-to-member, we just
10221          want the referenced member referenced.  */
10222       && TREE_CODE (expr) != OFFSET_REF)
10223     expr = convert_from_reference (expr);
10224
10225   return expr;
10226 }
10227
10228 /* Like tsubst, but deals with expressions.  This function just replaces
10229    template parms; to finish processing the resultant expression, use
10230    tsubst_expr.  */
10231
10232 static tree
10233 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10234 {
10235   enum tree_code code;
10236   tree r;
10237
10238   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10239     return t;
10240
10241   code = TREE_CODE (t);
10242
10243   switch (code)
10244     {
10245     case PARM_DECL:
10246       r = retrieve_local_specialization (t);
10247
10248       if (r == NULL)
10249         {
10250           tree c;
10251           /* This can happen for a parameter name used later in a function
10252              declaration (such as in a late-specified return type).  Just
10253              make a dummy decl, since it's only used for its type.  */
10254           gcc_assert (cp_unevaluated_operand != 0);
10255           /* We copy T because want to tsubst the PARM_DECL only,
10256              not the following PARM_DECLs that are chained to T.  */
10257           c = copy_node (t);
10258           r = tsubst_decl (c, args, complain);
10259           /* Give it the template pattern as its context; its true context
10260              hasn't been instantiated yet and this is good enough for
10261              mangling.  */
10262           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10263         }
10264       
10265       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10266         r = ARGUMENT_PACK_SELECT_ARG (r);
10267       mark_used (r);
10268       return r;
10269
10270     case CONST_DECL:
10271       {
10272         tree enum_type;
10273         tree v;
10274
10275         if (DECL_TEMPLATE_PARM_P (t))
10276           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10277         /* There is no need to substitute into namespace-scope
10278            enumerators.  */
10279         if (DECL_NAMESPACE_SCOPE_P (t))
10280           return t;
10281         /* If ARGS is NULL, then T is known to be non-dependent.  */
10282         if (args == NULL_TREE)
10283           return integral_constant_value (t);
10284
10285         /* Unfortunately, we cannot just call lookup_name here.
10286            Consider:
10287
10288              template <int I> int f() {
10289              enum E { a = I };
10290              struct S { void g() { E e = a; } };
10291              };
10292
10293            When we instantiate f<7>::S::g(), say, lookup_name is not
10294            clever enough to find f<7>::a.  */
10295         enum_type
10296           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10297                               /*entering_scope=*/0);
10298
10299         for (v = TYPE_VALUES (enum_type);
10300              v != NULL_TREE;
10301              v = TREE_CHAIN (v))
10302           if (TREE_PURPOSE (v) == DECL_NAME (t))
10303             return TREE_VALUE (v);
10304
10305           /* We didn't find the name.  That should never happen; if
10306              name-lookup found it during preliminary parsing, we
10307              should find it again here during instantiation.  */
10308         gcc_unreachable ();
10309       }
10310       return t;
10311
10312     case FIELD_DECL:
10313       if (DECL_CONTEXT (t))
10314         {
10315           tree ctx;
10316
10317           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10318                                   /*entering_scope=*/1);
10319           if (ctx != DECL_CONTEXT (t))
10320             {
10321               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10322               if (!r)
10323                 {
10324                   if (complain & tf_error)
10325                     error ("using invalid field %qD", t);
10326                   return error_mark_node;
10327                 }
10328               return r;
10329             }
10330         }
10331
10332       return t;
10333
10334     case VAR_DECL:
10335     case FUNCTION_DECL:
10336       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10337           || local_variable_p (t))
10338         t = tsubst (t, args, complain, in_decl);
10339       mark_used (t);
10340       return t;
10341
10342     case BASELINK:
10343       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10344
10345     case TEMPLATE_DECL:
10346       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10347         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10348                        args, complain, in_decl);
10349       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10350         return tsubst (t, args, complain, in_decl);
10351       else if (DECL_CLASS_SCOPE_P (t)
10352                && uses_template_parms (DECL_CONTEXT (t)))
10353         {
10354           /* Template template argument like the following example need
10355              special treatment:
10356
10357                template <template <class> class TT> struct C {};
10358                template <class T> struct D {
10359                  template <class U> struct E {};
10360                  C<E> c;                                // #1
10361                };
10362                D<int> d;                                // #2
10363
10364              We are processing the template argument `E' in #1 for
10365              the template instantiation #2.  Originally, `E' is a
10366              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10367              have to substitute this with one having context `D<int>'.  */
10368
10369           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10370           return lookup_field (context, DECL_NAME(t), 0, false);
10371         }
10372       else
10373         /* Ordinary template template argument.  */
10374         return t;
10375
10376     case CAST_EXPR:
10377     case REINTERPRET_CAST_EXPR:
10378     case CONST_CAST_EXPR:
10379     case STATIC_CAST_EXPR:
10380     case DYNAMIC_CAST_EXPR:
10381     case NOP_EXPR:
10382       return build1
10383         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10384          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10385
10386     case SIZEOF_EXPR:
10387       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10388         {
10389           /* We only want to compute the number of arguments.  */
10390           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10391                                                 complain, in_decl);
10392           int len = 0;
10393
10394           if (TREE_CODE (expanded) == TREE_VEC)
10395             len = TREE_VEC_LENGTH (expanded);
10396
10397           if (expanded == error_mark_node)
10398             return error_mark_node;
10399           else if (PACK_EXPANSION_P (expanded)
10400                    || (TREE_CODE (expanded) == TREE_VEC
10401                        && len > 0
10402                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10403             {
10404               if (TREE_CODE (expanded) == TREE_VEC)
10405                 expanded = TREE_VEC_ELT (expanded, len - 1);
10406
10407               if (TYPE_P (expanded))
10408                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10409                                                    complain & tf_error);
10410               else
10411                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10412                                                    complain & tf_error);
10413             }
10414           else
10415             return build_int_cst (size_type_node, len);
10416         }
10417       /* Fall through */
10418
10419     case INDIRECT_REF:
10420     case NEGATE_EXPR:
10421     case TRUTH_NOT_EXPR:
10422     case BIT_NOT_EXPR:
10423     case ADDR_EXPR:
10424     case UNARY_PLUS_EXPR:      /* Unary + */
10425     case ALIGNOF_EXPR:
10426     case ARROW_EXPR:
10427     case THROW_EXPR:
10428     case TYPEID_EXPR:
10429     case REALPART_EXPR:
10430     case IMAGPART_EXPR:
10431       return build1
10432         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10433          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10434
10435     case COMPONENT_REF:
10436       {
10437         tree object;
10438         tree name;
10439
10440         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10441         name = TREE_OPERAND (t, 1);
10442         if (TREE_CODE (name) == BIT_NOT_EXPR)
10443           {
10444             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10445                                 complain, in_decl);
10446             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10447           }
10448         else if (TREE_CODE (name) == SCOPE_REF
10449                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10450           {
10451             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10452                                      complain, in_decl);
10453             name = TREE_OPERAND (name, 1);
10454             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10455                                 complain, in_decl);
10456             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10457             name = build_qualified_name (/*type=*/NULL_TREE,
10458                                          base, name,
10459                                          /*template_p=*/false);
10460           }
10461         else if (TREE_CODE (name) == BASELINK)
10462           name = tsubst_baselink (name,
10463                                   non_reference (TREE_TYPE (object)),
10464                                   args, complain,
10465                                   in_decl);
10466         else
10467           name = tsubst_copy (name, args, complain, in_decl);
10468         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10469       }
10470
10471     case PLUS_EXPR:
10472     case MINUS_EXPR:
10473     case MULT_EXPR:
10474     case TRUNC_DIV_EXPR:
10475     case CEIL_DIV_EXPR:
10476     case FLOOR_DIV_EXPR:
10477     case ROUND_DIV_EXPR:
10478     case EXACT_DIV_EXPR:
10479     case BIT_AND_EXPR:
10480     case BIT_IOR_EXPR:
10481     case BIT_XOR_EXPR:
10482     case TRUNC_MOD_EXPR:
10483     case FLOOR_MOD_EXPR:
10484     case TRUTH_ANDIF_EXPR:
10485     case TRUTH_ORIF_EXPR:
10486     case TRUTH_AND_EXPR:
10487     case TRUTH_OR_EXPR:
10488     case RSHIFT_EXPR:
10489     case LSHIFT_EXPR:
10490     case RROTATE_EXPR:
10491     case LROTATE_EXPR:
10492     case EQ_EXPR:
10493     case NE_EXPR:
10494     case MAX_EXPR:
10495     case MIN_EXPR:
10496     case LE_EXPR:
10497     case GE_EXPR:
10498     case LT_EXPR:
10499     case GT_EXPR:
10500     case COMPOUND_EXPR:
10501     case DOTSTAR_EXPR:
10502     case MEMBER_REF:
10503     case PREDECREMENT_EXPR:
10504     case PREINCREMENT_EXPR:
10505     case POSTDECREMENT_EXPR:
10506     case POSTINCREMENT_EXPR:
10507       return build_nt
10508         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10509          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10510
10511     case SCOPE_REF:
10512       return build_qualified_name (/*type=*/NULL_TREE,
10513                                    tsubst_copy (TREE_OPERAND (t, 0),
10514                                                 args, complain, in_decl),
10515                                    tsubst_copy (TREE_OPERAND (t, 1),
10516                                                 args, complain, in_decl),
10517                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10518
10519     case ARRAY_REF:
10520       return build_nt
10521         (ARRAY_REF,
10522          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10523          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10524          NULL_TREE, NULL_TREE);
10525
10526     case CALL_EXPR:
10527       {
10528         int n = VL_EXP_OPERAND_LENGTH (t);
10529         tree result = build_vl_exp (CALL_EXPR, n);
10530         int i;
10531         for (i = 0; i < n; i++)
10532           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10533                                              complain, in_decl);
10534         return result;
10535       }
10536
10537     case COND_EXPR:
10538     case MODOP_EXPR:
10539     case PSEUDO_DTOR_EXPR:
10540       {
10541         r = build_nt
10542           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10543            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10544            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10545         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10546         return r;
10547       }
10548
10549     case NEW_EXPR:
10550       {
10551         r = build_nt
10552         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10553          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10554          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10555         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10556         return r;
10557       }
10558
10559     case DELETE_EXPR:
10560       {
10561         r = build_nt
10562         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10563          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10564         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10565         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10566         return r;
10567       }
10568
10569     case TEMPLATE_ID_EXPR:
10570       {
10571         /* Substituted template arguments */
10572         tree fn = TREE_OPERAND (t, 0);
10573         tree targs = TREE_OPERAND (t, 1);
10574
10575         fn = tsubst_copy (fn, args, complain, in_decl);
10576         if (targs)
10577           targs = tsubst_template_args (targs, args, complain, in_decl);
10578
10579         return lookup_template_function (fn, targs);
10580       }
10581
10582     case TREE_LIST:
10583       {
10584         tree purpose, value, chain;
10585
10586         if (t == void_list_node)
10587           return t;
10588
10589         purpose = TREE_PURPOSE (t);
10590         if (purpose)
10591           purpose = tsubst_copy (purpose, args, complain, in_decl);
10592         value = TREE_VALUE (t);
10593         if (value)
10594           value = tsubst_copy (value, args, complain, in_decl);
10595         chain = TREE_CHAIN (t);
10596         if (chain && chain != void_type_node)
10597           chain = tsubst_copy (chain, args, complain, in_decl);
10598         if (purpose == TREE_PURPOSE (t)
10599             && value == TREE_VALUE (t)
10600             && chain == TREE_CHAIN (t))
10601           return t;
10602         return tree_cons (purpose, value, chain);
10603       }
10604
10605     case RECORD_TYPE:
10606     case UNION_TYPE:
10607     case ENUMERAL_TYPE:
10608     case INTEGER_TYPE:
10609     case TEMPLATE_TYPE_PARM:
10610     case TEMPLATE_TEMPLATE_PARM:
10611     case BOUND_TEMPLATE_TEMPLATE_PARM:
10612     case TEMPLATE_PARM_INDEX:
10613     case POINTER_TYPE:
10614     case REFERENCE_TYPE:
10615     case OFFSET_TYPE:
10616     case FUNCTION_TYPE:
10617     case METHOD_TYPE:
10618     case ARRAY_TYPE:
10619     case TYPENAME_TYPE:
10620     case UNBOUND_CLASS_TEMPLATE:
10621     case TYPEOF_TYPE:
10622     case DECLTYPE_TYPE:
10623     case TYPE_DECL:
10624       return tsubst (t, args, complain, in_decl);
10625
10626     case IDENTIFIER_NODE:
10627       if (IDENTIFIER_TYPENAME_P (t))
10628         {
10629           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10630           return mangle_conv_op_name_for_type (new_type);
10631         }
10632       else
10633         return t;
10634
10635     case CONSTRUCTOR:
10636       /* This is handled by tsubst_copy_and_build.  */
10637       gcc_unreachable ();
10638
10639     case VA_ARG_EXPR:
10640       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10641                                           in_decl),
10642                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10643
10644     case CLEANUP_POINT_EXPR:
10645       /* We shouldn't have built any of these during initial template
10646          generation.  Instead, they should be built during instantiation
10647          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10648       gcc_unreachable ();
10649
10650     case OFFSET_REF:
10651       mark_used (TREE_OPERAND (t, 1));
10652       return t;
10653
10654     case EXPR_PACK_EXPANSION:
10655       error ("invalid use of pack expansion expression");
10656       return error_mark_node;
10657
10658     case NONTYPE_ARGUMENT_PACK:
10659       error ("use %<...%> to expand argument pack");
10660       return error_mark_node;
10661
10662     default:
10663       return t;
10664     }
10665 }
10666
10667 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10668
10669 static tree
10670 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10671                     tree in_decl)
10672 {
10673   tree new_clauses = NULL, nc, oc;
10674
10675   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10676     {
10677       nc = copy_node (oc);
10678       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10679       new_clauses = nc;
10680
10681       switch (OMP_CLAUSE_CODE (nc))
10682         {
10683         case OMP_CLAUSE_LASTPRIVATE:
10684           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10685             {
10686               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10687               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10688                            in_decl, /*integral_constant_expression_p=*/false);
10689               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10690                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10691             }
10692           /* FALLTHRU */
10693         case OMP_CLAUSE_PRIVATE:
10694         case OMP_CLAUSE_SHARED:
10695         case OMP_CLAUSE_FIRSTPRIVATE:
10696         case OMP_CLAUSE_REDUCTION:
10697         case OMP_CLAUSE_COPYIN:
10698         case OMP_CLAUSE_COPYPRIVATE:
10699         case OMP_CLAUSE_IF:
10700         case OMP_CLAUSE_NUM_THREADS:
10701         case OMP_CLAUSE_SCHEDULE:
10702         case OMP_CLAUSE_COLLAPSE:
10703           OMP_CLAUSE_OPERAND (nc, 0)
10704             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10705                            in_decl, /*integral_constant_expression_p=*/false);
10706           break;
10707         case OMP_CLAUSE_NOWAIT:
10708         case OMP_CLAUSE_ORDERED:
10709         case OMP_CLAUSE_DEFAULT:
10710         case OMP_CLAUSE_UNTIED:
10711           break;
10712         default:
10713           gcc_unreachable ();
10714         }
10715     }
10716
10717   return finish_omp_clauses (nreverse (new_clauses));
10718 }
10719
10720 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10721
10722 static tree
10723 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10724                           tree in_decl)
10725 {
10726 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10727
10728   tree purpose, value, chain;
10729
10730   if (t == NULL)
10731     return t;
10732
10733   if (TREE_CODE (t) != TREE_LIST)
10734     return tsubst_copy_and_build (t, args, complain, in_decl,
10735                                   /*function_p=*/false,
10736                                   /*integral_constant_expression_p=*/false);
10737
10738   if (t == void_list_node)
10739     return t;
10740
10741   purpose = TREE_PURPOSE (t);
10742   if (purpose)
10743     purpose = RECUR (purpose);
10744   value = TREE_VALUE (t);
10745   if (value)
10746     value = RECUR (value);
10747   chain = TREE_CHAIN (t);
10748   if (chain && chain != void_type_node)
10749     chain = RECUR (chain);
10750   return tree_cons (purpose, value, chain);
10751 #undef RECUR
10752 }
10753
10754 /* Substitute one OMP_FOR iterator.  */
10755
10756 static void
10757 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10758                          tree condv, tree incrv, tree *clauses,
10759                          tree args, tsubst_flags_t complain, tree in_decl,
10760                          bool integral_constant_expression_p)
10761 {
10762 #define RECUR(NODE)                             \
10763   tsubst_expr ((NODE), args, complain, in_decl, \
10764                integral_constant_expression_p)
10765   tree decl, init, cond, incr, auto_node;
10766
10767   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10768   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10769   decl = RECUR (TREE_OPERAND (init, 0));
10770   init = TREE_OPERAND (init, 1);
10771   auto_node = type_uses_auto (TREE_TYPE (decl));
10772   if (auto_node && init)
10773     {
10774       tree init_expr = init;
10775       if (TREE_CODE (init_expr) == DECL_EXPR)
10776         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10777       init_expr = RECUR (init_expr);
10778       TREE_TYPE (decl)
10779         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10780     }
10781   gcc_assert (!type_dependent_expression_p (decl));
10782
10783   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10784     {
10785       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10786       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10787       if (TREE_CODE (incr) == MODIFY_EXPR)
10788         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10789                                     RECUR (TREE_OPERAND (incr, 1)),
10790                                     complain);
10791       else
10792         incr = RECUR (incr);
10793       TREE_VEC_ELT (declv, i) = decl;
10794       TREE_VEC_ELT (initv, i) = init;
10795       TREE_VEC_ELT (condv, i) = cond;
10796       TREE_VEC_ELT (incrv, i) = incr;
10797       return;
10798     }
10799
10800   if (init && TREE_CODE (init) != DECL_EXPR)
10801     {
10802       tree c;
10803       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10804         {
10805           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10806                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10807               && OMP_CLAUSE_DECL (c) == decl)
10808             break;
10809           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10810                    && OMP_CLAUSE_DECL (c) == decl)
10811             error ("iteration variable %qD should not be firstprivate", decl);
10812           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10813                    && OMP_CLAUSE_DECL (c) == decl)
10814             error ("iteration variable %qD should not be reduction", decl);
10815         }
10816       if (c == NULL)
10817         {
10818           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
10819           OMP_CLAUSE_DECL (c) = decl;
10820           c = finish_omp_clauses (c);
10821           if (c)
10822             {
10823               OMP_CLAUSE_CHAIN (c) = *clauses;
10824               *clauses = c;
10825             }
10826         }
10827     }
10828   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10829   if (COMPARISON_CLASS_P (cond))
10830     cond = build2 (TREE_CODE (cond), boolean_type_node,
10831                    RECUR (TREE_OPERAND (cond, 0)),
10832                    RECUR (TREE_OPERAND (cond, 1)));
10833   else
10834     cond = RECUR (cond);
10835   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10836   switch (TREE_CODE (incr))
10837     {
10838     case PREINCREMENT_EXPR:
10839     case PREDECREMENT_EXPR:
10840     case POSTINCREMENT_EXPR:
10841     case POSTDECREMENT_EXPR:
10842       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10843                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10844       break;
10845     case MODIFY_EXPR:
10846       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10847           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10848         {
10849           tree rhs = TREE_OPERAND (incr, 1);
10850           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10851                          RECUR (TREE_OPERAND (incr, 0)),
10852                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10853                                  RECUR (TREE_OPERAND (rhs, 0)),
10854                                  RECUR (TREE_OPERAND (rhs, 1))));
10855         }
10856       else
10857         incr = RECUR (incr);
10858       break;
10859     case MODOP_EXPR:
10860       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10861           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10862         {
10863           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10864           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10865                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10866                                  TREE_TYPE (decl), lhs,
10867                                  RECUR (TREE_OPERAND (incr, 2))));
10868         }
10869       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10870                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10871                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10872         {
10873           tree rhs = TREE_OPERAND (incr, 2);
10874           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10875                          RECUR (TREE_OPERAND (incr, 0)),
10876                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10877                                  RECUR (TREE_OPERAND (rhs, 0)),
10878                                  RECUR (TREE_OPERAND (rhs, 1))));
10879         }
10880       else
10881         incr = RECUR (incr);
10882       break;
10883     default:
10884       incr = RECUR (incr);
10885       break;
10886     }
10887
10888   TREE_VEC_ELT (declv, i) = decl;
10889   TREE_VEC_ELT (initv, i) = init;
10890   TREE_VEC_ELT (condv, i) = cond;
10891   TREE_VEC_ELT (incrv, i) = incr;
10892 #undef RECUR
10893 }
10894
10895 /* Like tsubst_copy for expressions, etc. but also does semantic
10896    processing.  */
10897
10898 static tree
10899 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10900              bool integral_constant_expression_p)
10901 {
10902 #define RECUR(NODE)                             \
10903   tsubst_expr ((NODE), args, complain, in_decl, \
10904                integral_constant_expression_p)
10905
10906   tree stmt, tmp;
10907
10908   if (t == NULL_TREE || t == error_mark_node)
10909     return t;
10910
10911   if (EXPR_HAS_LOCATION (t))
10912     input_location = EXPR_LOCATION (t);
10913   if (STATEMENT_CODE_P (TREE_CODE (t)))
10914     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10915
10916   switch (TREE_CODE (t))
10917     {
10918     case STATEMENT_LIST:
10919       {
10920         tree_stmt_iterator i;
10921         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10922           RECUR (tsi_stmt (i));
10923         break;
10924       }
10925
10926     case CTOR_INITIALIZER:
10927       finish_mem_initializers (tsubst_initializer_list
10928                                (TREE_OPERAND (t, 0), args));
10929       break;
10930
10931     case RETURN_EXPR:
10932       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10933       break;
10934
10935     case EXPR_STMT:
10936       tmp = RECUR (EXPR_STMT_EXPR (t));
10937       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10938         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10939       else
10940         finish_expr_stmt (tmp);
10941       break;
10942
10943     case USING_STMT:
10944       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10945       break;
10946
10947     case DECL_EXPR:
10948       {
10949         tree decl;
10950         tree init;
10951
10952         decl = DECL_EXPR_DECL (t);
10953         if (TREE_CODE (decl) == LABEL_DECL)
10954           finish_label_decl (DECL_NAME (decl));
10955         else if (TREE_CODE (decl) == USING_DECL)
10956           {
10957             tree scope = USING_DECL_SCOPE (decl);
10958             tree name = DECL_NAME (decl);
10959             tree decl;
10960
10961             scope = RECUR (scope);
10962             decl = lookup_qualified_name (scope, name,
10963                                           /*is_type_p=*/false,
10964                                           /*complain=*/false);
10965             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10966               qualified_name_lookup_error (scope, name, decl, input_location);
10967             else
10968               do_local_using_decl (decl, scope, name);
10969           }
10970         else
10971           {
10972             init = DECL_INITIAL (decl);
10973             decl = tsubst (decl, args, complain, in_decl);
10974             if (decl != error_mark_node)
10975               {
10976                 /* By marking the declaration as instantiated, we avoid
10977                    trying to instantiate it.  Since instantiate_decl can't
10978                    handle local variables, and since we've already done
10979                    all that needs to be done, that's the right thing to
10980                    do.  */
10981                 if (TREE_CODE (decl) == VAR_DECL)
10982                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10983                 if (TREE_CODE (decl) == VAR_DECL
10984                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10985                   /* Anonymous aggregates are a special case.  */
10986                   finish_anon_union (decl);
10987                 else
10988                   {
10989                     maybe_push_decl (decl);
10990                     if (TREE_CODE (decl) == VAR_DECL
10991                         && DECL_PRETTY_FUNCTION_P (decl))
10992                       {
10993                         /* For __PRETTY_FUNCTION__ we have to adjust the
10994                            initializer.  */
10995                         const char *const name
10996                           = cxx_printable_name (current_function_decl, 2);
10997                         init = cp_fname_init (name, &TREE_TYPE (decl));
10998                       }
10999                     else
11000                       {
11001                         tree t = RECUR (init);
11002
11003                         if (init && !t)
11004                           /* If we had an initializer but it
11005                              instantiated to nothing,
11006                              value-initialize the object.  This will
11007                              only occur when the initializer was a
11008                              pack expansion where the parameter packs
11009                              used in that expansion were of length
11010                              zero.  */
11011                           init = build_value_init (TREE_TYPE (decl));
11012                         else
11013                           init = t;
11014                       }
11015
11016                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11017                   }
11018               }
11019           }
11020
11021         /* A DECL_EXPR can also be used as an expression, in the condition
11022            clause of an if/for/while construct.  */
11023         return decl;
11024       }
11025
11026     case FOR_STMT:
11027       stmt = begin_for_stmt ();
11028                           RECUR (FOR_INIT_STMT (t));
11029       finish_for_init_stmt (stmt);
11030       tmp = RECUR (FOR_COND (t));
11031       finish_for_cond (tmp, stmt);
11032       tmp = RECUR (FOR_EXPR (t));
11033       finish_for_expr (tmp, stmt);
11034       RECUR (FOR_BODY (t));
11035       finish_for_stmt (stmt);
11036       break;
11037
11038     case WHILE_STMT:
11039       stmt = begin_while_stmt ();
11040       tmp = RECUR (WHILE_COND (t));
11041       finish_while_stmt_cond (tmp, stmt);
11042       RECUR (WHILE_BODY (t));
11043       finish_while_stmt (stmt);
11044       break;
11045
11046     case DO_STMT:
11047       stmt = begin_do_stmt ();
11048       RECUR (DO_BODY (t));
11049       finish_do_body (stmt);
11050       tmp = RECUR (DO_COND (t));
11051       finish_do_stmt (tmp, stmt);
11052       break;
11053
11054     case IF_STMT:
11055       stmt = begin_if_stmt ();
11056       tmp = RECUR (IF_COND (t));
11057       finish_if_stmt_cond (tmp, stmt);
11058       RECUR (THEN_CLAUSE (t));
11059       finish_then_clause (stmt);
11060
11061       if (ELSE_CLAUSE (t))
11062         {
11063           begin_else_clause (stmt);
11064           RECUR (ELSE_CLAUSE (t));
11065           finish_else_clause (stmt);
11066         }
11067
11068       finish_if_stmt (stmt);
11069       break;
11070
11071     case BIND_EXPR:
11072       if (BIND_EXPR_BODY_BLOCK (t))
11073         stmt = begin_function_body ();
11074       else
11075         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11076                                     ? BCS_TRY_BLOCK : 0);
11077
11078       RECUR (BIND_EXPR_BODY (t));
11079
11080       if (BIND_EXPR_BODY_BLOCK (t))
11081         finish_function_body (stmt);
11082       else
11083         finish_compound_stmt (stmt);
11084       break;
11085
11086     case BREAK_STMT:
11087       finish_break_stmt ();
11088       break;
11089
11090     case CONTINUE_STMT:
11091       finish_continue_stmt ();
11092       break;
11093
11094     case SWITCH_STMT:
11095       stmt = begin_switch_stmt ();
11096       tmp = RECUR (SWITCH_STMT_COND (t));
11097       finish_switch_cond (tmp, stmt);
11098       RECUR (SWITCH_STMT_BODY (t));
11099       finish_switch_stmt (stmt);
11100       break;
11101
11102     case CASE_LABEL_EXPR:
11103       finish_case_label (EXPR_LOCATION (t),
11104                          RECUR (CASE_LOW (t)),
11105                          RECUR (CASE_HIGH (t)));
11106       break;
11107
11108     case LABEL_EXPR:
11109       {
11110         tree decl = LABEL_EXPR_LABEL (t);
11111         tree label;
11112
11113         label = finish_label_stmt (DECL_NAME (decl));
11114         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11115           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11116       }
11117       break;
11118
11119     case GOTO_EXPR:
11120       tmp = GOTO_DESTINATION (t);
11121       if (TREE_CODE (tmp) != LABEL_DECL)
11122         /* Computed goto's must be tsubst'd into.  On the other hand,
11123            non-computed gotos must not be; the identifier in question
11124            will have no binding.  */
11125         tmp = RECUR (tmp);
11126       else
11127         tmp = DECL_NAME (tmp);
11128       finish_goto_stmt (tmp);
11129       break;
11130
11131     case ASM_EXPR:
11132       tmp = finish_asm_stmt
11133         (ASM_VOLATILE_P (t),
11134          RECUR (ASM_STRING (t)),
11135          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11136          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11137          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
11138       {
11139         tree asm_expr = tmp;
11140         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11141           asm_expr = TREE_OPERAND (asm_expr, 0);
11142         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11143       }
11144       break;
11145
11146     case TRY_BLOCK:
11147       if (CLEANUP_P (t))
11148         {
11149           stmt = begin_try_block ();
11150           RECUR (TRY_STMTS (t));
11151           finish_cleanup_try_block (stmt);
11152           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11153         }
11154       else
11155         {
11156           tree compound_stmt = NULL_TREE;
11157
11158           if (FN_TRY_BLOCK_P (t))
11159             stmt = begin_function_try_block (&compound_stmt);
11160           else
11161             stmt = begin_try_block ();
11162
11163           RECUR (TRY_STMTS (t));
11164
11165           if (FN_TRY_BLOCK_P (t))
11166             finish_function_try_block (stmt);
11167           else
11168             finish_try_block (stmt);
11169
11170           RECUR (TRY_HANDLERS (t));
11171           if (FN_TRY_BLOCK_P (t))
11172             finish_function_handler_sequence (stmt, compound_stmt);
11173           else
11174             finish_handler_sequence (stmt);
11175         }
11176       break;
11177
11178     case HANDLER:
11179       {
11180         tree decl = HANDLER_PARMS (t);
11181
11182         if (decl)
11183           {
11184             decl = tsubst (decl, args, complain, in_decl);
11185             /* Prevent instantiate_decl from trying to instantiate
11186                this variable.  We've already done all that needs to be
11187                done.  */
11188             if (decl != error_mark_node)
11189               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11190           }
11191         stmt = begin_handler ();
11192         finish_handler_parms (decl, stmt);
11193         RECUR (HANDLER_BODY (t));
11194         finish_handler (stmt);
11195       }
11196       break;
11197
11198     case TAG_DEFN:
11199       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11200       break;
11201
11202     case STATIC_ASSERT:
11203       {
11204         tree condition = 
11205           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11206                        args,
11207                        complain, in_decl,
11208                        /*integral_constant_expression_p=*/true);
11209         finish_static_assert (condition,
11210                               STATIC_ASSERT_MESSAGE (t),
11211                               STATIC_ASSERT_SOURCE_LOCATION (t),
11212                               /*member_p=*/false);
11213       }
11214       break;
11215
11216     case OMP_PARALLEL:
11217       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11218                                 args, complain, in_decl);
11219       stmt = begin_omp_parallel ();
11220       RECUR (OMP_PARALLEL_BODY (t));
11221       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11222         = OMP_PARALLEL_COMBINED (t);
11223       break;
11224
11225     case OMP_TASK:
11226       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11227                                 args, complain, in_decl);
11228       stmt = begin_omp_task ();
11229       RECUR (OMP_TASK_BODY (t));
11230       finish_omp_task (tmp, stmt);
11231       break;
11232
11233     case OMP_FOR:
11234       {
11235         tree clauses, body, pre_body;
11236         tree declv, initv, condv, incrv;
11237         int i;
11238
11239         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11240                                       args, complain, in_decl);
11241         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11242         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11243         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11244         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11245
11246         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11247           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11248                                    &clauses, args, complain, in_decl,
11249                                    integral_constant_expression_p);
11250
11251         stmt = begin_omp_structured_block ();
11252
11253         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11254           if (TREE_VEC_ELT (initv, i) == NULL
11255               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11256             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11257           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11258             {
11259               tree init = RECUR (TREE_VEC_ELT (initv, i));
11260               gcc_assert (init == TREE_VEC_ELT (declv, i));
11261               TREE_VEC_ELT (initv, i) = NULL_TREE;
11262             }
11263           else
11264             {
11265               tree decl_expr = TREE_VEC_ELT (initv, i);
11266               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11267               gcc_assert (init != NULL);
11268               TREE_VEC_ELT (initv, i) = RECUR (init);
11269               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11270               RECUR (decl_expr);
11271               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11272             }
11273
11274         pre_body = push_stmt_list ();
11275         RECUR (OMP_FOR_PRE_BODY (t));
11276         pre_body = pop_stmt_list (pre_body);
11277
11278         body = push_stmt_list ();
11279         RECUR (OMP_FOR_BODY (t));
11280         body = pop_stmt_list (body);
11281
11282         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11283                             body, pre_body, clauses);
11284
11285         add_stmt (finish_omp_structured_block (stmt));
11286       }
11287       break;
11288
11289     case OMP_SECTIONS:
11290     case OMP_SINGLE:
11291       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11292       stmt = push_stmt_list ();
11293       RECUR (OMP_BODY (t));
11294       stmt = pop_stmt_list (stmt);
11295
11296       t = copy_node (t);
11297       OMP_BODY (t) = stmt;
11298       OMP_CLAUSES (t) = tmp;
11299       add_stmt (t);
11300       break;
11301
11302     case OMP_SECTION:
11303     case OMP_CRITICAL:
11304     case OMP_MASTER:
11305     case OMP_ORDERED:
11306       stmt = push_stmt_list ();
11307       RECUR (OMP_BODY (t));
11308       stmt = pop_stmt_list (stmt);
11309
11310       t = copy_node (t);
11311       OMP_BODY (t) = stmt;
11312       add_stmt (t);
11313       break;
11314
11315     case OMP_ATOMIC:
11316       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11317       {
11318         tree op1 = TREE_OPERAND (t, 1);
11319         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11320         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11321         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11322       }
11323       break;
11324
11325     case EXPR_PACK_EXPANSION:
11326       error ("invalid use of pack expansion expression");
11327       return error_mark_node;
11328
11329     case NONTYPE_ARGUMENT_PACK:
11330       error ("use %<...%> to expand argument pack");
11331       return error_mark_node;
11332
11333     default:
11334       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11335
11336       return tsubst_copy_and_build (t, args, complain, in_decl,
11337                                     /*function_p=*/false,
11338                                     integral_constant_expression_p);
11339     }
11340
11341   return NULL_TREE;
11342 #undef RECUR
11343 }
11344
11345 /* T is a postfix-expression that is not being used in a function
11346    call.  Return the substituted version of T.  */
11347
11348 static tree
11349 tsubst_non_call_postfix_expression (tree t, tree args,
11350                                     tsubst_flags_t complain,
11351                                     tree in_decl)
11352 {
11353   if (TREE_CODE (t) == SCOPE_REF)
11354     t = tsubst_qualified_id (t, args, complain, in_decl,
11355                              /*done=*/false, /*address_p=*/false);
11356   else
11357     t = tsubst_copy_and_build (t, args, complain, in_decl,
11358                                /*function_p=*/false,
11359                                /*integral_constant_expression_p=*/false);
11360
11361   return t;
11362 }
11363
11364 /* Like tsubst but deals with expressions and performs semantic
11365    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11366
11367 tree
11368 tsubst_copy_and_build (tree t,
11369                        tree args,
11370                        tsubst_flags_t complain,
11371                        tree in_decl,
11372                        bool function_p,
11373                        bool integral_constant_expression_p)
11374 {
11375 #define RECUR(NODE)                                             \
11376   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11377                          /*function_p=*/false,                  \
11378                          integral_constant_expression_p)
11379
11380   tree op1;
11381
11382   if (t == NULL_TREE || t == error_mark_node)
11383     return t;
11384
11385   switch (TREE_CODE (t))
11386     {
11387     case USING_DECL:
11388       t = DECL_NAME (t);
11389       /* Fall through.  */
11390     case IDENTIFIER_NODE:
11391       {
11392         tree decl;
11393         cp_id_kind idk;
11394         bool non_integral_constant_expression_p;
11395         const char *error_msg;
11396
11397         if (IDENTIFIER_TYPENAME_P (t))
11398           {
11399             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11400             t = mangle_conv_op_name_for_type (new_type);
11401           }
11402
11403         /* Look up the name.  */
11404         decl = lookup_name (t);
11405
11406         /* By convention, expressions use ERROR_MARK_NODE to indicate
11407            failure, not NULL_TREE.  */
11408         if (decl == NULL_TREE)
11409           decl = error_mark_node;
11410
11411         decl = finish_id_expression (t, decl, NULL_TREE,
11412                                      &idk,
11413                                      integral_constant_expression_p,
11414                                      /*allow_non_integral_constant_expression_p=*/false,
11415                                      &non_integral_constant_expression_p,
11416                                      /*template_p=*/false,
11417                                      /*done=*/true,
11418                                      /*address_p=*/false,
11419                                      /*template_arg_p=*/false,
11420                                      &error_msg,
11421                                      input_location);
11422         if (error_msg)
11423           error (error_msg);
11424         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11425           decl = unqualified_name_lookup_error (decl);
11426         return decl;
11427       }
11428
11429     case TEMPLATE_ID_EXPR:
11430       {
11431         tree object;
11432         tree templ = RECUR (TREE_OPERAND (t, 0));
11433         tree targs = TREE_OPERAND (t, 1);
11434
11435         if (targs)
11436           targs = tsubst_template_args (targs, args, complain, in_decl);
11437
11438         if (TREE_CODE (templ) == COMPONENT_REF)
11439           {
11440             object = TREE_OPERAND (templ, 0);
11441             templ = TREE_OPERAND (templ, 1);
11442           }
11443         else
11444           object = NULL_TREE;
11445         templ = lookup_template_function (templ, targs);
11446
11447         if (object)
11448           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11449                          object, templ, NULL_TREE);
11450         else
11451           return baselink_for_fns (templ);
11452       }
11453
11454     case INDIRECT_REF:
11455       {
11456         tree r = RECUR (TREE_OPERAND (t, 0));
11457
11458         if (REFERENCE_REF_P (t))
11459           {
11460             /* A type conversion to reference type will be enclosed in
11461                such an indirect ref, but the substitution of the cast
11462                will have also added such an indirect ref.  */
11463             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11464               r = convert_from_reference (r);
11465           }
11466         else
11467           r = build_x_indirect_ref (r, "unary *", complain);
11468         return r;
11469       }
11470
11471     case NOP_EXPR:
11472       return build_nop
11473         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11474          RECUR (TREE_OPERAND (t, 0)));
11475
11476     case CAST_EXPR:
11477     case REINTERPRET_CAST_EXPR:
11478     case CONST_CAST_EXPR:
11479     case DYNAMIC_CAST_EXPR:
11480     case STATIC_CAST_EXPR:
11481       {
11482         tree type;
11483         tree op;
11484
11485         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11486         if (integral_constant_expression_p
11487             && !cast_valid_in_integral_constant_expression_p (type))
11488           {
11489             if (complain & tf_error)
11490               error ("a cast to a type other than an integral or "
11491                      "enumeration type cannot appear in a constant-expression");
11492             return error_mark_node; 
11493           }
11494
11495         op = RECUR (TREE_OPERAND (t, 0));
11496
11497         switch (TREE_CODE (t))
11498           {
11499           case CAST_EXPR:
11500             return build_functional_cast (type, op, complain);
11501           case REINTERPRET_CAST_EXPR:
11502             return build_reinterpret_cast (type, op, complain);
11503           case CONST_CAST_EXPR:
11504             return build_const_cast (type, op, complain);
11505           case DYNAMIC_CAST_EXPR:
11506             return build_dynamic_cast (type, op, complain);
11507           case STATIC_CAST_EXPR:
11508             return build_static_cast (type, op, complain);
11509           default:
11510             gcc_unreachable ();
11511           }
11512       }
11513
11514     case POSTDECREMENT_EXPR:
11515     case POSTINCREMENT_EXPR:
11516       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11517                                                 args, complain, in_decl);
11518       return build_x_unary_op (TREE_CODE (t), op1, complain);
11519
11520     case PREDECREMENT_EXPR:
11521     case PREINCREMENT_EXPR:
11522     case NEGATE_EXPR:
11523     case BIT_NOT_EXPR:
11524     case ABS_EXPR:
11525     case TRUTH_NOT_EXPR:
11526     case UNARY_PLUS_EXPR:  /* Unary + */
11527     case REALPART_EXPR:
11528     case IMAGPART_EXPR:
11529       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11530                                complain);
11531
11532     case ADDR_EXPR:
11533       op1 = TREE_OPERAND (t, 0);
11534       if (TREE_CODE (op1) == SCOPE_REF)
11535         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11536                                    /*done=*/true, /*address_p=*/true);
11537       else
11538         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11539                                                   in_decl);
11540       if (TREE_CODE (op1) == LABEL_DECL)
11541         return finish_label_address_expr (DECL_NAME (op1),
11542                                           EXPR_LOCATION (op1));
11543       return build_x_unary_op (ADDR_EXPR, op1, complain);
11544
11545     case PLUS_EXPR:
11546     case MINUS_EXPR:
11547     case MULT_EXPR:
11548     case TRUNC_DIV_EXPR:
11549     case CEIL_DIV_EXPR:
11550     case FLOOR_DIV_EXPR:
11551     case ROUND_DIV_EXPR:
11552     case EXACT_DIV_EXPR:
11553     case BIT_AND_EXPR:
11554     case BIT_IOR_EXPR:
11555     case BIT_XOR_EXPR:
11556     case TRUNC_MOD_EXPR:
11557     case FLOOR_MOD_EXPR:
11558     case TRUTH_ANDIF_EXPR:
11559     case TRUTH_ORIF_EXPR:
11560     case TRUTH_AND_EXPR:
11561     case TRUTH_OR_EXPR:
11562     case RSHIFT_EXPR:
11563     case LSHIFT_EXPR:
11564     case RROTATE_EXPR:
11565     case LROTATE_EXPR:
11566     case EQ_EXPR:
11567     case NE_EXPR:
11568     case MAX_EXPR:
11569     case MIN_EXPR:
11570     case LE_EXPR:
11571     case GE_EXPR:
11572     case LT_EXPR:
11573     case GT_EXPR:
11574     case MEMBER_REF:
11575     case DOTSTAR_EXPR:
11576       return build_x_binary_op
11577         (TREE_CODE (t),
11578          RECUR (TREE_OPERAND (t, 0)),
11579          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11580           ? ERROR_MARK
11581           : TREE_CODE (TREE_OPERAND (t, 0))),
11582          RECUR (TREE_OPERAND (t, 1)),
11583          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11584           ? ERROR_MARK
11585           : TREE_CODE (TREE_OPERAND (t, 1))),
11586          /*overloaded_p=*/NULL,
11587          complain);
11588
11589     case SCOPE_REF:
11590       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11591                                   /*address_p=*/false);
11592     case ARRAY_REF:
11593       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11594                                                 args, complain, in_decl);
11595       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11596
11597     case SIZEOF_EXPR:
11598       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11599         return tsubst_copy (t, args, complain, in_decl);
11600       /* Fall through */
11601       
11602     case ALIGNOF_EXPR:
11603       op1 = TREE_OPERAND (t, 0);
11604       if (!args)
11605         {
11606           /* When there are no ARGS, we are trying to evaluate a
11607              non-dependent expression from the parser.  Trying to do
11608              the substitutions may not work.  */
11609           if (!TYPE_P (op1))
11610             op1 = TREE_TYPE (op1);
11611         }
11612       else
11613         {
11614           ++cp_unevaluated_operand;
11615           ++c_inhibit_evaluation_warnings;
11616           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11617                                        /*function_p=*/false,
11618                                        /*integral_constant_expression_p=*/false);
11619           --cp_unevaluated_operand;
11620           --c_inhibit_evaluation_warnings;
11621         }
11622       if (TYPE_P (op1))
11623         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11624                                            complain & tf_error);
11625       else
11626         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11627                                            complain & tf_error);
11628
11629     case MODOP_EXPR:
11630       {
11631         tree r = build_x_modify_expr
11632           (RECUR (TREE_OPERAND (t, 0)),
11633            TREE_CODE (TREE_OPERAND (t, 1)),
11634            RECUR (TREE_OPERAND (t, 2)),
11635            complain);
11636         /* TREE_NO_WARNING must be set if either the expression was
11637            parenthesized or it uses an operator such as >>= rather
11638            than plain assignment.  In the former case, it was already
11639            set and must be copied.  In the latter case,
11640            build_x_modify_expr sets it and it must not be reset
11641            here.  */
11642         if (TREE_NO_WARNING (t))
11643           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11644         return r;
11645       }
11646
11647     case ARROW_EXPR:
11648       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11649                                                 args, complain, in_decl);
11650       /* Remember that there was a reference to this entity.  */
11651       if (DECL_P (op1))
11652         mark_used (op1);
11653       return build_x_arrow (op1);
11654
11655     case NEW_EXPR:
11656       {
11657         tree placement = RECUR (TREE_OPERAND (t, 0));
11658         tree init = RECUR (TREE_OPERAND (t, 3));
11659         VEC(tree,gc) *placement_vec;
11660         VEC(tree,gc) *init_vec;
11661         tree ret;
11662
11663         if (placement == NULL_TREE)
11664           placement_vec = NULL;
11665         else
11666           {
11667             placement_vec = make_tree_vector ();
11668             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
11669               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
11670           }
11671
11672         /* If there was an initializer in the original tree, but it
11673            instantiated to an empty list, then we should pass a
11674            non-NULL empty vector to tell build_new that it was an
11675            empty initializer() rather than no initializer.  This can
11676            only happen when the initializer is a pack expansion whose
11677            parameter packs are of length zero.  */
11678         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
11679           init_vec = NULL;
11680         else
11681           {
11682             init_vec = make_tree_vector ();
11683             if (init == void_zero_node)
11684               gcc_assert (init_vec != NULL);
11685             else
11686               {
11687                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
11688                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
11689               }
11690           }
11691
11692         ret = build_new (&placement_vec,
11693                          RECUR (TREE_OPERAND (t, 1)),
11694                          RECUR (TREE_OPERAND (t, 2)),
11695                          &init_vec,
11696                          NEW_EXPR_USE_GLOBAL (t),
11697                          complain);
11698
11699         if (placement_vec != NULL)
11700           release_tree_vector (placement_vec);
11701         if (init_vec != NULL)
11702           release_tree_vector (init_vec);
11703
11704         return ret;
11705       }
11706
11707     case DELETE_EXPR:
11708      return delete_sanity
11709        (RECUR (TREE_OPERAND (t, 0)),
11710         RECUR (TREE_OPERAND (t, 1)),
11711         DELETE_EXPR_USE_VEC (t),
11712         DELETE_EXPR_USE_GLOBAL (t));
11713
11714     case COMPOUND_EXPR:
11715       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11716                                     RECUR (TREE_OPERAND (t, 1)),
11717                                     complain);
11718
11719     case CALL_EXPR:
11720       {
11721         tree function;
11722         VEC(tree,gc) *call_args;
11723         unsigned int nargs, i;
11724         bool qualified_p;
11725         bool koenig_p;
11726         tree ret;
11727
11728         function = CALL_EXPR_FN (t);
11729         /* When we parsed the expression,  we determined whether or
11730            not Koenig lookup should be performed.  */
11731         koenig_p = KOENIG_LOOKUP_P (t);
11732         if (TREE_CODE (function) == SCOPE_REF)
11733           {
11734             qualified_p = true;
11735             function = tsubst_qualified_id (function, args, complain, in_decl,
11736                                             /*done=*/false,
11737                                             /*address_p=*/false);
11738           }
11739         else
11740           {
11741             if (TREE_CODE (function) == COMPONENT_REF)
11742               {
11743                 tree op = TREE_OPERAND (function, 1);
11744
11745                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11746                                || (BASELINK_P (op)
11747                                    && BASELINK_QUALIFIED_P (op)));
11748               }
11749             else
11750               qualified_p = false;
11751
11752             function = tsubst_copy_and_build (function, args, complain,
11753                                               in_decl,
11754                                               !qualified_p,
11755                                               integral_constant_expression_p);
11756
11757             if (BASELINK_P (function))
11758               qualified_p = true;
11759           }
11760
11761         nargs = call_expr_nargs (t);
11762         call_args = make_tree_vector ();
11763         for (i = 0; i < nargs; ++i)
11764           {
11765             tree arg = CALL_EXPR_ARG (t, i);
11766
11767             if (!PACK_EXPANSION_P (arg))
11768               VEC_safe_push (tree, gc, call_args,
11769                              RECUR (CALL_EXPR_ARG (t, i)));
11770             else
11771               {
11772                 /* Expand the pack expansion and push each entry onto
11773                    CALL_ARGS.  */
11774                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
11775                 if (TREE_CODE (arg) == TREE_VEC)
11776                   {
11777                     unsigned int len, j;
11778
11779                     len = TREE_VEC_LENGTH (arg);
11780                     for (j = 0; j < len; ++j)
11781                       {
11782                         tree value = TREE_VEC_ELT (arg, j);
11783                         if (value != NULL_TREE)
11784                           value = convert_from_reference (value);
11785                         VEC_safe_push (tree, gc, call_args, value);
11786                       }
11787                   }
11788                 else
11789                   {
11790                     /* A partial substitution.  Add one entry.  */
11791                     VEC_safe_push (tree, gc, call_args, arg);
11792                   }
11793               }
11794           }
11795
11796         /* We do not perform argument-dependent lookup if normal
11797            lookup finds a non-function, in accordance with the
11798            expected resolution of DR 218.  */
11799         if (koenig_p
11800             && ((is_overloaded_fn (function)
11801                  /* If lookup found a member function, the Koenig lookup is
11802                     not appropriate, even if an unqualified-name was used
11803                     to denote the function.  */
11804                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11805                 || TREE_CODE (function) == IDENTIFIER_NODE)
11806             /* Only do this when substitution turns a dependent call
11807                into a non-dependent call.  */
11808             && type_dependent_expression_p_push (t)
11809             && !any_type_dependent_arguments_p (call_args))
11810           function = perform_koenig_lookup (function, call_args);
11811
11812         if (TREE_CODE (function) == IDENTIFIER_NODE)
11813           {
11814             unqualified_name_lookup_error (function);
11815             release_tree_vector (call_args);
11816             return error_mark_node;
11817           }
11818
11819         /* Remember that there was a reference to this entity.  */
11820         if (DECL_P (function))
11821           mark_used (function);
11822
11823         if (TREE_CODE (function) == OFFSET_REF)
11824           ret = build_offset_ref_call_from_tree (function, &call_args);
11825         else if (TREE_CODE (function) == COMPONENT_REF)
11826           {
11827             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11828               ret = finish_call_expr (function, &call_args,
11829                                        /*disallow_virtual=*/false,
11830                                        /*koenig_p=*/false,
11831                                        complain);
11832             else
11833               ret = (build_new_method_call
11834                       (TREE_OPERAND (function, 0),
11835                        TREE_OPERAND (function, 1),
11836                        &call_args, NULL_TREE,
11837                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11838                        /*fn_p=*/NULL,
11839                        complain));
11840           }
11841         else
11842           ret = finish_call_expr (function, &call_args,
11843                                   /*disallow_virtual=*/qualified_p,
11844                                   koenig_p,
11845                                   complain);
11846
11847         release_tree_vector (call_args);
11848
11849         return ret;
11850       }
11851
11852     case COND_EXPR:
11853       return build_x_conditional_expr
11854         (RECUR (TREE_OPERAND (t, 0)),
11855          RECUR (TREE_OPERAND (t, 1)),
11856          RECUR (TREE_OPERAND (t, 2)),
11857          complain);
11858
11859     case PSEUDO_DTOR_EXPR:
11860       return finish_pseudo_destructor_expr
11861         (RECUR (TREE_OPERAND (t, 0)),
11862          RECUR (TREE_OPERAND (t, 1)),
11863          RECUR (TREE_OPERAND (t, 2)));
11864
11865     case TREE_LIST:
11866       {
11867         tree purpose, value, chain;
11868
11869         if (t == void_list_node)
11870           return t;
11871
11872         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11873             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11874           {
11875             /* We have pack expansions, so expand those and
11876                create a new list out of it.  */
11877             tree purposevec = NULL_TREE;
11878             tree valuevec = NULL_TREE;
11879             tree chain;
11880             int i, len = -1;
11881
11882             /* Expand the argument expressions.  */
11883             if (TREE_PURPOSE (t))
11884               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11885                                                  complain, in_decl);
11886             if (TREE_VALUE (t))
11887               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11888                                                complain, in_decl);
11889
11890             /* Build the rest of the list.  */
11891             chain = TREE_CHAIN (t);
11892             if (chain && chain != void_type_node)
11893               chain = RECUR (chain);
11894
11895             /* Determine the number of arguments.  */
11896             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11897               {
11898                 len = TREE_VEC_LENGTH (purposevec);
11899                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11900               }
11901             else if (TREE_CODE (valuevec) == TREE_VEC)
11902               len = TREE_VEC_LENGTH (valuevec);
11903             else
11904               {
11905                 /* Since we only performed a partial substitution into
11906                    the argument pack, we only return a single list
11907                    node.  */
11908                 if (purposevec == TREE_PURPOSE (t)
11909                     && valuevec == TREE_VALUE (t)
11910                     && chain == TREE_CHAIN (t))
11911                   return t;
11912
11913                 return tree_cons (purposevec, valuevec, chain);
11914               }
11915             
11916             /* Convert the argument vectors into a TREE_LIST */
11917             i = len;
11918             while (i > 0)
11919               {
11920                 /* Grab the Ith values.  */
11921                 i--;
11922                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11923                                      : NULL_TREE;
11924                 value 
11925                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11926                              : NULL_TREE;
11927
11928                 /* Build the list (backwards).  */
11929                 chain = tree_cons (purpose, value, chain);
11930               }
11931
11932             return chain;
11933           }
11934
11935         purpose = TREE_PURPOSE (t);
11936         if (purpose)
11937           purpose = RECUR (purpose);
11938         value = TREE_VALUE (t);
11939         if (value)
11940           value = RECUR (value);
11941         chain = TREE_CHAIN (t);
11942         if (chain && chain != void_type_node)
11943           chain = RECUR (chain);
11944         if (purpose == TREE_PURPOSE (t)
11945             && value == TREE_VALUE (t)
11946             && chain == TREE_CHAIN (t))
11947           return t;
11948         return tree_cons (purpose, value, chain);
11949       }
11950
11951     case COMPONENT_REF:
11952       {
11953         tree object;
11954         tree object_type;
11955         tree member;
11956
11957         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11958                                                      args, complain, in_decl);
11959         /* Remember that there was a reference to this entity.  */
11960         if (DECL_P (object))
11961           mark_used (object);
11962         object_type = TREE_TYPE (object);
11963
11964         member = TREE_OPERAND (t, 1);
11965         if (BASELINK_P (member))
11966           member = tsubst_baselink (member,
11967                                     non_reference (TREE_TYPE (object)),
11968                                     args, complain, in_decl);
11969         else
11970           member = tsubst_copy (member, args, complain, in_decl);
11971         if (member == error_mark_node)
11972           return error_mark_node;
11973
11974         if (object_type && !CLASS_TYPE_P (object_type))
11975           {
11976             if (SCALAR_TYPE_P (object_type))
11977               {
11978                 tree s = NULL_TREE;
11979                 tree dtor = member;
11980
11981                 if (TREE_CODE (dtor) == SCOPE_REF)
11982                   {
11983                     s = TREE_OPERAND (dtor, 0);
11984                     dtor = TREE_OPERAND (dtor, 1);
11985                   }
11986                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11987                   {
11988                     dtor = TREE_OPERAND (dtor, 0);
11989                     if (TYPE_P (dtor))
11990                       return finish_pseudo_destructor_expr (object, s, dtor);
11991                   }
11992               }
11993           }
11994         else if (TREE_CODE (member) == SCOPE_REF
11995                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11996           {
11997             tree tmpl;
11998             tree args;
11999
12000             /* Lookup the template functions now that we know what the
12001                scope is.  */
12002             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12003             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12004             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12005                                             /*is_type_p=*/false,
12006                                             /*complain=*/false);
12007             if (BASELINK_P (member))
12008               {
12009                 BASELINK_FUNCTIONS (member)
12010                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12011                               args);
12012                 member = (adjust_result_of_qualified_name_lookup
12013                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12014                            object_type));
12015               }
12016             else
12017               {
12018                 qualified_name_lookup_error (object_type, tmpl, member,
12019                                              input_location);
12020                 return error_mark_node;
12021               }
12022           }
12023         else if (TREE_CODE (member) == SCOPE_REF
12024                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12025                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12026           {
12027             if (complain & tf_error)
12028               {
12029                 if (TYPE_P (TREE_OPERAND (member, 0)))
12030                   error ("%qT is not a class or namespace",
12031                          TREE_OPERAND (member, 0));
12032                 else
12033                   error ("%qD is not a class or namespace",
12034                          TREE_OPERAND (member, 0));
12035               }
12036             return error_mark_node;
12037           }
12038         else if (TREE_CODE (member) == FIELD_DECL)
12039           return finish_non_static_data_member (member, object, NULL_TREE);
12040
12041         return finish_class_member_access_expr (object, member,
12042                                                 /*template_p=*/false,
12043                                                 complain);
12044       }
12045
12046     case THROW_EXPR:
12047       return build_throw
12048         (RECUR (TREE_OPERAND (t, 0)));
12049
12050     case CONSTRUCTOR:
12051       {
12052         VEC(constructor_elt,gc) *n;
12053         constructor_elt *ce;
12054         unsigned HOST_WIDE_INT idx;
12055         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12056         bool process_index_p;
12057         int newlen;
12058         bool need_copy_p = false;
12059         tree r;
12060
12061         if (type == error_mark_node)
12062           return error_mark_node;
12063
12064         /* digest_init will do the wrong thing if we let it.  */
12065         if (type && TYPE_PTRMEMFUNC_P (type))
12066           return t;
12067
12068         /* We do not want to process the index of aggregate
12069            initializers as they are identifier nodes which will be
12070            looked up by digest_init.  */
12071         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12072
12073         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12074         newlen = VEC_length (constructor_elt, n);
12075         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12076           {
12077             if (ce->index && process_index_p)
12078               ce->index = RECUR (ce->index);
12079
12080             if (PACK_EXPANSION_P (ce->value))
12081               {
12082                 /* Substitute into the pack expansion.  */
12083                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12084                                                   in_decl);
12085
12086                 if (ce->value == error_mark_node)
12087                   ;
12088                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12089                   /* Just move the argument into place.  */
12090                   ce->value = TREE_VEC_ELT (ce->value, 0);
12091                 else
12092                   {
12093                     /* Update the length of the final CONSTRUCTOR
12094                        arguments vector, and note that we will need to
12095                        copy.*/
12096                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12097                     need_copy_p = true;
12098                   }
12099               }
12100             else
12101               ce->value = RECUR (ce->value);
12102           }
12103
12104         if (need_copy_p)
12105           {
12106             VEC(constructor_elt,gc) *old_n = n;
12107
12108             n = VEC_alloc (constructor_elt, gc, newlen);
12109             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12110                  idx++)
12111               {
12112                 if (TREE_CODE (ce->value) == TREE_VEC)
12113                   {
12114                     int i, len = TREE_VEC_LENGTH (ce->value);
12115                     for (i = 0; i < len; ++i)
12116                       CONSTRUCTOR_APPEND_ELT (n, 0,
12117                                               TREE_VEC_ELT (ce->value, i));
12118                   }
12119                 else
12120                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12121               }
12122           }
12123
12124         r = build_constructor (init_list_type_node, n);
12125         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12126
12127         if (TREE_HAS_CONSTRUCTOR (t))
12128           return finish_compound_literal (type, r);
12129
12130         return r;
12131       }
12132
12133     case TYPEID_EXPR:
12134       {
12135         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12136         if (TYPE_P (operand_0))
12137           return get_typeid (operand_0);
12138         return build_typeid (operand_0);
12139       }
12140
12141     case VAR_DECL:
12142       if (!args)
12143         return t;
12144       /* Fall through */
12145
12146     case PARM_DECL:
12147       {
12148         tree r = tsubst_copy (t, args, complain, in_decl);
12149
12150         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12151           /* If the original type was a reference, we'll be wrapped in
12152              the appropriate INDIRECT_REF.  */
12153           r = convert_from_reference (r);
12154         return r;
12155       }
12156
12157     case VA_ARG_EXPR:
12158       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12159                              tsubst_copy (TREE_TYPE (t), args, complain,
12160                                           in_decl));
12161
12162     case OFFSETOF_EXPR:
12163       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12164
12165     case TRAIT_EXPR:
12166       {
12167         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12168                                   complain, in_decl);
12169
12170         tree type2 = TRAIT_EXPR_TYPE2 (t);
12171         if (type2)
12172           type2 = tsubst_copy (type2, args, complain, in_decl);
12173         
12174         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12175       }
12176
12177     case STMT_EXPR:
12178       {
12179         tree old_stmt_expr = cur_stmt_expr;
12180         tree stmt_expr = begin_stmt_expr ();
12181
12182         cur_stmt_expr = stmt_expr;
12183         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12184                      integral_constant_expression_p);
12185         stmt_expr = finish_stmt_expr (stmt_expr, false);
12186         cur_stmt_expr = old_stmt_expr;
12187
12188         return stmt_expr;
12189       }
12190
12191     case CONST_DECL:
12192       t = tsubst_copy (t, args, complain, in_decl);
12193       /* As in finish_id_expression, we resolve enumeration constants
12194          to their underlying values.  */
12195       if (TREE_CODE (t) == CONST_DECL)
12196         {
12197           used_types_insert (TREE_TYPE (t));
12198           return DECL_INITIAL (t);
12199         }
12200       return t;
12201
12202     default:
12203       /* Handle Objective-C++ constructs, if appropriate.  */
12204       {
12205         tree subst
12206           = objcp_tsubst_copy_and_build (t, args, complain,
12207                                          in_decl, /*function_p=*/false);
12208         if (subst)
12209           return subst;
12210       }
12211       return tsubst_copy (t, args, complain, in_decl);
12212     }
12213
12214 #undef RECUR
12215 }
12216
12217 /* Verify that the instantiated ARGS are valid. For type arguments,
12218    make sure that the type's linkage is ok. For non-type arguments,
12219    make sure they are constants if they are integral or enumerations.
12220    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12221
12222 static bool
12223 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12224 {
12225   if (ARGUMENT_PACK_P (t))
12226     {
12227       tree vec = ARGUMENT_PACK_ARGS (t);
12228       int len = TREE_VEC_LENGTH (vec);
12229       bool result = false;
12230       int i;
12231
12232       for (i = 0; i < len; ++i)
12233         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12234           result = true;
12235       return result;
12236     }
12237   else if (TYPE_P (t))
12238     {
12239       /* [basic.link]: A name with no linkage (notably, the name
12240          of a class or enumeration declared in a local scope)
12241          shall not be used to declare an entity with linkage.
12242          This implies that names with no linkage cannot be used as
12243          template arguments.  */
12244       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
12245
12246       if (nt)
12247         {
12248           /* DR 488 makes use of a type with no linkage cause
12249              type deduction to fail.  */
12250           if (complain & tf_error)
12251             {
12252               if (TYPE_ANONYMOUS_P (nt))
12253                 error ("%qT is/uses anonymous type", t);
12254               else
12255                 error ("template argument for %qD uses local type %qT",
12256                        tmpl, t);
12257             }
12258           return true;
12259         }
12260       /* In order to avoid all sorts of complications, we do not
12261          allow variably-modified types as template arguments.  */
12262       else if (variably_modified_type_p (t, NULL_TREE))
12263         {
12264           if (complain & tf_error)
12265             error ("%qT is a variably modified type", t);
12266           return true;
12267         }
12268     }
12269   /* A non-type argument of integral or enumerated type must be a
12270      constant.  */
12271   else if (TREE_TYPE (t)
12272            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12273            && !TREE_CONSTANT (t))
12274     {
12275       if (complain & tf_error)
12276         error ("integral expression %qE is not constant", t);
12277       return true;
12278     }
12279   return false;
12280 }
12281
12282 static bool
12283 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12284 {
12285   int ix, len = DECL_NTPARMS (tmpl);
12286   bool result = false;
12287
12288   for (ix = 0; ix != len; ix++)
12289     {
12290       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12291         result = true;
12292     }
12293   if (result && (complain & tf_error))
12294     error ("  trying to instantiate %qD", tmpl);
12295   return result;
12296 }
12297
12298 /* Instantiate the indicated variable or function template TMPL with
12299    the template arguments in TARG_PTR.  */
12300
12301 tree
12302 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12303 {
12304   tree targ_ptr = orig_args;
12305   tree fndecl;
12306   tree gen_tmpl;
12307   tree spec;
12308   HOST_WIDE_INT saved_processing_template_decl;
12309
12310   if (tmpl == error_mark_node)
12311     return error_mark_node;
12312
12313   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12314
12315   /* If this function is a clone, handle it specially.  */
12316   if (DECL_CLONED_FUNCTION_P (tmpl))
12317     {
12318       tree spec;
12319       tree clone;
12320
12321       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12322          DECL_CLONED_FUNCTION.  */
12323       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12324                                    targ_ptr, complain);
12325       if (spec == error_mark_node)
12326         return error_mark_node;
12327
12328       /* Look for the clone.  */
12329       FOR_EACH_CLONE (clone, spec)
12330         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12331           return clone;
12332       /* We should always have found the clone by now.  */
12333       gcc_unreachable ();
12334       return NULL_TREE;
12335     }
12336
12337   /* Check to see if we already have this specialization.  */
12338   gen_tmpl = most_general_template (tmpl);
12339   if (tmpl != gen_tmpl)
12340     /* The TMPL is a partial instantiation.  To get a full set of
12341        arguments we must add the arguments used to perform the
12342        partial instantiation.  */
12343     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12344                                             targ_ptr);
12345
12346   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12347      but it doesn't seem to be on the hot path.  */
12348   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12349
12350   gcc_assert (tmpl == gen_tmpl
12351               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12352                   == spec)
12353               || fndecl == NULL_TREE);
12354
12355   if (spec != NULL_TREE)
12356     return spec;
12357
12358   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12359                                complain))
12360     return error_mark_node;
12361
12362   /* We are building a FUNCTION_DECL, during which the access of its
12363      parameters and return types have to be checked.  However this
12364      FUNCTION_DECL which is the desired context for access checking
12365      is not built yet.  We solve this chicken-and-egg problem by
12366      deferring all checks until we have the FUNCTION_DECL.  */
12367   push_deferring_access_checks (dk_deferred);
12368
12369   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12370      (because, for example, we have encountered a non-dependent
12371      function call in the body of a template function and must now
12372      determine which of several overloaded functions will be called),
12373      within the instantiation itself we are not processing a
12374      template.  */  
12375   saved_processing_template_decl = processing_template_decl;
12376   processing_template_decl = 0;
12377   /* Substitute template parameters to obtain the specialization.  */
12378   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12379                    targ_ptr, complain, gen_tmpl);
12380   processing_template_decl = saved_processing_template_decl;
12381   if (fndecl == error_mark_node)
12382     return error_mark_node;
12383
12384   /* Now we know the specialization, compute access previously
12385      deferred.  */
12386   push_access_scope (fndecl);
12387
12388   /* Some typedefs referenced from within the template code need to be access
12389      checked at template instantiation time, i.e now. These types were
12390      added to the template at parsing time. Let's get those and perfom
12391      the acces checks then.  */
12392   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12393   perform_deferred_access_checks ();
12394   pop_access_scope (fndecl);
12395   pop_deferring_access_checks ();
12396
12397   /* The DECL_TI_TEMPLATE should always be the immediate parent
12398      template, not the most general template.  */
12399   DECL_TI_TEMPLATE (fndecl) = tmpl;
12400
12401   /* If we've just instantiated the main entry point for a function,
12402      instantiate all the alternate entry points as well.  We do this
12403      by cloning the instantiation of the main entry point, not by
12404      instantiating the template clones.  */
12405   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12406     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12407
12408   return fndecl;
12409 }
12410
12411 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12412    NARGS elements of the arguments that are being used when calling
12413    it.  TARGS is a vector into which the deduced template arguments
12414    are placed.
12415
12416    Return zero for success, 2 for an incomplete match that doesn't resolve
12417    all the types, and 1 for complete failure.  An error message will be
12418    printed only for an incomplete match.
12419
12420    If FN is a conversion operator, or we are trying to produce a specific
12421    specialization, RETURN_TYPE is the return type desired.
12422
12423    The EXPLICIT_TARGS are explicit template arguments provided via a
12424    template-id.
12425
12426    The parameter STRICT is one of:
12427
12428    DEDUCE_CALL:
12429      We are deducing arguments for a function call, as in
12430      [temp.deduct.call].
12431
12432    DEDUCE_CONV:
12433      We are deducing arguments for a conversion function, as in
12434      [temp.deduct.conv].
12435
12436    DEDUCE_EXACT:
12437      We are deducing arguments when doing an explicit instantiation
12438      as in [temp.explicit], when determining an explicit specialization
12439      as in [temp.expl.spec], or when taking the address of a function
12440      template, as in [temp.deduct.funcaddr].  */
12441
12442 int
12443 fn_type_unification (tree fn,
12444                      tree explicit_targs,
12445                      tree targs,
12446                      const tree *args,
12447                      unsigned int nargs,
12448                      tree return_type,
12449                      unification_kind_t strict,
12450                      int flags)
12451 {
12452   tree parms;
12453   tree fntype;
12454   int result;
12455   bool incomplete_argument_packs_p = false;
12456
12457   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12458
12459   fntype = TREE_TYPE (fn);
12460   if (explicit_targs)
12461     {
12462       /* [temp.deduct]
12463
12464          The specified template arguments must match the template
12465          parameters in kind (i.e., type, nontype, template), and there
12466          must not be more arguments than there are parameters;
12467          otherwise type deduction fails.
12468
12469          Nontype arguments must match the types of the corresponding
12470          nontype template parameters, or must be convertible to the
12471          types of the corresponding nontype parameters as specified in
12472          _temp.arg.nontype_, otherwise type deduction fails.
12473
12474          All references in the function type of the function template
12475          to the corresponding template parameters are replaced by the
12476          specified template argument values.  If a substitution in a
12477          template parameter or in the function type of the function
12478          template results in an invalid type, type deduction fails.  */
12479       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12480       int i, len = TREE_VEC_LENGTH (tparms);
12481       tree converted_args;
12482       bool incomplete = false;
12483
12484       if (explicit_targs == error_mark_node)
12485         return 1;
12486
12487       converted_args
12488         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12489                                   /*require_all_args=*/false,
12490                                   /*use_default_args=*/false));
12491       if (converted_args == error_mark_node)
12492         return 1;
12493
12494       /* Substitute the explicit args into the function type.  This is
12495          necessary so that, for instance, explicitly declared function
12496          arguments can match null pointed constants.  If we were given
12497          an incomplete set of explicit args, we must not do semantic
12498          processing during substitution as we could create partial
12499          instantiations.  */
12500       for (i = 0; i < len; i++)
12501         {
12502           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12503           bool parameter_pack = false;
12504
12505           /* Dig out the actual parm.  */
12506           if (TREE_CODE (parm) == TYPE_DECL
12507               || TREE_CODE (parm) == TEMPLATE_DECL)
12508             {
12509               parm = TREE_TYPE (parm);
12510               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12511             }
12512           else if (TREE_CODE (parm) == PARM_DECL)
12513             {
12514               parm = DECL_INITIAL (parm);
12515               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12516             }
12517
12518           if (parameter_pack)
12519             {
12520               int level, idx;
12521               tree targ;
12522               template_parm_level_and_index (parm, &level, &idx);
12523
12524               /* Mark the argument pack as "incomplete". We could
12525                  still deduce more arguments during unification.  */
12526               targ = TMPL_ARG (converted_args, level, idx);
12527               if (targ)
12528                 {
12529                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12530                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12531                     = ARGUMENT_PACK_ARGS (targ);
12532                 }
12533
12534               /* We have some incomplete argument packs.  */
12535               incomplete_argument_packs_p = true;
12536             }
12537         }
12538
12539       if (incomplete_argument_packs_p)
12540         /* Any substitution is guaranteed to be incomplete if there
12541            are incomplete argument packs, because we can still deduce
12542            more arguments.  */
12543         incomplete = 1;
12544       else
12545         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12546
12547       processing_template_decl += incomplete;
12548       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12549       processing_template_decl -= incomplete;
12550
12551       if (fntype == error_mark_node)
12552         return 1;
12553
12554       /* Place the explicitly specified arguments in TARGS.  */
12555       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12556         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12557     }
12558
12559   /* Never do unification on the 'this' parameter.  */
12560   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12561
12562   if (return_type)
12563     {
12564       tree *new_args;
12565
12566       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12567       new_args = XALLOCAVEC (tree, nargs + 1);
12568       new_args[0] = return_type;
12569       memcpy (new_args + 1, args, nargs * sizeof (tree));
12570       args = new_args;
12571       ++nargs;
12572     }
12573
12574   /* We allow incomplete unification without an error message here
12575      because the standard doesn't seem to explicitly prohibit it.  Our
12576      callers must be ready to deal with unification failures in any
12577      event.  */
12578   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12579                                   targs, parms, args, nargs, /*subr=*/0,
12580                                   strict, flags);
12581
12582   if (result == 0 && incomplete_argument_packs_p)
12583     {
12584       int i, len = NUM_TMPL_ARGS (targs);
12585
12586       /* Clear the "incomplete" flags on all argument packs.  */
12587       for (i = 0; i < len; i++)
12588         {
12589           tree arg = TREE_VEC_ELT (targs, i);
12590           if (ARGUMENT_PACK_P (arg))
12591             {
12592               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12593               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12594             }
12595         }
12596     }
12597
12598   /* Now that we have bindings for all of the template arguments,
12599      ensure that the arguments deduced for the template template
12600      parameters have compatible template parameter lists.  We cannot
12601      check this property before we have deduced all template
12602      arguments, because the template parameter types of a template
12603      template parameter might depend on prior template parameters
12604      deduced after the template template parameter.  The following
12605      ill-formed example illustrates this issue:
12606
12607        template<typename T, template<T> class C> void f(C<5>, T);
12608
12609        template<int N> struct X {};
12610
12611        void g() {
12612          f(X<5>(), 5l); // error: template argument deduction fails
12613        }
12614
12615      The template parameter list of 'C' depends on the template type
12616      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12617      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12618      time that we deduce 'C'.  */
12619   if (result == 0
12620       && !template_template_parm_bindings_ok_p 
12621            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12622     return 1;
12623
12624   if (result == 0)
12625     /* All is well so far.  Now, check:
12626
12627        [temp.deduct]
12628
12629        When all template arguments have been deduced, all uses of
12630        template parameters in nondeduced contexts are replaced with
12631        the corresponding deduced argument values.  If the
12632        substitution results in an invalid type, as described above,
12633        type deduction fails.  */
12634     {
12635       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12636       if (substed == error_mark_node)
12637         return 1;
12638
12639       /* If we're looking for an exact match, check that what we got
12640          is indeed an exact match.  It might not be if some template
12641          parameters are used in non-deduced contexts.  */
12642       if (strict == DEDUCE_EXACT)
12643         {
12644           unsigned int i;
12645
12646           tree sarg
12647             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12648           if (return_type)
12649             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12650           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
12651             if (!same_type_p (args[i], TREE_VALUE (sarg)))
12652               return 1;
12653         }
12654     }
12655
12656   return result;
12657 }
12658
12659 /* Adjust types before performing type deduction, as described in
12660    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12661    sections are symmetric.  PARM is the type of a function parameter
12662    or the return type of the conversion function.  ARG is the type of
12663    the argument passed to the call, or the type of the value
12664    initialized with the result of the conversion function.
12665    ARG_EXPR is the original argument expression, which may be null.  */
12666
12667 static int
12668 maybe_adjust_types_for_deduction (unification_kind_t strict,
12669                                   tree* parm,
12670                                   tree* arg,
12671                                   tree arg_expr)
12672 {
12673   int result = 0;
12674
12675   switch (strict)
12676     {
12677     case DEDUCE_CALL:
12678       break;
12679
12680     case DEDUCE_CONV:
12681       {
12682         /* Swap PARM and ARG throughout the remainder of this
12683            function; the handling is precisely symmetric since PARM
12684            will initialize ARG rather than vice versa.  */
12685         tree* temp = parm;
12686         parm = arg;
12687         arg = temp;
12688         break;
12689       }
12690
12691     case DEDUCE_EXACT:
12692       /* There is nothing to do in this case.  */
12693       return 0;
12694
12695     default:
12696       gcc_unreachable ();
12697     }
12698
12699   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12700     {
12701       /* [temp.deduct.call]
12702
12703          If P is not a reference type:
12704
12705          --If A is an array type, the pointer type produced by the
12706          array-to-pointer standard conversion (_conv.array_) is
12707          used in place of A for type deduction; otherwise,
12708
12709          --If A is a function type, the pointer type produced by
12710          the function-to-pointer standard conversion
12711          (_conv.func_) is used in place of A for type deduction;
12712          otherwise,
12713
12714          --If A is a cv-qualified type, the top level
12715          cv-qualifiers of A's type are ignored for type
12716          deduction.  */
12717       if (TREE_CODE (*arg) == ARRAY_TYPE)
12718         *arg = build_pointer_type (TREE_TYPE (*arg));
12719       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12720         *arg = build_pointer_type (*arg);
12721       else
12722         *arg = TYPE_MAIN_VARIANT (*arg);
12723     }
12724
12725   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12726      of the form T&&, where T is a template parameter, and the argument
12727      is an lvalue, T is deduced as A& */
12728   if (TREE_CODE (*parm) == REFERENCE_TYPE
12729       && TYPE_REF_IS_RVALUE (*parm)
12730       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12731       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12732       && arg_expr && real_lvalue_p (arg_expr))
12733     *arg = build_reference_type (*arg);
12734
12735   /* [temp.deduct.call]
12736
12737      If P is a cv-qualified type, the top level cv-qualifiers
12738      of P's type are ignored for type deduction.  If P is a
12739      reference type, the type referred to by P is used for
12740      type deduction.  */
12741   *parm = TYPE_MAIN_VARIANT (*parm);
12742   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12743     {
12744       *parm = TREE_TYPE (*parm);
12745       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12746     }
12747
12748   /* DR 322. For conversion deduction, remove a reference type on parm
12749      too (which has been swapped into ARG).  */
12750   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12751     *arg = TREE_TYPE (*arg);
12752
12753   return result;
12754 }
12755
12756 /* Most parms like fn_type_unification.
12757
12758    If SUBR is 1, we're being called recursively (to unify the
12759    arguments of a function or method parameter of a function
12760    template). */
12761
12762 static int
12763 type_unification_real (tree tparms,
12764                        tree targs,
12765                        tree xparms,
12766                        const tree *xargs,
12767                        unsigned int xnargs,
12768                        int subr,
12769                        unification_kind_t strict,
12770                        int flags)
12771 {
12772   tree parm, arg, arg_expr;
12773   int i;
12774   int ntparms = TREE_VEC_LENGTH (tparms);
12775   int sub_strict;
12776   int saw_undeduced = 0;
12777   tree parms;
12778   const tree *args;
12779   unsigned int nargs;
12780   unsigned int ia;
12781
12782   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12783   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12784   gcc_assert (ntparms > 0);
12785
12786   switch (strict)
12787     {
12788     case DEDUCE_CALL:
12789       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12790                     | UNIFY_ALLOW_DERIVED);
12791       break;
12792
12793     case DEDUCE_CONV:
12794       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12795       break;
12796
12797     case DEDUCE_EXACT:
12798       sub_strict = UNIFY_ALLOW_NONE;
12799       break;
12800
12801     default:
12802       gcc_unreachable ();
12803     }
12804
12805  again:
12806   parms = xparms;
12807   args = xargs;
12808   nargs = xnargs;
12809
12810   ia = 0;
12811   while (parms && parms != void_list_node
12812          && ia < nargs)
12813     {
12814       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12815         break;
12816
12817       parm = TREE_VALUE (parms);
12818       parms = TREE_CHAIN (parms);
12819       arg = args[ia];
12820       ++ia;
12821       arg_expr = NULL;
12822
12823       if (arg == error_mark_node)
12824         return 1;
12825       if (arg == unknown_type_node)
12826         /* We can't deduce anything from this, but we might get all the
12827            template args from other function args.  */
12828         continue;
12829
12830       /* Conversions will be performed on a function argument that
12831          corresponds with a function parameter that contains only
12832          non-deducible template parameters and explicitly specified
12833          template parameters.  */
12834       if (!uses_template_parms (parm))
12835         {
12836           tree type;
12837
12838           if (!TYPE_P (arg))
12839             type = TREE_TYPE (arg);
12840           else
12841             type = arg;
12842
12843           if (same_type_p (parm, type))
12844             continue;
12845           if (strict != DEDUCE_EXACT
12846               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12847                                   flags))
12848             continue;
12849
12850           return 1;
12851         }
12852
12853       if (!TYPE_P (arg))
12854         {
12855           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12856           if (type_unknown_p (arg))
12857             {
12858               /* [temp.deduct.type] 
12859
12860                  A template-argument can be deduced from a pointer to
12861                  function or pointer to member function argument if
12862                  the set of overloaded functions does not contain
12863                  function templates and at most one of a set of
12864                  overloaded functions provides a unique match.  */
12865               if (resolve_overloaded_unification
12866                   (tparms, targs, parm, arg, strict, sub_strict))
12867                 continue;
12868
12869               return 1;
12870             }
12871           arg_expr = arg;
12872           arg = unlowered_expr_type (arg);
12873           if (arg == error_mark_node)
12874             return 1;
12875         }
12876
12877       {
12878         int arg_strict = sub_strict;
12879
12880         if (!subr)
12881           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12882                                                           arg_expr);
12883
12884         if (arg == init_list_type_node && arg_expr)
12885           arg = arg_expr;
12886         if (unify (tparms, targs, parm, arg, arg_strict))
12887           return 1;
12888       }
12889     }
12890
12891
12892   if (parms 
12893       && parms != void_list_node
12894       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12895     {
12896       /* Unify the remaining arguments with the pack expansion type.  */
12897       tree argvec;
12898       tree parmvec = make_tree_vec (1);
12899
12900       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12901       argvec = make_tree_vec (nargs - ia);
12902       for (i = 0; ia < nargs; ++ia, ++i)
12903         TREE_VEC_ELT (argvec, i) = args[ia];
12904
12905       /* Copy the parameter into parmvec.  */
12906       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12907       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12908                                 /*call_args_p=*/true, /*subr=*/subr))
12909         return 1;
12910
12911       /* Advance to the end of the list of parameters.  */
12912       parms = TREE_CHAIN (parms);
12913     }
12914
12915   /* Fail if we've reached the end of the parm list, and more args
12916      are present, and the parm list isn't variadic.  */
12917   if (ia < nargs && parms == void_list_node)
12918     return 1;
12919   /* Fail if parms are left and they don't have default values.  */
12920   if (parms && parms != void_list_node
12921       && TREE_PURPOSE (parms) == NULL_TREE)
12922     return 1;
12923
12924   if (!subr)
12925     for (i = 0; i < ntparms; i++)
12926       if (!TREE_VEC_ELT (targs, i))
12927         {
12928           tree tparm;
12929
12930           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12931             continue;
12932
12933           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12934
12935           /* If this is an undeduced nontype parameter that depends on
12936              a type parameter, try another pass; its type may have been
12937              deduced from a later argument than the one from which
12938              this parameter can be deduced.  */
12939           if (TREE_CODE (tparm) == PARM_DECL
12940               && uses_template_parms (TREE_TYPE (tparm))
12941               && !saw_undeduced++)
12942             goto again;
12943
12944           /* Core issue #226 (C++0x) [temp.deduct]:
12945
12946                If a template argument has not been deduced, its
12947                default template argument, if any, is used. 
12948
12949              When we are in C++98 mode, TREE_PURPOSE will either
12950              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12951              to explicitly check cxx_dialect here.  */
12952           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12953             {
12954               tree arg = tsubst_template_arg
12955                                 (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)),
12956                                  targs, tf_none, NULL_TREE);
12957               if (arg == error_mark_node)
12958                 return 1;
12959               else
12960                 {
12961                   TREE_VEC_ELT (targs, i) = arg;
12962                   continue;
12963                 }
12964             }
12965
12966           /* If the type parameter is a parameter pack, then it will
12967              be deduced to an empty parameter pack.  */
12968           if (template_parameter_pack_p (tparm))
12969             {
12970               tree arg;
12971
12972               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12973                 {
12974                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12975                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12976                   TREE_CONSTANT (arg) = 1;
12977                 }
12978               else
12979                 arg = make_node (TYPE_ARGUMENT_PACK);
12980
12981               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12982
12983               TREE_VEC_ELT (targs, i) = arg;
12984               continue;
12985             }
12986
12987           return 2;
12988         }
12989
12990   return 0;
12991 }
12992
12993 /* Subroutine of type_unification_real.  Args are like the variables
12994    at the call site.  ARG is an overloaded function (or template-id);
12995    we try deducing template args from each of the overloads, and if
12996    only one succeeds, we go with that.  Modifies TARGS and returns
12997    true on success.  */
12998
12999 static bool
13000 resolve_overloaded_unification (tree tparms,
13001                                 tree targs,
13002                                 tree parm,
13003                                 tree arg,
13004                                 unification_kind_t strict,
13005                                 int sub_strict)
13006 {
13007   tree tempargs = copy_node (targs);
13008   int good = 0;
13009   tree goodfn = NULL_TREE;
13010   bool addr_p;
13011
13012   if (TREE_CODE (arg) == ADDR_EXPR)
13013     {
13014       arg = TREE_OPERAND (arg, 0);
13015       addr_p = true;
13016     }
13017   else
13018     addr_p = false;
13019
13020   if (TREE_CODE (arg) == COMPONENT_REF)
13021     /* Handle `&x' where `x' is some static or non-static member
13022        function name.  */
13023     arg = TREE_OPERAND (arg, 1);
13024
13025   if (TREE_CODE (arg) == OFFSET_REF)
13026     arg = TREE_OPERAND (arg, 1);
13027
13028   /* Strip baselink information.  */
13029   if (BASELINK_P (arg))
13030     arg = BASELINK_FUNCTIONS (arg);
13031
13032   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13033     {
13034       /* If we got some explicit template args, we need to plug them into
13035          the affected templates before we try to unify, in case the
13036          explicit args will completely resolve the templates in question.  */
13037
13038       tree expl_subargs = TREE_OPERAND (arg, 1);
13039       arg = TREE_OPERAND (arg, 0);
13040
13041       for (; arg; arg = OVL_NEXT (arg))
13042         {
13043           tree fn = OVL_CURRENT (arg);
13044           tree subargs, elem;
13045
13046           if (TREE_CODE (fn) != TEMPLATE_DECL)
13047             continue;
13048
13049           ++processing_template_decl;
13050           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13051                                   expl_subargs, /*check_ret=*/false);
13052           if (subargs)
13053             {
13054               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13055               if (try_one_overload (tparms, targs, tempargs, parm,
13056                                     elem, strict, sub_strict, addr_p)
13057                   && (!goodfn || !decls_match (goodfn, elem)))
13058                 {
13059                   goodfn = elem;
13060                   ++good;
13061                 }
13062             }
13063           --processing_template_decl;
13064         }
13065     }
13066   else if (TREE_CODE (arg) != OVERLOAD
13067            && TREE_CODE (arg) != FUNCTION_DECL)
13068     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13069        -- but the deduction does not succeed because the expression is
13070        not just the function on its own.  */
13071     return false;
13072   else
13073     for (; arg; arg = OVL_NEXT (arg))
13074       if (try_one_overload (tparms, targs, tempargs, parm,
13075                             TREE_TYPE (OVL_CURRENT (arg)),
13076                             strict, sub_strict, addr_p)
13077           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13078         {
13079           goodfn = OVL_CURRENT (arg);
13080           ++good;
13081         }
13082
13083   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13084      to function or pointer to member function argument if the set of
13085      overloaded functions does not contain function templates and at most
13086      one of a set of overloaded functions provides a unique match.
13087
13088      So if we found multiple possibilities, we return success but don't
13089      deduce anything.  */
13090
13091   if (good == 1)
13092     {
13093       int i = TREE_VEC_LENGTH (targs);
13094       for (; i--; )
13095         if (TREE_VEC_ELT (tempargs, i))
13096           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13097     }
13098   if (good)
13099     return true;
13100
13101   return false;
13102 }
13103
13104 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13105    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13106    different overloads deduce different arguments for a given parm.
13107    ADDR_P is true if the expression for which deduction is being
13108    performed was of the form "& fn" rather than simply "fn".
13109
13110    Returns 1 on success.  */
13111
13112 static int
13113 try_one_overload (tree tparms,
13114                   tree orig_targs,
13115                   tree targs,
13116                   tree parm,
13117                   tree arg,
13118                   unification_kind_t strict,
13119                   int sub_strict,
13120                   bool addr_p)
13121 {
13122   int nargs;
13123   tree tempargs;
13124   int i;
13125
13126   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13127      to function or pointer to member function argument if the set of
13128      overloaded functions does not contain function templates and at most
13129      one of a set of overloaded functions provides a unique match.
13130
13131      So if this is a template, just return success.  */
13132
13133   if (uses_template_parms (arg))
13134     return 1;
13135
13136   if (TREE_CODE (arg) == METHOD_TYPE)
13137     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13138   else if (addr_p)
13139     arg = build_pointer_type (arg);
13140
13141   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13142
13143   /* We don't copy orig_targs for this because if we have already deduced
13144      some template args from previous args, unify would complain when we
13145      try to deduce a template parameter for the same argument, even though
13146      there isn't really a conflict.  */
13147   nargs = TREE_VEC_LENGTH (targs);
13148   tempargs = make_tree_vec (nargs);
13149
13150   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13151     return 0;
13152
13153   /* First make sure we didn't deduce anything that conflicts with
13154      explicitly specified args.  */
13155   for (i = nargs; i--; )
13156     {
13157       tree elt = TREE_VEC_ELT (tempargs, i);
13158       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13159
13160       if (!elt)
13161         /*NOP*/;
13162       else if (uses_template_parms (elt))
13163         /* Since we're unifying against ourselves, we will fill in
13164            template args used in the function parm list with our own
13165            template parms.  Discard them.  */
13166         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13167       else if (oldelt && !template_args_equal (oldelt, elt))
13168         return 0;
13169     }
13170
13171   for (i = nargs; i--; )
13172     {
13173       tree elt = TREE_VEC_ELT (tempargs, i);
13174
13175       if (elt)
13176         TREE_VEC_ELT (targs, i) = elt;
13177     }
13178
13179   return 1;
13180 }
13181
13182 /* PARM is a template class (perhaps with unbound template
13183    parameters).  ARG is a fully instantiated type.  If ARG can be
13184    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13185    TARGS are as for unify.  */
13186
13187 static tree
13188 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13189 {
13190   tree copy_of_targs;
13191
13192   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13193       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13194           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13195     return NULL_TREE;
13196
13197   /* We need to make a new template argument vector for the call to
13198      unify.  If we used TARGS, we'd clutter it up with the result of
13199      the attempted unification, even if this class didn't work out.
13200      We also don't want to commit ourselves to all the unifications
13201      we've already done, since unification is supposed to be done on
13202      an argument-by-argument basis.  In other words, consider the
13203      following pathological case:
13204
13205        template <int I, int J, int K>
13206        struct S {};
13207
13208        template <int I, int J>
13209        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13210
13211        template <int I, int J, int K>
13212        void f(S<I, J, K>, S<I, I, I>);
13213
13214        void g() {
13215          S<0, 0, 0> s0;
13216          S<0, 1, 2> s2;
13217
13218          f(s0, s2);
13219        }
13220
13221      Now, by the time we consider the unification involving `s2', we
13222      already know that we must have `f<0, 0, 0>'.  But, even though
13223      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13224      because there are two ways to unify base classes of S<0, 1, 2>
13225      with S<I, I, I>.  If we kept the already deduced knowledge, we
13226      would reject the possibility I=1.  */
13227   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13228
13229   /* If unification failed, we're done.  */
13230   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13231              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13232     return NULL_TREE;
13233
13234   return arg;
13235 }
13236
13237 /* Given a template type PARM and a class type ARG, find the unique
13238    base type in ARG that is an instance of PARM.  We do not examine
13239    ARG itself; only its base-classes.  If there is not exactly one
13240    appropriate base class, return NULL_TREE.  PARM may be the type of
13241    a partial specialization, as well as a plain template type.  Used
13242    by unify.  */
13243
13244 static tree
13245 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13246 {
13247   tree rval = NULL_TREE;
13248   tree binfo;
13249
13250   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13251
13252   binfo = TYPE_BINFO (complete_type (arg));
13253   if (!binfo)
13254     /* The type could not be completed.  */
13255     return NULL_TREE;
13256
13257   /* Walk in inheritance graph order.  The search order is not
13258      important, and this avoids multiple walks of virtual bases.  */
13259   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13260     {
13261       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13262
13263       if (r)
13264         {
13265           /* If there is more than one satisfactory baseclass, then:
13266
13267                [temp.deduct.call]
13268
13269               If they yield more than one possible deduced A, the type
13270               deduction fails.
13271
13272              applies.  */
13273           if (rval && !same_type_p (r, rval))
13274             return NULL_TREE;
13275
13276           rval = r;
13277         }
13278     }
13279
13280   return rval;
13281 }
13282
13283 /* Returns the level of DECL, which declares a template parameter.  */
13284
13285 static int
13286 template_decl_level (tree decl)
13287 {
13288   switch (TREE_CODE (decl))
13289     {
13290     case TYPE_DECL:
13291     case TEMPLATE_DECL:
13292       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13293
13294     case PARM_DECL:
13295       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13296
13297     default:
13298       gcc_unreachable ();
13299     }
13300   return 0;
13301 }
13302
13303 /* Decide whether ARG can be unified with PARM, considering only the
13304    cv-qualifiers of each type, given STRICT as documented for unify.
13305    Returns nonzero iff the unification is OK on that basis.  */
13306
13307 static int
13308 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13309 {
13310   int arg_quals = cp_type_quals (arg);
13311   int parm_quals = cp_type_quals (parm);
13312
13313   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13314       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13315     {
13316       /*  Although a CVR qualifier is ignored when being applied to a
13317           substituted template parameter ([8.3.2]/1 for example), that
13318           does not apply during deduction [14.8.2.4]/1, (even though
13319           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13320           this).  Except when we're allowing additional CV qualifiers
13321           at the outer level [14.8.2.1]/3,1st bullet.  */
13322       if ((TREE_CODE (arg) == REFERENCE_TYPE
13323            || TREE_CODE (arg) == FUNCTION_TYPE
13324            || TREE_CODE (arg) == METHOD_TYPE)
13325           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13326         return 0;
13327
13328       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13329           && (parm_quals & TYPE_QUAL_RESTRICT))
13330         return 0;
13331     }
13332
13333   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13334       && (arg_quals & parm_quals) != parm_quals)
13335     return 0;
13336
13337   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13338       && (parm_quals & arg_quals) != arg_quals)
13339     return 0;
13340
13341   return 1;
13342 }
13343
13344 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13345 void 
13346 template_parm_level_and_index (tree parm, int* level, int* index)
13347 {
13348   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13349       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13350       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13351     {
13352       *index = TEMPLATE_TYPE_IDX (parm);
13353       *level = TEMPLATE_TYPE_LEVEL (parm);
13354     }
13355   else
13356     {
13357       *index = TEMPLATE_PARM_IDX (parm);
13358       *level = TEMPLATE_PARM_LEVEL (parm);
13359     }
13360 }
13361
13362 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13363    expansion at the end of PACKED_PARMS. Returns 0 if the type
13364    deduction succeeds, 1 otherwise. STRICT is the same as in
13365    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13366    call argument list. We'll need to adjust the arguments to make them
13367    types. SUBR tells us if this is from a recursive call to
13368    type_unification_real.  */
13369 int
13370 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13371                       tree packed_args, int strict, bool call_args_p,
13372                       bool subr)
13373 {
13374   tree parm 
13375     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13376   tree pattern = PACK_EXPANSION_PATTERN (parm);
13377   tree pack, packs = NULL_TREE;
13378   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13379   int len = TREE_VEC_LENGTH (packed_args);
13380
13381   /* Determine the parameter packs we will be deducing from the
13382      pattern, and record their current deductions.  */
13383   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13384        pack; pack = TREE_CHAIN (pack))
13385     {
13386       tree parm_pack = TREE_VALUE (pack);
13387       int idx, level;
13388
13389       /* Determine the index and level of this parameter pack.  */
13390       template_parm_level_and_index (parm_pack, &level, &idx);
13391
13392       /* Keep track of the parameter packs and their corresponding
13393          argument packs.  */
13394       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13395       TREE_TYPE (packs) = make_tree_vec (len - start);
13396     }
13397   
13398   /* Loop through all of the arguments that have not yet been
13399      unified and unify each with the pattern.  */
13400   for (i = start; i < len; i++)
13401     {
13402       tree parm = pattern;
13403
13404       /* For each parameter pack, clear out the deduced value so that
13405          we can deduce it again.  */
13406       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13407         {
13408           int idx, level;
13409           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13410
13411           TMPL_ARG (targs, level, idx) = NULL_TREE;
13412         }
13413
13414       /* Unify the pattern with the current argument.  */
13415       {
13416         tree arg = TREE_VEC_ELT (packed_args, i);
13417         tree arg_expr = NULL_TREE;
13418         int arg_strict = strict;
13419         bool skip_arg_p = false;
13420
13421         if (call_args_p)
13422           {
13423             int sub_strict;
13424
13425             /* This mirrors what we do in type_unification_real.  */
13426             switch (strict)
13427               {
13428               case DEDUCE_CALL:
13429                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13430                               | UNIFY_ALLOW_MORE_CV_QUAL
13431                               | UNIFY_ALLOW_DERIVED);
13432                 break;
13433                 
13434               case DEDUCE_CONV:
13435                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13436                 break;
13437                 
13438               case DEDUCE_EXACT:
13439                 sub_strict = UNIFY_ALLOW_NONE;
13440                 break;
13441                 
13442               default:
13443                 gcc_unreachable ();
13444               }
13445
13446             if (!TYPE_P (arg))
13447               {
13448                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13449                 if (type_unknown_p (arg))
13450                   {
13451                     /* [temp.deduct.type] A template-argument can be
13452                        deduced from a pointer to function or pointer
13453                        to member function argument if the set of
13454                        overloaded functions does not contain function
13455                        templates and at most one of a set of
13456                        overloaded functions provides a unique
13457                        match.  */
13458
13459                     if (resolve_overloaded_unification
13460                         (tparms, targs, parm, arg,
13461                          (unification_kind_t) strict,
13462                          sub_strict)
13463                         != 0)
13464                       return 1;
13465                     skip_arg_p = true;
13466                   }
13467
13468                 if (!skip_arg_p)
13469                   {
13470                     arg_expr = arg;
13471                     arg = unlowered_expr_type (arg);
13472                     if (arg == error_mark_node)
13473                       return 1;
13474                   }
13475               }
13476       
13477             arg_strict = sub_strict;
13478
13479             if (!subr)
13480               arg_strict |= 
13481                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13482                                                   &parm, &arg, arg_expr);
13483           }
13484
13485         if (!skip_arg_p)
13486           {
13487             if (unify (tparms, targs, parm, arg, arg_strict))
13488               return 1;
13489           }
13490       }
13491
13492       /* For each parameter pack, collect the deduced value.  */
13493       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13494         {
13495           int idx, level;
13496           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13497
13498           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13499             TMPL_ARG (targs, level, idx);
13500         }
13501     }
13502
13503   /* Verify that the results of unification with the parameter packs
13504      produce results consistent with what we've seen before, and make
13505      the deduced argument packs available.  */
13506   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13507     {
13508       tree old_pack = TREE_VALUE (pack);
13509       tree new_args = TREE_TYPE (pack);
13510       int i, len = TREE_VEC_LENGTH (new_args);
13511       bool nondeduced_p = false;
13512
13513       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13514          actually deduce anything.  */
13515       for (i = 0; i < len && !nondeduced_p; ++i)
13516         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13517           nondeduced_p = true;
13518       if (nondeduced_p)
13519         continue;
13520
13521       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13522         {
13523           /* Prepend the explicit arguments onto NEW_ARGS.  */
13524           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13525           tree old_args = new_args;
13526           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13527           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13528
13529           /* Copy the explicit arguments.  */
13530           new_args = make_tree_vec (len);
13531           for (i = 0; i < explicit_len; i++)
13532             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13533
13534           /* Copy the deduced arguments.  */
13535           for (; i < len; i++)
13536             TREE_VEC_ELT (new_args, i) =
13537               TREE_VEC_ELT (old_args, i - explicit_len);
13538         }
13539
13540       if (!old_pack)
13541         {
13542           tree result;
13543           int idx, level;
13544           
13545           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13546
13547           /* Build the deduced *_ARGUMENT_PACK.  */
13548           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13549             {
13550               result = make_node (NONTYPE_ARGUMENT_PACK);
13551               TREE_TYPE (result) = 
13552                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13553               TREE_CONSTANT (result) = 1;
13554             }
13555           else
13556             result = make_node (TYPE_ARGUMENT_PACK);
13557
13558           SET_ARGUMENT_PACK_ARGS (result, new_args);
13559
13560           /* Note the deduced argument packs for this parameter
13561              pack.  */
13562           TMPL_ARG (targs, level, idx) = result;
13563         }
13564       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13565                && (ARGUMENT_PACK_ARGS (old_pack) 
13566                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13567         {
13568           /* We only had the explicitly-provided arguments before, but
13569              now we have a complete set of arguments.  */
13570           int idx, level;
13571           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13572           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13573
13574           /* Keep the original deduced argument pack.  */
13575           TMPL_ARG (targs, level, idx) = old_pack;
13576
13577           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13578           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13579           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13580         }
13581       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13582                                     new_args))
13583         /* Inconsistent unification of this parameter pack.  */
13584         return 1;
13585       else
13586         {
13587           int idx, level;
13588           
13589           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13590
13591           /* Keep the original deduced argument pack.  */
13592           TMPL_ARG (targs, level, idx) = old_pack;
13593         }
13594     }
13595
13596   return 0;
13597 }
13598
13599 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13600    set of template parameters to a template.  TARGS is the bindings
13601    for those template parameters, as determined thus far; TARGS may
13602    include template arguments for outer levels of template parameters
13603    as well.  PARM is a parameter to a template function, or a
13604    subcomponent of that parameter; ARG is the corresponding argument.
13605    This function attempts to match PARM with ARG in a manner
13606    consistent with the existing assignments in TARGS.  If more values
13607    are deduced, then TARGS is updated.
13608
13609    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13610    parameter STRICT is a bitwise or of the following flags:
13611
13612      UNIFY_ALLOW_NONE:
13613        Require an exact match between PARM and ARG.
13614      UNIFY_ALLOW_MORE_CV_QUAL:
13615        Allow the deduced ARG to be more cv-qualified (by qualification
13616        conversion) than ARG.
13617      UNIFY_ALLOW_LESS_CV_QUAL:
13618        Allow the deduced ARG to be less cv-qualified than ARG.
13619      UNIFY_ALLOW_DERIVED:
13620        Allow the deduced ARG to be a template base class of ARG,
13621        or a pointer to a template base class of the type pointed to by
13622        ARG.
13623      UNIFY_ALLOW_INTEGER:
13624        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13625        case for more information.
13626      UNIFY_ALLOW_OUTER_LEVEL:
13627        This is the outermost level of a deduction. Used to determine validity
13628        of qualification conversions. A valid qualification conversion must
13629        have const qualified pointers leading up to the inner type which
13630        requires additional CV quals, except at the outer level, where const
13631        is not required [conv.qual]. It would be normal to set this flag in
13632        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13633      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13634        This is the outermost level of a deduction, and PARM can be more CV
13635        qualified at this point.
13636      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13637        This is the outermost level of a deduction, and PARM can be less CV
13638        qualified at this point.  */
13639
13640 static int
13641 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13642 {
13643   int idx;
13644   tree targ;
13645   tree tparm;
13646   int strict_in = strict;
13647
13648   /* I don't think this will do the right thing with respect to types.
13649      But the only case I've seen it in so far has been array bounds, where
13650      signedness is the only information lost, and I think that will be
13651      okay.  */
13652   while (TREE_CODE (parm) == NOP_EXPR)
13653     parm = TREE_OPERAND (parm, 0);
13654
13655   if (arg == error_mark_node)
13656     return 1;
13657   if (arg == unknown_type_node
13658       || arg == init_list_type_node)
13659     /* We can't deduce anything from this, but we might get all the
13660        template args from other function args.  */
13661     return 0;
13662
13663   /* If PARM uses template parameters, then we can't bail out here,
13664      even if ARG == PARM, since we won't record unifications for the
13665      template parameters.  We might need them if we're trying to
13666      figure out which of two things is more specialized.  */
13667   if (arg == parm && !uses_template_parms (parm))
13668     return 0;
13669
13670   /* Handle init lists early, so the rest of the function can assume
13671      we're dealing with a type. */
13672   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13673     {
13674       tree elt, elttype;
13675       unsigned i;
13676
13677       if (!is_std_init_list (parm))
13678         /* We can only deduce from an initializer list argument if the
13679            parameter is std::initializer_list; otherwise this is a
13680            non-deduced context. */
13681         return 0;
13682
13683       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13684
13685       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13686         {
13687           int elt_strict = strict;
13688           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13689             {
13690               tree type = TREE_TYPE (elt);
13691               /* It should only be possible to get here for a call.  */
13692               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13693               elt_strict |= maybe_adjust_types_for_deduction
13694                 (DEDUCE_CALL, &elttype, &type, elt);
13695               elt = type;
13696             }
13697
13698           if (unify (tparms, targs, elttype, elt, elt_strict))
13699             return 1;
13700         }
13701       return 0;
13702     }
13703
13704   /* Immediately reject some pairs that won't unify because of
13705      cv-qualification mismatches.  */
13706   if (TREE_CODE (arg) == TREE_CODE (parm)
13707       && TYPE_P (arg)
13708       /* It is the elements of the array which hold the cv quals of an array
13709          type, and the elements might be template type parms. We'll check
13710          when we recurse.  */
13711       && TREE_CODE (arg) != ARRAY_TYPE
13712       /* We check the cv-qualifiers when unifying with template type
13713          parameters below.  We want to allow ARG `const T' to unify with
13714          PARM `T' for example, when computing which of two templates
13715          is more specialized, for example.  */
13716       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13717       && !check_cv_quals_for_unify (strict_in, arg, parm))
13718     return 1;
13719
13720   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13721       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13722     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13723   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13724   strict &= ~UNIFY_ALLOW_DERIVED;
13725   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13726   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13727
13728   switch (TREE_CODE (parm))
13729     {
13730     case TYPENAME_TYPE:
13731     case SCOPE_REF:
13732     case UNBOUND_CLASS_TEMPLATE:
13733       /* In a type which contains a nested-name-specifier, template
13734          argument values cannot be deduced for template parameters used
13735          within the nested-name-specifier.  */
13736       return 0;
13737
13738     case TEMPLATE_TYPE_PARM:
13739     case TEMPLATE_TEMPLATE_PARM:
13740     case BOUND_TEMPLATE_TEMPLATE_PARM:
13741       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13742       if (tparm == error_mark_node)
13743         return 1;
13744
13745       if (TEMPLATE_TYPE_LEVEL (parm)
13746           != template_decl_level (tparm))
13747         /* The PARM is not one we're trying to unify.  Just check
13748            to see if it matches ARG.  */
13749         return (TREE_CODE (arg) == TREE_CODE (parm)
13750                 && same_type_p (parm, arg)) ? 0 : 1;
13751       idx = TEMPLATE_TYPE_IDX (parm);
13752       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13753       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13754
13755       /* Check for mixed types and values.  */
13756       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13757            && TREE_CODE (tparm) != TYPE_DECL)
13758           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13759               && TREE_CODE (tparm) != TEMPLATE_DECL))
13760         return 1;
13761
13762       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13763         {
13764           /* ARG must be constructed from a template class or a template
13765              template parameter.  */
13766           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13767               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13768             return 1;
13769
13770           {
13771             tree parmvec = TYPE_TI_ARGS (parm);
13772             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13773             tree parm_parms 
13774               = DECL_INNERMOST_TEMPLATE_PARMS
13775                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13776             int i, len;
13777             int parm_variadic_p = 0;
13778
13779             /* The resolution to DR150 makes clear that default
13780                arguments for an N-argument may not be used to bind T
13781                to a template template parameter with fewer than N
13782                parameters.  It is not safe to permit the binding of
13783                default arguments as an extension, as that may change
13784                the meaning of a conforming program.  Consider:
13785
13786                   struct Dense { static const unsigned int dim = 1; };
13787
13788                   template <template <typename> class View,
13789                             typename Block>
13790                   void operator+(float, View<Block> const&);
13791
13792                   template <typename Block,
13793                             unsigned int Dim = Block::dim>
13794                   struct Lvalue_proxy { operator float() const; };
13795
13796                   void
13797                   test_1d (void) {
13798                     Lvalue_proxy<Dense> p;
13799                     float b;
13800                     b + p;
13801                   }
13802
13803               Here, if Lvalue_proxy is permitted to bind to View, then
13804               the global operator+ will be used; if they are not, the
13805               Lvalue_proxy will be converted to float.  */
13806             if (coerce_template_parms (parm_parms,
13807                                        argvec,
13808                                        TYPE_TI_TEMPLATE (parm),
13809                                        tf_none,
13810                                        /*require_all_args=*/true,
13811                                        /*use_default_args=*/false)
13812                 == error_mark_node)
13813               return 1;
13814
13815             /* Deduce arguments T, i from TT<T> or TT<i>.
13816                We check each element of PARMVEC and ARGVEC individually
13817                rather than the whole TREE_VEC since they can have
13818                different number of elements.  */
13819
13820             parmvec = expand_template_argument_pack (parmvec);
13821             argvec = expand_template_argument_pack (argvec);
13822
13823             len = TREE_VEC_LENGTH (parmvec);
13824
13825             /* Check if the parameters end in a pack, making them
13826                variadic.  */
13827             if (len > 0
13828                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13829               parm_variadic_p = 1;
13830             
13831             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13832               return 1;
13833
13834              for (i = 0; i < len - parm_variadic_p; ++i)
13835               {
13836                 if (unify (tparms, targs,
13837                            TREE_VEC_ELT (parmvec, i),
13838                            TREE_VEC_ELT (argvec, i),
13839                            UNIFY_ALLOW_NONE))
13840                   return 1;
13841               }
13842
13843             if (parm_variadic_p
13844                 && unify_pack_expansion (tparms, targs,
13845                                          parmvec, argvec,
13846                                          UNIFY_ALLOW_NONE,
13847                                          /*call_args_p=*/false,
13848                                          /*subr=*/false))
13849               return 1;
13850           }
13851           arg = TYPE_TI_TEMPLATE (arg);
13852
13853           /* Fall through to deduce template name.  */
13854         }
13855
13856       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13857           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13858         {
13859           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13860
13861           /* Simple cases: Value already set, does match or doesn't.  */
13862           if (targ != NULL_TREE && template_args_equal (targ, arg))
13863             return 0;
13864           else if (targ)
13865             return 1;
13866         }
13867       else
13868         {
13869           /* If PARM is `const T' and ARG is only `int', we don't have
13870              a match unless we are allowing additional qualification.
13871              If ARG is `const int' and PARM is just `T' that's OK;
13872              that binds `const int' to `T'.  */
13873           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13874                                          arg, parm))
13875             return 1;
13876
13877           /* Consider the case where ARG is `const volatile int' and
13878              PARM is `const T'.  Then, T should be `volatile int'.  */
13879           arg = cp_build_qualified_type_real
13880             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13881           if (arg == error_mark_node)
13882             return 1;
13883
13884           /* Simple cases: Value already set, does match or doesn't.  */
13885           if (targ != NULL_TREE && same_type_p (targ, arg))
13886             return 0;
13887           else if (targ)
13888             return 1;
13889
13890           /* Make sure that ARG is not a variable-sized array.  (Note
13891              that were talking about variable-sized arrays (like
13892              `int[n]'), rather than arrays of unknown size (like
13893              `int[]').)  We'll get very confused by such a type since
13894              the bound of the array will not be computable in an
13895              instantiation.  Besides, such types are not allowed in
13896              ISO C++, so we can do as we please here.  */
13897           if (variably_modified_type_p (arg, NULL_TREE))
13898             return 1;
13899
13900           /* Strip typedefs as in convert_template_argument.  */
13901           arg = strip_typedefs (arg);
13902         }
13903
13904       /* If ARG is a parameter pack or an expansion, we cannot unify
13905          against it unless PARM is also a parameter pack.  */
13906       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13907           && !template_parameter_pack_p (parm))
13908         return 1;
13909
13910       /* If the argument deduction results is a METHOD_TYPE,
13911          then there is a problem.
13912          METHOD_TYPE doesn't map to any real C++ type the result of
13913          the deduction can not be of that type.  */
13914       if (TREE_CODE (arg) == METHOD_TYPE)
13915         return 1;
13916
13917       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13918       return 0;
13919
13920     case TEMPLATE_PARM_INDEX:
13921       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13922       if (tparm == error_mark_node)
13923         return 1;
13924
13925       if (TEMPLATE_PARM_LEVEL (parm)
13926           != template_decl_level (tparm))
13927         /* The PARM is not one we're trying to unify.  Just check
13928            to see if it matches ARG.  */
13929         return !(TREE_CODE (arg) == TREE_CODE (parm)
13930                  && cp_tree_equal (parm, arg));
13931
13932       idx = TEMPLATE_PARM_IDX (parm);
13933       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13934
13935       if (targ)
13936         return !cp_tree_equal (targ, arg);
13937
13938       /* [temp.deduct.type] If, in the declaration of a function template
13939          with a non-type template-parameter, the non-type
13940          template-parameter is used in an expression in the function
13941          parameter-list and, if the corresponding template-argument is
13942          deduced, the template-argument type shall match the type of the
13943          template-parameter exactly, except that a template-argument
13944          deduced from an array bound may be of any integral type.
13945          The non-type parameter might use already deduced type parameters.  */
13946       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13947       if (!TREE_TYPE (arg))
13948         /* Template-parameter dependent expression.  Just accept it for now.
13949            It will later be processed in convert_template_argument.  */
13950         ;
13951       else if (same_type_p (TREE_TYPE (arg), tparm))
13952         /* OK */;
13953       else if ((strict & UNIFY_ALLOW_INTEGER)
13954                && (TREE_CODE (tparm) == INTEGER_TYPE
13955                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13956         /* Convert the ARG to the type of PARM; the deduced non-type
13957            template argument must exactly match the types of the
13958            corresponding parameter.  */
13959         arg = fold (build_nop (tparm, arg));
13960       else if (uses_template_parms (tparm))
13961         /* We haven't deduced the type of this parameter yet.  Try again
13962            later.  */
13963         return 0;
13964       else
13965         return 1;
13966
13967       /* If ARG is a parameter pack or an expansion, we cannot unify
13968          against it unless PARM is also a parameter pack.  */
13969       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13970           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13971         return 1;
13972
13973       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13974       return 0;
13975
13976     case PTRMEM_CST:
13977      {
13978         /* A pointer-to-member constant can be unified only with
13979          another constant.  */
13980       if (TREE_CODE (arg) != PTRMEM_CST)
13981         return 1;
13982
13983       /* Just unify the class member. It would be useless (and possibly
13984          wrong, depending on the strict flags) to unify also
13985          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13986          arg refer to the same variable, even if through different
13987          classes. For instance:
13988
13989          struct A { int x; };
13990          struct B : A { };
13991
13992          Unification of &A::x and &B::x must succeed.  */
13993       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13994                     PTRMEM_CST_MEMBER (arg), strict);
13995      }
13996
13997     case POINTER_TYPE:
13998       {
13999         if (TREE_CODE (arg) != POINTER_TYPE)
14000           return 1;
14001
14002         /* [temp.deduct.call]
14003
14004            A can be another pointer or pointer to member type that can
14005            be converted to the deduced A via a qualification
14006            conversion (_conv.qual_).
14007
14008            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14009            This will allow for additional cv-qualification of the
14010            pointed-to types if appropriate.  */
14011
14012         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14013           /* The derived-to-base conversion only persists through one
14014              level of pointers.  */
14015           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14016
14017         return unify (tparms, targs, TREE_TYPE (parm),
14018                       TREE_TYPE (arg), strict);
14019       }
14020
14021     case REFERENCE_TYPE:
14022       if (TREE_CODE (arg) != REFERENCE_TYPE)
14023         return 1;
14024       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14025                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14026
14027     case ARRAY_TYPE:
14028       if (TREE_CODE (arg) != ARRAY_TYPE)
14029         return 1;
14030       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14031           != (TYPE_DOMAIN (arg) == NULL_TREE))
14032         return 1;
14033       if (TYPE_DOMAIN (parm) != NULL_TREE)
14034         {
14035           tree parm_max;
14036           tree arg_max;
14037           bool parm_cst;
14038           bool arg_cst;
14039
14040           /* Our representation of array types uses "N - 1" as the
14041              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14042              not an integer constant.  We cannot unify arbitrarily
14043              complex expressions, so we eliminate the MINUS_EXPRs
14044              here.  */
14045           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14046           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14047           if (!parm_cst)
14048             {
14049               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14050               parm_max = TREE_OPERAND (parm_max, 0);
14051             }
14052           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14053           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14054           if (!arg_cst)
14055             {
14056               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14057                  trying to unify the type of a variable with the type
14058                  of a template parameter.  For example:
14059
14060                    template <unsigned int N>
14061                    void f (char (&) [N]);
14062                    int g(); 
14063                    void h(int i) {
14064                      char a[g(i)];
14065                      f(a); 
14066                    }
14067
14068                 Here, the type of the ARG will be "int [g(i)]", and
14069                 may be a SAVE_EXPR, etc.  */
14070               if (TREE_CODE (arg_max) != MINUS_EXPR)
14071                 return 1;
14072               arg_max = TREE_OPERAND (arg_max, 0);
14073             }
14074
14075           /* If only one of the bounds used a MINUS_EXPR, compensate
14076              by adding one to the other bound.  */
14077           if (parm_cst && !arg_cst)
14078             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14079                                     integer_type_node,
14080                                     parm_max,
14081                                     integer_one_node);
14082           else if (arg_cst && !parm_cst)
14083             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14084                                    integer_type_node,
14085                                    arg_max,
14086                                    integer_one_node);
14087
14088           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14089             return 1;
14090         }
14091       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14092                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14093
14094     case REAL_TYPE:
14095     case COMPLEX_TYPE:
14096     case VECTOR_TYPE:
14097     case INTEGER_TYPE:
14098     case BOOLEAN_TYPE:
14099     case ENUMERAL_TYPE:
14100     case VOID_TYPE:
14101       if (TREE_CODE (arg) != TREE_CODE (parm))
14102         return 1;
14103
14104       /* We have already checked cv-qualification at the top of the
14105          function.  */
14106       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14107         return 1;
14108
14109       /* As far as unification is concerned, this wins.  Later checks
14110          will invalidate it if necessary.  */
14111       return 0;
14112
14113       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14114       /* Type INTEGER_CST can come from ordinary constant template args.  */
14115     case INTEGER_CST:
14116       while (TREE_CODE (arg) == NOP_EXPR)
14117         arg = TREE_OPERAND (arg, 0);
14118
14119       if (TREE_CODE (arg) != INTEGER_CST)
14120         return 1;
14121       return !tree_int_cst_equal (parm, arg);
14122
14123     case TREE_VEC:
14124       {
14125         int i;
14126         if (TREE_CODE (arg) != TREE_VEC)
14127           return 1;
14128         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14129           return 1;
14130         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14131           if (unify (tparms, targs,
14132                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14133                      UNIFY_ALLOW_NONE))
14134             return 1;
14135         return 0;
14136       }
14137
14138     case RECORD_TYPE:
14139     case UNION_TYPE:
14140       if (TREE_CODE (arg) != TREE_CODE (parm))
14141         return 1;
14142
14143       if (TYPE_PTRMEMFUNC_P (parm))
14144         {
14145           if (!TYPE_PTRMEMFUNC_P (arg))
14146             return 1;
14147
14148           return unify (tparms, targs,
14149                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14150                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14151                         strict);
14152         }
14153
14154       if (CLASSTYPE_TEMPLATE_INFO (parm))
14155         {
14156           tree t = NULL_TREE;
14157
14158           if (strict_in & UNIFY_ALLOW_DERIVED)
14159             {
14160               /* First, we try to unify the PARM and ARG directly.  */
14161               t = try_class_unification (tparms, targs,
14162                                          parm, arg);
14163
14164               if (!t)
14165                 {
14166                   /* Fallback to the special case allowed in
14167                      [temp.deduct.call]:
14168
14169                        If P is a class, and P has the form
14170                        template-id, then A can be a derived class of
14171                        the deduced A.  Likewise, if P is a pointer to
14172                        a class of the form template-id, A can be a
14173                        pointer to a derived class pointed to by the
14174                        deduced A.  */
14175                   t = get_template_base (tparms, targs, parm, arg);
14176
14177                   if (!t)
14178                     return 1;
14179                 }
14180             }
14181           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14182                    && (CLASSTYPE_TI_TEMPLATE (parm)
14183                        == CLASSTYPE_TI_TEMPLATE (arg)))
14184             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14185                Then, we should unify `int' and `U'.  */
14186             t = arg;
14187           else
14188             /* There's no chance of unification succeeding.  */
14189             return 1;
14190
14191           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14192                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14193         }
14194       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14195         return 1;
14196       return 0;
14197
14198     case METHOD_TYPE:
14199     case FUNCTION_TYPE:
14200       {
14201         unsigned int nargs;
14202         tree *args;
14203         tree a;
14204         unsigned int i;
14205
14206         if (TREE_CODE (arg) != TREE_CODE (parm))
14207           return 1;
14208
14209         /* CV qualifications for methods can never be deduced, they must
14210            match exactly.  We need to check them explicitly here,
14211            because type_unification_real treats them as any other
14212            cv-qualified parameter.  */
14213         if (TREE_CODE (parm) == METHOD_TYPE
14214             && (!check_cv_quals_for_unify
14215                 (UNIFY_ALLOW_NONE,
14216                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14217                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14218           return 1;
14219
14220         if (unify (tparms, targs, TREE_TYPE (parm),
14221                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14222           return 1;
14223
14224         nargs = list_length (TYPE_ARG_TYPES (arg));
14225         args = XALLOCAVEC (tree, nargs);
14226         for (a = TYPE_ARG_TYPES (arg), i = 0;
14227              a != NULL_TREE && a != void_list_node;
14228              a = TREE_CHAIN (a), ++i)
14229           args[i] = TREE_VALUE (a);
14230         nargs = i;
14231
14232         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14233                                       args, nargs, 1, DEDUCE_EXACT,
14234                                       LOOKUP_NORMAL);
14235       }
14236
14237     case OFFSET_TYPE:
14238       /* Unify a pointer to member with a pointer to member function, which
14239          deduces the type of the member as a function type. */
14240       if (TYPE_PTRMEMFUNC_P (arg))
14241         {
14242           tree method_type;
14243           tree fntype;
14244           cp_cv_quals cv_quals;
14245
14246           /* Check top-level cv qualifiers */
14247           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14248             return 1;
14249
14250           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14251                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14252             return 1;
14253
14254           /* Determine the type of the function we are unifying against. */
14255           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14256           fntype =
14257             build_function_type (TREE_TYPE (method_type),
14258                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14259
14260           /* Extract the cv-qualifiers of the member function from the
14261              implicit object parameter and place them on the function
14262              type to be restored later. */
14263           cv_quals =
14264             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14265           fntype = build_qualified_type (fntype, cv_quals);
14266           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14267         }
14268
14269       if (TREE_CODE (arg) != OFFSET_TYPE)
14270         return 1;
14271       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14272                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14273         return 1;
14274       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14275                     strict);
14276
14277     case CONST_DECL:
14278       if (DECL_TEMPLATE_PARM_P (parm))
14279         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14280       if (arg != integral_constant_value (parm))
14281         return 1;
14282       return 0;
14283
14284     case FIELD_DECL:
14285     case TEMPLATE_DECL:
14286       /* Matched cases are handled by the ARG == PARM test above.  */
14287       return 1;
14288
14289     case TYPE_ARGUMENT_PACK:
14290     case NONTYPE_ARGUMENT_PACK:
14291       {
14292         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14293         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14294         int i, len = TREE_VEC_LENGTH (packed_parms);
14295         int argslen = TREE_VEC_LENGTH (packed_args);
14296         int parm_variadic_p = 0;
14297
14298         for (i = 0; i < len; ++i)
14299           {
14300             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14301               {
14302                 if (i == len - 1)
14303                   /* We can unify against something with a trailing
14304                      parameter pack.  */
14305                   parm_variadic_p = 1;
14306                 else
14307                   /* Since there is something following the pack
14308                      expansion, we cannot unify this template argument
14309                      list.  */
14310                   return 0;
14311               }
14312           }
14313           
14314
14315         /* If we don't have enough arguments to satisfy the parameters
14316            (not counting the pack expression at the end), or we have
14317            too many arguments for a parameter list that doesn't end in
14318            a pack expression, we can't unify.  */
14319         if (argslen < (len - parm_variadic_p)
14320             || (argslen > len && !parm_variadic_p))
14321           return 1;
14322
14323         /* Unify all of the parameters that precede the (optional)
14324            pack expression.  */
14325         for (i = 0; i < len - parm_variadic_p; ++i)
14326           {
14327             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14328                        TREE_VEC_ELT (packed_args, i), strict))
14329               return 1;
14330           }
14331
14332         if (parm_variadic_p)
14333           return unify_pack_expansion (tparms, targs, 
14334                                        packed_parms, packed_args,
14335                                        strict, /*call_args_p=*/false,
14336                                        /*subr=*/false);
14337         return 0;
14338       }
14339
14340       break;
14341
14342     case TYPEOF_TYPE:
14343     case DECLTYPE_TYPE:
14344       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14345          nodes.  */
14346       return 0;
14347
14348     case ERROR_MARK:
14349       /* Unification fails if we hit an error node.  */
14350       return 1;
14351
14352     default:
14353       gcc_assert (EXPR_P (parm));
14354
14355       /* We must be looking at an expression.  This can happen with
14356          something like:
14357
14358            template <int I>
14359            void foo(S<I>, S<I + 2>);
14360
14361          This is a "nondeduced context":
14362
14363            [deduct.type]
14364
14365            The nondeduced contexts are:
14366
14367            --A type that is a template-id in which one or more of
14368              the template-arguments is an expression that references
14369              a template-parameter.
14370
14371          In these cases, we assume deduction succeeded, but don't
14372          actually infer any unifications.  */
14373
14374       if (!uses_template_parms (parm)
14375           && !template_args_equal (parm, arg))
14376         return 1;
14377       else
14378         return 0;
14379     }
14380 }
14381 \f
14382 /* Note that DECL can be defined in this translation unit, if
14383    required.  */
14384
14385 static void
14386 mark_definable (tree decl)
14387 {
14388   tree clone;
14389   DECL_NOT_REALLY_EXTERN (decl) = 1;
14390   FOR_EACH_CLONE (clone, decl)
14391     DECL_NOT_REALLY_EXTERN (clone) = 1;
14392 }
14393
14394 /* Called if RESULT is explicitly instantiated, or is a member of an
14395    explicitly instantiated class.  */
14396
14397 void
14398 mark_decl_instantiated (tree result, int extern_p)
14399 {
14400   SET_DECL_EXPLICIT_INSTANTIATION (result);
14401
14402   /* If this entity has already been written out, it's too late to
14403      make any modifications.  */
14404   if (TREE_ASM_WRITTEN (result))
14405     return;
14406
14407   if (TREE_CODE (result) != FUNCTION_DECL)
14408     /* The TREE_PUBLIC flag for function declarations will have been
14409        set correctly by tsubst.  */
14410     TREE_PUBLIC (result) = 1;
14411
14412   /* This might have been set by an earlier implicit instantiation.  */
14413   DECL_COMDAT (result) = 0;
14414
14415   if (extern_p)
14416     DECL_NOT_REALLY_EXTERN (result) = 0;
14417   else
14418     {
14419       mark_definable (result);
14420       /* Always make artificials weak.  */
14421       if (DECL_ARTIFICIAL (result) && flag_weak)
14422         comdat_linkage (result);
14423       /* For WIN32 we also want to put explicit instantiations in
14424          linkonce sections.  */
14425       else if (TREE_PUBLIC (result))
14426         maybe_make_one_only (result);
14427     }
14428
14429   /* If EXTERN_P, then this function will not be emitted -- unless
14430      followed by an explicit instantiation, at which point its linkage
14431      will be adjusted.  If !EXTERN_P, then this function will be
14432      emitted here.  In neither circumstance do we want
14433      import_export_decl to adjust the linkage.  */
14434   DECL_INTERFACE_KNOWN (result) = 1;
14435 }
14436
14437 /* Given two function templates PAT1 and PAT2, return:
14438
14439    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14440    -1 if PAT2 is more specialized than PAT1.
14441    0 if neither is more specialized.
14442
14443    LEN indicates the number of parameters we should consider
14444    (defaulted parameters should not be considered).
14445
14446    The 1998 std underspecified function template partial ordering, and
14447    DR214 addresses the issue.  We take pairs of arguments, one from
14448    each of the templates, and deduce them against each other.  One of
14449    the templates will be more specialized if all the *other*
14450    template's arguments deduce against its arguments and at least one
14451    of its arguments *does* *not* deduce against the other template's
14452    corresponding argument.  Deduction is done as for class templates.
14453    The arguments used in deduction have reference and top level cv
14454    qualifiers removed.  Iff both arguments were originally reference
14455    types *and* deduction succeeds in both directions, the template
14456    with the more cv-qualified argument wins for that pairing (if
14457    neither is more cv-qualified, they both are equal).  Unlike regular
14458    deduction, after all the arguments have been deduced in this way,
14459    we do *not* verify the deduced template argument values can be
14460    substituted into non-deduced contexts, nor do we have to verify
14461    that all template arguments have been deduced.  */
14462
14463 int
14464 more_specialized_fn (tree pat1, tree pat2, int len)
14465 {
14466   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14467   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14468   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14469   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14470   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14471   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14472   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14473   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14474   int better1 = 0;
14475   int better2 = 0;
14476
14477   /* Remove the this parameter from non-static member functions.  If
14478      one is a non-static member function and the other is not a static
14479      member function, remove the first parameter from that function
14480      also.  This situation occurs for operator functions where we
14481      locate both a member function (with this pointer) and non-member
14482      operator (with explicit first operand).  */
14483   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14484     {
14485       len--; /* LEN is the number of significant arguments for DECL1 */
14486       args1 = TREE_CHAIN (args1);
14487       if (!DECL_STATIC_FUNCTION_P (decl2))
14488         args2 = TREE_CHAIN (args2);
14489     }
14490   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14491     {
14492       args2 = TREE_CHAIN (args2);
14493       if (!DECL_STATIC_FUNCTION_P (decl1))
14494         {
14495           len--;
14496           args1 = TREE_CHAIN (args1);
14497         }
14498     }
14499
14500   /* If only one is a conversion operator, they are unordered.  */
14501   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14502     return 0;
14503
14504   /* Consider the return type for a conversion function */
14505   if (DECL_CONV_FN_P (decl1))
14506     {
14507       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14508       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14509       len++;
14510     }
14511
14512   processing_template_decl++;
14513
14514   while (len--
14515          /* Stop when an ellipsis is seen.  */
14516          && args1 != NULL_TREE && args2 != NULL_TREE)
14517     {
14518       tree arg1 = TREE_VALUE (args1);
14519       tree arg2 = TREE_VALUE (args2);
14520       int deduce1, deduce2;
14521       int quals1 = -1;
14522       int quals2 = -1;
14523
14524       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14525           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14526         {
14527           /* When both arguments are pack expansions, we need only
14528              unify the patterns themselves.  */
14529           arg1 = PACK_EXPANSION_PATTERN (arg1);
14530           arg2 = PACK_EXPANSION_PATTERN (arg2);
14531
14532           /* This is the last comparison we need to do.  */
14533           len = 0;
14534         }
14535
14536       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14537         {
14538           arg1 = TREE_TYPE (arg1);
14539           quals1 = cp_type_quals (arg1);
14540         }
14541
14542       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14543         {
14544           arg2 = TREE_TYPE (arg2);
14545           quals2 = cp_type_quals (arg2);
14546         }
14547
14548       if ((quals1 < 0) != (quals2 < 0))
14549         {
14550           /* Only of the args is a reference, see if we should apply
14551              array/function pointer decay to it.  This is not part of
14552              DR214, but is, IMHO, consistent with the deduction rules
14553              for the function call itself, and with our earlier
14554              implementation of the underspecified partial ordering
14555              rules.  (nathan).  */
14556           if (quals1 >= 0)
14557             {
14558               switch (TREE_CODE (arg1))
14559                 {
14560                 case ARRAY_TYPE:
14561                   arg1 = TREE_TYPE (arg1);
14562                   /* FALLTHROUGH. */
14563                 case FUNCTION_TYPE:
14564                   arg1 = build_pointer_type (arg1);
14565                   break;
14566
14567                 default:
14568                   break;
14569                 }
14570             }
14571           else
14572             {
14573               switch (TREE_CODE (arg2))
14574                 {
14575                 case ARRAY_TYPE:
14576                   arg2 = TREE_TYPE (arg2);
14577                   /* FALLTHROUGH. */
14578                 case FUNCTION_TYPE:
14579                   arg2 = build_pointer_type (arg2);
14580                   break;
14581
14582                 default:
14583                   break;
14584                 }
14585             }
14586         }
14587
14588       arg1 = TYPE_MAIN_VARIANT (arg1);
14589       arg2 = TYPE_MAIN_VARIANT (arg2);
14590
14591       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14592         {
14593           int i, len2 = list_length (args2);
14594           tree parmvec = make_tree_vec (1);
14595           tree argvec = make_tree_vec (len2);
14596           tree ta = args2;
14597
14598           /* Setup the parameter vector, which contains only ARG1.  */
14599           TREE_VEC_ELT (parmvec, 0) = arg1;
14600
14601           /* Setup the argument vector, which contains the remaining
14602              arguments.  */
14603           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14604             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14605
14606           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14607                                            argvec, UNIFY_ALLOW_NONE, 
14608                                            /*call_args_p=*/false, 
14609                                            /*subr=*/0);
14610
14611           /* We cannot deduce in the other direction, because ARG1 is
14612              a pack expansion but ARG2 is not.  */
14613           deduce2 = 0;
14614         }
14615       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14616         {
14617           int i, len1 = list_length (args1);
14618           tree parmvec = make_tree_vec (1);
14619           tree argvec = make_tree_vec (len1);
14620           tree ta = args1;
14621
14622           /* Setup the parameter vector, which contains only ARG1.  */
14623           TREE_VEC_ELT (parmvec, 0) = arg2;
14624
14625           /* Setup the argument vector, which contains the remaining
14626              arguments.  */
14627           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14628             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14629
14630           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14631                                            argvec, UNIFY_ALLOW_NONE, 
14632                                            /*call_args_p=*/false, 
14633                                            /*subr=*/0);
14634
14635           /* We cannot deduce in the other direction, because ARG2 is
14636              a pack expansion but ARG1 is not.*/
14637           deduce1 = 0;
14638         }
14639
14640       else
14641         {
14642           /* The normal case, where neither argument is a pack
14643              expansion.  */
14644           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14645           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14646         }
14647
14648       if (!deduce1)
14649         better2 = -1;
14650       if (!deduce2)
14651         better1 = -1;
14652       if (better1 < 0 && better2 < 0)
14653         /* We've failed to deduce something in either direction.
14654            These must be unordered.  */
14655         break;
14656
14657       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14658         {
14659           /* Deduces in both directions, see if quals can
14660              disambiguate.  Pretend the worse one failed to deduce. */
14661           if ((quals1 & quals2) == quals2)
14662             deduce1 = 0;
14663           if ((quals1 & quals2) == quals1)
14664             deduce2 = 0;
14665         }
14666       if (deduce1 && !deduce2 && !better2)
14667         better2 = 1;
14668       if (deduce2 && !deduce1 && !better1)
14669         better1 = 1;
14670
14671       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14672           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14673         /* We have already processed all of the arguments in our
14674            handing of the pack expansion type.  */
14675         len = 0;
14676
14677       args1 = TREE_CHAIN (args1);
14678       args2 = TREE_CHAIN (args2);
14679     }
14680
14681   processing_template_decl--;
14682
14683   /* All things being equal, if the next argument is a pack expansion
14684      for one function but not for the other, prefer the
14685      non-variadic function.  */
14686   if ((better1 > 0) - (better2 > 0) == 0
14687       && args1 && TREE_VALUE (args1)
14688       && args2 && TREE_VALUE (args2))
14689     {
14690       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14691         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14692       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14693         return 1;
14694     }
14695
14696   return (better1 > 0) - (better2 > 0);
14697 }
14698
14699 /* Determine which of two partial specializations is more specialized.
14700
14701    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14702    to the first partial specialization.  The TREE_VALUE is the
14703    innermost set of template parameters for the partial
14704    specialization.  PAT2 is similar, but for the second template.
14705
14706    Return 1 if the first partial specialization is more specialized;
14707    -1 if the second is more specialized; 0 if neither is more
14708    specialized.
14709
14710    See [temp.class.order] for information about determining which of
14711    two templates is more specialized.  */
14712
14713 static int
14714 more_specialized_class (tree pat1, tree pat2)
14715 {
14716   tree targs;
14717   tree tmpl1, tmpl2;
14718   int winner = 0;
14719   bool any_deductions = false;
14720
14721   tmpl1 = TREE_TYPE (pat1);
14722   tmpl2 = TREE_TYPE (pat2);
14723
14724   /* Just like what happens for functions, if we are ordering between
14725      different class template specializations, we may encounter dependent
14726      types in the arguments, and we need our dependency check functions
14727      to behave correctly.  */
14728   ++processing_template_decl;
14729   targs = get_class_bindings (TREE_VALUE (pat1),
14730                               CLASSTYPE_TI_ARGS (tmpl1),
14731                               CLASSTYPE_TI_ARGS (tmpl2));
14732   if (targs)
14733     {
14734       --winner;
14735       any_deductions = true;
14736     }
14737
14738   targs = get_class_bindings (TREE_VALUE (pat2),
14739                               CLASSTYPE_TI_ARGS (tmpl2),
14740                               CLASSTYPE_TI_ARGS (tmpl1));
14741   if (targs)
14742     {
14743       ++winner;
14744       any_deductions = true;
14745     }
14746   --processing_template_decl;
14747
14748   /* In the case of a tie where at least one of the class templates
14749      has a parameter pack at the end, the template with the most
14750      non-packed parameters wins.  */
14751   if (winner == 0
14752       && any_deductions
14753       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14754           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14755     {
14756       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14757       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14758       int len1 = TREE_VEC_LENGTH (args1);
14759       int len2 = TREE_VEC_LENGTH (args2);
14760
14761       /* We don't count the pack expansion at the end.  */
14762       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14763         --len1;
14764       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14765         --len2;
14766
14767       if (len1 > len2)
14768         return 1;
14769       else if (len1 < len2)
14770         return -1;
14771     }
14772
14773   return winner;
14774 }
14775
14776 /* Return the template arguments that will produce the function signature
14777    DECL from the function template FN, with the explicit template
14778    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14779    also match.  Return NULL_TREE if no satisfactory arguments could be
14780    found.  */
14781
14782 static tree
14783 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14784 {
14785   int ntparms = DECL_NTPARMS (fn);
14786   tree targs = make_tree_vec (ntparms);
14787   tree decl_type;
14788   tree decl_arg_types;
14789   tree *args;
14790   unsigned int nargs, ix;
14791   tree arg;
14792
14793   /* Substitute the explicit template arguments into the type of DECL.
14794      The call to fn_type_unification will handle substitution into the
14795      FN.  */
14796   decl_type = TREE_TYPE (decl);
14797   if (explicit_args && uses_template_parms (decl_type))
14798     {
14799       tree tmpl;
14800       tree converted_args;
14801
14802       if (DECL_TEMPLATE_INFO (decl))
14803         tmpl = DECL_TI_TEMPLATE (decl);
14804       else
14805         /* We can get here for some invalid specializations.  */
14806         return NULL_TREE;
14807
14808       converted_args
14809         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14810                                  explicit_args, NULL_TREE,
14811                                  tf_none,
14812                                  /*require_all_args=*/false,
14813                                  /*use_default_args=*/false);
14814       if (converted_args == error_mark_node)
14815         return NULL_TREE;
14816
14817       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14818       if (decl_type == error_mark_node)
14819         return NULL_TREE;
14820     }
14821
14822   /* Never do unification on the 'this' parameter.  */
14823   decl_arg_types = skip_artificial_parms_for (decl, 
14824                                               TYPE_ARG_TYPES (decl_type));
14825
14826   nargs = list_length (decl_arg_types);
14827   args = XALLOCAVEC (tree, nargs);
14828   for (arg = decl_arg_types, ix = 0;
14829        arg != NULL_TREE && arg != void_list_node;
14830        arg = TREE_CHAIN (arg), ++ix)
14831     args[ix] = TREE_VALUE (arg);
14832
14833   if (fn_type_unification (fn, explicit_args, targs,
14834                            args, ix,
14835                            (check_rettype || DECL_CONV_FN_P (fn)
14836                             ? TREE_TYPE (decl_type) : NULL_TREE),
14837                            DEDUCE_EXACT, LOOKUP_NORMAL))
14838     return NULL_TREE;
14839
14840   return targs;
14841 }
14842
14843 /* Return the innermost template arguments that, when applied to a
14844    template specialization whose innermost template parameters are
14845    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
14846    ARGS.
14847
14848    For example, suppose we have:
14849
14850      template <class T, class U> struct S {};
14851      template <class T> struct S<T*, int> {};
14852
14853    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14854    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14855    int}.  The resulting vector will be {double}, indicating that `T'
14856    is bound to `double'.  */
14857
14858 static tree
14859 get_class_bindings (tree tparms, tree spec_args, tree args)
14860 {
14861   int i, ntparms = TREE_VEC_LENGTH (tparms);
14862   tree deduced_args;
14863   tree innermost_deduced_args;
14864
14865   innermost_deduced_args = make_tree_vec (ntparms);
14866   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14867     {
14868       deduced_args = copy_node (args);
14869       SET_TMPL_ARGS_LEVEL (deduced_args,
14870                            TMPL_ARGS_DEPTH (deduced_args),
14871                            innermost_deduced_args);
14872     }
14873   else
14874     deduced_args = innermost_deduced_args;
14875
14876   if (unify (tparms, deduced_args,
14877              INNERMOST_TEMPLATE_ARGS (spec_args),
14878              INNERMOST_TEMPLATE_ARGS (args),
14879              UNIFY_ALLOW_NONE))
14880     return NULL_TREE;
14881
14882   for (i =  0; i < ntparms; ++i)
14883     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14884       return NULL_TREE;
14885
14886   /* Verify that nondeduced template arguments agree with the type
14887      obtained from argument deduction.
14888
14889      For example:
14890
14891        struct A { typedef int X; };
14892        template <class T, class U> struct C {};
14893        template <class T> struct C<T, typename T::X> {};
14894
14895      Then with the instantiation `C<A, int>', we can deduce that
14896      `T' is `A' but unify () does not check whether `typename T::X'
14897      is `int'.  */
14898   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14899   if (spec_args == error_mark_node
14900       /* We only need to check the innermost arguments; the other
14901          arguments will always agree.  */
14902       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14903                               INNERMOST_TEMPLATE_ARGS (args)))
14904     return NULL_TREE;
14905
14906   /* Now that we have bindings for all of the template arguments,
14907      ensure that the arguments deduced for the template template
14908      parameters have compatible template parameter lists.  See the use
14909      of template_template_parm_bindings_ok_p in fn_type_unification
14910      for more information.  */
14911   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14912     return NULL_TREE;
14913
14914   return deduced_args;
14915 }
14916
14917 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14918    Return the TREE_LIST node with the most specialized template, if
14919    any.  If there is no most specialized template, the error_mark_node
14920    is returned.
14921
14922    Note that this function does not look at, or modify, the
14923    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14924    returned is one of the elements of INSTANTIATIONS, callers may
14925    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14926    and retrieve it from the value returned.  */
14927
14928 tree
14929 most_specialized_instantiation (tree templates)
14930 {
14931   tree fn, champ;
14932
14933   ++processing_template_decl;
14934
14935   champ = templates;
14936   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14937     {
14938       int fate = 0;
14939
14940       if (get_bindings (TREE_VALUE (champ),
14941                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14942                         NULL_TREE, /*check_ret=*/false))
14943         fate--;
14944
14945       if (get_bindings (TREE_VALUE (fn),
14946                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14947                         NULL_TREE, /*check_ret=*/false))
14948         fate++;
14949
14950       if (fate == -1)
14951         champ = fn;
14952       else if (!fate)
14953         {
14954           /* Equally specialized, move to next function.  If there
14955              is no next function, nothing's most specialized.  */
14956           fn = TREE_CHAIN (fn);
14957           champ = fn;
14958           if (!fn)
14959             break;
14960         }
14961     }
14962
14963   if (champ)
14964     /* Now verify that champ is better than everything earlier in the
14965        instantiation list.  */
14966     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14967       if (get_bindings (TREE_VALUE (champ),
14968                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14969                         NULL_TREE, /*check_ret=*/false)
14970           || !get_bindings (TREE_VALUE (fn),
14971                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14972                             NULL_TREE, /*check_ret=*/false))
14973         {
14974           champ = NULL_TREE;
14975           break;
14976         }
14977
14978   processing_template_decl--;
14979
14980   if (!champ)
14981     return error_mark_node;
14982
14983   return champ;
14984 }
14985
14986 /* If DECL is a specialization of some template, return the most
14987    general such template.  Otherwise, returns NULL_TREE.
14988
14989    For example, given:
14990
14991      template <class T> struct S { template <class U> void f(U); };
14992
14993    if TMPL is `template <class U> void S<int>::f(U)' this will return
14994    the full template.  This function will not trace past partial
14995    specializations, however.  For example, given in addition:
14996
14997      template <class T> struct S<T*> { template <class U> void f(U); };
14998
14999    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15000    `template <class T> template <class U> S<T*>::f(U)'.  */
15001
15002 tree
15003 most_general_template (tree decl)
15004 {
15005   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15006      an immediate specialization.  */
15007   if (TREE_CODE (decl) == FUNCTION_DECL)
15008     {
15009       if (DECL_TEMPLATE_INFO (decl)) {
15010         decl = DECL_TI_TEMPLATE (decl);
15011
15012         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15013            template friend.  */
15014         if (TREE_CODE (decl) != TEMPLATE_DECL)
15015           return NULL_TREE;
15016       } else
15017         return NULL_TREE;
15018     }
15019
15020   /* Look for more and more general templates.  */
15021   while (DECL_TEMPLATE_INFO (decl))
15022     {
15023       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15024          (See cp-tree.h for details.)  */
15025       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15026         break;
15027
15028       if (CLASS_TYPE_P (TREE_TYPE (decl))
15029           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15030         break;
15031
15032       /* Stop if we run into an explicitly specialized class template.  */
15033       if (!DECL_NAMESPACE_SCOPE_P (decl)
15034           && DECL_CONTEXT (decl)
15035           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15036         break;
15037
15038       decl = DECL_TI_TEMPLATE (decl);
15039     }
15040
15041   return decl;
15042 }
15043
15044 /* Return the most specialized of the class template partial
15045    specializations of TMPL which can produce TYPE, a specialization of
15046    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15047    a _TYPE node corresponding to the partial specialization, while the
15048    TREE_PURPOSE is the set of template arguments that must be
15049    substituted into the TREE_TYPE in order to generate TYPE.
15050
15051    If the choice of partial specialization is ambiguous, a diagnostic
15052    is issued, and the error_mark_node is returned.  If there are no
15053    partial specializations of TMPL matching TYPE, then NULL_TREE is
15054    returned.  */
15055
15056 static tree
15057 most_specialized_class (tree type, tree tmpl)
15058 {
15059   tree list = NULL_TREE;
15060   tree t;
15061   tree champ;
15062   int fate;
15063   bool ambiguous_p;
15064   tree args;
15065   tree outer_args = NULL_TREE;
15066
15067   tmpl = most_general_template (tmpl);
15068   args = CLASSTYPE_TI_ARGS (type);
15069
15070   /* For determining which partial specialization to use, only the
15071      innermost args are interesting.  */
15072   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15073     {
15074       outer_args = strip_innermost_template_args (args, 1);
15075       args = INNERMOST_TEMPLATE_ARGS (args);
15076     }
15077
15078   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15079     {
15080       tree partial_spec_args;
15081       tree spec_args;
15082       tree parms = TREE_VALUE (t);
15083
15084       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15085       if (outer_args)
15086         {
15087           int i;
15088
15089           ++processing_template_decl;
15090
15091           /* Discard the outer levels of args, and then substitute in the
15092              template args from the enclosing class.  */
15093           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15094           partial_spec_args = tsubst_template_args
15095             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15096
15097           /* PARMS already refers to just the innermost parms, but the
15098              template parms in partial_spec_args had their levels lowered
15099              by tsubst, so we need to do the same for the parm list.  We
15100              can't just tsubst the TREE_VEC itself, as tsubst wants to
15101              treat a TREE_VEC as an argument vector.  */
15102           parms = copy_node (parms);
15103           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15104             TREE_VEC_ELT (parms, i) =
15105               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15106
15107           --processing_template_decl;
15108         }
15109       spec_args = get_class_bindings (parms,
15110                                       partial_spec_args,
15111                                       args);
15112       if (spec_args)
15113         {
15114           if (outer_args)
15115             spec_args = add_to_template_args (outer_args, spec_args);
15116           list = tree_cons (spec_args, TREE_VALUE (t), list);
15117           TREE_TYPE (list) = TREE_TYPE (t);
15118         }
15119     }
15120
15121   if (! list)
15122     return NULL_TREE;
15123
15124   ambiguous_p = false;
15125   t = list;
15126   champ = t;
15127   t = TREE_CHAIN (t);
15128   for (; t; t = TREE_CHAIN (t))
15129     {
15130       fate = more_specialized_class (champ, t);
15131       if (fate == 1)
15132         ;
15133       else
15134         {
15135           if (fate == 0)
15136             {
15137               t = TREE_CHAIN (t);
15138               if (! t)
15139                 {
15140                   ambiguous_p = true;
15141                   break;
15142                 }
15143             }
15144           champ = t;
15145         }
15146     }
15147
15148   if (!ambiguous_p)
15149     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15150       {
15151         fate = more_specialized_class (champ, t);
15152         if (fate != 1)
15153           {
15154             ambiguous_p = true;
15155             break;
15156           }
15157       }
15158
15159   if (ambiguous_p)
15160     {
15161       const char *str = "candidates are:";
15162       error ("ambiguous class template instantiation for %q#T", type);
15163       for (t = list; t; t = TREE_CHAIN (t))
15164         {
15165           error ("%s %+#T", str, TREE_TYPE (t));
15166           str = "               ";
15167         }
15168       return error_mark_node;
15169     }
15170
15171   return champ;
15172 }
15173
15174 /* Explicitly instantiate DECL.  */
15175
15176 void
15177 do_decl_instantiation (tree decl, tree storage)
15178 {
15179   tree result = NULL_TREE;
15180   int extern_p = 0;
15181
15182   if (!decl || decl == error_mark_node)
15183     /* An error occurred, for which grokdeclarator has already issued
15184        an appropriate message.  */
15185     return;
15186   else if (! DECL_LANG_SPECIFIC (decl))
15187     {
15188       error ("explicit instantiation of non-template %q#D", decl);
15189       return;
15190     }
15191   else if (TREE_CODE (decl) == VAR_DECL)
15192     {
15193       /* There is an asymmetry here in the way VAR_DECLs and
15194          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15195          the latter, the DECL we get back will be marked as a
15196          template instantiation, and the appropriate
15197          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15198          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15199          should handle VAR_DECLs as it currently handles
15200          FUNCTION_DECLs.  */
15201       if (!DECL_CLASS_SCOPE_P (decl))
15202         {
15203           error ("%qD is not a static data member of a class template", decl);
15204           return;
15205         }
15206       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15207       if (!result || TREE_CODE (result) != VAR_DECL)
15208         {
15209           error ("no matching template for %qD found", decl);
15210           return;
15211         }
15212       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15213         {
15214           error ("type %qT for explicit instantiation %qD does not match "
15215                  "declared type %qT", TREE_TYPE (result), decl,
15216                  TREE_TYPE (decl));
15217           return;
15218         }
15219     }
15220   else if (TREE_CODE (decl) != FUNCTION_DECL)
15221     {
15222       error ("explicit instantiation of %q#D", decl);
15223       return;
15224     }
15225   else
15226     result = decl;
15227
15228   /* Check for various error cases.  Note that if the explicit
15229      instantiation is valid the RESULT will currently be marked as an
15230      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15231      until we get here.  */
15232
15233   if (DECL_TEMPLATE_SPECIALIZATION (result))
15234     {
15235       /* DR 259 [temp.spec].
15236
15237          Both an explicit instantiation and a declaration of an explicit
15238          specialization shall not appear in a program unless the explicit
15239          instantiation follows a declaration of the explicit specialization.
15240
15241          For a given set of template parameters, if an explicit
15242          instantiation of a template appears after a declaration of an
15243          explicit specialization for that template, the explicit
15244          instantiation has no effect.  */
15245       return;
15246     }
15247   else if (DECL_EXPLICIT_INSTANTIATION (result))
15248     {
15249       /* [temp.spec]
15250
15251          No program shall explicitly instantiate any template more
15252          than once.
15253
15254          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15255          the first instantiation was `extern' and the second is not,
15256          and EXTERN_P for the opposite case.  */
15257       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15258         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15259       /* If an "extern" explicit instantiation follows an ordinary
15260          explicit instantiation, the template is instantiated.  */
15261       if (extern_p)
15262         return;
15263     }
15264   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15265     {
15266       error ("no matching template for %qD found", result);
15267       return;
15268     }
15269   else if (!DECL_TEMPLATE_INFO (result))
15270     {
15271       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15272       return;
15273     }
15274
15275   if (storage == NULL_TREE)
15276     ;
15277   else if (storage == ridpointers[(int) RID_EXTERN])
15278     {
15279       if (!in_system_header && (cxx_dialect == cxx98))
15280         pedwarn (input_location, OPT_pedantic, 
15281                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15282                  "instantiations");
15283       extern_p = 1;
15284     }
15285   else
15286     error ("storage class %qD applied to template instantiation", storage);
15287
15288   check_explicit_instantiation_namespace (result);
15289   mark_decl_instantiated (result, extern_p);
15290   if (! extern_p)
15291     instantiate_decl (result, /*defer_ok=*/1,
15292                       /*expl_inst_class_mem_p=*/false);
15293 }
15294
15295 static void
15296 mark_class_instantiated (tree t, int extern_p)
15297 {
15298   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15299   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15300   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15301   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15302   if (! extern_p)
15303     {
15304       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15305       rest_of_type_compilation (t, 1);
15306     }
15307 }
15308
15309 /* Called from do_type_instantiation through binding_table_foreach to
15310    do recursive instantiation for the type bound in ENTRY.  */
15311 static void
15312 bt_instantiate_type_proc (binding_entry entry, void *data)
15313 {
15314   tree storage = *(tree *) data;
15315
15316   if (MAYBE_CLASS_TYPE_P (entry->type)
15317       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15318     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15319 }
15320
15321 /* Called from do_type_instantiation to instantiate a member
15322    (a member function or a static member variable) of an
15323    explicitly instantiated class template.  */
15324 static void
15325 instantiate_class_member (tree decl, int extern_p)
15326 {
15327   mark_decl_instantiated (decl, extern_p);
15328   if (! extern_p)
15329     instantiate_decl (decl, /*defer_ok=*/1,
15330                       /*expl_inst_class_mem_p=*/true);
15331 }
15332
15333 /* Perform an explicit instantiation of template class T.  STORAGE, if
15334    non-null, is the RID for extern, inline or static.  COMPLAIN is
15335    nonzero if this is called from the parser, zero if called recursively,
15336    since the standard is unclear (as detailed below).  */
15337
15338 void
15339 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15340 {
15341   int extern_p = 0;
15342   int nomem_p = 0;
15343   int static_p = 0;
15344   int previous_instantiation_extern_p = 0;
15345
15346   if (TREE_CODE (t) == TYPE_DECL)
15347     t = TREE_TYPE (t);
15348
15349   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15350     {
15351       error ("explicit instantiation of non-template type %qT", t);
15352       return;
15353     }
15354
15355   complete_type (t);
15356
15357   if (!COMPLETE_TYPE_P (t))
15358     {
15359       if (complain & tf_error)
15360         error ("explicit instantiation of %q#T before definition of template",
15361                t);
15362       return;
15363     }
15364
15365   if (storage != NULL_TREE)
15366     {
15367       if (!in_system_header)
15368         {
15369           if (storage == ridpointers[(int) RID_EXTERN])
15370             {
15371               if (cxx_dialect == cxx98)
15372                 pedwarn (input_location, OPT_pedantic, 
15373                          "ISO C++ 1998 forbids the use of %<extern%> on "
15374                          "explicit instantiations");
15375             }
15376           else
15377             pedwarn (input_location, OPT_pedantic, 
15378                      "ISO C++ forbids the use of %qE"
15379                      " on explicit instantiations", storage);
15380         }
15381
15382       if (storage == ridpointers[(int) RID_INLINE])
15383         nomem_p = 1;
15384       else if (storage == ridpointers[(int) RID_EXTERN])
15385         extern_p = 1;
15386       else if (storage == ridpointers[(int) RID_STATIC])
15387         static_p = 1;
15388       else
15389         {
15390           error ("storage class %qD applied to template instantiation",
15391                  storage);
15392           extern_p = 0;
15393         }
15394     }
15395
15396   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15397     {
15398       /* DR 259 [temp.spec].
15399
15400          Both an explicit instantiation and a declaration of an explicit
15401          specialization shall not appear in a program unless the explicit
15402          instantiation follows a declaration of the explicit specialization.
15403
15404          For a given set of template parameters, if an explicit
15405          instantiation of a template appears after a declaration of an
15406          explicit specialization for that template, the explicit
15407          instantiation has no effect.  */
15408       return;
15409     }
15410   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15411     {
15412       /* [temp.spec]
15413
15414          No program shall explicitly instantiate any template more
15415          than once.
15416
15417          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15418          instantiation was `extern'.  If EXTERN_P then the second is.
15419          These cases are OK.  */
15420       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15421
15422       if (!previous_instantiation_extern_p && !extern_p
15423           && (complain & tf_error))
15424         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15425
15426       /* If we've already instantiated the template, just return now.  */
15427       if (!CLASSTYPE_INTERFACE_ONLY (t))
15428         return;
15429     }
15430
15431   check_explicit_instantiation_namespace (TYPE_NAME (t));
15432   mark_class_instantiated (t, extern_p);
15433
15434   if (nomem_p)
15435     return;
15436
15437   {
15438     tree tmp;
15439
15440     /* In contrast to implicit instantiation, where only the
15441        declarations, and not the definitions, of members are
15442        instantiated, we have here:
15443
15444          [temp.explicit]
15445
15446          The explicit instantiation of a class template specialization
15447          implies the instantiation of all of its members not
15448          previously explicitly specialized in the translation unit
15449          containing the explicit instantiation.
15450
15451        Of course, we can't instantiate member template classes, since
15452        we don't have any arguments for them.  Note that the standard
15453        is unclear on whether the instantiation of the members are
15454        *explicit* instantiations or not.  However, the most natural
15455        interpretation is that it should be an explicit instantiation.  */
15456
15457     if (! static_p)
15458       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15459         if (TREE_CODE (tmp) == FUNCTION_DECL
15460             && DECL_TEMPLATE_INSTANTIATION (tmp))
15461           instantiate_class_member (tmp, extern_p);
15462
15463     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15464       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15465         instantiate_class_member (tmp, extern_p);
15466
15467     if (CLASSTYPE_NESTED_UTDS (t))
15468       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15469                              bt_instantiate_type_proc, &storage);
15470   }
15471 }
15472
15473 /* Given a function DECL, which is a specialization of TMPL, modify
15474    DECL to be a re-instantiation of TMPL with the same template
15475    arguments.  TMPL should be the template into which tsubst'ing
15476    should occur for DECL, not the most general template.
15477
15478    One reason for doing this is a scenario like this:
15479
15480      template <class T>
15481      void f(const T&, int i);
15482
15483      void g() { f(3, 7); }
15484
15485      template <class T>
15486      void f(const T& t, const int i) { }
15487
15488    Note that when the template is first instantiated, with
15489    instantiate_template, the resulting DECL will have no name for the
15490    first parameter, and the wrong type for the second.  So, when we go
15491    to instantiate the DECL, we regenerate it.  */
15492
15493 static void
15494 regenerate_decl_from_template (tree decl, tree tmpl)
15495 {
15496   /* The arguments used to instantiate DECL, from the most general
15497      template.  */
15498   tree args;
15499   tree code_pattern;
15500
15501   args = DECL_TI_ARGS (decl);
15502   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15503
15504   /* Make sure that we can see identifiers, and compute access
15505      correctly.  */
15506   push_access_scope (decl);
15507
15508   if (TREE_CODE (decl) == FUNCTION_DECL)
15509     {
15510       tree decl_parm;
15511       tree pattern_parm;
15512       tree specs;
15513       int args_depth;
15514       int parms_depth;
15515
15516       args_depth = TMPL_ARGS_DEPTH (args);
15517       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15518       if (args_depth > parms_depth)
15519         args = get_innermost_template_args (args, parms_depth);
15520
15521       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15522                                               args, tf_error, NULL_TREE);
15523       if (specs)
15524         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15525                                                     specs);
15526
15527       /* Merge parameter declarations.  */
15528       decl_parm = skip_artificial_parms_for (decl,
15529                                              DECL_ARGUMENTS (decl));
15530       pattern_parm
15531         = skip_artificial_parms_for (code_pattern,
15532                                      DECL_ARGUMENTS (code_pattern));
15533       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15534         {
15535           tree parm_type;
15536           tree attributes;
15537           
15538           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15539             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15540           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15541                               NULL_TREE);
15542           parm_type = type_decays_to (parm_type);
15543           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15544             TREE_TYPE (decl_parm) = parm_type;
15545           attributes = DECL_ATTRIBUTES (pattern_parm);
15546           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15547             {
15548               DECL_ATTRIBUTES (decl_parm) = attributes;
15549               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15550             }
15551           decl_parm = TREE_CHAIN (decl_parm);
15552           pattern_parm = TREE_CHAIN (pattern_parm);
15553         }
15554       /* Merge any parameters that match with the function parameter
15555          pack.  */
15556       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15557         {
15558           int i, len;
15559           tree expanded_types;
15560           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15561              the parameters in this function parameter pack.  */
15562           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15563                                                  args, tf_error, NULL_TREE);
15564           len = TREE_VEC_LENGTH (expanded_types);
15565           for (i = 0; i < len; i++)
15566             {
15567               tree parm_type;
15568               tree attributes;
15569           
15570               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15571                 /* Rename the parameter to include the index.  */
15572                 DECL_NAME (decl_parm) = 
15573                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15574               parm_type = TREE_VEC_ELT (expanded_types, i);
15575               parm_type = type_decays_to (parm_type);
15576               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15577                 TREE_TYPE (decl_parm) = parm_type;
15578               attributes = DECL_ATTRIBUTES (pattern_parm);
15579               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15580                 {
15581                   DECL_ATTRIBUTES (decl_parm) = attributes;
15582                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15583                 }
15584               decl_parm = TREE_CHAIN (decl_parm);
15585             }
15586         }
15587       /* Merge additional specifiers from the CODE_PATTERN.  */
15588       if (DECL_DECLARED_INLINE_P (code_pattern)
15589           && !DECL_DECLARED_INLINE_P (decl))
15590         DECL_DECLARED_INLINE_P (decl) = 1;
15591     }
15592   else if (TREE_CODE (decl) == VAR_DECL)
15593     DECL_INITIAL (decl) =
15594       tsubst_expr (DECL_INITIAL (code_pattern), args,
15595                    tf_error, DECL_TI_TEMPLATE (decl),
15596                    /*integral_constant_expression_p=*/false);
15597   else
15598     gcc_unreachable ();
15599
15600   pop_access_scope (decl);
15601 }
15602
15603 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15604    substituted to get DECL.  */
15605
15606 tree
15607 template_for_substitution (tree decl)
15608 {
15609   tree tmpl = DECL_TI_TEMPLATE (decl);
15610
15611   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15612      for the instantiation.  This is not always the most general
15613      template.  Consider, for example:
15614
15615         template <class T>
15616         struct S { template <class U> void f();
15617                    template <> void f<int>(); };
15618
15619      and an instantiation of S<double>::f<int>.  We want TD to be the
15620      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15621   while (/* An instantiation cannot have a definition, so we need a
15622             more general template.  */
15623          DECL_TEMPLATE_INSTANTIATION (tmpl)
15624            /* We must also deal with friend templates.  Given:
15625
15626                 template <class T> struct S {
15627                   template <class U> friend void f() {};
15628                 };
15629
15630               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15631               so far as the language is concerned, but that's still
15632               where we get the pattern for the instantiation from.  On
15633               other hand, if the definition comes outside the class, say:
15634
15635                 template <class T> struct S {
15636                   template <class U> friend void f();
15637                 };
15638                 template <class U> friend void f() {}
15639
15640               we don't need to look any further.  That's what the check for
15641               DECL_INITIAL is for.  */
15642           || (TREE_CODE (decl) == FUNCTION_DECL
15643               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15644               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15645     {
15646       /* The present template, TD, should not be a definition.  If it
15647          were a definition, we should be using it!  Note that we
15648          cannot restructure the loop to just keep going until we find
15649          a template with a definition, since that might go too far if
15650          a specialization was declared, but not defined.  */
15651       gcc_assert (TREE_CODE (decl) != VAR_DECL
15652                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15653
15654       /* Fetch the more general template.  */
15655       tmpl = DECL_TI_TEMPLATE (tmpl);
15656     }
15657
15658   return tmpl;
15659 }
15660
15661 /* Produce the definition of D, a _DECL generated from a template.  If
15662    DEFER_OK is nonzero, then we don't have to actually do the
15663    instantiation now; we just have to do it sometime.  Normally it is
15664    an error if this is an explicit instantiation but D is undefined.
15665    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15666    explicitly instantiated class template.  */
15667
15668 tree
15669 instantiate_decl (tree d, int defer_ok,
15670                   bool expl_inst_class_mem_p)
15671 {
15672   tree tmpl = DECL_TI_TEMPLATE (d);
15673   tree gen_args;
15674   tree args;
15675   tree td;
15676   tree code_pattern;
15677   tree spec;
15678   tree gen_tmpl;
15679   bool pattern_defined;
15680   int need_push;
15681   location_t saved_loc = input_location;
15682   bool external_p;
15683
15684   /* This function should only be used to instantiate templates for
15685      functions and static member variables.  */
15686   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15687               || TREE_CODE (d) == VAR_DECL);
15688
15689   /* Variables are never deferred; if instantiation is required, they
15690      are instantiated right away.  That allows for better code in the
15691      case that an expression refers to the value of the variable --
15692      if the variable has a constant value the referring expression can
15693      take advantage of that fact.  */
15694   if (TREE_CODE (d) == VAR_DECL)
15695     defer_ok = 0;
15696
15697   /* Don't instantiate cloned functions.  Instead, instantiate the
15698      functions they cloned.  */
15699   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15700     d = DECL_CLONED_FUNCTION (d);
15701
15702   if (DECL_TEMPLATE_INSTANTIATED (d)
15703       || DECL_TEMPLATE_SPECIALIZATION (d))
15704     /* D has already been instantiated or explicitly specialized, so
15705        there's nothing for us to do here.
15706
15707        It might seem reasonable to check whether or not D is an explicit
15708        instantiation, and, if so, stop here.  But when an explicit
15709        instantiation is deferred until the end of the compilation,
15710        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
15711        the instantiation.  */
15712     return d;
15713
15714   gen_tmpl = most_general_template (tmpl);
15715   gen_args = DECL_TI_ARGS (d);
15716
15717   if (tmpl != gen_tmpl)
15718     /* We should already have the extra args.  */
15719     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
15720                 == TMPL_ARGS_DEPTH (gen_args));
15721   /* And what's in the hash table should match D.  */
15722   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
15723               || spec == NULL_TREE);
15724
15725   /* This needs to happen before any tsubsting.  */
15726   if (! push_tinst_level (d))
15727     return d;
15728
15729   timevar_push (TV_PARSE);
15730
15731   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15732      for the instantiation.  */
15733   td = template_for_substitution (d);
15734   code_pattern = DECL_TEMPLATE_RESULT (td);
15735
15736   /* We should never be trying to instantiate a member of a class
15737      template or partial specialization.  */
15738   gcc_assert (d != code_pattern);
15739
15740   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15741       || DECL_TEMPLATE_SPECIALIZATION (td))
15742     /* In the case of a friend template whose definition is provided
15743        outside the class, we may have too many arguments.  Drop the
15744        ones we don't need.  The same is true for specializations.  */
15745     args = get_innermost_template_args
15746       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15747   else
15748     args = gen_args;
15749
15750   if (TREE_CODE (d) == FUNCTION_DECL)
15751     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15752   else
15753     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15754
15755   /* We may be in the middle of deferred access check.  Disable it now.  */
15756   push_deferring_access_checks (dk_no_deferred);
15757
15758   /* Unless an explicit instantiation directive has already determined
15759      the linkage of D, remember that a definition is available for
15760      this entity.  */
15761   if (pattern_defined
15762       && !DECL_INTERFACE_KNOWN (d)
15763       && !DECL_NOT_REALLY_EXTERN (d))
15764     mark_definable (d);
15765
15766   input_location = DECL_SOURCE_LOCATION (d);
15767
15768   /* If D is a member of an explicitly instantiated class template,
15769      and no definition is available, treat it like an implicit
15770      instantiation.  */
15771   if (!pattern_defined && expl_inst_class_mem_p
15772       && DECL_EXPLICIT_INSTANTIATION (d))
15773     {
15774       DECL_NOT_REALLY_EXTERN (d) = 0;
15775       DECL_INTERFACE_KNOWN (d) = 0;
15776       SET_DECL_IMPLICIT_INSTANTIATION (d);
15777     }
15778
15779   if (!defer_ok)
15780     {
15781       /* Recheck the substitutions to obtain any warning messages
15782          about ignoring cv qualifiers.  */
15783       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15784       tree type = TREE_TYPE (gen);
15785
15786       /* Make sure that we can see identifiers, and compute access
15787          correctly.  D is already the target FUNCTION_DECL with the
15788          right context.  */
15789       push_access_scope (d);
15790
15791       if (TREE_CODE (gen) == FUNCTION_DECL)
15792         {
15793           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15794           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15795                                           d);
15796           /* Don't simply tsubst the function type, as that will give
15797              duplicate warnings about poor parameter qualifications.
15798              The function arguments are the same as the decl_arguments
15799              without the top level cv qualifiers.  */
15800           type = TREE_TYPE (type);
15801         }
15802       tsubst (type, gen_args, tf_warning_or_error, d);
15803
15804       pop_access_scope (d);
15805     }
15806
15807   /* Check to see whether we know that this template will be
15808      instantiated in some other file, as with "extern template"
15809      extension.  */
15810   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15811   /* In general, we do not instantiate such templates...  */
15812   if (external_p
15813       /* ... but we instantiate inline functions so that we can inline
15814          them.  An explicit instantiation declaration prohibits implicit
15815          instantiation of non-inline functions.  With high levels of
15816          optimization, we would normally inline non-inline functions
15817          -- but we're not allowed to do that for "extern template" functions.
15818          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15819          possibly_inlined_p.  And ...  */
15820       && ! (TREE_CODE (d) == FUNCTION_DECL
15821             && DECL_DECLARED_INLINE_P (d))
15822       /* ... we instantiate static data members whose values are
15823          needed in integral constant expressions.  */
15824       && ! (TREE_CODE (d) == VAR_DECL
15825             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15826     goto out;
15827   /* Defer all other templates, unless we have been explicitly
15828      forbidden from doing so.  */
15829   if (/* If there is no definition, we cannot instantiate the
15830          template.  */
15831       ! pattern_defined
15832       /* If it's OK to postpone instantiation, do so.  */
15833       || defer_ok
15834       /* If this is a static data member that will be defined
15835          elsewhere, we don't want to instantiate the entire data
15836          member, but we do want to instantiate the initializer so that
15837          we can substitute that elsewhere.  */
15838       || (external_p && TREE_CODE (d) == VAR_DECL))
15839     {
15840       /* The definition of the static data member is now required so
15841          we must substitute the initializer.  */
15842       if (TREE_CODE (d) == VAR_DECL
15843           && !DECL_INITIAL (d)
15844           && DECL_INITIAL (code_pattern))
15845         {
15846           tree ns;
15847           tree init;
15848
15849           ns = decl_namespace_context (d);
15850           push_nested_namespace (ns);
15851           push_nested_class (DECL_CONTEXT (d));
15852           init = tsubst_expr (DECL_INITIAL (code_pattern),
15853                               args,
15854                               tf_warning_or_error, NULL_TREE,
15855                               /*integral_constant_expression_p=*/false);
15856           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15857                           /*asmspec_tree=*/NULL_TREE,
15858                           LOOKUP_ONLYCONVERTING);
15859           pop_nested_class ();
15860           pop_nested_namespace (ns);
15861         }
15862
15863       /* We restore the source position here because it's used by
15864          add_pending_template.  */
15865       input_location = saved_loc;
15866
15867       if (at_eof && !pattern_defined
15868           && DECL_EXPLICIT_INSTANTIATION (d)
15869           && DECL_NOT_REALLY_EXTERN (d))
15870         /* [temp.explicit]
15871
15872            The definition of a non-exported function template, a
15873            non-exported member function template, or a non-exported
15874            member function or static data member of a class template
15875            shall be present in every translation unit in which it is
15876            explicitly instantiated.  */
15877         permerror (input_location,  "explicit instantiation of %qD "
15878                    "but no definition available", d);
15879
15880       /* ??? Historically, we have instantiated inline functions, even
15881          when marked as "extern template".  */
15882       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15883         add_pending_template (d);
15884       goto out;
15885     }
15886   /* Tell the repository that D is available in this translation unit
15887      -- and see if it is supposed to be instantiated here.  */
15888   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15889     {
15890       /* In a PCH file, despite the fact that the repository hasn't
15891          requested instantiation in the PCH it is still possible that
15892          an instantiation will be required in a file that includes the
15893          PCH.  */
15894       if (pch_file)
15895         add_pending_template (d);
15896       /* Instantiate inline functions so that the inliner can do its
15897          job, even though we'll not be emitting a copy of this
15898          function.  */
15899       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15900         goto out;
15901     }
15902
15903   need_push = !cfun || !global_bindings_p ();
15904   if (need_push)
15905     push_to_top_level ();
15906
15907   /* Mark D as instantiated so that recursive calls to
15908      instantiate_decl do not try to instantiate it again.  */
15909   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15910
15911   /* Regenerate the declaration in case the template has been modified
15912      by a subsequent redeclaration.  */
15913   regenerate_decl_from_template (d, td);
15914
15915   /* We already set the file and line above.  Reset them now in case
15916      they changed as a result of calling regenerate_decl_from_template.  */
15917   input_location = DECL_SOURCE_LOCATION (d);
15918
15919   if (TREE_CODE (d) == VAR_DECL)
15920     {
15921       tree init;
15922
15923       /* Clear out DECL_RTL; whatever was there before may not be right
15924          since we've reset the type of the declaration.  */
15925       SET_DECL_RTL (d, NULL_RTX);
15926       DECL_IN_AGGR_P (d) = 0;
15927
15928       /* The initializer is placed in DECL_INITIAL by
15929          regenerate_decl_from_template.  Pull it out so that
15930          cp_finish_decl can process it.  */
15931       init = DECL_INITIAL (d);
15932       DECL_INITIAL (d) = NULL_TREE;
15933       DECL_INITIALIZED_P (d) = 0;
15934
15935       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15936          initializer.  That function will defer actual emission until
15937          we have a chance to determine linkage.  */
15938       DECL_EXTERNAL (d) = 0;
15939
15940       /* Enter the scope of D so that access-checking works correctly.  */
15941       push_nested_class (DECL_CONTEXT (d));
15942       cp_finish_decl (d, init, false, NULL_TREE, 0);
15943       pop_nested_class ();
15944     }
15945   else if (TREE_CODE (d) == FUNCTION_DECL)
15946     {
15947       htab_t saved_local_specializations;
15948       tree subst_decl;
15949       tree tmpl_parm;
15950       tree spec_parm;
15951
15952       /* Save away the current list, in case we are instantiating one
15953          template from within the body of another.  */
15954       saved_local_specializations = local_specializations;
15955
15956       /* Set up the list of local specializations.  */
15957       local_specializations = htab_create (37,
15958                                            hash_local_specialization,
15959                                            eq_local_specializations,
15960                                            NULL);
15961
15962       /* Set up context.  */
15963       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15964
15965       /* Create substitution entries for the parameters.  */
15966       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15967       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15968       spec_parm = DECL_ARGUMENTS (d);
15969       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15970         {
15971           register_local_specialization (spec_parm, tmpl_parm);
15972           spec_parm = skip_artificial_parms_for (d, spec_parm);
15973           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15974         }
15975       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15976         {
15977           register_local_specialization (spec_parm, tmpl_parm);
15978           tmpl_parm = TREE_CHAIN (tmpl_parm);
15979           spec_parm = TREE_CHAIN (spec_parm);
15980         }
15981       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15982         {
15983           /* Register the (value) argument pack as a specialization of
15984              TMPL_PARM, then move on.  */
15985           tree argpack = make_fnparm_pack (spec_parm);
15986           register_local_specialization (argpack, tmpl_parm);
15987           tmpl_parm = TREE_CHAIN (tmpl_parm);
15988           spec_parm = NULL_TREE;
15989         }
15990       gcc_assert (!spec_parm);
15991
15992       /* Substitute into the body of the function.  */
15993       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15994                    tf_warning_or_error, tmpl,
15995                    /*integral_constant_expression_p=*/false);
15996
15997       /* Set the current input_location to the end of the function
15998          so that finish_function knows where we are.  */
15999       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16000
16001       /* We don't need the local specializations any more.  */
16002       htab_delete (local_specializations);
16003       local_specializations = saved_local_specializations;
16004
16005       /* Finish the function.  */
16006       d = finish_function (0);
16007       expand_or_defer_fn (d);
16008     }
16009
16010   /* We're not deferring instantiation any more.  */
16011   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16012
16013   if (need_push)
16014     pop_from_top_level ();
16015
16016 out:
16017   input_location = saved_loc;
16018   pop_deferring_access_checks ();
16019   pop_tinst_level ();
16020
16021   timevar_pop (TV_PARSE);
16022
16023   return d;
16024 }
16025
16026 /* Run through the list of templates that we wish we could
16027    instantiate, and instantiate any we can.  RETRIES is the
16028    number of times we retry pending template instantiation.  */
16029
16030 void
16031 instantiate_pending_templates (int retries)
16032 {
16033   int reconsider;
16034   location_t saved_loc = input_location;
16035
16036   /* Instantiating templates may trigger vtable generation.  This in turn
16037      may require further template instantiations.  We place a limit here
16038      to avoid infinite loop.  */
16039   if (pending_templates && retries >= max_tinst_depth)
16040     {
16041       tree decl = pending_templates->tinst->decl;
16042
16043       error ("template instantiation depth exceeds maximum of %d"
16044              " instantiating %q+D, possibly from virtual table generation"
16045              " (use -ftemplate-depth-NN to increase the maximum)",
16046              max_tinst_depth, decl);
16047       if (TREE_CODE (decl) == FUNCTION_DECL)
16048         /* Pretend that we defined it.  */
16049         DECL_INITIAL (decl) = error_mark_node;
16050       return;
16051     }
16052
16053   do
16054     {
16055       struct pending_template **t = &pending_templates;
16056       struct pending_template *last = NULL;
16057       reconsider = 0;
16058       while (*t)
16059         {
16060           tree instantiation = reopen_tinst_level ((*t)->tinst);
16061           bool complete = false;
16062
16063           if (TYPE_P (instantiation))
16064             {
16065               tree fn;
16066
16067               if (!COMPLETE_TYPE_P (instantiation))
16068                 {
16069                   instantiate_class_template (instantiation);
16070                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16071                     for (fn = TYPE_METHODS (instantiation);
16072                          fn;
16073                          fn = TREE_CHAIN (fn))
16074                       if (! DECL_ARTIFICIAL (fn))
16075                         instantiate_decl (fn,
16076                                           /*defer_ok=*/0,
16077                                           /*expl_inst_class_mem_p=*/false);
16078                   if (COMPLETE_TYPE_P (instantiation))
16079                     reconsider = 1;
16080                 }
16081
16082               complete = COMPLETE_TYPE_P (instantiation);
16083             }
16084           else
16085             {
16086               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16087                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16088                 {
16089                   instantiation
16090                     = instantiate_decl (instantiation,
16091                                         /*defer_ok=*/0,
16092                                         /*expl_inst_class_mem_p=*/false);
16093                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16094                     reconsider = 1;
16095                 }
16096
16097               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16098                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16099             }
16100
16101           if (complete)
16102             /* If INSTANTIATION has been instantiated, then we don't
16103                need to consider it again in the future.  */
16104             *t = (*t)->next;
16105           else
16106             {
16107               last = *t;
16108               t = &(*t)->next;
16109             }
16110           tinst_depth = 0;
16111           current_tinst_level = NULL;
16112         }
16113       last_pending_template = last;
16114     }
16115   while (reconsider);
16116
16117   input_location = saved_loc;
16118 }
16119
16120 /* Substitute ARGVEC into T, which is a list of initializers for
16121    either base class or a non-static data member.  The TREE_PURPOSEs
16122    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16123    instantiate_decl.  */
16124
16125 static tree
16126 tsubst_initializer_list (tree t, tree argvec)
16127 {
16128   tree inits = NULL_TREE;
16129
16130   for (; t; t = TREE_CHAIN (t))
16131     {
16132       tree decl;
16133       tree init;
16134       tree expanded_bases = NULL_TREE;
16135       tree expanded_arguments = NULL_TREE;
16136       int i, len = 1;
16137
16138       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16139         {
16140           tree expr;
16141           tree arg;
16142
16143           /* Expand the base class expansion type into separate base
16144              classes.  */
16145           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16146                                                  tf_warning_or_error,
16147                                                  NULL_TREE);
16148           if (expanded_bases == error_mark_node)
16149             continue;
16150           
16151           /* We'll be building separate TREE_LISTs of arguments for
16152              each base.  */
16153           len = TREE_VEC_LENGTH (expanded_bases);
16154           expanded_arguments = make_tree_vec (len);
16155           for (i = 0; i < len; i++)
16156             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16157
16158           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16159              expand each argument in the TREE_VALUE of t.  */
16160           expr = make_node (EXPR_PACK_EXPANSION);
16161           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16162             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16163
16164           if (TREE_VALUE (t) == void_type_node)
16165             /* VOID_TYPE_NODE is used to indicate
16166                value-initialization.  */
16167             {
16168               for (i = 0; i < len; i++)
16169                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16170             }
16171           else
16172             {
16173               /* Substitute parameter packs into each argument in the
16174                  TREE_LIST.  */
16175               in_base_initializer = 1;
16176               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16177                 {
16178                   tree expanded_exprs;
16179
16180                   /* Expand the argument.  */
16181                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16182                   expanded_exprs 
16183                     = tsubst_pack_expansion (expr, argvec,
16184                                              tf_warning_or_error,
16185                                              NULL_TREE);
16186                   if (expanded_exprs == error_mark_node)
16187                     continue;
16188
16189                   /* Prepend each of the expanded expressions to the
16190                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16191                   for (i = 0; i < len; i++)
16192                     {
16193                       TREE_VEC_ELT (expanded_arguments, i) = 
16194                         tree_cons (NULL_TREE, 
16195                                    TREE_VEC_ELT (expanded_exprs, i),
16196                                    TREE_VEC_ELT (expanded_arguments, i));
16197                     }
16198                 }
16199               in_base_initializer = 0;
16200
16201               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16202                  since we built them backwards.  */
16203               for (i = 0; i < len; i++)
16204                 {
16205                   TREE_VEC_ELT (expanded_arguments, i) = 
16206                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16207                 }
16208             }
16209         }
16210
16211       for (i = 0; i < len; ++i)
16212         {
16213           if (expanded_bases)
16214             {
16215               decl = TREE_VEC_ELT (expanded_bases, i);
16216               decl = expand_member_init (decl);
16217               init = TREE_VEC_ELT (expanded_arguments, i);
16218             }
16219           else
16220             {
16221               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16222                                   tf_warning_or_error, NULL_TREE);
16223
16224               decl = expand_member_init (decl);
16225               if (decl && !DECL_P (decl))
16226                 in_base_initializer = 1;
16227
16228               init = tsubst_expr (TREE_VALUE (t), argvec, 
16229                                   tf_warning_or_error, NULL_TREE,
16230                                   /*integral_constant_expression_p=*/false);
16231               in_base_initializer = 0;
16232             }
16233
16234           if (decl)
16235             {
16236               init = build_tree_list (decl, init);
16237               TREE_CHAIN (init) = inits;
16238               inits = init;
16239             }
16240         }
16241     }
16242   return inits;
16243 }
16244
16245 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16246
16247 static void
16248 set_current_access_from_decl (tree decl)
16249 {
16250   if (TREE_PRIVATE (decl))
16251     current_access_specifier = access_private_node;
16252   else if (TREE_PROTECTED (decl))
16253     current_access_specifier = access_protected_node;
16254   else
16255     current_access_specifier = access_public_node;
16256 }
16257
16258 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16259    is the instantiation (which should have been created with
16260    start_enum) and ARGS are the template arguments to use.  */
16261
16262 static void
16263 tsubst_enum (tree tag, tree newtag, tree args)
16264 {
16265   tree e;
16266
16267   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16268     {
16269       tree value;
16270       tree decl;
16271
16272       decl = TREE_VALUE (e);
16273       /* Note that in a template enum, the TREE_VALUE is the
16274          CONST_DECL, not the corresponding INTEGER_CST.  */
16275       value = tsubst_expr (DECL_INITIAL (decl),
16276                            args, tf_warning_or_error, NULL_TREE,
16277                            /*integral_constant_expression_p=*/true);
16278
16279       /* Give this enumeration constant the correct access.  */
16280       set_current_access_from_decl (decl);
16281
16282       /* Actually build the enumerator itself.  */
16283       build_enumerator (DECL_NAME (decl), value, newtag);
16284     }
16285
16286   finish_enum (newtag);
16287   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16288     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16289 }
16290
16291 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16292    its type -- but without substituting the innermost set of template
16293    arguments.  So, innermost set of template parameters will appear in
16294    the type.  */
16295
16296 tree
16297 get_mostly_instantiated_function_type (tree decl)
16298 {
16299   tree fn_type;
16300   tree tmpl;
16301   tree targs;
16302   tree tparms;
16303   int parm_depth;
16304
16305   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16306   targs = DECL_TI_ARGS (decl);
16307   tparms = DECL_TEMPLATE_PARMS (tmpl);
16308   parm_depth = TMPL_PARMS_DEPTH (tparms);
16309
16310   /* There should be as many levels of arguments as there are levels
16311      of parameters.  */
16312   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16313
16314   fn_type = TREE_TYPE (tmpl);
16315
16316   if (parm_depth == 1)
16317     /* No substitution is necessary.  */
16318     ;
16319   else
16320     {
16321       int i, save_access_control;
16322       tree partial_args;
16323
16324       /* Replace the innermost level of the TARGS with NULL_TREEs to
16325          let tsubst know not to substitute for those parameters.  */
16326       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16327       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16328         SET_TMPL_ARGS_LEVEL (partial_args, i,
16329                              TMPL_ARGS_LEVEL (targs, i));
16330       SET_TMPL_ARGS_LEVEL (partial_args,
16331                            TMPL_ARGS_DEPTH (targs),
16332                            make_tree_vec (DECL_NTPARMS (tmpl)));
16333
16334       /* Disable access control as this function is used only during
16335          name-mangling.  */
16336       save_access_control = flag_access_control;
16337       flag_access_control = 0;
16338
16339       ++processing_template_decl;
16340       /* Now, do the (partial) substitution to figure out the
16341          appropriate function type.  */
16342       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16343       --processing_template_decl;
16344
16345       /* Substitute into the template parameters to obtain the real
16346          innermost set of parameters.  This step is important if the
16347          innermost set of template parameters contains value
16348          parameters whose types depend on outer template parameters.  */
16349       TREE_VEC_LENGTH (partial_args)--;
16350       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16351
16352       flag_access_control = save_access_control;
16353     }
16354
16355   return fn_type;
16356 }
16357
16358 /* Return truthvalue if we're processing a template different from
16359    the last one involved in diagnostics.  */
16360 int
16361 problematic_instantiation_changed (void)
16362 {
16363   return last_template_error_tick != tinst_level_tick;
16364 }
16365
16366 /* Remember current template involved in diagnostics.  */
16367 void
16368 record_last_problematic_instantiation (void)
16369 {
16370   last_template_error_tick = tinst_level_tick;
16371 }
16372
16373 struct tinst_level *
16374 current_instantiation (void)
16375 {
16376   return current_tinst_level;
16377 }
16378
16379 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16380    type. Return zero for ok, nonzero for disallowed. Issue error and
16381    warning messages under control of COMPLAIN.  */
16382
16383 static int
16384 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16385 {
16386   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16387     return 0;
16388   else if (POINTER_TYPE_P (type))
16389     return 0;
16390   else if (TYPE_PTR_TO_MEMBER_P (type))
16391     return 0;
16392   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16393     return 0;
16394   else if (TREE_CODE (type) == TYPENAME_TYPE)
16395     return 0;
16396
16397   if (complain & tf_error)
16398     error ("%q#T is not a valid type for a template constant parameter", type);
16399   return 1;
16400 }
16401
16402 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16403    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16404
16405 static bool
16406 dependent_type_p_r (tree type)
16407 {
16408   tree scope;
16409
16410   /* [temp.dep.type]
16411
16412      A type is dependent if it is:
16413
16414      -- a template parameter. Template template parameters are types
16415         for us (since TYPE_P holds true for them) so we handle
16416         them here.  */
16417   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16418       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16419     return true;
16420   /* -- a qualified-id with a nested-name-specifier which contains a
16421         class-name that names a dependent type or whose unqualified-id
16422         names a dependent type.  */
16423   if (TREE_CODE (type) == TYPENAME_TYPE)
16424     return true;
16425   /* -- a cv-qualified type where the cv-unqualified type is
16426         dependent.  */
16427   type = TYPE_MAIN_VARIANT (type);
16428   /* -- a compound type constructed from any dependent type.  */
16429   if (TYPE_PTR_TO_MEMBER_P (type))
16430     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16431             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16432                                            (type)));
16433   else if (TREE_CODE (type) == POINTER_TYPE
16434            || TREE_CODE (type) == REFERENCE_TYPE)
16435     return dependent_type_p (TREE_TYPE (type));
16436   else if (TREE_CODE (type) == FUNCTION_TYPE
16437            || TREE_CODE (type) == METHOD_TYPE)
16438     {
16439       tree arg_type;
16440
16441       if (dependent_type_p (TREE_TYPE (type)))
16442         return true;
16443       for (arg_type = TYPE_ARG_TYPES (type);
16444            arg_type;
16445            arg_type = TREE_CHAIN (arg_type))
16446         if (dependent_type_p (TREE_VALUE (arg_type)))
16447           return true;
16448       return false;
16449     }
16450   /* -- an array type constructed from any dependent type or whose
16451         size is specified by a constant expression that is
16452         value-dependent.  */
16453   if (TREE_CODE (type) == ARRAY_TYPE)
16454     {
16455       if (TYPE_DOMAIN (type)
16456           && dependent_type_p (TYPE_DOMAIN (type)))
16457         return true;
16458       return dependent_type_p (TREE_TYPE (type));
16459     }
16460   else if (TREE_CODE (type) == INTEGER_TYPE
16461            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16462     {
16463       /* If this is the TYPE_DOMAIN of an array type, consider it
16464          dependent.  We already checked for value-dependence in
16465          compute_array_index_type.  */
16466       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16467     }
16468
16469   /* -- a template-id in which either the template name is a template
16470      parameter ...  */
16471   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16472     return true;
16473   /* ... or any of the template arguments is a dependent type or
16474         an expression that is type-dependent or value-dependent.  */
16475   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16476            && (any_dependent_template_arguments_p
16477                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16478     return true;
16479
16480   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16481      argument of the `typeof' expression is not type-dependent, then
16482      it should already been have resolved.  */
16483   if (TREE_CODE (type) == TYPEOF_TYPE
16484       || TREE_CODE (type) == DECLTYPE_TYPE)
16485     return true;
16486
16487   /* A template argument pack is dependent if any of its packed
16488      arguments are.  */
16489   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16490     {
16491       tree args = ARGUMENT_PACK_ARGS (type);
16492       int i, len = TREE_VEC_LENGTH (args);
16493       for (i = 0; i < len; ++i)
16494         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16495           return true;
16496     }
16497
16498   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16499      be template parameters.  */
16500   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16501     return true;
16502
16503   /* The standard does not specifically mention types that are local
16504      to template functions or local classes, but they should be
16505      considered dependent too.  For example:
16506
16507        template <int I> void f() {
16508          enum E { a = I };
16509          S<sizeof (E)> s;
16510        }
16511
16512      The size of `E' cannot be known until the value of `I' has been
16513      determined.  Therefore, `E' must be considered dependent.  */
16514   scope = TYPE_CONTEXT (type);
16515   if (scope && TYPE_P (scope))
16516     return dependent_type_p (scope);
16517   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16518     return type_dependent_expression_p (scope);
16519
16520   /* Other types are non-dependent.  */
16521   return false;
16522 }
16523
16524 /* Returns TRUE if TYPE is dependent, in the sense of
16525    [temp.dep.type].  */
16526
16527 bool
16528 dependent_type_p (tree type)
16529 {
16530   /* If there are no template parameters in scope, then there can't be
16531      any dependent types.  */
16532   if (!processing_template_decl)
16533     {
16534       /* If we are not processing a template, then nobody should be
16535          providing us with a dependent type.  */
16536       gcc_assert (type);
16537       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16538       return false;
16539     }
16540
16541   /* If the type is NULL, we have not computed a type for the entity
16542      in question; in that case, the type is dependent.  */
16543   if (!type)
16544     return true;
16545
16546   /* Erroneous types can be considered non-dependent.  */
16547   if (type == error_mark_node)
16548     return false;
16549
16550   /* If we have not already computed the appropriate value for TYPE,
16551      do so now.  */
16552   if (!TYPE_DEPENDENT_P_VALID (type))
16553     {
16554       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16555       TYPE_DEPENDENT_P_VALID (type) = 1;
16556     }
16557
16558   return TYPE_DEPENDENT_P (type);
16559 }
16560
16561 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16562    lookup.  In other words, a dependent type that is not the current
16563    instantiation.  */
16564
16565 bool
16566 dependent_scope_p (tree scope)
16567 {
16568   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16569           && !currently_open_class (scope));
16570 }
16571
16572 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16573
16574 static bool
16575 dependent_scope_ref_p (tree expression, bool criterion (tree))
16576 {
16577   tree scope;
16578   tree name;
16579
16580   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16581
16582   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16583     return true;
16584
16585   scope = TREE_OPERAND (expression, 0);
16586   name = TREE_OPERAND (expression, 1);
16587
16588   /* [temp.dep.expr]
16589
16590      An id-expression is type-dependent if it contains a
16591      nested-name-specifier that contains a class-name that names a
16592      dependent type.  */
16593   /* The suggested resolution to Core Issue 224 implies that if the
16594      qualifying type is the current class, then we must peek
16595      inside it.  */
16596   if (DECL_P (name)
16597       && currently_open_class (scope)
16598       && !criterion (name))
16599     return false;
16600   if (dependent_type_p (scope))
16601     return true;
16602
16603   return false;
16604 }
16605
16606 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16607    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16608    expression.  */
16609
16610 bool
16611 value_dependent_expression_p (tree expression)
16612 {
16613   if (!processing_template_decl)
16614     return false;
16615
16616   /* A name declared with a dependent type.  */
16617   if (DECL_P (expression) && type_dependent_expression_p (expression))
16618     return true;
16619
16620   switch (TREE_CODE (expression))
16621     {
16622     case IDENTIFIER_NODE:
16623       /* A name that has not been looked up -- must be dependent.  */
16624       return true;
16625
16626     case TEMPLATE_PARM_INDEX:
16627       /* A non-type template parm.  */
16628       return true;
16629
16630     case CONST_DECL:
16631       /* A non-type template parm.  */
16632       if (DECL_TEMPLATE_PARM_P (expression))
16633         return true;
16634       return value_dependent_expression_p (DECL_INITIAL (expression));
16635
16636     case VAR_DECL:
16637        /* A constant with integral or enumeration type and is initialized
16638           with an expression that is value-dependent.  */
16639       if (DECL_INITIAL (expression)
16640           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16641           && value_dependent_expression_p (DECL_INITIAL (expression)))
16642         return true;
16643       return false;
16644
16645     case DYNAMIC_CAST_EXPR:
16646     case STATIC_CAST_EXPR:
16647     case CONST_CAST_EXPR:
16648     case REINTERPRET_CAST_EXPR:
16649     case CAST_EXPR:
16650       /* These expressions are value-dependent if the type to which
16651          the cast occurs is dependent or the expression being casted
16652          is value-dependent.  */
16653       {
16654         tree type = TREE_TYPE (expression);
16655
16656         if (dependent_type_p (type))
16657           return true;
16658
16659         /* A functional cast has a list of operands.  */
16660         expression = TREE_OPERAND (expression, 0);
16661         if (!expression)
16662           {
16663             /* If there are no operands, it must be an expression such
16664                as "int()". This should not happen for aggregate types
16665                because it would form non-constant expressions.  */
16666             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16667
16668             return false;
16669           }
16670
16671         if (TREE_CODE (expression) == TREE_LIST)
16672           return any_value_dependent_elements_p (expression);
16673
16674         return value_dependent_expression_p (expression);
16675       }
16676
16677     case SIZEOF_EXPR:
16678     case ALIGNOF_EXPR:
16679       /* A `sizeof' expression is value-dependent if the operand is
16680          type-dependent or is a pack expansion.  */
16681       expression = TREE_OPERAND (expression, 0);
16682       if (PACK_EXPANSION_P (expression))
16683         return true;
16684       else if (TYPE_P (expression))
16685         return dependent_type_p (expression);
16686       return type_dependent_expression_p (expression);
16687
16688     case SCOPE_REF:
16689       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16690
16691     case COMPONENT_REF:
16692       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16693               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16694
16695     case CALL_EXPR:
16696       /* A CALL_EXPR may appear in a constant expression if it is a
16697          call to a builtin function, e.g., __builtin_constant_p.  All
16698          such calls are value-dependent.  */
16699       return true;
16700
16701     case NONTYPE_ARGUMENT_PACK:
16702       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16703          is value-dependent.  */
16704       {
16705         tree values = ARGUMENT_PACK_ARGS (expression);
16706         int i, len = TREE_VEC_LENGTH (values);
16707         
16708         for (i = 0; i < len; ++i)
16709           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16710             return true;
16711         
16712         return false;
16713       }
16714
16715     case TRAIT_EXPR:
16716       {
16717         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16718         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16719                 || (type2 ? dependent_type_p (type2) : false));
16720       }
16721
16722     case MODOP_EXPR:
16723       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16724               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16725
16726     default:
16727       /* A constant expression is value-dependent if any subexpression is
16728          value-dependent.  */
16729       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16730         {
16731         case tcc_reference:
16732         case tcc_unary:
16733           return (value_dependent_expression_p
16734                   (TREE_OPERAND (expression, 0)));
16735
16736         case tcc_comparison:
16737         case tcc_binary:
16738           return ((value_dependent_expression_p
16739                    (TREE_OPERAND (expression, 0)))
16740                   || (value_dependent_expression_p
16741                       (TREE_OPERAND (expression, 1))));
16742
16743         case tcc_expression:
16744         case tcc_vl_exp:
16745           {
16746             int i;
16747             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16748               /* In some cases, some of the operands may be missing.
16749                  (For example, in the case of PREDECREMENT_EXPR, the
16750                  amount to increment by may be missing.)  That doesn't
16751                  make the expression dependent.  */
16752               if (TREE_OPERAND (expression, i)
16753                   && (value_dependent_expression_p
16754                       (TREE_OPERAND (expression, i))))
16755                 return true;
16756             return false;
16757           }
16758
16759         default:
16760           break;
16761         }
16762     }
16763
16764   /* The expression is not value-dependent.  */
16765   return false;
16766 }
16767
16768 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16769    [temp.dep.expr].  */
16770
16771 bool
16772 type_dependent_expression_p (tree expression)
16773 {
16774   if (!processing_template_decl)
16775     return false;
16776
16777   if (expression == error_mark_node)
16778     return false;
16779
16780   /* An unresolved name is always dependent.  */
16781   if (TREE_CODE (expression) == IDENTIFIER_NODE
16782       || TREE_CODE (expression) == USING_DECL)
16783     return true;
16784
16785   /* Some expression forms are never type-dependent.  */
16786   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16787       || TREE_CODE (expression) == SIZEOF_EXPR
16788       || TREE_CODE (expression) == ALIGNOF_EXPR
16789       || TREE_CODE (expression) == TRAIT_EXPR
16790       || TREE_CODE (expression) == TYPEID_EXPR
16791       || TREE_CODE (expression) == DELETE_EXPR
16792       || TREE_CODE (expression) == VEC_DELETE_EXPR
16793       || TREE_CODE (expression) == THROW_EXPR)
16794     return false;
16795
16796   /* The types of these expressions depends only on the type to which
16797      the cast occurs.  */
16798   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16799       || TREE_CODE (expression) == STATIC_CAST_EXPR
16800       || TREE_CODE (expression) == CONST_CAST_EXPR
16801       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16802       || TREE_CODE (expression) == CAST_EXPR)
16803     return dependent_type_p (TREE_TYPE (expression));
16804
16805   /* The types of these expressions depends only on the type created
16806      by the expression.  */
16807   if (TREE_CODE (expression) == NEW_EXPR
16808       || TREE_CODE (expression) == VEC_NEW_EXPR)
16809     {
16810       /* For NEW_EXPR tree nodes created inside a template, either
16811          the object type itself or a TREE_LIST may appear as the
16812          operand 1.  */
16813       tree type = TREE_OPERAND (expression, 1);
16814       if (TREE_CODE (type) == TREE_LIST)
16815         /* This is an array type.  We need to check array dimensions
16816            as well.  */
16817         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16818                || value_dependent_expression_p
16819                     (TREE_OPERAND (TREE_VALUE (type), 1));
16820       else
16821         return dependent_type_p (type);
16822     }
16823
16824   if (TREE_CODE (expression) == SCOPE_REF
16825       && dependent_scope_ref_p (expression,
16826                                 type_dependent_expression_p))
16827     return true;
16828
16829   if (TREE_CODE (expression) == FUNCTION_DECL
16830       && DECL_LANG_SPECIFIC (expression)
16831       && DECL_TEMPLATE_INFO (expression)
16832       && (any_dependent_template_arguments_p
16833           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16834     return true;
16835
16836   if (TREE_CODE (expression) == TEMPLATE_DECL
16837       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16838     return false;
16839
16840   if (TREE_CODE (expression) == STMT_EXPR)
16841     expression = stmt_expr_value_expr (expression);
16842
16843   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16844     {
16845       tree elt;
16846       unsigned i;
16847
16848       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16849         {
16850           if (type_dependent_expression_p (elt))
16851             return true;
16852         }
16853       return false;
16854     }
16855
16856   if (TREE_TYPE (expression) == unknown_type_node)
16857     {
16858       if (TREE_CODE (expression) == ADDR_EXPR)
16859         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16860       if (TREE_CODE (expression) == COMPONENT_REF
16861           || TREE_CODE (expression) == OFFSET_REF)
16862         {
16863           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16864             return true;
16865           expression = TREE_OPERAND (expression, 1);
16866           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16867             return false;
16868         }
16869       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16870       if (TREE_CODE (expression) == SCOPE_REF)
16871         return false;
16872
16873       if (TREE_CODE (expression) == BASELINK)
16874         expression = BASELINK_FUNCTIONS (expression);
16875
16876       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16877         {
16878           if (any_dependent_template_arguments_p
16879               (TREE_OPERAND (expression, 1)))
16880             return true;
16881           expression = TREE_OPERAND (expression, 0);
16882         }
16883       gcc_assert (TREE_CODE (expression) == OVERLOAD
16884                   || TREE_CODE (expression) == FUNCTION_DECL);
16885
16886       while (expression)
16887         {
16888           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16889             return true;
16890           expression = OVL_NEXT (expression);
16891         }
16892       return false;
16893     }
16894
16895   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16896
16897   return (dependent_type_p (TREE_TYPE (expression)));
16898 }
16899
16900 /* Like type_dependent_expression_p, but it also works while not processing
16901    a template definition, i.e. during substitution or mangling.  */
16902
16903 bool
16904 type_dependent_expression_p_push (tree expr)
16905 {
16906   bool b;
16907   ++processing_template_decl;
16908   b = type_dependent_expression_p (expr);
16909   --processing_template_decl;
16910   return b;
16911 }
16912
16913 /* Returns TRUE if ARGS contains a type-dependent expression.  */
16914
16915 bool
16916 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
16917 {
16918   unsigned int i;
16919   tree arg;
16920
16921   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
16922     {
16923       if (type_dependent_expression_p (arg))
16924         return true;
16925     }
16926   return false;
16927 }
16928
16929 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16930    expressions) contains any value-dependent expressions.  */
16931
16932 bool
16933 any_value_dependent_elements_p (const_tree list)
16934 {
16935   for (; list; list = TREE_CHAIN (list))
16936     if (value_dependent_expression_p (TREE_VALUE (list)))
16937       return true;
16938
16939   return false;
16940 }
16941
16942 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16943
16944 bool
16945 dependent_template_arg_p (tree arg)
16946 {
16947   if (!processing_template_decl)
16948     return false;
16949
16950   if (TREE_CODE (arg) == TEMPLATE_DECL
16951       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16952     return dependent_template_p (arg);
16953   else if (ARGUMENT_PACK_P (arg))
16954     {
16955       tree args = ARGUMENT_PACK_ARGS (arg);
16956       int i, len = TREE_VEC_LENGTH (args);
16957       for (i = 0; i < len; ++i)
16958         {
16959           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16960             return true;
16961         }
16962
16963       return false;
16964     }
16965   else if (TYPE_P (arg))
16966     return dependent_type_p (arg);
16967   else
16968     return (type_dependent_expression_p (arg)
16969             || value_dependent_expression_p (arg));
16970 }
16971
16972 /* Returns true if ARGS (a collection of template arguments) contains
16973    any types that require structural equality testing.  */
16974
16975 bool
16976 any_template_arguments_need_structural_equality_p (tree args)
16977 {
16978   int i;
16979   int j;
16980
16981   if (!args)
16982     return false;
16983   if (args == error_mark_node)
16984     return true;
16985
16986   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16987     {
16988       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16989       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16990         {
16991           tree arg = TREE_VEC_ELT (level, j);
16992           tree packed_args = NULL_TREE;
16993           int k, len = 1;
16994
16995           if (ARGUMENT_PACK_P (arg))
16996             {
16997               /* Look inside the argument pack.  */
16998               packed_args = ARGUMENT_PACK_ARGS (arg);
16999               len = TREE_VEC_LENGTH (packed_args);
17000             }
17001
17002           for (k = 0; k < len; ++k)
17003             {
17004               if (packed_args)
17005                 arg = TREE_VEC_ELT (packed_args, k);
17006
17007               if (error_operand_p (arg))
17008                 return true;
17009               else if (TREE_CODE (arg) == TEMPLATE_DECL
17010                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17011                 continue;
17012               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17013                 return true;
17014               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17015                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17016                 return true;
17017             }
17018         }
17019     }
17020
17021   return false;
17022 }
17023
17024 /* Returns true if ARGS (a collection of template arguments) contains
17025    any dependent arguments.  */
17026
17027 bool
17028 any_dependent_template_arguments_p (const_tree args)
17029 {
17030   int i;
17031   int j;
17032
17033   if (!args)
17034     return false;
17035   if (args == error_mark_node)
17036     return true;
17037
17038   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17039     {
17040       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17041       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17042         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17043           return true;
17044     }
17045
17046   return false;
17047 }
17048
17049 /* Returns TRUE if the template TMPL is dependent.  */
17050
17051 bool
17052 dependent_template_p (tree tmpl)
17053 {
17054   if (TREE_CODE (tmpl) == OVERLOAD)
17055     {
17056       while (tmpl)
17057         {
17058           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17059             return true;
17060           tmpl = OVL_CHAIN (tmpl);
17061         }
17062       return false;
17063     }
17064
17065   /* Template template parameters are dependent.  */
17066   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17067       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17068     return true;
17069   /* So are names that have not been looked up.  */
17070   if (TREE_CODE (tmpl) == SCOPE_REF
17071       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17072     return true;
17073   /* So are member templates of dependent classes.  */
17074   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17075     return dependent_type_p (DECL_CONTEXT (tmpl));
17076   return false;
17077 }
17078
17079 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17080
17081 bool
17082 dependent_template_id_p (tree tmpl, tree args)
17083 {
17084   return (dependent_template_p (tmpl)
17085           || any_dependent_template_arguments_p (args));
17086 }
17087
17088 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17089    is dependent.  */
17090
17091 bool
17092 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17093 {
17094   int i;
17095
17096   if (!processing_template_decl)
17097     return false;
17098
17099   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17100     {
17101       tree decl = TREE_VEC_ELT (declv, i);
17102       tree init = TREE_VEC_ELT (initv, i);
17103       tree cond = TREE_VEC_ELT (condv, i);
17104       tree incr = TREE_VEC_ELT (incrv, i);
17105
17106       if (type_dependent_expression_p (decl))
17107         return true;
17108
17109       if (init && type_dependent_expression_p (init))
17110         return true;
17111
17112       if (type_dependent_expression_p (cond))
17113         return true;
17114
17115       if (COMPARISON_CLASS_P (cond)
17116           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17117               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17118         return true;
17119
17120       if (TREE_CODE (incr) == MODOP_EXPR)
17121         {
17122           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17123               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17124             return true;
17125         }
17126       else if (type_dependent_expression_p (incr))
17127         return true;
17128       else if (TREE_CODE (incr) == MODIFY_EXPR)
17129         {
17130           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17131             return true;
17132           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17133             {
17134               tree t = TREE_OPERAND (incr, 1);
17135               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17136                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17137                 return true;
17138             }
17139         }
17140     }
17141
17142   return false;
17143 }
17144
17145 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17146    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17147    no such TYPE can be found.  Note that this function peers inside
17148    uninstantiated templates and therefore should be used only in
17149    extremely limited situations.  ONLY_CURRENT_P restricts this
17150    peering to the currently open classes hierarchy (which is required
17151    when comparing types).  */
17152
17153 tree
17154 resolve_typename_type (tree type, bool only_current_p)
17155 {
17156   tree scope;
17157   tree name;
17158   tree decl;
17159   int quals;
17160   tree pushed_scope;
17161   tree result;
17162
17163   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17164
17165   scope = TYPE_CONTEXT (type);
17166   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17167      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17168      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17169      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17170      identifier  of the TYPENAME_TYPE anymore.
17171      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17172      TYPENAME_TYPE instead, we avoid messing up with a possible
17173      typedef variant case.  */
17174   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17175
17176   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17177      it first before we can figure out what NAME refers to.  */
17178   if (TREE_CODE (scope) == TYPENAME_TYPE)
17179     scope = resolve_typename_type (scope, only_current_p);
17180   /* If we don't know what SCOPE refers to, then we cannot resolve the
17181      TYPENAME_TYPE.  */
17182   if (TREE_CODE (scope) == TYPENAME_TYPE)
17183     return type;
17184   /* If the SCOPE is a template type parameter, we have no way of
17185      resolving the name.  */
17186   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17187     return type;
17188   /* If the SCOPE is not the current instantiation, there's no reason
17189      to look inside it.  */
17190   if (only_current_p && !currently_open_class (scope))
17191     return type;
17192   /* If SCOPE isn't the template itself, it will not have a valid
17193      TYPE_FIELDS list.  */
17194   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17195     /* scope is either the template itself or a compatible instantiation
17196        like X<T>, so look up the name in the original template.  */
17197     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17198   else
17199     /* scope is a partial instantiation, so we can't do the lookup or we
17200        will lose the template arguments.  */
17201     return type;
17202   /* Enter the SCOPE so that name lookup will be resolved as if we
17203      were in the class definition.  In particular, SCOPE will no
17204      longer be considered a dependent type.  */
17205   pushed_scope = push_scope (scope);
17206   /* Look up the declaration.  */
17207   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17208
17209   result = NULL_TREE;
17210   
17211   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17212      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17213   if (!decl)
17214     /*nop*/;
17215   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17216            && TREE_CODE (decl) == TYPE_DECL)
17217     {
17218       result = TREE_TYPE (decl);
17219       if (result == error_mark_node)
17220         result = NULL_TREE;
17221     }
17222   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17223            && DECL_CLASS_TEMPLATE_P (decl))
17224     {
17225       tree tmpl;
17226       tree args;
17227       /* Obtain the template and the arguments.  */
17228       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17229       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17230       /* Instantiate the template.  */
17231       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17232                                       /*entering_scope=*/0,
17233                                       tf_error | tf_user);
17234       if (result == error_mark_node)
17235         result = NULL_TREE;
17236     }
17237   
17238   /* Leave the SCOPE.  */
17239   if (pushed_scope)
17240     pop_scope (pushed_scope);
17241
17242   /* If we failed to resolve it, return the original typename.  */
17243   if (!result)
17244     return type;
17245   
17246   /* If lookup found a typename type, resolve that too.  */
17247   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17248     {
17249       /* Ill-formed programs can cause infinite recursion here, so we
17250          must catch that.  */
17251       TYPENAME_IS_RESOLVING_P (type) = 1;
17252       result = resolve_typename_type (result, only_current_p);
17253       TYPENAME_IS_RESOLVING_P (type) = 0;
17254     }
17255   
17256   /* Qualify the resulting type.  */
17257   quals = cp_type_quals (type);
17258   if (quals)
17259     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17260
17261   return result;
17262 }
17263
17264 /* EXPR is an expression which is not type-dependent.  Return a proxy
17265    for EXPR that can be used to compute the types of larger
17266    expressions containing EXPR.  */
17267
17268 tree
17269 build_non_dependent_expr (tree expr)
17270 {
17271   tree inner_expr;
17272
17273   /* Preserve null pointer constants so that the type of things like
17274      "p == 0" where "p" is a pointer can be determined.  */
17275   if (null_ptr_cst_p (expr))
17276     return expr;
17277   /* Preserve OVERLOADs; the functions must be available to resolve
17278      types.  */
17279   inner_expr = expr;
17280   if (TREE_CODE (inner_expr) == STMT_EXPR)
17281     inner_expr = stmt_expr_value_expr (inner_expr);
17282   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17283     inner_expr = TREE_OPERAND (inner_expr, 0);
17284   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17285     inner_expr = TREE_OPERAND (inner_expr, 1);
17286   if (is_overloaded_fn (inner_expr)
17287       || TREE_CODE (inner_expr) == OFFSET_REF)
17288     return expr;
17289   /* There is no need to return a proxy for a variable.  */
17290   if (TREE_CODE (expr) == VAR_DECL)
17291     return expr;
17292   /* Preserve string constants; conversions from string constants to
17293      "char *" are allowed, even though normally a "const char *"
17294      cannot be used to initialize a "char *".  */
17295   if (TREE_CODE (expr) == STRING_CST)
17296     return expr;
17297   /* Preserve arithmetic constants, as an optimization -- there is no
17298      reason to create a new node.  */
17299   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17300     return expr;
17301   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17302      There is at least one place where we want to know that a
17303      particular expression is a throw-expression: when checking a ?:
17304      expression, there are special rules if the second or third
17305      argument is a throw-expression.  */
17306   if (TREE_CODE (expr) == THROW_EXPR)
17307     return expr;
17308
17309   if (TREE_CODE (expr) == COND_EXPR)
17310     return build3 (COND_EXPR,
17311                    TREE_TYPE (expr),
17312                    TREE_OPERAND (expr, 0),
17313                    (TREE_OPERAND (expr, 1)
17314                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17315                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17316                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17317   if (TREE_CODE (expr) == COMPOUND_EXPR
17318       && !COMPOUND_EXPR_OVERLOADED (expr))
17319     return build2 (COMPOUND_EXPR,
17320                    TREE_TYPE (expr),
17321                    TREE_OPERAND (expr, 0),
17322                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17323
17324   /* If the type is unknown, it can't really be non-dependent */
17325   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17326
17327   /* Otherwise, build a NON_DEPENDENT_EXPR.
17328
17329      REFERENCE_TYPEs are not stripped for expressions in templates
17330      because doing so would play havoc with mangling.  Consider, for
17331      example:
17332
17333        template <typename T> void f<T& g>() { g(); }
17334
17335      In the body of "f", the expression for "g" will have
17336      REFERENCE_TYPE, even though the standard says that it should
17337      not.  The reason is that we must preserve the syntactic form of
17338      the expression so that mangling (say) "f<g>" inside the body of
17339      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17340      stripped here.  */
17341   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17342 }
17343
17344 /* ARGS is a vector of expressions as arguments to a function call.
17345    Replace the arguments with equivalent non-dependent expressions.
17346    This modifies ARGS in place.  */
17347
17348 void
17349 make_args_non_dependent (VEC(tree,gc) *args)
17350 {
17351   unsigned int ix;
17352   tree arg;
17353
17354   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17355     {
17356       tree newarg = build_non_dependent_expr (arg);
17357       if (newarg != arg)
17358         VEC_replace (tree, args, ix, newarg);
17359     }
17360 }
17361
17362 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17363    with a level one deeper than the actual template parms.  */
17364
17365 tree
17366 make_auto (void)
17367 {
17368   tree au;
17369
17370   /* ??? Is it worth caching this for multiple autos at the same level?  */
17371   au = cxx_make_type (TEMPLATE_TYPE_PARM);
17372   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17373                                TYPE_DECL, get_identifier ("auto"), au);
17374   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17375   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17376     (0, processing_template_decl + 1, processing_template_decl + 1,
17377      TYPE_NAME (au), NULL_TREE);
17378   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17379   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17380   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17381
17382   return au;
17383 }
17384
17385 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17386
17387 static tree
17388 listify_autos (tree type, tree auto_node)
17389 {
17390   tree std_init_list = namespace_binding
17391     (get_identifier ("initializer_list"), std_node);
17392   tree argvec;
17393   tree init_auto;
17394   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17395     {    
17396       error ("deducing auto from brace-enclosed initializer list requires "
17397              "#include <initializer_list>");
17398       return error_mark_node;
17399     }
17400   argvec = make_tree_vec (1);
17401   TREE_VEC_ELT (argvec, 0) = auto_node;
17402   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
17403                                      NULL_TREE, 0, tf_warning_or_error);
17404
17405   TREE_VEC_ELT (argvec, 0) = init_auto;
17406   if (processing_template_decl)
17407     argvec = add_to_template_args (current_template_args (), argvec);
17408   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17409 }
17410
17411 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17412    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17413
17414 tree
17415 do_auto_deduction (tree type, tree init, tree auto_node)
17416 {
17417   tree parms, tparms, targs;
17418   tree args[1];
17419   int val;
17420
17421   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17422      with either a new invented type template parameter U or, if the
17423      initializer is a braced-init-list (8.5.4), with
17424      std::initializer_list<U>.  */
17425   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17426     type = listify_autos (type, auto_node);
17427
17428   parms = build_tree_list (NULL_TREE, type);
17429   args[0] = init;
17430   tparms = make_tree_vec (1);
17431   targs = make_tree_vec (1);
17432   TREE_VEC_ELT (tparms, 0)
17433     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17434   val = type_unification_real (tparms, targs, parms, args, 1, 0,
17435                                DEDUCE_CALL, LOOKUP_NORMAL);
17436   if (val > 0)
17437     {
17438       error ("unable to deduce %qT from %qE", type, init);
17439       return error_mark_node;
17440     }
17441
17442   if (processing_template_decl)
17443     targs = add_to_template_args (current_template_args (), targs);
17444   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17445 }
17446
17447 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17448    result.  */
17449
17450 tree
17451 splice_late_return_type (tree type, tree late_return_type)
17452 {
17453   tree argvec;
17454
17455   if (late_return_type == NULL_TREE)
17456     return type;
17457   argvec = make_tree_vec (1);
17458   TREE_VEC_ELT (argvec, 0) = late_return_type;
17459   if (processing_template_decl)
17460     argvec = add_to_template_args (current_template_args (), argvec);
17461   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17462 }
17463
17464 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17465
17466 bool
17467 is_auto (const_tree type)
17468 {
17469   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17470       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17471     return true;
17472   else
17473     return false;
17474 }
17475
17476 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17477    appear as a type-specifier for the declaration in question, we don't
17478    have to look through the whole type.  */
17479
17480 tree
17481 type_uses_auto (tree type)
17482 {
17483   enum tree_code code;
17484   if (is_auto (type))
17485     return type;
17486
17487   code = TREE_CODE (type);
17488
17489   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17490       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17491       || code == METHOD_TYPE || code == ARRAY_TYPE)
17492     return type_uses_auto (TREE_TYPE (type));
17493
17494   if (TYPE_PTRMEMFUNC_P (type))
17495     return type_uses_auto (TREE_TYPE (TREE_TYPE
17496                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17497
17498   return NULL_TREE;
17499 }
17500
17501 /* For a given template T, return the list of typedefs referenced
17502    in T for which access check is needed at T instantiation time.
17503    T is either  a FUNCTION_DECL or a RECORD_TYPE.
17504    Those typedefs were added to T by the function
17505    append_type_to_template_for_access_check.  */
17506
17507 tree
17508 get_types_needing_access_check (tree t)
17509 {
17510   tree ti, result = NULL_TREE;
17511
17512   if (!t || t == error_mark_node)
17513     return t;
17514
17515   if (!(ti = get_template_info (t)))
17516     return NULL_TREE;
17517
17518   if (CLASS_TYPE_P (t)
17519       || TREE_CODE (t) == FUNCTION_DECL)
17520     {
17521       if (!TI_TEMPLATE (ti))
17522         return NULL_TREE;
17523
17524       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
17525     }
17526
17527   return result;
17528 }
17529
17530 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
17531    tied to T. That list of typedefs will be access checked at
17532    T instantiation time.
17533    T is either a FUNCTION_DECL or a RECORD_TYPE.
17534    TYPE_DECL is a TYPE_DECL node representing a typedef.
17535    SCOPE is the scope through which TYPE_DECL is accessed.
17536
17537    This function is a subroutine of
17538    append_type_to_template_for_access_check.  */
17539
17540 static void
17541 append_type_to_template_for_access_check_1 (tree t,
17542                                             tree type_decl,
17543                                             tree scope)
17544 {
17545   tree ti;
17546
17547   if (!t || t == error_mark_node)
17548     return;
17549
17550   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
17551                || CLASS_TYPE_P (t))
17552               && type_decl
17553               && TREE_CODE (type_decl) == TYPE_DECL
17554               && scope);
17555
17556   if (!(ti = get_template_info (t)))
17557     return;
17558
17559   gcc_assert (TI_TEMPLATE (ti));
17560
17561   TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti) =
17562     tree_cons (type_decl, scope, TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti));
17563 }
17564
17565 /* Append TYPE_DECL to the template TEMPL.
17566    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
17567    At TEMPL instanciation time, TYPE_DECL will be checked to see
17568    if it can be accessed through SCOPE.
17569
17570    e.g. consider the following code snippet:
17571
17572      class C
17573      {
17574        typedef int myint;
17575      };
17576
17577      template<class U> struct S
17578      {
17579        C::myint mi;
17580      };
17581
17582      S<char> s;
17583
17584    At S<char> instantiation time, we need to check the access of C::myint
17585    In other words, we need to check the access of the myint typedef through
17586    the C scope. For that purpose, this function will add the myint typedef
17587    and the scope C through which its being accessed to a list of typedefs
17588    tied to the template S. That list will be walked at template instantiation
17589    time and access check performed on each typedefs it contains.
17590    Note that this particular code snippet should yield an error because
17591    myint is private to C.  */
17592
17593 void
17594 append_type_to_template_for_access_check (tree templ,
17595                                           tree type_decl,
17596                                           tree scope)
17597 {
17598   tree node;
17599
17600   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
17601
17602   /* Make sure we don't append the type to the template twice.  */
17603   for (node = get_types_needing_access_check (templ);
17604        node;
17605        node = TREE_CHAIN (node))
17606     {
17607       tree decl = TREE_PURPOSE (node);
17608       tree type_scope = TREE_VALUE (node);
17609
17610       if (decl == type_decl && type_scope == scope)
17611         return;
17612     }
17613
17614   append_type_to_template_for_access_check_1 (templ, type_decl, scope);
17615 }
17616
17617 /* Set up the hash tables for template instantiations.  */
17618
17619 void
17620 init_template_processing (void)
17621 {
17622   decl_specializations = htab_create_ggc (37,
17623                                           hash_specialization,
17624                                           eq_specializations,
17625                                           ggc_free);
17626   type_specializations = htab_create_ggc (37,
17627                                           hash_specialization,
17628                                           eq_specializations,
17629                                           ggc_free);
17630 }
17631
17632 #include "gt-cp-pt.h"