OSDN Git Service

2009-05-06 Dodji Seketeli <dodji@redhat.com>
[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 /* Contains canonical template parameter types. The vector is indexed by
86    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
87    TREE_LIST, whose TREE_VALUEs contain the canonical template
88    parameters of various types and levels.  */
89 static GTY(()) VEC(tree,gc) *canonical_template_parms;
90
91 #define UNIFY_ALLOW_NONE 0
92 #define UNIFY_ALLOW_MORE_CV_QUAL 1
93 #define UNIFY_ALLOW_LESS_CV_QUAL 2
94 #define UNIFY_ALLOW_DERIVED 4
95 #define UNIFY_ALLOW_INTEGER 8
96 #define UNIFY_ALLOW_OUTER_LEVEL 16
97 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
98 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
99
100 static void push_access_scope (tree);
101 static void pop_access_scope (tree);
102 static bool resolve_overloaded_unification (tree, tree, tree, tree,
103                                             unification_kind_t, int);
104 static int try_one_overload (tree, tree, tree, tree, tree,
105                              unification_kind_t, int, bool);
106 static int unify (tree, tree, tree, tree, int);
107 static void add_pending_template (tree);
108 static int push_tinst_level (tree);
109 static void pop_tinst_level (void);
110 static tree reopen_tinst_level (struct tinst_level *);
111 static tree tsubst_initializer_list (tree, tree);
112 static tree get_class_bindings (tree, tree, tree);
113 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
114                                    bool, bool);
115 static void tsubst_enum (tree, tree, tree);
116 static tree add_to_template_args (tree, tree);
117 static tree add_outermost_template_args (tree, tree);
118 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
119 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
120                                              tree);
121 static int  type_unification_real (tree, tree, tree, tree,
122                                    int, unification_kind_t, int);
123 static void note_template_header (int);
124 static tree convert_nontype_argument_function (tree, tree);
125 static tree convert_nontype_argument (tree, tree);
126 static tree convert_template_argument (tree, tree, tree,
127                                        tsubst_flags_t, int, tree);
128 static int for_each_template_parm (tree, tree_fn_t, void*,
129                                    struct pointer_set_t*, bool);
130 static tree expand_template_argument_pack (tree);
131 static tree build_template_parm_index (int, int, int, tree, tree);
132 static bool inline_needs_template_parms (tree);
133 static void push_inline_template_parms_recursive (tree, int);
134 static tree retrieve_local_specialization (tree);
135 static void register_local_specialization (tree, tree);
136 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
137 static int mark_template_parm (tree, void *);
138 static int template_parm_this_level_p (tree, void *);
139 static tree tsubst_friend_function (tree, tree);
140 static tree tsubst_friend_class (tree, tree);
141 static int can_complete_type_without_circularity (tree);
142 static tree get_bindings (tree, tree, tree, bool);
143 static int template_decl_level (tree);
144 static int check_cv_quals_for_unify (int, tree, tree);
145 static void template_parm_level_and_index (tree, int*, int*);
146 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
147 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
149 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
150 static void regenerate_decl_from_template (tree, tree);
151 static tree most_specialized_class (tree, tree);
152 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
153 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
154 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
155 static bool check_specialization_scope (void);
156 static tree process_partial_specialization (tree);
157 static void set_current_access_from_decl (tree);
158 static tree get_template_base (tree, tree, tree, tree);
159 static tree try_class_unification (tree, tree, tree, tree);
160 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
161                                            tree, tree);
162 static bool template_template_parm_bindings_ok_p (tree, tree);
163 static int template_args_equal (tree, tree);
164 static void tsubst_default_arguments (tree);
165 static tree for_each_template_parm_r (tree *, int *, void *);
166 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
167 static void copy_default_args_to_explicit_spec (tree);
168 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
169 static int eq_local_specializations (const void *, const void *);
170 static bool dependent_template_arg_p (tree);
171 static bool any_template_arguments_need_structural_equality_p (tree);
172 static bool dependent_type_p_r (tree);
173 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
174 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
175 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_decl (tree, tree, tsubst_flags_t);
177 static void perform_typedefs_access_check (tree tmpl, tree targs);
178
179 /* Make the current scope suitable for access checking when we are
180    processing T.  T can be FUNCTION_DECL for instantiated function
181    template, or VAR_DECL for static member variable (need by
182    instantiate_decl).  */
183
184 static void
185 push_access_scope (tree t)
186 {
187   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
188               || TREE_CODE (t) == VAR_DECL);
189
190   if (DECL_FRIEND_CONTEXT (t))
191     push_nested_class (DECL_FRIEND_CONTEXT (t));
192   else if (DECL_CLASS_SCOPE_P (t))
193     push_nested_class (DECL_CONTEXT (t));
194   else
195     push_to_top_level ();
196
197   if (TREE_CODE (t) == FUNCTION_DECL)
198     {
199       saved_access_scope = tree_cons
200         (NULL_TREE, current_function_decl, saved_access_scope);
201       current_function_decl = t;
202     }
203 }
204
205 /* Restore the scope set up by push_access_scope.  T is the node we
206    are processing.  */
207
208 static void
209 pop_access_scope (tree t)
210 {
211   if (TREE_CODE (t) == FUNCTION_DECL)
212     {
213       current_function_decl = TREE_VALUE (saved_access_scope);
214       saved_access_scope = TREE_CHAIN (saved_access_scope);
215     }
216
217   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
218     pop_nested_class ();
219   else
220     pop_from_top_level ();
221 }
222
223 /* Do any processing required when DECL (a member template
224    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
225    to DECL, unless it is a specialization, in which case the DECL
226    itself is returned.  */
227
228 tree
229 finish_member_template_decl (tree decl)
230 {
231   if (decl == error_mark_node)
232     return error_mark_node;
233
234   gcc_assert (DECL_P (decl));
235
236   if (TREE_CODE (decl) == TYPE_DECL)
237     {
238       tree type;
239
240       type = TREE_TYPE (decl);
241       if (type == error_mark_node)
242         return error_mark_node;
243       if (MAYBE_CLASS_TYPE_P (type)
244           && CLASSTYPE_TEMPLATE_INFO (type)
245           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
246         {
247           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
248           check_member_template (tmpl);
249           return tmpl;
250         }
251       return NULL_TREE;
252     }
253   else if (TREE_CODE (decl) == FIELD_DECL)
254     error ("data member %qD cannot be a member template", decl);
255   else if (DECL_TEMPLATE_INFO (decl))
256     {
257       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
258         {
259           check_member_template (DECL_TI_TEMPLATE (decl));
260           return DECL_TI_TEMPLATE (decl);
261         }
262       else
263         return decl;
264     }
265   else
266     error ("invalid member template declaration %qD", decl);
267
268   return error_mark_node;
269 }
270
271 /* Return the template info node corresponding to T, whatever T is.  */
272
273 tree
274 get_template_info (tree t)
275 {
276   tree tinfo = NULL_TREE;
277
278   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
279     tinfo = DECL_TEMPLATE_INFO (t);
280
281   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
282     t = TREE_TYPE (t);
283
284   if (TAGGED_TYPE_P (t))
285     tinfo = TYPE_TEMPLATE_INFO (t);
286
287   return tinfo;
288 }
289
290 /* Returns the template nesting level of the indicated class TYPE.
291
292    For example, in:
293      template <class T>
294      struct A
295      {
296        template <class U>
297        struct B {};
298      };
299
300    A<T>::B<U> has depth two, while A<T> has depth one.
301    Both A<T>::B<int> and A<int>::B<U> have depth one, if
302    they are instantiations, not specializations.
303
304    This function is guaranteed to return 0 if passed NULL_TREE so
305    that, for example, `template_class_depth (current_class_type)' is
306    always safe.  */
307
308 int
309 template_class_depth (tree type)
310 {
311   int depth;
312
313   for (depth = 0;
314        type && TREE_CODE (type) != NAMESPACE_DECL;
315        type = (TREE_CODE (type) == FUNCTION_DECL)
316          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
317     {
318       tree tinfo = get_template_info (type);
319
320       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
321           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
322         ++depth;
323     }
324
325   return depth;
326 }
327
328 /* Subroutine of maybe_begin_member_template_processing.
329    Returns true if processing DECL needs us to push template parms.  */
330
331 static bool
332 inline_needs_template_parms (tree decl)
333 {
334   if (! DECL_TEMPLATE_INFO (decl))
335     return false;
336
337   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
338           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
339 }
340
341 /* Subroutine of maybe_begin_member_template_processing.
342    Push the template parms in PARMS, starting from LEVELS steps into the
343    chain, and ending at the beginning, since template parms are listed
344    innermost first.  */
345
346 static void
347 push_inline_template_parms_recursive (tree parmlist, int levels)
348 {
349   tree parms = TREE_VALUE (parmlist);
350   int i;
351
352   if (levels > 1)
353     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
354
355   ++processing_template_decl;
356   current_template_parms
357     = tree_cons (size_int (processing_template_decl),
358                  parms, current_template_parms);
359   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
360
361   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
362                NULL);
363   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
364     {
365       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
366
367       if (parm == error_mark_node)
368         continue;
369
370       gcc_assert (DECL_P (parm));
371
372       switch (TREE_CODE (parm))
373         {
374         case TYPE_DECL:
375         case TEMPLATE_DECL:
376           pushdecl (parm);
377           break;
378
379         case PARM_DECL:
380           {
381             /* Make a CONST_DECL as is done in process_template_parm.
382                It is ugly that we recreate this here; the original
383                version built in process_template_parm is no longer
384                available.  */
385             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
386                                     TREE_TYPE (parm));
387             DECL_ARTIFICIAL (decl) = 1;
388             TREE_CONSTANT (decl) = 1;
389             TREE_READONLY (decl) = 1;
390             DECL_INITIAL (decl) = DECL_INITIAL (parm);
391             SET_DECL_TEMPLATE_PARM_P (decl);
392             pushdecl (decl);
393           }
394           break;
395
396         default:
397           gcc_unreachable ();
398         }
399     }
400 }
401
402 /* Restore the template parameter context for a member template or
403    a friend template defined in a class definition.  */
404
405 void
406 maybe_begin_member_template_processing (tree decl)
407 {
408   tree parms;
409   int levels = 0;
410
411   if (inline_needs_template_parms (decl))
412     {
413       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
414       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
415
416       if (DECL_TEMPLATE_SPECIALIZATION (decl))
417         {
418           --levels;
419           parms = TREE_CHAIN (parms);
420         }
421
422       push_inline_template_parms_recursive (parms, levels);
423     }
424
425   /* Remember how many levels of template parameters we pushed so that
426      we can pop them later.  */
427   VEC_safe_push (int, heap, inline_parm_levels, levels);
428 }
429
430 /* Undo the effects of maybe_begin_member_template_processing.  */
431
432 void
433 maybe_end_member_template_processing (void)
434 {
435   int i;
436   int last;
437
438   if (VEC_length (int, inline_parm_levels) == 0)
439     return;
440
441   last = VEC_pop (int, inline_parm_levels);
442   for (i = 0; i < last; ++i)
443     {
444       --processing_template_decl;
445       current_template_parms = TREE_CHAIN (current_template_parms);
446       poplevel (0, 0, 0);
447     }
448 }
449
450 /* Return a new template argument vector which contains all of ARGS,
451    but has as its innermost set of arguments the EXTRA_ARGS.  */
452
453 static tree
454 add_to_template_args (tree args, tree extra_args)
455 {
456   tree new_args;
457   int extra_depth;
458   int i;
459   int j;
460
461   extra_depth = TMPL_ARGS_DEPTH (extra_args);
462   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
463
464   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
465     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
466
467   for (j = 1; j <= extra_depth; ++j, ++i)
468     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
469
470   return new_args;
471 }
472
473 /* Like add_to_template_args, but only the outermost ARGS are added to
474    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
475    (EXTRA_ARGS) levels are added.  This function is used to combine
476    the template arguments from a partial instantiation with the
477    template arguments used to attain the full instantiation from the
478    partial instantiation.  */
479
480 static tree
481 add_outermost_template_args (tree args, tree extra_args)
482 {
483   tree new_args;
484
485   /* If there are more levels of EXTRA_ARGS than there are ARGS,
486      something very fishy is going on.  */
487   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
488
489   /* If *all* the new arguments will be the EXTRA_ARGS, just return
490      them.  */
491   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
492     return extra_args;
493
494   /* For the moment, we make ARGS look like it contains fewer levels.  */
495   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
496
497   new_args = add_to_template_args (args, extra_args);
498
499   /* Now, we restore ARGS to its full dimensions.  */
500   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
501
502   return new_args;
503 }
504
505 /* Return the N levels of innermost template arguments from the ARGS.  */
506
507 tree
508 get_innermost_template_args (tree args, int n)
509 {
510   tree new_args;
511   int extra_levels;
512   int i;
513
514   gcc_assert (n >= 0);
515
516   /* If N is 1, just return the innermost set of template arguments.  */
517   if (n == 1)
518     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
519
520   /* If we're not removing anything, just return the arguments we were
521      given.  */
522   extra_levels = TMPL_ARGS_DEPTH (args) - n;
523   gcc_assert (extra_levels >= 0);
524   if (extra_levels == 0)
525     return args;
526
527   /* Make a new set of arguments, not containing the outer arguments.  */
528   new_args = make_tree_vec (n);
529   for (i = 1; i <= n; ++i)
530     SET_TMPL_ARGS_LEVEL (new_args, i,
531                          TMPL_ARGS_LEVEL (args, i + extra_levels));
532
533   return new_args;
534 }
535
536 /* The inverse of get_innermost_template_args: Return all but the innermost
537    EXTRA_LEVELS levels of template arguments from the ARGS.  */
538
539 static tree
540 strip_innermost_template_args (tree args, int extra_levels)
541 {
542   tree new_args;
543   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
544   int i;
545
546   gcc_assert (n >= 0);
547
548   /* If N is 1, just return the outermost set of template arguments.  */
549   if (n == 1)
550     return TMPL_ARGS_LEVEL (args, 1);
551
552   /* If we're not removing anything, just return the arguments we were
553      given.  */
554   gcc_assert (extra_levels >= 0);
555   if (extra_levels == 0)
556     return args;
557
558   /* Make a new set of arguments, not containing the inner arguments.  */
559   new_args = make_tree_vec (n);
560   for (i = 1; i <= n; ++i)
561     SET_TMPL_ARGS_LEVEL (new_args, i,
562                          TMPL_ARGS_LEVEL (args, i));
563
564   return new_args;
565 }
566
567 /* We've got a template header coming up; push to a new level for storing
568    the parms.  */
569
570 void
571 begin_template_parm_list (void)
572 {
573   /* We use a non-tag-transparent scope here, which causes pushtag to
574      put tags in this scope, rather than in the enclosing class or
575      namespace scope.  This is the right thing, since we want
576      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
577      global template class, push_template_decl handles putting the
578      TEMPLATE_DECL into top-level scope.  For a nested template class,
579      e.g.:
580
581        template <class T> struct S1 {
582          template <class T> struct S2 {};
583        };
584
585      pushtag contains special code to call pushdecl_with_scope on the
586      TEMPLATE_DECL for S2.  */
587   begin_scope (sk_template_parms, NULL);
588   ++processing_template_decl;
589   ++processing_template_parmlist;
590   note_template_header (0);
591 }
592
593 /* This routine is called when a specialization is declared.  If it is
594    invalid to declare a specialization here, an error is reported and
595    false is returned, otherwise this routine will return true.  */
596
597 static bool
598 check_specialization_scope (void)
599 {
600   tree scope = current_scope ();
601
602   /* [temp.expl.spec]
603
604      An explicit specialization shall be declared in the namespace of
605      which the template is a member, or, for member templates, in the
606      namespace of which the enclosing class or enclosing class
607      template is a member.  An explicit specialization of a member
608      function, member class or static data member of a class template
609      shall be declared in the namespace of which the class template
610      is a member.  */
611   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
612     {
613       error ("explicit specialization in non-namespace scope %qD", scope);
614       return false;
615     }
616
617   /* [temp.expl.spec]
618
619      In an explicit specialization declaration for a member of a class
620      template or a member template that appears in namespace scope,
621      the member template and some of its enclosing class templates may
622      remain unspecialized, except that the declaration shall not
623      explicitly specialize a class member template if its enclosing
624      class templates are not explicitly specialized as well.  */
625   if (current_template_parms)
626     {
627       error ("enclosing class templates are not explicitly specialized");
628       return false;
629     }
630
631   return true;
632 }
633
634 /* We've just seen template <>.  */
635
636 bool
637 begin_specialization (void)
638 {
639   begin_scope (sk_template_spec, NULL);
640   note_template_header (1);
641   return check_specialization_scope ();
642 }
643
644 /* Called at then end of processing a declaration preceded by
645    template<>.  */
646
647 void
648 end_specialization (void)
649 {
650   finish_scope ();
651   reset_specialization ();
652 }
653
654 /* Any template <>'s that we have seen thus far are not referring to a
655    function specialization.  */
656
657 void
658 reset_specialization (void)
659 {
660   processing_specialization = 0;
661   template_header_count = 0;
662 }
663
664 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
665    it was of the form template <>.  */
666
667 static void
668 note_template_header (int specialization)
669 {
670   processing_specialization = specialization;
671   template_header_count++;
672 }
673
674 /* We're beginning an explicit instantiation.  */
675
676 void
677 begin_explicit_instantiation (void)
678 {
679   gcc_assert (!processing_explicit_instantiation);
680   processing_explicit_instantiation = true;
681 }
682
683
684 void
685 end_explicit_instantiation (void)
686 {
687   gcc_assert (processing_explicit_instantiation);
688   processing_explicit_instantiation = false;
689 }
690
691 /* An explicit specialization or partial specialization TMPL is being
692    declared.  Check that the namespace in which the specialization is
693    occurring is permissible.  Returns false iff it is invalid to
694    specialize TMPL in the current namespace.  */
695
696 static bool
697 check_specialization_namespace (tree tmpl)
698 {
699   tree tpl_ns = decl_namespace_context (tmpl);
700
701   /* [tmpl.expl.spec]
702
703      An explicit specialization shall be declared in the namespace of
704      which the template is a member, or, for member templates, in the
705      namespace of which the enclosing class or enclosing class
706      template is a member.  An explicit specialization of a member
707      function, member class or static data member of a class template
708      shall be declared in the namespace of which the class template is
709      a member.  */
710   if (is_associated_namespace (current_namespace, tpl_ns))
711     /* Same or super-using namespace.  */
712     return true;
713   else
714     {
715       permerror (input_location, "specialization of %qD in different namespace", tmpl);
716       permerror (input_location, "  from definition of %q+#D", tmpl);
717       return false;
718     }
719 }
720
721 /* SPEC is an explicit instantiation.  Check that it is valid to
722    perform this explicit instantiation in the current namespace.  */
723
724 static void
725 check_explicit_instantiation_namespace (tree spec)
726 {
727   tree ns;
728
729   /* DR 275: An explicit instantiation shall appear in an enclosing
730      namespace of its template.  */
731   ns = decl_namespace_context (spec);
732   if (!is_ancestor (current_namespace, ns))
733     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
734                "(which does not enclose namespace %qD)",
735                spec, current_namespace, ns);
736 }
737
738 /* The TYPE is being declared.  If it is a template type, that means it
739    is a partial specialization.  Do appropriate error-checking.  */
740
741 tree
742 maybe_process_partial_specialization (tree type)
743 {
744   tree context;
745
746   if (type == error_mark_node)
747     return error_mark_node;
748
749   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
750     {
751       error ("name of class shadows template template parameter %qD",
752              TYPE_NAME (type));
753       return error_mark_node;
754     }
755
756   context = TYPE_CONTEXT (type);
757
758   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
759     {
760       /* This is for ordinary explicit specialization and partial
761          specialization of a template class such as:
762
763            template <> class C<int>;
764
765          or:
766
767            template <class T> class C<T*>;
768
769          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
770
771       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
772           && !COMPLETE_TYPE_P (type))
773         {
774           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
775           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
776           if (processing_template_decl)
777             {
778               if (push_template_decl (TYPE_MAIN_DECL (type))
779                   == error_mark_node)
780                 return error_mark_node;
781             }
782         }
783       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
784         error ("specialization of %qT after instantiation", type);
785     }
786   else if (CLASS_TYPE_P (type)
787            && !CLASSTYPE_USE_TEMPLATE (type)
788            && CLASSTYPE_TEMPLATE_INFO (type)
789            && context && CLASS_TYPE_P (context)
790            && CLASSTYPE_TEMPLATE_INFO (context))
791     {
792       /* This is for an explicit specialization of member class
793          template according to [temp.expl.spec/18]:
794
795            template <> template <class U> class C<int>::D;
796
797          The context `C<int>' must be an implicit instantiation.
798          Otherwise this is just a member class template declared
799          earlier like:
800
801            template <> class C<int> { template <class U> class D; };
802            template <> template <class U> class C<int>::D;
803
804          In the first case, `C<int>::D' is a specialization of `C<T>::D'
805          while in the second case, `C<int>::D' is a primary template
806          and `C<T>::D' may not exist.  */
807
808       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
809           && !COMPLETE_TYPE_P (type))
810         {
811           tree t;
812
813           if (current_namespace
814               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
815             {
816               permerror (input_location, "specializing %q#T in different namespace", type);
817               permerror (input_location, "  from definition of %q+#D",
818                          CLASSTYPE_TI_TEMPLATE (type));
819             }
820
821           /* Check for invalid specialization after instantiation:
822
823                template <> template <> class C<int>::D<int>;
824                template <> template <class U> class C<int>::D;  */
825
826           for (t = DECL_TEMPLATE_INSTANTIATIONS
827                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
828                t; t = TREE_CHAIN (t))
829             if (TREE_VALUE (t) != type
830                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
831               error ("specialization %qT after instantiation %qT",
832                      type, TREE_VALUE (t));
833
834           /* Mark TYPE as a specialization.  And as a result, we only
835              have one level of template argument for the innermost
836              class template.  */
837           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
838           CLASSTYPE_TI_ARGS (type)
839             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
840         }
841     }
842   else if (processing_specialization)
843     {
844       error ("explicit specialization of non-template %qT", type);
845       return error_mark_node;
846     }
847
848   return type;
849 }
850
851 /* Returns nonzero if we can optimize the retrieval of specializations
852    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
853    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
854
855 static inline bool
856 optimize_specialization_lookup_p (tree tmpl)
857 {
858   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
859           && DECL_CLASS_SCOPE_P (tmpl)
860           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
861              parameter.  */
862           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
863           /* The optimized lookup depends on the fact that the
864              template arguments for the member function template apply
865              purely to the containing class, which is not true if the
866              containing class is an explicit or partial
867              specialization.  */
868           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
869           && !DECL_MEMBER_TEMPLATE_P (tmpl)
870           && !DECL_CONV_FN_P (tmpl)
871           /* It is possible to have a template that is not a member
872              template and is not a member of a template class:
873
874              template <typename T>
875              struct S { friend A::f(); };
876
877              Here, the friend function is a template, but the context does
878              not have template information.  The optimized lookup relies
879              on having ARGS be the template arguments for both the class
880              and the function template.  */
881           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
882 }
883
884 /* Retrieve the specialization (in the sense of [temp.spec] - a
885    specialization is either an instantiation or an explicit
886    specialization) of TMPL for the given template ARGS.  If there is
887    no such specialization, return NULL_TREE.  The ARGS are a vector of
888    arguments, or a vector of vectors of arguments, in the case of
889    templates with more than one level of parameters.
890
891    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
892    then we search for a partial specialization matching ARGS.  This
893    parameter is ignored if TMPL is not a class template.  */
894
895 static tree
896 retrieve_specialization (tree tmpl, tree args,
897                          bool class_specializations_p)
898 {
899   if (args == error_mark_node)
900     return NULL_TREE;
901
902   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
903
904   /* There should be as many levels of arguments as there are
905      levels of parameters.  */
906   gcc_assert (TMPL_ARGS_DEPTH (args)
907               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
908
909   if (optimize_specialization_lookup_p (tmpl))
910     {
911       tree class_template;
912       tree class_specialization;
913       VEC(tree,gc) *methods;
914       tree fns;
915       int idx;
916
917       /* The template arguments actually apply to the containing
918          class.  Find the class specialization with those
919          arguments.  */
920       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
921       class_specialization
922         = retrieve_specialization (class_template, args,
923                                    /*class_specializations_p=*/false);
924       if (!class_specialization)
925         return NULL_TREE;
926       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
927          for the specialization.  */
928       idx = class_method_index_for_fn (class_specialization, tmpl);
929       if (idx == -1)
930         return NULL_TREE;
931       /* Iterate through the methods with the indicated name, looking
932          for the one that has an instance of TMPL.  */
933       methods = CLASSTYPE_METHOD_VEC (class_specialization);
934       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
935         {
936           tree fn = OVL_CURRENT (fns);
937           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
938             return fn;
939         }
940       return NULL_TREE;
941     }
942   else
943     {
944       tree *sp;
945       tree *head;
946
947       /* Class templates store their instantiations on the
948          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
949          DECL_TEMPLATE_SPECIALIZATIONS list.  */
950       if (!class_specializations_p
951           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
952           && !is_typedef_decl (DECL_TEMPLATE_RESULT (tmpl))
953           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
954         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
955       else
956         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
957       head = sp;
958       /* Iterate through the list until we find a matching template.  */
959       while (*sp != NULL_TREE)
960         {
961           tree spec = *sp;
962
963           if (comp_template_args (TREE_PURPOSE (spec), args))
964             {
965               /* Use the move-to-front heuristic to speed up future
966                  searches.  */
967               if (spec != *head)
968                 {
969                   *sp = TREE_CHAIN (*sp);
970                   TREE_CHAIN (spec) = *head;
971                   *head = spec;
972                 }
973               return TREE_VALUE (spec);
974             }
975           sp = &TREE_CHAIN (spec);
976         }
977     }
978
979   return NULL_TREE;
980 }
981
982 /* Like retrieve_specialization, but for local declarations.  */
983
984 static tree
985 retrieve_local_specialization (tree tmpl)
986 {
987   tree spec;
988
989   if (local_specializations == NULL)
990     return NULL_TREE;
991
992   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
993                                      htab_hash_pointer (tmpl));
994   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
995 }
996
997 /* Returns nonzero iff DECL is a specialization of TMPL.  */
998
999 int
1000 is_specialization_of (tree decl, tree tmpl)
1001 {
1002   tree t;
1003
1004   if (TREE_CODE (decl) == FUNCTION_DECL)
1005     {
1006       for (t = decl;
1007            t != NULL_TREE;
1008            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1009         if (t == tmpl)
1010           return 1;
1011     }
1012   else
1013     {
1014       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1015
1016       for (t = TREE_TYPE (decl);
1017            t != NULL_TREE;
1018            t = CLASSTYPE_USE_TEMPLATE (t)
1019              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1020         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1021           return 1;
1022     }
1023
1024   return 0;
1025 }
1026
1027 /* Returns nonzero iff DECL is a specialization of friend declaration
1028    FRIEND_DECL according to [temp.friend].  */
1029
1030 bool
1031 is_specialization_of_friend (tree decl, tree friend_decl)
1032 {
1033   bool need_template = true;
1034   int template_depth;
1035
1036   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1037               || TREE_CODE (decl) == TYPE_DECL);
1038
1039   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1040      of a template class, we want to check if DECL is a specialization
1041      if this.  */
1042   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1043       && DECL_TEMPLATE_INFO (friend_decl)
1044       && !DECL_USE_TEMPLATE (friend_decl))
1045     {
1046       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1047       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1048       need_template = false;
1049     }
1050   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1051            && !PRIMARY_TEMPLATE_P (friend_decl))
1052     need_template = false;
1053
1054   /* There is nothing to do if this is not a template friend.  */
1055   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1056     return false;
1057
1058   if (is_specialization_of (decl, friend_decl))
1059     return true;
1060
1061   /* [temp.friend/6]
1062      A member of a class template may be declared to be a friend of a
1063      non-template class.  In this case, the corresponding member of
1064      every specialization of the class template is a friend of the
1065      class granting friendship.
1066
1067      For example, given a template friend declaration
1068
1069        template <class T> friend void A<T>::f();
1070
1071      the member function below is considered a friend
1072
1073        template <> struct A<int> {
1074          void f();
1075        };
1076
1077      For this type of template friend, TEMPLATE_DEPTH below will be
1078      nonzero.  To determine if DECL is a friend of FRIEND, we first
1079      check if the enclosing class is a specialization of another.  */
1080
1081   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1082   if (template_depth
1083       && DECL_CLASS_SCOPE_P (decl)
1084       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1085                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1086     {
1087       /* Next, we check the members themselves.  In order to handle
1088          a few tricky cases, such as when FRIEND_DECL's are
1089
1090            template <class T> friend void A<T>::g(T t);
1091            template <class T> template <T t> friend void A<T>::h();
1092
1093          and DECL's are
1094
1095            void A<int>::g(int);
1096            template <int> void A<int>::h();
1097
1098          we need to figure out ARGS, the template arguments from
1099          the context of DECL.  This is required for template substitution
1100          of `T' in the function parameter of `g' and template parameter
1101          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1102
1103       tree context = DECL_CONTEXT (decl);
1104       tree args = NULL_TREE;
1105       int current_depth = 0;
1106
1107       while (current_depth < template_depth)
1108         {
1109           if (CLASSTYPE_TEMPLATE_INFO (context))
1110             {
1111               if (current_depth == 0)
1112                 args = TYPE_TI_ARGS (context);
1113               else
1114                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1115               current_depth++;
1116             }
1117           context = TYPE_CONTEXT (context);
1118         }
1119
1120       if (TREE_CODE (decl) == FUNCTION_DECL)
1121         {
1122           bool is_template;
1123           tree friend_type;
1124           tree decl_type;
1125           tree friend_args_type;
1126           tree decl_args_type;
1127
1128           /* Make sure that both DECL and FRIEND_DECL are templates or
1129              non-templates.  */
1130           is_template = DECL_TEMPLATE_INFO (decl)
1131                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1132           if (need_template ^ is_template)
1133             return false;
1134           else if (is_template)
1135             {
1136               /* If both are templates, check template parameter list.  */
1137               tree friend_parms
1138                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1139                                          args, tf_none);
1140               if (!comp_template_parms
1141                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1142                       friend_parms))
1143                 return false;
1144
1145               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1146             }
1147           else
1148             decl_type = TREE_TYPE (decl);
1149
1150           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1151                                               tf_none, NULL_TREE);
1152           if (friend_type == error_mark_node)
1153             return false;
1154
1155           /* Check if return types match.  */
1156           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1157             return false;
1158
1159           /* Check if function parameter types match, ignoring the
1160              `this' parameter.  */
1161           friend_args_type = TYPE_ARG_TYPES (friend_type);
1162           decl_args_type = TYPE_ARG_TYPES (decl_type);
1163           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1164             friend_args_type = TREE_CHAIN (friend_args_type);
1165           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1166             decl_args_type = TREE_CHAIN (decl_args_type);
1167
1168           return compparms (decl_args_type, friend_args_type);
1169         }
1170       else
1171         {
1172           /* DECL is a TYPE_DECL */
1173           bool is_template;
1174           tree decl_type = TREE_TYPE (decl);
1175
1176           /* Make sure that both DECL and FRIEND_DECL are templates or
1177              non-templates.  */
1178           is_template
1179             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1180               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1181
1182           if (need_template ^ is_template)
1183             return false;
1184           else if (is_template)
1185             {
1186               tree friend_parms;
1187               /* If both are templates, check the name of the two
1188                  TEMPLATE_DECL's first because is_friend didn't.  */
1189               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1190                   != DECL_NAME (friend_decl))
1191                 return false;
1192
1193               /* Now check template parameter list.  */
1194               friend_parms
1195                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1196                                          args, tf_none);
1197               return comp_template_parms
1198                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1199                  friend_parms);
1200             }
1201           else
1202             return (DECL_NAME (decl)
1203                     == DECL_NAME (friend_decl));
1204         }
1205     }
1206   return false;
1207 }
1208
1209 /* Register the specialization SPEC as a specialization of TMPL with
1210    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1211    is actually just a friend declaration.  Returns SPEC, or an
1212    equivalent prior declaration, if available.  */
1213
1214 static tree
1215 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1216 {
1217   tree fn;
1218
1219   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1220
1221   if (TREE_CODE (spec) == FUNCTION_DECL
1222       && uses_template_parms (DECL_TI_ARGS (spec)))
1223     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1224        register it; we want the corresponding TEMPLATE_DECL instead.
1225        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1226        the more obvious `uses_template_parms (spec)' to avoid problems
1227        with default function arguments.  In particular, given
1228        something like this:
1229
1230           template <class T> void f(T t1, T t = T())
1231
1232        the default argument expression is not substituted for in an
1233        instantiation unless and until it is actually needed.  */
1234     return spec;
1235
1236   fn = retrieve_specialization (tmpl, args,
1237                                 /*class_specializations_p=*/false);
1238   /* We can sometimes try to re-register a specialization that we've
1239      already got.  In particular, regenerate_decl_from_template calls
1240      duplicate_decls which will update the specialization list.  But,
1241      we'll still get called again here anyhow.  It's more convenient
1242      to simply allow this than to try to prevent it.  */
1243   if (fn == spec)
1244     return spec;
1245   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1246     {
1247       if (DECL_TEMPLATE_INSTANTIATION (fn))
1248         {
1249           if (TREE_USED (fn)
1250               || DECL_EXPLICIT_INSTANTIATION (fn))
1251             {
1252               error ("specialization of %qD after instantiation",
1253                      fn);
1254               return error_mark_node;
1255             }
1256           else
1257             {
1258               tree clone;
1259               /* This situation should occur only if the first
1260                  specialization is an implicit instantiation, the
1261                  second is an explicit specialization, and the
1262                  implicit instantiation has not yet been used.  That
1263                  situation can occur if we have implicitly
1264                  instantiated a member function and then specialized
1265                  it later.
1266
1267                  We can also wind up here if a friend declaration that
1268                  looked like an instantiation turns out to be a
1269                  specialization:
1270
1271                    template <class T> void foo(T);
1272                    class S { friend void foo<>(int) };
1273                    template <> void foo(int);
1274
1275                  We transform the existing DECL in place so that any
1276                  pointers to it become pointers to the updated
1277                  declaration.
1278
1279                  If there was a definition for the template, but not
1280                  for the specialization, we want this to look as if
1281                  there were no definition, and vice versa.  */
1282               DECL_INITIAL (fn) = NULL_TREE;
1283               duplicate_decls (spec, fn, is_friend);
1284               /* The call to duplicate_decls will have applied
1285                  [temp.expl.spec]:
1286
1287                    An explicit specialization of a function template
1288                    is inline only if it is explicitly declared to be,
1289                    and independently of whether its function template
1290                    is.
1291
1292                 to the primary function; now copy the inline bits to
1293                 the various clones.  */
1294               FOR_EACH_CLONE (clone, fn)
1295                 DECL_DECLARED_INLINE_P (clone)
1296                   = DECL_DECLARED_INLINE_P (fn);
1297               check_specialization_namespace (fn);
1298
1299               return fn;
1300             }
1301         }
1302       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1303         {
1304           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1305             /* Dup decl failed, but this is a new definition. Set the
1306                line number so any errors match this new
1307                definition.  */
1308             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1309
1310           return fn;
1311         }
1312     }
1313
1314   /* A specialization must be declared in the same namespace as the
1315      template it is specializing.  */
1316   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1317       && !check_specialization_namespace (tmpl))
1318     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1319
1320   if (!optimize_specialization_lookup_p (tmpl))
1321     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1322       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1323
1324   return spec;
1325 }
1326
1327 /* Unregister the specialization SPEC as a specialization of TMPL.
1328    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1329    if the SPEC was listed as a specialization of TMPL.  */
1330
1331 bool
1332 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1333 {
1334   tree* s;
1335
1336   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1337        *s != NULL_TREE;
1338        s = &TREE_CHAIN (*s))
1339     if (TREE_VALUE (*s) == spec)
1340       {
1341         if (!new_spec)
1342           *s = TREE_CHAIN (*s);
1343         else
1344           TREE_VALUE (*s) = new_spec;
1345         return 1;
1346       }
1347
1348   return 0;
1349 }
1350
1351 /* Compare an entry in the local specializations hash table P1 (which
1352    is really a pointer to a TREE_LIST) with P2 (which is really a
1353    DECL).  */
1354
1355 static int
1356 eq_local_specializations (const void *p1, const void *p2)
1357 {
1358   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1359 }
1360
1361 /* Hash P1, an entry in the local specializations table.  */
1362
1363 static hashval_t
1364 hash_local_specialization (const void* p1)
1365 {
1366   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1367 }
1368
1369 /* Like register_specialization, but for local declarations.  We are
1370    registering SPEC, an instantiation of TMPL.  */
1371
1372 static void
1373 register_local_specialization (tree spec, tree tmpl)
1374 {
1375   void **slot;
1376
1377   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1378                                    htab_hash_pointer (tmpl), INSERT);
1379   *slot = build_tree_list (spec, tmpl);
1380 }
1381
1382 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1383    specialized class.  */
1384
1385 bool
1386 explicit_class_specialization_p (tree type)
1387 {
1388   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1389     return false;
1390   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1391 }
1392
1393 /* Print the list of candidate FNS in an error message.  */
1394
1395 void
1396 print_candidates (tree fns)
1397 {
1398   tree fn;
1399
1400   const char *str = "candidates are:";
1401
1402   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1403     {
1404       tree f;
1405
1406       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1407         error ("%s %+#D", str, OVL_CURRENT (f));
1408       str = "               ";
1409     }
1410 }
1411
1412 /* Returns the template (one of the functions given by TEMPLATE_ID)
1413    which can be specialized to match the indicated DECL with the
1414    explicit template args given in TEMPLATE_ID.  The DECL may be
1415    NULL_TREE if none is available.  In that case, the functions in
1416    TEMPLATE_ID are non-members.
1417
1418    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1419    specialization of a member template.
1420
1421    The TEMPLATE_COUNT is the number of references to qualifying
1422    template classes that appeared in the name of the function. See
1423    check_explicit_specialization for a more accurate description.
1424
1425    TSK indicates what kind of template declaration (if any) is being
1426    declared.  TSK_TEMPLATE indicates that the declaration given by
1427    DECL, though a FUNCTION_DECL, has template parameters, and is
1428    therefore a template function.
1429
1430    The template args (those explicitly specified and those deduced)
1431    are output in a newly created vector *TARGS_OUT.
1432
1433    If it is impossible to determine the result, an error message is
1434    issued.  The error_mark_node is returned to indicate failure.  */
1435
1436 static tree
1437 determine_specialization (tree template_id,
1438                           tree decl,
1439                           tree* targs_out,
1440                           int need_member_template,
1441                           int template_count,
1442                           tmpl_spec_kind tsk)
1443 {
1444   tree fns;
1445   tree targs;
1446   tree explicit_targs;
1447   tree candidates = NULL_TREE;
1448   /* A TREE_LIST of templates of which DECL may be a specialization.
1449      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1450      corresponding TREE_PURPOSE is the set of template arguments that,
1451      when used to instantiate the template, would produce a function
1452      with the signature of DECL.  */
1453   tree templates = NULL_TREE;
1454   int header_count;
1455   struct cp_binding_level *b;
1456
1457   *targs_out = NULL_TREE;
1458
1459   if (template_id == error_mark_node || decl == error_mark_node)
1460     return error_mark_node;
1461
1462   fns = TREE_OPERAND (template_id, 0);
1463   explicit_targs = TREE_OPERAND (template_id, 1);
1464
1465   if (fns == error_mark_node)
1466     return error_mark_node;
1467
1468   /* Check for baselinks.  */
1469   if (BASELINK_P (fns))
1470     fns = BASELINK_FUNCTIONS (fns);
1471
1472   if (!is_overloaded_fn (fns))
1473     {
1474       error ("%qD is not a function template", fns);
1475       return error_mark_node;
1476     }
1477
1478   /* Count the number of template headers specified for this
1479      specialization.  */
1480   header_count = 0;
1481   for (b = current_binding_level;
1482        b->kind == sk_template_parms;
1483        b = b->level_chain)
1484     ++header_count;
1485
1486   for (; fns; fns = OVL_NEXT (fns))
1487     {
1488       tree fn = OVL_CURRENT (fns);
1489
1490       if (TREE_CODE (fn) == TEMPLATE_DECL)
1491         {
1492           tree decl_arg_types;
1493           tree fn_arg_types;
1494
1495           /* In case of explicit specialization, we need to check if
1496              the number of template headers appearing in the specialization
1497              is correct. This is usually done in check_explicit_specialization,
1498              but the check done there cannot be exhaustive when specializing
1499              member functions. Consider the following code:
1500
1501              template <> void A<int>::f(int);
1502              template <> template <> void A<int>::f(int);
1503
1504              Assuming that A<int> is not itself an explicit specialization
1505              already, the first line specializes "f" which is a non-template
1506              member function, whilst the second line specializes "f" which
1507              is a template member function. So both lines are syntactically
1508              correct, and check_explicit_specialization does not reject
1509              them.
1510
1511              Here, we can do better, as we are matching the specialization
1512              against the declarations. We count the number of template
1513              headers, and we check if they match TEMPLATE_COUNT + 1
1514              (TEMPLATE_COUNT is the number of qualifying template classes,
1515              plus there must be another header for the member template
1516              itself).
1517
1518              Notice that if header_count is zero, this is not a
1519              specialization but rather a template instantiation, so there
1520              is no check we can perform here.  */
1521           if (header_count && header_count != template_count + 1)
1522             continue;
1523
1524           /* Check that the number of template arguments at the
1525              innermost level for DECL is the same as for FN.  */
1526           if (current_binding_level->kind == sk_template_parms
1527               && !current_binding_level->explicit_spec_p
1528               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1529                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1530                                       (current_template_parms))))
1531             continue;
1532
1533           /* DECL might be a specialization of FN.  */
1534           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1535           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1536
1537           /* For a non-static member function, we need to make sure
1538              that the const qualification is the same.  Since
1539              get_bindings does not try to merge the "this" parameter,
1540              we must do the comparison explicitly.  */
1541           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1542               && !same_type_p (TREE_VALUE (fn_arg_types),
1543                                TREE_VALUE (decl_arg_types)))
1544             continue;
1545
1546           /* Skip the "this" parameter and, for constructors of
1547              classes with virtual bases, the VTT parameter.  A
1548              full specialization of a constructor will have a VTT
1549              parameter, but a template never will.  */ 
1550           decl_arg_types 
1551             = skip_artificial_parms_for (decl, decl_arg_types);
1552           fn_arg_types 
1553             = skip_artificial_parms_for (fn, fn_arg_types);
1554
1555           /* Check that the number of function parameters matches.
1556              For example,
1557                template <class T> void f(int i = 0);
1558                template <> void f<int>();
1559              The specialization f<int> is invalid but is not caught
1560              by get_bindings below.  */
1561           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1562             continue;
1563
1564           /* Function templates cannot be specializations; there are
1565              no partial specializations of functions.  Therefore, if
1566              the type of DECL does not match FN, there is no
1567              match.  */
1568           if (tsk == tsk_template)
1569             {
1570               if (compparms (fn_arg_types, decl_arg_types))
1571                 candidates = tree_cons (NULL_TREE, fn, candidates);
1572               continue;
1573             }
1574
1575           /* See whether this function might be a specialization of this
1576              template.  */
1577           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1578
1579           if (!targs)
1580             /* We cannot deduce template arguments that when used to
1581                specialize TMPL will produce DECL.  */
1582             continue;
1583
1584           /* Save this template, and the arguments deduced.  */
1585           templates = tree_cons (targs, fn, templates);
1586         }
1587       else if (need_member_template)
1588         /* FN is an ordinary member function, and we need a
1589            specialization of a member template.  */
1590         ;
1591       else if (TREE_CODE (fn) != FUNCTION_DECL)
1592         /* We can get IDENTIFIER_NODEs here in certain erroneous
1593            cases.  */
1594         ;
1595       else if (!DECL_FUNCTION_MEMBER_P (fn))
1596         /* This is just an ordinary non-member function.  Nothing can
1597            be a specialization of that.  */
1598         ;
1599       else if (DECL_ARTIFICIAL (fn))
1600         /* Cannot specialize functions that are created implicitly.  */
1601         ;
1602       else
1603         {
1604           tree decl_arg_types;
1605
1606           /* This is an ordinary member function.  However, since
1607              we're here, we can assume it's enclosing class is a
1608              template class.  For example,
1609
1610                template <typename T> struct S { void f(); };
1611                template <> void S<int>::f() {}
1612
1613              Here, S<int>::f is a non-template, but S<int> is a
1614              template class.  If FN has the same type as DECL, we
1615              might be in business.  */
1616
1617           if (!DECL_TEMPLATE_INFO (fn))
1618             /* Its enclosing class is an explicit specialization
1619                of a template class.  This is not a candidate.  */
1620             continue;
1621
1622           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1623                             TREE_TYPE (TREE_TYPE (fn))))
1624             /* The return types differ.  */
1625             continue;
1626
1627           /* Adjust the type of DECL in case FN is a static member.  */
1628           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1629           if (DECL_STATIC_FUNCTION_P (fn)
1630               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1631             decl_arg_types = TREE_CHAIN (decl_arg_types);
1632
1633           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1634                          decl_arg_types))
1635             /* They match!  */
1636             candidates = tree_cons (NULL_TREE, fn, candidates);
1637         }
1638     }
1639
1640   if (templates && TREE_CHAIN (templates))
1641     {
1642       /* We have:
1643
1644            [temp.expl.spec]
1645
1646            It is possible for a specialization with a given function
1647            signature to be instantiated from more than one function
1648            template.  In such cases, explicit specification of the
1649            template arguments must be used to uniquely identify the
1650            function template specialization being specialized.
1651
1652          Note that here, there's no suggestion that we're supposed to
1653          determine which of the candidate templates is most
1654          specialized.  However, we, also have:
1655
1656            [temp.func.order]
1657
1658            Partial ordering of overloaded function template
1659            declarations is used in the following contexts to select
1660            the function template to which a function template
1661            specialization refers:
1662
1663            -- when an explicit specialization refers to a function
1664               template.
1665
1666          So, we do use the partial ordering rules, at least for now.
1667          This extension can only serve to make invalid programs valid,
1668          so it's safe.  And, there is strong anecdotal evidence that
1669          the committee intended the partial ordering rules to apply;
1670          the EDG front end has that behavior, and John Spicer claims
1671          that the committee simply forgot to delete the wording in
1672          [temp.expl.spec].  */
1673       tree tmpl = most_specialized_instantiation (templates);
1674       if (tmpl != error_mark_node)
1675         {
1676           templates = tmpl;
1677           TREE_CHAIN (templates) = NULL_TREE;
1678         }
1679     }
1680
1681   if (templates == NULL_TREE && candidates == NULL_TREE)
1682     {
1683       error ("template-id %qD for %q+D does not match any template "
1684              "declaration", template_id, decl);
1685       return error_mark_node;
1686     }
1687   else if ((templates && TREE_CHAIN (templates))
1688            || (candidates && TREE_CHAIN (candidates))
1689            || (templates && candidates))
1690     {
1691       error ("ambiguous template specialization %qD for %q+D",
1692              template_id, decl);
1693       chainon (candidates, templates);
1694       print_candidates (candidates);
1695       return error_mark_node;
1696     }
1697
1698   /* We have one, and exactly one, match.  */
1699   if (candidates)
1700     {
1701       tree fn = TREE_VALUE (candidates);
1702       /* DECL is a re-declaration of a template function.  */
1703       if (TREE_CODE (fn) == TEMPLATE_DECL)
1704         return fn;
1705       /* It was a specialization of an ordinary member function in a
1706          template class.  */
1707       *targs_out = copy_node (DECL_TI_ARGS (fn));
1708       return DECL_TI_TEMPLATE (fn);
1709     }
1710
1711   /* It was a specialization of a template.  */
1712   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1713   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1714     {
1715       *targs_out = copy_node (targs);
1716       SET_TMPL_ARGS_LEVEL (*targs_out,
1717                            TMPL_ARGS_DEPTH (*targs_out),
1718                            TREE_PURPOSE (templates));
1719     }
1720   else
1721     *targs_out = TREE_PURPOSE (templates);
1722   return TREE_VALUE (templates);
1723 }
1724
1725 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1726    but with the default argument values filled in from those in the
1727    TMPL_TYPES.  */
1728
1729 static tree
1730 copy_default_args_to_explicit_spec_1 (tree spec_types,
1731                                       tree tmpl_types)
1732 {
1733   tree new_spec_types;
1734
1735   if (!spec_types)
1736     return NULL_TREE;
1737
1738   if (spec_types == void_list_node)
1739     return void_list_node;
1740
1741   /* Substitute into the rest of the list.  */
1742   new_spec_types =
1743     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1744                                           TREE_CHAIN (tmpl_types));
1745
1746   /* Add the default argument for this parameter.  */
1747   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1748                          TREE_VALUE (spec_types),
1749                          new_spec_types);
1750 }
1751
1752 /* DECL is an explicit specialization.  Replicate default arguments
1753    from the template it specializes.  (That way, code like:
1754
1755      template <class T> void f(T = 3);
1756      template <> void f(double);
1757      void g () { f (); }
1758
1759    works, as required.)  An alternative approach would be to look up
1760    the correct default arguments at the call-site, but this approach
1761    is consistent with how implicit instantiations are handled.  */
1762
1763 static void
1764 copy_default_args_to_explicit_spec (tree decl)
1765 {
1766   tree tmpl;
1767   tree spec_types;
1768   tree tmpl_types;
1769   tree new_spec_types;
1770   tree old_type;
1771   tree new_type;
1772   tree t;
1773   tree object_type = NULL_TREE;
1774   tree in_charge = NULL_TREE;
1775   tree vtt = NULL_TREE;
1776
1777   /* See if there's anything we need to do.  */
1778   tmpl = DECL_TI_TEMPLATE (decl);
1779   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1780   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1781     if (TREE_PURPOSE (t))
1782       break;
1783   if (!t)
1784     return;
1785
1786   old_type = TREE_TYPE (decl);
1787   spec_types = TYPE_ARG_TYPES (old_type);
1788
1789   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1790     {
1791       /* Remove the this pointer, but remember the object's type for
1792          CV quals.  */
1793       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1794       spec_types = TREE_CHAIN (spec_types);
1795       tmpl_types = TREE_CHAIN (tmpl_types);
1796
1797       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1798         {
1799           /* DECL may contain more parameters than TMPL due to the extra
1800              in-charge parameter in constructors and destructors.  */
1801           in_charge = spec_types;
1802           spec_types = TREE_CHAIN (spec_types);
1803         }
1804       if (DECL_HAS_VTT_PARM_P (decl))
1805         {
1806           vtt = spec_types;
1807           spec_types = TREE_CHAIN (spec_types);
1808         }
1809     }
1810
1811   /* Compute the merged default arguments.  */
1812   new_spec_types =
1813     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1814
1815   /* Compute the new FUNCTION_TYPE.  */
1816   if (object_type)
1817     {
1818       if (vtt)
1819         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1820                                          TREE_VALUE (vtt),
1821                                          new_spec_types);
1822
1823       if (in_charge)
1824         /* Put the in-charge parameter back.  */
1825         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1826                                          TREE_VALUE (in_charge),
1827                                          new_spec_types);
1828
1829       new_type = build_method_type_directly (object_type,
1830                                              TREE_TYPE (old_type),
1831                                              new_spec_types);
1832     }
1833   else
1834     new_type = build_function_type (TREE_TYPE (old_type),
1835                                     new_spec_types);
1836   new_type = cp_build_type_attribute_variant (new_type,
1837                                               TYPE_ATTRIBUTES (old_type));
1838   new_type = build_exception_variant (new_type,
1839                                       TYPE_RAISES_EXCEPTIONS (old_type));
1840   TREE_TYPE (decl) = new_type;
1841 }
1842
1843 /* Check to see if the function just declared, as indicated in
1844    DECLARATOR, and in DECL, is a specialization of a function
1845    template.  We may also discover that the declaration is an explicit
1846    instantiation at this point.
1847
1848    Returns DECL, or an equivalent declaration that should be used
1849    instead if all goes well.  Issues an error message if something is
1850    amiss.  Returns error_mark_node if the error is not easily
1851    recoverable.
1852
1853    FLAGS is a bitmask consisting of the following flags:
1854
1855    2: The function has a definition.
1856    4: The function is a friend.
1857
1858    The TEMPLATE_COUNT is the number of references to qualifying
1859    template classes that appeared in the name of the function.  For
1860    example, in
1861
1862      template <class T> struct S { void f(); };
1863      void S<int>::f();
1864
1865    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1866    classes are not counted in the TEMPLATE_COUNT, so that in
1867
1868      template <class T> struct S {};
1869      template <> struct S<int> { void f(); }
1870      template <> void S<int>::f();
1871
1872    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1873    invalid; there should be no template <>.)
1874
1875    If the function is a specialization, it is marked as such via
1876    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1877    is set up correctly, and it is added to the list of specializations
1878    for that template.  */
1879
1880 tree
1881 check_explicit_specialization (tree declarator,
1882                                tree decl,
1883                                int template_count,
1884                                int flags)
1885 {
1886   int have_def = flags & 2;
1887   int is_friend = flags & 4;
1888   int specialization = 0;
1889   int explicit_instantiation = 0;
1890   int member_specialization = 0;
1891   tree ctype = DECL_CLASS_CONTEXT (decl);
1892   tree dname = DECL_NAME (decl);
1893   tmpl_spec_kind tsk;
1894
1895   if (is_friend)
1896     {
1897       if (!processing_specialization)
1898         tsk = tsk_none;
1899       else
1900         tsk = tsk_excessive_parms;
1901     }
1902   else
1903     tsk = current_tmpl_spec_kind (template_count);
1904
1905   switch (tsk)
1906     {
1907     case tsk_none:
1908       if (processing_specialization)
1909         {
1910           specialization = 1;
1911           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1912         }
1913       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1914         {
1915           if (is_friend)
1916             /* This could be something like:
1917
1918                template <class T> void f(T);
1919                class S { friend void f<>(int); }  */
1920             specialization = 1;
1921           else
1922             {
1923               /* This case handles bogus declarations like template <>
1924                  template <class T> void f<int>(); */
1925
1926               error ("template-id %qD in declaration of primary template",
1927                      declarator);
1928               return decl;
1929             }
1930         }
1931       break;
1932
1933     case tsk_invalid_member_spec:
1934       /* The error has already been reported in
1935          check_specialization_scope.  */
1936       return error_mark_node;
1937
1938     case tsk_invalid_expl_inst:
1939       error ("template parameter list used in explicit instantiation");
1940
1941       /* Fall through.  */
1942
1943     case tsk_expl_inst:
1944       if (have_def)
1945         error ("definition provided for explicit instantiation");
1946
1947       explicit_instantiation = 1;
1948       break;
1949
1950     case tsk_excessive_parms:
1951     case tsk_insufficient_parms:
1952       if (tsk == tsk_excessive_parms)
1953         error ("too many template parameter lists in declaration of %qD",
1954                decl);
1955       else if (template_header_count)
1956         error("too few template parameter lists in declaration of %qD", decl);
1957       else
1958         error("explicit specialization of %qD must be introduced by "
1959               "%<template <>%>", decl);
1960
1961       /* Fall through.  */
1962     case tsk_expl_spec:
1963       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1964       if (ctype)
1965         member_specialization = 1;
1966       else
1967         specialization = 1;
1968       break;
1969
1970     case tsk_template:
1971       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1972         {
1973           /* This case handles bogus declarations like template <>
1974              template <class T> void f<int>(); */
1975
1976           if (uses_template_parms (declarator))
1977             error ("function template partial specialization %qD "
1978                    "is not allowed", declarator);
1979           else
1980             error ("template-id %qD in declaration of primary template",
1981                    declarator);
1982           return decl;
1983         }
1984
1985       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1986         /* This is a specialization of a member template, without
1987            specialization the containing class.  Something like:
1988
1989              template <class T> struct S {
1990                template <class U> void f (U);
1991              };
1992              template <> template <class U> void S<int>::f(U) {}
1993
1994            That's a specialization -- but of the entire template.  */
1995         specialization = 1;
1996       break;
1997
1998     default:
1999       gcc_unreachable ();
2000     }
2001
2002   if (specialization || member_specialization)
2003     {
2004       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2005       for (; t; t = TREE_CHAIN (t))
2006         if (TREE_PURPOSE (t))
2007           {
2008             permerror (input_location, 
2009                        "default argument specified in explicit specialization");
2010             break;
2011           }
2012     }
2013
2014   if (specialization || member_specialization || explicit_instantiation)
2015     {
2016       tree tmpl = NULL_TREE;
2017       tree targs = NULL_TREE;
2018
2019       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2020       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2021         {
2022           tree fns;
2023
2024           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2025           if (ctype)
2026             fns = dname;
2027           else
2028             {
2029               /* If there is no class context, the explicit instantiation
2030                  must be at namespace scope.  */
2031               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2032
2033               /* Find the namespace binding, using the declaration
2034                  context.  */
2035               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2036                                            false, true);
2037               if (fns == error_mark_node || !is_overloaded_fn (fns))
2038                 {
2039                   error ("%qD is not a template function", dname);
2040                   fns = error_mark_node;
2041                 }
2042               else
2043                 {
2044                   tree fn = OVL_CURRENT (fns);
2045                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2046                                                 CP_DECL_CONTEXT (fn)))
2047                     error ("%qD is not declared in %qD",
2048                            decl, current_namespace);
2049                 }
2050             }
2051
2052           declarator = lookup_template_function (fns, NULL_TREE);
2053         }
2054
2055       if (declarator == error_mark_node)
2056         return error_mark_node;
2057
2058       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2059         {
2060           if (!explicit_instantiation)
2061             /* A specialization in class scope.  This is invalid,
2062                but the error will already have been flagged by
2063                check_specialization_scope.  */
2064             return error_mark_node;
2065           else
2066             {
2067               /* It's not valid to write an explicit instantiation in
2068                  class scope, e.g.:
2069
2070                    class C { template void f(); }
2071
2072                    This case is caught by the parser.  However, on
2073                    something like:
2074
2075                    template class C { void f(); };
2076
2077                    (which is invalid) we can get here.  The error will be
2078                    issued later.  */
2079               ;
2080             }
2081
2082           return decl;
2083         }
2084       else if (ctype != NULL_TREE
2085                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2086                    IDENTIFIER_NODE))
2087         {
2088           /* Find the list of functions in ctype that have the same
2089              name as the declared function.  */
2090           tree name = TREE_OPERAND (declarator, 0);
2091           tree fns = NULL_TREE;
2092           int idx;
2093
2094           if (constructor_name_p (name, ctype))
2095             {
2096               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2097
2098               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2099                   : !CLASSTYPE_DESTRUCTORS (ctype))
2100                 {
2101                   /* From [temp.expl.spec]:
2102
2103                      If such an explicit specialization for the member
2104                      of a class template names an implicitly-declared
2105                      special member function (clause _special_), the
2106                      program is ill-formed.
2107
2108                      Similar language is found in [temp.explicit].  */
2109                   error ("specialization of implicitly-declared special member function");
2110                   return error_mark_node;
2111                 }
2112
2113               name = is_constructor ? ctor_identifier : dtor_identifier;
2114             }
2115
2116           if (!DECL_CONV_FN_P (decl))
2117             {
2118               idx = lookup_fnfields_1 (ctype, name);
2119               if (idx >= 0)
2120                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2121             }
2122           else
2123             {
2124               VEC(tree,gc) *methods;
2125               tree ovl;
2126
2127               /* For a type-conversion operator, we cannot do a
2128                  name-based lookup.  We might be looking for `operator
2129                  int' which will be a specialization of `operator T'.
2130                  So, we find *all* the conversion operators, and then
2131                  select from them.  */
2132               fns = NULL_TREE;
2133
2134               methods = CLASSTYPE_METHOD_VEC (ctype);
2135               if (methods)
2136                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2137                      VEC_iterate (tree, methods, idx, ovl);
2138                      ++idx)
2139                   {
2140                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2141                       /* There are no more conversion functions.  */
2142                       break;
2143
2144                     /* Glue all these conversion functions together
2145                        with those we already have.  */
2146                     for (; ovl; ovl = OVL_NEXT (ovl))
2147                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2148                   }
2149             }
2150
2151           if (fns == NULL_TREE)
2152             {
2153               error ("no member function %qD declared in %qT", name, ctype);
2154               return error_mark_node;
2155             }
2156           else
2157             TREE_OPERAND (declarator, 0) = fns;
2158         }
2159
2160       /* Figure out what exactly is being specialized at this point.
2161          Note that for an explicit instantiation, even one for a
2162          member function, we cannot tell apriori whether the
2163          instantiation is for a member template, or just a member
2164          function of a template class.  Even if a member template is
2165          being instantiated, the member template arguments may be
2166          elided if they can be deduced from the rest of the
2167          declaration.  */
2168       tmpl = determine_specialization (declarator, decl,
2169                                        &targs,
2170                                        member_specialization,
2171                                        template_count,
2172                                        tsk);
2173
2174       if (!tmpl || tmpl == error_mark_node)
2175         /* We couldn't figure out what this declaration was
2176            specializing.  */
2177         return error_mark_node;
2178       else
2179         {
2180           tree gen_tmpl = most_general_template (tmpl);
2181
2182           if (explicit_instantiation)
2183             {
2184               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2185                  is done by do_decl_instantiation later.  */
2186
2187               int arg_depth = TMPL_ARGS_DEPTH (targs);
2188               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2189
2190               if (arg_depth > parm_depth)
2191                 {
2192                   /* If TMPL is not the most general template (for
2193                      example, if TMPL is a friend template that is
2194                      injected into namespace scope), then there will
2195                      be too many levels of TARGS.  Remove some of them
2196                      here.  */
2197                   int i;
2198                   tree new_targs;
2199
2200                   new_targs = make_tree_vec (parm_depth);
2201                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2202                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2203                       = TREE_VEC_ELT (targs, i);
2204                   targs = new_targs;
2205                 }
2206
2207               return instantiate_template (tmpl, targs, tf_error);
2208             }
2209
2210           /* If we thought that the DECL was a member function, but it
2211              turns out to be specializing a static member function,
2212              make DECL a static member function as well.  */
2213           if (DECL_STATIC_FUNCTION_P (tmpl)
2214               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2215             revert_static_member_fn (decl);
2216
2217           /* If this is a specialization of a member template of a
2218              template class, we want to return the TEMPLATE_DECL, not
2219              the specialization of it.  */
2220           if (tsk == tsk_template)
2221             {
2222               tree result = DECL_TEMPLATE_RESULT (tmpl);
2223               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2224               DECL_INITIAL (result) = NULL_TREE;
2225               if (have_def)
2226                 {
2227                   tree parm;
2228                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2229                   DECL_SOURCE_LOCATION (result)
2230                     = DECL_SOURCE_LOCATION (decl);
2231                   /* We want to use the argument list specified in the
2232                      definition, not in the original declaration.  */
2233                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2234                   for (parm = DECL_ARGUMENTS (result); parm;
2235                        parm = TREE_CHAIN (parm))
2236                     DECL_CONTEXT (parm) = result;
2237                 }
2238               return tmpl;
2239             }
2240
2241           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2242           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2243
2244           /* Inherit default function arguments from the template
2245              DECL is specializing.  */
2246           copy_default_args_to_explicit_spec (decl);
2247
2248           /* This specialization has the same protection as the
2249              template it specializes.  */
2250           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2251           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2252
2253           /* 7.1.1-1 [dcl.stc]
2254
2255              A storage-class-specifier shall not be specified in an
2256              explicit specialization...
2257
2258              The parser rejects these, so unless action is taken here,
2259              explicit function specializations will always appear with
2260              global linkage.
2261
2262              The action recommended by the C++ CWG in response to C++
2263              defect report 605 is to make the storage class and linkage
2264              of the explicit specialization match the templated function:
2265
2266              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2267            */
2268           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2269             {
2270               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2271               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2272
2273               /* This specialization has the same linkage and visibility as
2274                  the function template it specializes.  */
2275               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2276               if (! TREE_PUBLIC (decl))
2277                 {
2278                   DECL_INTERFACE_KNOWN (decl) = 1;
2279                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2280                 }
2281               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2282               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2283                 {
2284                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2285                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2286                 }
2287             }
2288
2289           /* If DECL is a friend declaration, declared using an
2290              unqualified name, the namespace associated with DECL may
2291              have been set incorrectly.  For example, in:
2292
2293                template <typename T> void f(T);
2294                namespace N {
2295                  struct S { friend void f<int>(int); }
2296                }
2297
2298              we will have set the DECL_CONTEXT for the friend
2299              declaration to N, rather than to the global namespace.  */
2300           if (DECL_NAMESPACE_SCOPE_P (decl))
2301             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2302
2303           if (is_friend && !have_def)
2304             /* This is not really a declaration of a specialization.
2305                It's just the name of an instantiation.  But, it's not
2306                a request for an instantiation, either.  */
2307             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2308           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2309             /* This is indeed a specialization.  In case of constructors
2310                and destructors, we need in-charge and not-in-charge
2311                versions in V3 ABI.  */
2312             clone_function_decl (decl, /*update_method_vec_p=*/0);
2313
2314           /* Register this specialization so that we can find it
2315              again.  */
2316           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2317         }
2318     }
2319
2320   return decl;
2321 }
2322
2323 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2324    parameters.  These are represented in the same format used for
2325    DECL_TEMPLATE_PARMS.  */
2326
2327 int
2328 comp_template_parms (const_tree parms1, const_tree parms2)
2329 {
2330   const_tree p1;
2331   const_tree p2;
2332
2333   if (parms1 == parms2)
2334     return 1;
2335
2336   for (p1 = parms1, p2 = parms2;
2337        p1 != NULL_TREE && p2 != NULL_TREE;
2338        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2339     {
2340       tree t1 = TREE_VALUE (p1);
2341       tree t2 = TREE_VALUE (p2);
2342       int i;
2343
2344       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2345       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2346
2347       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2348         return 0;
2349
2350       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2351         {
2352           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2353           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2354
2355           /* If either of the template parameters are invalid, assume
2356              they match for the sake of error recovery. */
2357           if (parm1 == error_mark_node || parm2 == error_mark_node)
2358             return 1;
2359
2360           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2361             return 0;
2362
2363           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2364               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2365                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2366             continue;
2367           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2368             return 0;
2369         }
2370     }
2371
2372   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2373     /* One set of parameters has more parameters lists than the
2374        other.  */
2375     return 0;
2376
2377   return 1;
2378 }
2379
2380 /* Determine whether PARM is a parameter pack.  */
2381 bool 
2382 template_parameter_pack_p (const_tree parm)
2383 {
2384   /* Determine if we have a non-type template parameter pack.  */
2385   if (TREE_CODE (parm) == PARM_DECL)
2386     return (DECL_TEMPLATE_PARM_P (parm) 
2387             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2388
2389   /* If this is a list of template parameters, we could get a
2390      TYPE_DECL or a TEMPLATE_DECL.  */ 
2391   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2392     parm = TREE_TYPE (parm);
2393
2394   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2395            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2396           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2397 }
2398
2399 /* Determine whether ARGS describes a variadic template args list,
2400    i.e., one that is terminated by a template argument pack.  */
2401 static bool 
2402 template_args_variadic_p (tree args)
2403 {
2404   int nargs;
2405   tree last_parm;
2406
2407   if (args == NULL_TREE)
2408     return false;
2409
2410   args = INNERMOST_TEMPLATE_ARGS (args);
2411   nargs = TREE_VEC_LENGTH (args);
2412
2413   if (nargs == 0)
2414     return false;
2415
2416   last_parm = TREE_VEC_ELT (args, nargs - 1);
2417
2418   return ARGUMENT_PACK_P (last_parm);
2419 }
2420
2421 /* Generate a new name for the parameter pack name NAME (an
2422    IDENTIFIER_NODE) that incorporates its */
2423 static tree
2424 make_ith_pack_parameter_name (tree name, int i)
2425 {
2426   /* Munge the name to include the parameter index.  */
2427   char numbuf[128];
2428   char* newname;
2429   
2430   sprintf(numbuf, "%i", i);
2431   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2432   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2433   return get_identifier (newname);
2434 }
2435
2436 /* Structure used to track the progress of find_parameter_packs_r.  */
2437 struct find_parameter_pack_data 
2438 {
2439   /* TREE_LIST that will contain all of the parameter packs found by
2440      the traversal.  */
2441   tree* parameter_packs;
2442
2443   /* Set of AST nodes that have been visited by the traversal.  */
2444   struct pointer_set_t *visited;
2445 };
2446
2447 /* Identifies all of the argument packs that occur in a template
2448    argument and appends them to the TREE_LIST inside DATA, which is a
2449    find_parameter_pack_data structure. This is a subroutine of
2450    make_pack_expansion and uses_parameter_packs.  */
2451 static tree
2452 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2453 {
2454   tree t = *tp;
2455   struct find_parameter_pack_data* ppd = 
2456     (struct find_parameter_pack_data*)data;
2457   bool parameter_pack_p = false;
2458
2459   /* Identify whether this is a parameter pack or not.  */
2460   switch (TREE_CODE (t))
2461     {
2462     case TEMPLATE_PARM_INDEX:
2463       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2464         parameter_pack_p = true;
2465       break;
2466
2467     case TEMPLATE_TYPE_PARM:
2468     case TEMPLATE_TEMPLATE_PARM:
2469       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2470         parameter_pack_p = true;
2471       break;
2472
2473     case PARM_DECL:
2474       if (FUNCTION_PARAMETER_PACK_P (t))
2475         {
2476           /* We don't want to walk into the type of a PARM_DECL,
2477              because we don't want to see the type parameter pack.  */
2478           *walk_subtrees = 0;
2479           parameter_pack_p = true;
2480         }
2481       break;
2482
2483     default:
2484       /* Not a parameter pack.  */
2485       break;
2486     }
2487
2488   if (parameter_pack_p)
2489     {
2490       /* Add this parameter pack to the list.  */
2491       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2492     }
2493
2494   if (TYPE_P (t))
2495     cp_walk_tree (&TYPE_CONTEXT (t), 
2496                   &find_parameter_packs_r, ppd, ppd->visited);
2497
2498   /* This switch statement will return immediately if we don't find a
2499      parameter pack.  */
2500   switch (TREE_CODE (t)) 
2501     {
2502     case TEMPLATE_PARM_INDEX:
2503       return NULL_TREE;
2504
2505     case BOUND_TEMPLATE_TEMPLATE_PARM:
2506       /* Check the template itself.  */
2507       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2508                     &find_parameter_packs_r, ppd, ppd->visited);
2509       /* Check the template arguments.  */
2510       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2511                     ppd->visited);
2512       *walk_subtrees = 0;
2513       return NULL_TREE;
2514
2515     case TEMPLATE_TYPE_PARM:
2516     case TEMPLATE_TEMPLATE_PARM:
2517       return NULL_TREE;
2518
2519     case PARM_DECL:
2520       return NULL_TREE;
2521
2522     case RECORD_TYPE:
2523       if (TYPE_PTRMEMFUNC_P (t))
2524         return NULL_TREE;
2525       /* Fall through.  */
2526
2527     case UNION_TYPE:
2528     case ENUMERAL_TYPE:
2529       if (TYPE_TEMPLATE_INFO (t))
2530         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2531                       &find_parameter_packs_r, ppd, ppd->visited);
2532
2533       *walk_subtrees = 0;
2534       return NULL_TREE;
2535
2536     case TEMPLATE_DECL:
2537       cp_walk_tree (&TREE_TYPE (t),
2538                     &find_parameter_packs_r, ppd, ppd->visited);
2539       return NULL_TREE;
2540  
2541     case TYPENAME_TYPE:
2542       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2543                    ppd, ppd->visited);
2544       *walk_subtrees = 0;
2545       return NULL_TREE;
2546       
2547     case TYPE_PACK_EXPANSION:
2548     case EXPR_PACK_EXPANSION:
2549       *walk_subtrees = 0;
2550       return NULL_TREE;
2551
2552     case INTEGER_TYPE:
2553       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2554                     ppd, ppd->visited);
2555       *walk_subtrees = 0;
2556       return NULL_TREE;
2557
2558     case IDENTIFIER_NODE:
2559       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2560                     ppd->visited);
2561       *walk_subtrees = 0;
2562       return NULL_TREE;
2563
2564     default:
2565       return NULL_TREE;
2566     }
2567
2568   return NULL_TREE;
2569 }
2570
2571 /* Determines if the expression or type T uses any parameter packs.  */
2572 bool
2573 uses_parameter_packs (tree t)
2574 {
2575   tree parameter_packs = NULL_TREE;
2576   struct find_parameter_pack_data ppd;
2577   ppd.parameter_packs = &parameter_packs;
2578   ppd.visited = pointer_set_create ();
2579   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2580   pointer_set_destroy (ppd.visited);
2581   return parameter_packs != NULL_TREE;
2582 }
2583
2584 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2585    representation a base-class initializer into a parameter pack
2586    expansion. If all goes well, the resulting node will be an
2587    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2588    respectively.  */
2589 tree 
2590 make_pack_expansion (tree arg)
2591 {
2592   tree result;
2593   tree parameter_packs = NULL_TREE;
2594   bool for_types = false;
2595   struct find_parameter_pack_data ppd;
2596
2597   if (!arg || arg == error_mark_node)
2598     return arg;
2599
2600   if (TREE_CODE (arg) == TREE_LIST)
2601     {
2602       /* The only time we will see a TREE_LIST here is for a base
2603          class initializer.  In this case, the TREE_PURPOSE will be a
2604          _TYPE node (representing the base class expansion we're
2605          initializing) and the TREE_VALUE will be a TREE_LIST
2606          containing the initialization arguments. 
2607
2608          The resulting expansion looks somewhat different from most
2609          expansions. Rather than returning just one _EXPANSION, we
2610          return a TREE_LIST whose TREE_PURPOSE is a
2611          TYPE_PACK_EXPANSION containing the bases that will be
2612          initialized.  The TREE_VALUE will be identical to the
2613          original TREE_VALUE, which is a list of arguments that will
2614          be passed to each base.  We do not introduce any new pack
2615          expansion nodes into the TREE_VALUE (although it is possible
2616          that some already exist), because the TREE_PURPOSE and
2617          TREE_VALUE all need to be expanded together with the same
2618          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2619          resulting TREE_PURPOSE will mention the parameter packs in
2620          both the bases and the arguments to the bases.  */
2621       tree purpose;
2622       tree value;
2623       tree parameter_packs = NULL_TREE;
2624
2625       /* Determine which parameter packs will be used by the base
2626          class expansion.  */
2627       ppd.visited = pointer_set_create ();
2628       ppd.parameter_packs = &parameter_packs;
2629       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2630                     &ppd, ppd.visited);
2631
2632       if (parameter_packs == NULL_TREE)
2633         {
2634           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2635           pointer_set_destroy (ppd.visited);
2636           return error_mark_node;
2637         }
2638
2639       if (TREE_VALUE (arg) != void_type_node)
2640         {
2641           /* Collect the sets of parameter packs used in each of the
2642              initialization arguments.  */
2643           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2644             {
2645               /* Determine which parameter packs will be expanded in this
2646                  argument.  */
2647               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2648                             &ppd, ppd.visited);
2649             }
2650         }
2651
2652       pointer_set_destroy (ppd.visited);
2653
2654       /* Create the pack expansion type for the base type.  */
2655       purpose = make_node (TYPE_PACK_EXPANSION);
2656       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2657       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2658
2659       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2660          they will rarely be compared to anything.  */
2661       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2662
2663       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2664     }
2665
2666   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2667     for_types = true;
2668
2669   /* Build the PACK_EXPANSION_* node.  */
2670   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2671   SET_PACK_EXPANSION_PATTERN (result, arg);
2672   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2673     {
2674       /* Propagate type and const-expression information.  */
2675       TREE_TYPE (result) = TREE_TYPE (arg);
2676       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2677     }
2678   else
2679     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2680        they will rarely be compared to anything.  */
2681     SET_TYPE_STRUCTURAL_EQUALITY (result);
2682
2683   /* Determine which parameter packs will be expanded.  */
2684   ppd.parameter_packs = &parameter_packs;
2685   ppd.visited = pointer_set_create ();
2686   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2687   pointer_set_destroy (ppd.visited);
2688
2689   /* Make sure we found some parameter packs.  */
2690   if (parameter_packs == NULL_TREE)
2691     {
2692       if (TYPE_P (arg))
2693         error ("expansion pattern %<%T%> contains no argument packs", arg);
2694       else
2695         error ("expansion pattern %<%E%> contains no argument packs", arg);
2696       return error_mark_node;
2697     }
2698   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2699
2700   return result;
2701 }
2702
2703 /* Checks T for any "bare" parameter packs, which have not yet been
2704    expanded, and issues an error if any are found. This operation can
2705    only be done on full expressions or types (e.g., an expression
2706    statement, "if" condition, etc.), because we could have expressions like:
2707
2708      foo(f(g(h(args)))...)
2709
2710    where "args" is a parameter pack. check_for_bare_parameter_packs
2711    should not be called for the subexpressions args, h(args),
2712    g(h(args)), or f(g(h(args))), because we would produce erroneous
2713    error messages. 
2714
2715    Returns TRUE and emits an error if there were bare parameter packs,
2716    returns FALSE otherwise.  */
2717 bool 
2718 check_for_bare_parameter_packs (tree t)
2719 {
2720   tree parameter_packs = NULL_TREE;
2721   struct find_parameter_pack_data ppd;
2722
2723   if (!processing_template_decl || !t || t == error_mark_node)
2724     return false;
2725
2726   if (TREE_CODE (t) == TYPE_DECL)
2727     t = TREE_TYPE (t);
2728
2729   ppd.parameter_packs = &parameter_packs;
2730   ppd.visited = pointer_set_create ();
2731   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2732   pointer_set_destroy (ppd.visited);
2733
2734   if (parameter_packs) 
2735     {
2736       error ("parameter packs not expanded with %<...%>:");
2737       while (parameter_packs)
2738         {
2739           tree pack = TREE_VALUE (parameter_packs);
2740           tree name = NULL_TREE;
2741
2742           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2743               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2744             name = TYPE_NAME (pack);
2745           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2746             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2747           else
2748             name = DECL_NAME (pack);
2749
2750           if (name)
2751             inform (input_location, "        %qD", name);
2752           else
2753             inform (input_location, "        <anonymous>");
2754
2755           parameter_packs = TREE_CHAIN (parameter_packs);
2756         }
2757
2758       return true;
2759     }
2760
2761   return false;
2762 }
2763
2764 /* Expand any parameter packs that occur in the template arguments in
2765    ARGS.  */
2766 tree
2767 expand_template_argument_pack (tree args)
2768 {
2769   tree result_args = NULL_TREE;
2770   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2771   int num_result_args = -1;
2772
2773   /* First, determine if we need to expand anything, and the number of
2774      slots we'll need.  */
2775   for (in_arg = 0; in_arg < nargs; ++in_arg)
2776     {
2777       tree arg = TREE_VEC_ELT (args, in_arg);
2778       if (ARGUMENT_PACK_P (arg))
2779         {
2780           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2781           if (num_result_args < 0)
2782             num_result_args = in_arg + num_packed;
2783           else
2784             num_result_args += num_packed;
2785         }
2786       else
2787         {
2788           if (num_result_args >= 0)
2789             num_result_args++;
2790         }
2791     }
2792
2793   /* If no expansion is necessary, we're done.  */
2794   if (num_result_args < 0)
2795     return args;
2796
2797   /* Expand arguments.  */
2798   result_args = make_tree_vec (num_result_args);
2799   for (in_arg = 0; in_arg < nargs; ++in_arg)
2800     {
2801       tree arg = TREE_VEC_ELT (args, in_arg);
2802       if (ARGUMENT_PACK_P (arg))
2803         {
2804           tree packed = ARGUMENT_PACK_ARGS (arg);
2805           int i, num_packed = TREE_VEC_LENGTH (packed);
2806           for (i = 0; i < num_packed; ++i, ++out_arg)
2807             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2808         }
2809       else
2810         {
2811           TREE_VEC_ELT (result_args, out_arg) = arg;
2812           ++out_arg;
2813         }
2814     }
2815
2816   return result_args;
2817 }
2818
2819 /* Checks if DECL shadows a template parameter.
2820
2821    [temp.local]: A template-parameter shall not be redeclared within its
2822    scope (including nested scopes).
2823
2824    Emits an error and returns TRUE if the DECL shadows a parameter,
2825    returns FALSE otherwise.  */
2826
2827 bool
2828 check_template_shadow (tree decl)
2829 {
2830   tree olddecl;
2831
2832   /* If we're not in a template, we can't possibly shadow a template
2833      parameter.  */
2834   if (!current_template_parms)
2835     return true;
2836
2837   /* Figure out what we're shadowing.  */
2838   if (TREE_CODE (decl) == OVERLOAD)
2839     decl = OVL_CURRENT (decl);
2840   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2841
2842   /* If there's no previous binding for this name, we're not shadowing
2843      anything, let alone a template parameter.  */
2844   if (!olddecl)
2845     return true;
2846
2847   /* If we're not shadowing a template parameter, we're done.  Note
2848      that OLDDECL might be an OVERLOAD (or perhaps even an
2849      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2850      node.  */
2851   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2852     return true;
2853
2854   /* We check for decl != olddecl to avoid bogus errors for using a
2855      name inside a class.  We check TPFI to avoid duplicate errors for
2856      inline member templates.  */
2857   if (decl == olddecl
2858       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2859     return true;
2860
2861   error ("declaration of %q+#D", decl);
2862   error (" shadows template parm %q+#D", olddecl);
2863   return false;
2864 }
2865
2866 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2867    ORIG_LEVEL, DECL, and TYPE.  */
2868
2869 static tree
2870 build_template_parm_index (int index,
2871                            int level,
2872                            int orig_level,
2873                            tree decl,
2874                            tree type)
2875 {
2876   tree t = make_node (TEMPLATE_PARM_INDEX);
2877   TEMPLATE_PARM_IDX (t) = index;
2878   TEMPLATE_PARM_LEVEL (t) = level;
2879   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2880   TEMPLATE_PARM_DECL (t) = decl;
2881   TREE_TYPE (t) = type;
2882   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2883   TREE_READONLY (t) = TREE_READONLY (decl);
2884
2885   return t;
2886 }
2887
2888 /* Find the canonical type parameter for the given template type
2889    parameter.  Returns the canonical type parameter, which may be TYPE
2890    if no such parameter existed.  */
2891 static tree
2892 canonical_type_parameter (tree type)
2893 {
2894   tree list;
2895   int idx = TEMPLATE_TYPE_IDX (type);
2896   if (!canonical_template_parms)
2897     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2898
2899   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2900     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2901
2902   list = VEC_index (tree, canonical_template_parms, idx);
2903   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2904     list = TREE_CHAIN (list);
2905
2906   if (list)
2907     return TREE_VALUE (list);
2908   else
2909     {
2910       VEC_replace(tree, canonical_template_parms, idx,
2911                   tree_cons (NULL_TREE, type, 
2912                              VEC_index (tree, canonical_template_parms, idx)));
2913       return type;
2914     }
2915 }
2916
2917 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2918    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2919    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2920    new one is created.  */
2921
2922 static tree
2923 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2924                             tsubst_flags_t complain)
2925 {
2926   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2927       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2928           != TEMPLATE_PARM_LEVEL (index) - levels))
2929     {
2930       tree orig_decl = TEMPLATE_PARM_DECL (index);
2931       tree decl, t;
2932
2933       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2934       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2935       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2936       DECL_ARTIFICIAL (decl) = 1;
2937       SET_DECL_TEMPLATE_PARM_P (decl);
2938
2939       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2940                                      TEMPLATE_PARM_LEVEL (index) - levels,
2941                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2942                                      decl, type);
2943       TEMPLATE_PARM_DESCENDANTS (index) = t;
2944       TEMPLATE_PARM_PARAMETER_PACK (t) 
2945         = TEMPLATE_PARM_PARAMETER_PACK (index);
2946
2947         /* Template template parameters need this.  */
2948       if (TREE_CODE (decl) == TEMPLATE_DECL)
2949         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2950           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2951            args, complain);
2952     }
2953
2954   return TEMPLATE_PARM_DESCENDANTS (index);
2955 }
2956
2957 /* Process information from new template parameter PARM and append it to the
2958    LIST being built.  This new parameter is a non-type parameter iff
2959    IS_NON_TYPE is true. This new parameter is a parameter
2960    pack iff IS_PARAMETER_PACK is true.  */
2961
2962 tree
2963 process_template_parm (tree list, tree parm, bool is_non_type, 
2964                        bool is_parameter_pack)
2965 {
2966   tree decl = 0;
2967   tree defval;
2968   tree err_parm_list;
2969   int idx = 0;
2970
2971   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2972   defval = TREE_PURPOSE (parm);
2973
2974   if (list)
2975     {
2976       tree p = tree_last (list);
2977
2978       if (p && TREE_VALUE (p) != error_mark_node)
2979         {
2980           p = TREE_VALUE (p);
2981           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2982             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2983           else
2984             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2985         }
2986
2987       ++idx;
2988     }
2989   else
2990     idx = 0;
2991
2992   if (is_non_type)
2993     {
2994       parm = TREE_VALUE (parm);
2995
2996       SET_DECL_TEMPLATE_PARM_P (parm);
2997
2998       if (TREE_TYPE (parm) == error_mark_node)
2999         {
3000           err_parm_list = build_tree_list (defval, parm);
3001           TREE_VALUE (err_parm_list) = error_mark_node;
3002            return chainon (list, err_parm_list);
3003         }
3004       else
3005       {
3006         /* [temp.param]
3007
3008            The top-level cv-qualifiers on the template-parameter are
3009            ignored when determining its type.  */
3010         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3011         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3012           {
3013             err_parm_list = build_tree_list (defval, parm);
3014             TREE_VALUE (err_parm_list) = error_mark_node;
3015              return chainon (list, err_parm_list);
3016           }
3017
3018         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3019           {
3020             /* This template parameter is not a parameter pack, but it
3021                should be. Complain about "bare" parameter packs.  */
3022             check_for_bare_parameter_packs (TREE_TYPE (parm));
3023             
3024             /* Recover by calling this a parameter pack.  */
3025             is_parameter_pack = true;
3026           }
3027       }
3028
3029       /* A template parameter is not modifiable.  */
3030       TREE_CONSTANT (parm) = 1;
3031       TREE_READONLY (parm) = 1;
3032       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3033       TREE_CONSTANT (decl) = 1;
3034       TREE_READONLY (decl) = 1;
3035       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3036         = build_template_parm_index (idx, processing_template_decl,
3037                                      processing_template_decl,
3038                                      decl, TREE_TYPE (parm));
3039
3040       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3041         = is_parameter_pack;
3042     }
3043   else
3044     {
3045       tree t;
3046       parm = TREE_VALUE (TREE_VALUE (parm));
3047
3048       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3049         {
3050           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3051           /* This is for distinguishing between real templates and template
3052              template parameters */
3053           TREE_TYPE (parm) = t;
3054           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3055           decl = parm;
3056         }
3057       else
3058         {
3059           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3060           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3061           decl = build_decl (TYPE_DECL, parm, t);
3062         }
3063
3064       TYPE_NAME (t) = decl;
3065       TYPE_STUB_DECL (t) = decl;
3066       parm = decl;
3067       TEMPLATE_TYPE_PARM_INDEX (t)
3068         = build_template_parm_index (idx, processing_template_decl,
3069                                      processing_template_decl,
3070                                      decl, TREE_TYPE (parm));
3071       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3072       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3073     }
3074   DECL_ARTIFICIAL (decl) = 1;
3075   SET_DECL_TEMPLATE_PARM_P (decl);
3076   pushdecl (decl);
3077   parm = build_tree_list (defval, parm);
3078   return chainon (list, parm);
3079 }
3080
3081 /* The end of a template parameter list has been reached.  Process the
3082    tree list into a parameter vector, converting each parameter into a more
3083    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3084    as PARM_DECLs.  */
3085
3086 tree
3087 end_template_parm_list (tree parms)
3088 {
3089   int nparms;
3090   tree parm, next;
3091   tree saved_parmlist = make_tree_vec (list_length (parms));
3092
3093   current_template_parms
3094     = tree_cons (size_int (processing_template_decl),
3095                  saved_parmlist, current_template_parms);
3096
3097   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3098     {
3099       next = TREE_CHAIN (parm);
3100       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3101       TREE_CHAIN (parm) = NULL_TREE;
3102     }
3103
3104   --processing_template_parmlist;
3105
3106   return saved_parmlist;
3107 }
3108
3109 /* end_template_decl is called after a template declaration is seen.  */
3110
3111 void
3112 end_template_decl (void)
3113 {
3114   reset_specialization ();
3115
3116   if (! processing_template_decl)
3117     return;
3118
3119   /* This matches the pushlevel in begin_template_parm_list.  */
3120   finish_scope ();
3121
3122   --processing_template_decl;
3123   current_template_parms = TREE_CHAIN (current_template_parms);
3124 }
3125
3126 /* Within the declaration of a template, return all levels of template
3127    parameters that apply.  The template parameters are represented as
3128    a TREE_VEC, in the form documented in cp-tree.h for template
3129    arguments.  */
3130
3131 static tree
3132 current_template_args (void)
3133 {
3134   tree header;
3135   tree args = NULL_TREE;
3136   int length = TMPL_PARMS_DEPTH (current_template_parms);
3137   int l = length;
3138
3139   /* If there is only one level of template parameters, we do not
3140      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3141      TREE_VEC containing the arguments.  */
3142   if (length > 1)
3143     args = make_tree_vec (length);
3144
3145   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3146     {
3147       tree a = copy_node (TREE_VALUE (header));
3148       int i;
3149
3150       TREE_TYPE (a) = NULL_TREE;
3151       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3152         {
3153           tree t = TREE_VEC_ELT (a, i);
3154
3155           /* T will be a list if we are called from within a
3156              begin/end_template_parm_list pair, but a vector directly
3157              if within a begin/end_member_template_processing pair.  */
3158           if (TREE_CODE (t) == TREE_LIST)
3159             {
3160               t = TREE_VALUE (t);
3161
3162               if (!error_operand_p (t))
3163                 {
3164                   if (TREE_CODE (t) == TYPE_DECL
3165                       || TREE_CODE (t) == TEMPLATE_DECL)
3166                     {
3167                       t = TREE_TYPE (t);
3168                       
3169                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3170                         {
3171                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3172                              with a single element, which expands T.  */
3173                           tree vec = make_tree_vec (1);
3174                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3175                           
3176                           t = make_node (TYPE_ARGUMENT_PACK);
3177                           SET_ARGUMENT_PACK_ARGS (t, vec);
3178                         }
3179                     }
3180                   else
3181                     {
3182                       t = DECL_INITIAL (t);
3183                       
3184                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3185                         {
3186                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3187                              with a single element, which expands T.  */
3188                           tree vec = make_tree_vec (1);
3189                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3190                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3191                           
3192                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3193                           SET_ARGUMENT_PACK_ARGS (t, vec);
3194                           TREE_TYPE (t) = type;
3195                         }
3196                     }
3197                   TREE_VEC_ELT (a, i) = t;
3198                 }
3199             }
3200         }
3201
3202       if (length > 1)
3203         TREE_VEC_ELT (args, --l) = a;
3204       else
3205         args = a;
3206     }
3207
3208   return args;
3209 }
3210
3211 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3212    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3213    a member template.  Used by push_template_decl below.  */
3214
3215 static tree
3216 build_template_decl (tree decl, tree parms, bool member_template_p)
3217 {
3218   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3219   DECL_TEMPLATE_PARMS (tmpl) = parms;
3220   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3221   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3222   if (DECL_LANG_SPECIFIC (decl))
3223     {
3224       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3225       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3226       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3227       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3228       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3229       if (DECL_OVERLOADED_OPERATOR_P (decl))
3230         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3231                                       DECL_OVERLOADED_OPERATOR_P (decl));
3232     }
3233
3234   return tmpl;
3235 }
3236
3237 struct template_parm_data
3238 {
3239   /* The level of the template parameters we are currently
3240      processing.  */
3241   int level;
3242
3243   /* The index of the specialization argument we are currently
3244      processing.  */
3245   int current_arg;
3246
3247   /* An array whose size is the number of template parameters.  The
3248      elements are nonzero if the parameter has been used in any one
3249      of the arguments processed so far.  */
3250   int* parms;
3251
3252   /* An array whose size is the number of template arguments.  The
3253      elements are nonzero if the argument makes use of template
3254      parameters of this level.  */
3255   int* arg_uses_template_parms;
3256 };
3257
3258 /* Subroutine of push_template_decl used to see if each template
3259    parameter in a partial specialization is used in the explicit
3260    argument list.  If T is of the LEVEL given in DATA (which is
3261    treated as a template_parm_data*), then DATA->PARMS is marked
3262    appropriately.  */
3263
3264 static int
3265 mark_template_parm (tree t, void* data)
3266 {
3267   int level;
3268   int idx;
3269   struct template_parm_data* tpd = (struct template_parm_data*) data;
3270
3271   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3272     {
3273       level = TEMPLATE_PARM_LEVEL (t);
3274       idx = TEMPLATE_PARM_IDX (t);
3275     }
3276   else
3277     {
3278       level = TEMPLATE_TYPE_LEVEL (t);
3279       idx = TEMPLATE_TYPE_IDX (t);
3280     }
3281
3282   if (level == tpd->level)
3283     {
3284       tpd->parms[idx] = 1;
3285       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3286     }
3287
3288   /* Return zero so that for_each_template_parm will continue the
3289      traversal of the tree; we want to mark *every* template parm.  */
3290   return 0;
3291 }
3292
3293 /* Process the partial specialization DECL.  */
3294
3295 static tree
3296 process_partial_specialization (tree decl)
3297 {
3298   tree type = TREE_TYPE (decl);
3299   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3300   tree specargs = CLASSTYPE_TI_ARGS (type);
3301   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3302   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3303   tree inner_parms;
3304   int nargs = TREE_VEC_LENGTH (inner_args);
3305   int ntparms;
3306   int  i;
3307   int did_error_intro = 0;
3308   struct template_parm_data tpd;
3309   struct template_parm_data tpd2;
3310
3311   gcc_assert (current_template_parms);
3312
3313   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3314   ntparms = TREE_VEC_LENGTH (inner_parms);
3315
3316   /* We check that each of the template parameters given in the
3317      partial specialization is used in the argument list to the
3318      specialization.  For example:
3319
3320        template <class T> struct S;
3321        template <class T> struct S<T*>;
3322
3323      The second declaration is OK because `T*' uses the template
3324      parameter T, whereas
3325
3326        template <class T> struct S<int>;
3327
3328      is no good.  Even trickier is:
3329
3330        template <class T>
3331        struct S1
3332        {
3333           template <class U>
3334           struct S2;
3335           template <class U>
3336           struct S2<T>;
3337        };
3338
3339      The S2<T> declaration is actually invalid; it is a
3340      full-specialization.  Of course,
3341
3342           template <class U>
3343           struct S2<T (*)(U)>;
3344
3345      or some such would have been OK.  */
3346   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3347   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3348   memset (tpd.parms, 0, sizeof (int) * ntparms);
3349
3350   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3351   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3352   for (i = 0; i < nargs; ++i)
3353     {
3354       tpd.current_arg = i;
3355       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3356                               &mark_template_parm,
3357                               &tpd,
3358                               NULL,
3359                               /*include_nondeduced_p=*/false);
3360     }
3361   for (i = 0; i < ntparms; ++i)
3362     if (tpd.parms[i] == 0)
3363       {
3364         /* One of the template parms was not used in the
3365            specialization.  */
3366         if (!did_error_intro)
3367           {
3368             error ("template parameters not used in partial specialization:");
3369             did_error_intro = 1;
3370           }
3371
3372         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3373       }
3374
3375   /* [temp.class.spec]
3376
3377      The argument list of the specialization shall not be identical to
3378      the implicit argument list of the primary template.  */
3379   if (comp_template_args
3380       (inner_args,
3381        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3382                                                    (maintmpl)))))
3383     error ("partial specialization %qT does not specialize any template arguments", type);
3384
3385   /* [temp.class.spec]
3386
3387      A partially specialized non-type argument expression shall not
3388      involve template parameters of the partial specialization except
3389      when the argument expression is a simple identifier.
3390
3391      The type of a template parameter corresponding to a specialized
3392      non-type argument shall not be dependent on a parameter of the
3393      specialization. 
3394
3395      Also, we verify that pack expansions only occur at the
3396      end of the argument list.  */
3397   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3398   tpd2.parms = 0;
3399   for (i = 0; i < nargs; ++i)
3400     {
3401       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3402       tree arg = TREE_VEC_ELT (inner_args, i);
3403       tree packed_args = NULL_TREE;
3404       int j, len = 1;
3405
3406       if (ARGUMENT_PACK_P (arg))
3407         {
3408           /* Extract the arguments from the argument pack. We'll be
3409              iterating over these in the following loop.  */
3410           packed_args = ARGUMENT_PACK_ARGS (arg);
3411           len = TREE_VEC_LENGTH (packed_args);
3412         }
3413
3414       for (j = 0; j < len; j++)
3415         {
3416           if (packed_args)
3417             /* Get the Jth argument in the parameter pack.  */
3418             arg = TREE_VEC_ELT (packed_args, j);
3419
3420           if (PACK_EXPANSION_P (arg))
3421             {
3422               /* Pack expansions must come at the end of the
3423                  argument list.  */
3424               if ((packed_args && j < len - 1)
3425                   || (!packed_args && i < nargs - 1))
3426                 {
3427                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3428                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3429                   else
3430                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3431
3432                   if (packed_args)
3433                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3434                 }
3435             }
3436
3437           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3438             /* We only care about the pattern.  */
3439             arg = PACK_EXPANSION_PATTERN (arg);
3440
3441           if (/* These first two lines are the `non-type' bit.  */
3442               !TYPE_P (arg)
3443               && TREE_CODE (arg) != TEMPLATE_DECL
3444               /* This next line is the `argument expression is not just a
3445                  simple identifier' condition and also the `specialized
3446                  non-type argument' bit.  */
3447               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3448             {
3449               if ((!packed_args && tpd.arg_uses_template_parms[i])
3450                   || (packed_args && uses_template_parms (arg)))
3451                 error ("template argument %qE involves template parameter(s)",
3452                        arg);
3453               else 
3454                 {
3455                   /* Look at the corresponding template parameter,
3456                      marking which template parameters its type depends
3457                      upon.  */
3458                   tree type = TREE_TYPE (parm);
3459
3460                   if (!tpd2.parms)
3461                     {
3462                       /* We haven't yet initialized TPD2.  Do so now.  */
3463                       tpd2.arg_uses_template_parms 
3464                         = (int *) alloca (sizeof (int) * nargs);
3465                       /* The number of parameters here is the number in the
3466                          main template, which, as checked in the assertion
3467                          above, is NARGS.  */
3468                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3469                       tpd2.level = 
3470                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3471                     }
3472
3473                   /* Mark the template parameters.  But this time, we're
3474                      looking for the template parameters of the main
3475                      template, not in the specialization.  */
3476                   tpd2.current_arg = i;
3477                   tpd2.arg_uses_template_parms[i] = 0;
3478                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3479                   for_each_template_parm (type,
3480                                           &mark_template_parm,
3481                                           &tpd2,
3482                                           NULL,
3483                                           /*include_nondeduced_p=*/false);
3484
3485                   if (tpd2.arg_uses_template_parms [i])
3486                     {
3487                       /* The type depended on some template parameters.
3488                          If they are fully specialized in the
3489                          specialization, that's OK.  */
3490                       int j;
3491                       for (j = 0; j < nargs; ++j)
3492                         if (tpd2.parms[j] != 0
3493                             && tpd.arg_uses_template_parms [j])
3494                           {
3495                             error ("type %qT of template argument %qE depends "
3496                                    "on template parameter(s)", 
3497                                    type,
3498                                    arg);
3499                             break;
3500                           }
3501                     }
3502                 }
3503             }
3504         }
3505     }
3506
3507   if (retrieve_specialization (maintmpl, specargs,
3508                                /*class_specializations_p=*/true))
3509     /* We've already got this specialization.  */
3510     return decl;
3511
3512   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3513     = tree_cons (specargs, inner_parms,
3514                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3515   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3516   return decl;
3517 }
3518
3519 /* Check that a template declaration's use of default arguments and
3520    parameter packs is not invalid.  Here, PARMS are the template
3521    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3522    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3523    specialization.
3524    
3525
3526    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3527    declaration (but not a definition); 1 indicates a declaration, 2
3528    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3529    emitted for extraneous default arguments.
3530
3531    Returns TRUE if there were no errors found, FALSE otherwise. */
3532
3533 bool
3534 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3535                          int is_partial, int is_friend_decl)
3536 {
3537   const char *msg;
3538   int last_level_to_check;
3539   tree parm_level;
3540   bool no_errors = true;
3541
3542   /* [temp.param]
3543
3544      A default template-argument shall not be specified in a
3545      function template declaration or a function template definition, nor
3546      in the template-parameter-list of the definition of a member of a
3547      class template.  */
3548
3549   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3550     /* You can't have a function template declaration in a local
3551        scope, nor you can you define a member of a class template in a
3552        local scope.  */
3553     return true;
3554
3555   if (current_class_type
3556       && !TYPE_BEING_DEFINED (current_class_type)
3557       && DECL_LANG_SPECIFIC (decl)
3558       /* If this is either a friend defined in the scope of the class
3559          or a member function.  */
3560       && (DECL_FUNCTION_MEMBER_P (decl)
3561           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3562           : DECL_FRIEND_CONTEXT (decl)
3563           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3564           : false)
3565       /* And, if it was a member function, it really was defined in
3566          the scope of the class.  */
3567       && (!DECL_FUNCTION_MEMBER_P (decl)
3568           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3569     /* We already checked these parameters when the template was
3570        declared, so there's no need to do it again now.  This function
3571        was defined in class scope, but we're processing it's body now
3572        that the class is complete.  */
3573     return true;
3574
3575   /* Core issue 226 (C++0x only): the following only applies to class
3576      templates.  */
3577   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3578     {
3579       /* [temp.param]
3580
3581          If a template-parameter has a default template-argument, all
3582          subsequent template-parameters shall have a default
3583          template-argument supplied.  */
3584       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3585         {
3586           tree inner_parms = TREE_VALUE (parm_level);
3587           int ntparms = TREE_VEC_LENGTH (inner_parms);
3588           int seen_def_arg_p = 0;
3589           int i;
3590
3591           for (i = 0; i < ntparms; ++i)
3592             {
3593               tree parm = TREE_VEC_ELT (inner_parms, i);
3594
3595               if (parm == error_mark_node)
3596                 continue;
3597
3598               if (TREE_PURPOSE (parm))
3599                 seen_def_arg_p = 1;
3600               else if (seen_def_arg_p
3601                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3602                 {
3603                   error ("no default argument for %qD", TREE_VALUE (parm));
3604                   /* For better subsequent error-recovery, we indicate that
3605                      there should have been a default argument.  */
3606                   TREE_PURPOSE (parm) = error_mark_node;
3607                   no_errors = false;
3608                 }
3609               else if (is_primary
3610                        && !is_partial
3611                        && !is_friend_decl
3612                        /* Don't complain about an enclosing partial
3613                           specialization.  */
3614                        && parm_level == parms
3615                        && TREE_CODE (decl) == TYPE_DECL
3616                        && i < ntparms - 1
3617                        && template_parameter_pack_p (TREE_VALUE (parm)))
3618                 {
3619                   /* A primary class template can only have one
3620                      parameter pack, at the end of the template
3621                      parameter list.  */
3622
3623                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3624                     error ("parameter pack %qE must be at the end of the"
3625                            " template parameter list", TREE_VALUE (parm));
3626                   else
3627                     error ("parameter pack %qT must be at the end of the"
3628                            " template parameter list", 
3629                            TREE_TYPE (TREE_VALUE (parm)));
3630
3631                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3632                     = error_mark_node;
3633                   no_errors = false;
3634                 }
3635             }
3636         }
3637     }
3638
3639   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3640       || is_partial 
3641       || !is_primary
3642       || is_friend_decl)
3643     /* For an ordinary class template, default template arguments are
3644        allowed at the innermost level, e.g.:
3645          template <class T = int>
3646          struct S {};
3647        but, in a partial specialization, they're not allowed even
3648        there, as we have in [temp.class.spec]:
3649
3650          The template parameter list of a specialization shall not
3651          contain default template argument values.
3652
3653        So, for a partial specialization, or for a function template
3654        (in C++98/C++03), we look at all of them.  */
3655     ;
3656   else
3657     /* But, for a primary class template that is not a partial
3658        specialization we look at all template parameters except the
3659        innermost ones.  */
3660     parms = TREE_CHAIN (parms);
3661
3662   /* Figure out what error message to issue.  */
3663   if (is_friend_decl == 2)
3664     msg = "default template arguments may not be used in function template friend re-declaration";
3665   else if (is_friend_decl)
3666     msg = "default template arguments may not be used in function template friend declarations";
3667   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3668     msg = "default template arguments may not be used in function templates";
3669   else if (is_partial)
3670     msg = "default template arguments may not be used in partial specializations";
3671   else
3672     msg = "default argument for template parameter for class enclosing %qD";
3673
3674   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3675     /* If we're inside a class definition, there's no need to
3676        examine the parameters to the class itself.  On the one
3677        hand, they will be checked when the class is defined, and,
3678        on the other, default arguments are valid in things like:
3679          template <class T = double>
3680          struct S { template <class U> void f(U); };
3681        Here the default argument for `S' has no bearing on the
3682        declaration of `f'.  */
3683     last_level_to_check = template_class_depth (current_class_type) + 1;
3684   else
3685     /* Check everything.  */
3686     last_level_to_check = 0;
3687
3688   for (parm_level = parms;
3689        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3690        parm_level = TREE_CHAIN (parm_level))
3691     {
3692       tree inner_parms = TREE_VALUE (parm_level);
3693       int i;
3694       int ntparms;
3695
3696       ntparms = TREE_VEC_LENGTH (inner_parms);
3697       for (i = 0; i < ntparms; ++i)
3698         {
3699           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3700             continue;
3701
3702           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3703             {
3704               if (msg)
3705                 {
3706                   no_errors = false;
3707                   if (is_friend_decl == 2)
3708                     return no_errors;
3709
3710                   error (msg, decl);
3711                   msg = 0;
3712                 }
3713
3714               /* Clear out the default argument so that we are not
3715                  confused later.  */
3716               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3717             }
3718         }
3719
3720       /* At this point, if we're still interested in issuing messages,
3721          they must apply to classes surrounding the object declared.  */
3722       if (msg)
3723         msg = "default argument for template parameter for class enclosing %qD";
3724     }
3725
3726   return no_errors;
3727 }
3728
3729 /* Worker for push_template_decl_real, called via
3730    for_each_template_parm.  DATA is really an int, indicating the
3731    level of the parameters we are interested in.  If T is a template
3732    parameter of that level, return nonzero.  */
3733
3734 static int
3735 template_parm_this_level_p (tree t, void* data)
3736 {
3737   int this_level = *(int *)data;
3738   int level;
3739
3740   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3741     level = TEMPLATE_PARM_LEVEL (t);
3742   else
3743     level = TEMPLATE_TYPE_LEVEL (t);
3744   return level == this_level;
3745 }
3746
3747 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3748    parameters given by current_template_args, or reuses a
3749    previously existing one, if appropriate.  Returns the DECL, or an
3750    equivalent one, if it is replaced via a call to duplicate_decls.
3751
3752    If IS_FRIEND is true, DECL is a friend declaration.  */
3753
3754 tree
3755 push_template_decl_real (tree decl, bool is_friend)
3756 {
3757   tree tmpl;
3758   tree args;
3759   tree info;
3760   tree ctx;
3761   int primary;
3762   int is_partial;
3763   int new_template_p = 0;
3764   /* True if the template is a member template, in the sense of
3765      [temp.mem].  */
3766   bool member_template_p = false;
3767
3768   if (decl == error_mark_node || !current_template_parms)
3769     return error_mark_node;
3770
3771   /* See if this is a partial specialization.  */
3772   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3773                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3774                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3775
3776   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3777     is_friend = true;
3778
3779   if (is_friend)
3780     /* For a friend, we want the context of the friend function, not
3781        the type of which it is a friend.  */
3782     ctx = DECL_CONTEXT (decl);
3783   else if (CP_DECL_CONTEXT (decl)
3784            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3785     /* In the case of a virtual function, we want the class in which
3786        it is defined.  */
3787     ctx = CP_DECL_CONTEXT (decl);
3788   else
3789     /* Otherwise, if we're currently defining some class, the DECL
3790        is assumed to be a member of the class.  */
3791     ctx = current_scope ();
3792
3793   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3794     ctx = NULL_TREE;
3795
3796   if (!DECL_CONTEXT (decl))
3797     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3798
3799   /* See if this is a primary template.  */
3800   if (is_friend && ctx)
3801     /* A friend template that specifies a class context, i.e.
3802          template <typename T> friend void A<T>::f();
3803        is not primary.  */
3804     primary = 0;
3805   else
3806     primary = template_parm_scope_p ();
3807
3808   if (primary)
3809     {
3810       if (DECL_CLASS_SCOPE_P (decl))
3811         member_template_p = true;
3812       if (TREE_CODE (decl) == TYPE_DECL
3813           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3814         {
3815           error ("template class without a name");
3816           return error_mark_node;
3817         }
3818       else if (TREE_CODE (decl) == FUNCTION_DECL)
3819         {
3820           if (DECL_DESTRUCTOR_P (decl))
3821             {
3822               /* [temp.mem]
3823
3824                  A destructor shall not be a member template.  */
3825               error ("destructor %qD declared as member template", decl);
3826               return error_mark_node;
3827             }
3828           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3829               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3830                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3831                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3832                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3833                       == void_list_node)))
3834             {
3835               /* [basic.stc.dynamic.allocation]
3836
3837                  An allocation function can be a function
3838                  template. ... Template allocation functions shall
3839                  have two or more parameters.  */
3840               error ("invalid template declaration of %qD", decl);
3841               return error_mark_node;
3842             }
3843         }
3844       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3845                && CLASS_TYPE_P (TREE_TYPE (decl)))
3846         /* OK */;
3847       else
3848         {
3849           error ("template declaration of %q#D", decl);
3850           return error_mark_node;
3851         }
3852     }
3853
3854   /* Check to see that the rules regarding the use of default
3855      arguments are not being violated.  */
3856   check_default_tmpl_args (decl, current_template_parms,
3857                            primary, is_partial, /*is_friend_decl=*/0);
3858
3859   /* Ensure that there are no parameter packs in the type of this
3860      declaration that have not been expanded.  */
3861   if (TREE_CODE (decl) == FUNCTION_DECL)
3862     {
3863       /* Check each of the arguments individually to see if there are
3864          any bare parameter packs.  */
3865       tree type = TREE_TYPE (decl);
3866       tree arg = DECL_ARGUMENTS (decl);
3867       tree argtype = TYPE_ARG_TYPES (type);
3868
3869       while (arg && argtype)
3870         {
3871           if (!FUNCTION_PARAMETER_PACK_P (arg)
3872               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3873             {
3874             /* This is a PARM_DECL that contains unexpanded parameter
3875                packs. We have already complained about this in the
3876                check_for_bare_parameter_packs call, so just replace
3877                these types with ERROR_MARK_NODE.  */
3878               TREE_TYPE (arg) = error_mark_node;
3879               TREE_VALUE (argtype) = error_mark_node;
3880             }
3881
3882           arg = TREE_CHAIN (arg);
3883           argtype = TREE_CHAIN (argtype);
3884         }
3885
3886       /* Check for bare parameter packs in the return type and the
3887          exception specifiers.  */
3888       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3889         /* Errors were already issued, set return type to int
3890            as the frontend doesn't expect error_mark_node as
3891            the return type.  */
3892         TREE_TYPE (type) = integer_type_node;
3893       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3894         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3895     }
3896   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3897     {
3898       TREE_TYPE (decl) = error_mark_node;
3899       return error_mark_node;
3900     }
3901
3902   if (is_partial)
3903     return process_partial_specialization (decl);
3904
3905   args = current_template_args ();
3906
3907   if (!ctx
3908       || TREE_CODE (ctx) == FUNCTION_DECL
3909       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3910       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3911     {
3912       if (DECL_LANG_SPECIFIC (decl)
3913           && DECL_TEMPLATE_INFO (decl)
3914           && DECL_TI_TEMPLATE (decl))
3915         tmpl = DECL_TI_TEMPLATE (decl);
3916       /* If DECL is a TYPE_DECL for a class-template, then there won't
3917          be DECL_LANG_SPECIFIC.  The information equivalent to
3918          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3919       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3920                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3921                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3922         {
3923           /* Since a template declaration already existed for this
3924              class-type, we must be redeclaring it here.  Make sure
3925              that the redeclaration is valid.  */
3926           redeclare_class_template (TREE_TYPE (decl),
3927                                     current_template_parms);
3928           /* We don't need to create a new TEMPLATE_DECL; just use the
3929              one we already had.  */
3930           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3931         }
3932       else
3933         {
3934           tmpl = build_template_decl (decl, current_template_parms,
3935                                       member_template_p);
3936           new_template_p = 1;
3937
3938           if (DECL_LANG_SPECIFIC (decl)
3939               && DECL_TEMPLATE_SPECIALIZATION (decl))
3940             {
3941               /* A specialization of a member template of a template
3942                  class.  */
3943               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3944               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3945               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3946             }
3947         }
3948     }
3949   else
3950     {
3951       tree a, t, current, parms;
3952       int i;
3953       tree tinfo = get_template_info (decl);
3954
3955       if (!tinfo)
3956         {
3957           error ("template definition of non-template %q#D", decl);
3958           return error_mark_node;
3959         }
3960
3961       tmpl = TI_TEMPLATE (tinfo);
3962
3963       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3964           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3965           && DECL_TEMPLATE_SPECIALIZATION (decl)
3966           && DECL_MEMBER_TEMPLATE_P (tmpl))
3967         {
3968           tree new_tmpl;
3969
3970           /* The declaration is a specialization of a member
3971              template, declared outside the class.  Therefore, the
3972              innermost template arguments will be NULL, so we
3973              replace them with the arguments determined by the
3974              earlier call to check_explicit_specialization.  */
3975           args = DECL_TI_ARGS (decl);
3976
3977           new_tmpl
3978             = build_template_decl (decl, current_template_parms,
3979                                    member_template_p);
3980           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3981           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3982           DECL_TI_TEMPLATE (decl) = new_tmpl;
3983           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3984           DECL_TEMPLATE_INFO (new_tmpl)
3985             = tree_cons (tmpl, args, NULL_TREE);
3986
3987           register_specialization (new_tmpl,
3988                                    most_general_template (tmpl),
3989                                    args,
3990                                    is_friend);
3991           return decl;
3992         }
3993
3994       /* Make sure the template headers we got make sense.  */
3995
3996       parms = DECL_TEMPLATE_PARMS (tmpl);
3997       i = TMPL_PARMS_DEPTH (parms);
3998       if (TMPL_ARGS_DEPTH (args) != i)
3999         {
4000           error ("expected %d levels of template parms for %q#D, got %d",
4001                  i, decl, TMPL_ARGS_DEPTH (args));
4002         }
4003       else
4004         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4005           {
4006             a = TMPL_ARGS_LEVEL (args, i);
4007             t = INNERMOST_TEMPLATE_PARMS (parms);
4008
4009             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4010               {
4011                 if (current == decl)
4012                   error ("got %d template parameters for %q#D",
4013                          TREE_VEC_LENGTH (a), decl);
4014                 else
4015                   error ("got %d template parameters for %q#T",
4016                          TREE_VEC_LENGTH (a), current);
4017                 error ("  but %d required", TREE_VEC_LENGTH (t));
4018                 return error_mark_node;
4019               }
4020
4021             if (current == decl)
4022               current = ctx;
4023             else
4024               current = (TYPE_P (current)
4025                          ? TYPE_CONTEXT (current)
4026                          : DECL_CONTEXT (current));
4027           }
4028
4029       /* Check that the parms are used in the appropriate qualifying scopes
4030          in the declarator.  */
4031       if (!comp_template_args
4032           (TI_ARGS (tinfo),
4033            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4034         {
4035           error ("\
4036 template arguments to %qD do not match original template %qD",
4037                  decl, DECL_TEMPLATE_RESULT (tmpl));
4038           if (!uses_template_parms (TI_ARGS (tinfo)))
4039             inform (input_location, "use template<> for an explicit specialization");
4040           /* Avoid crash in import_export_decl.  */
4041           DECL_INTERFACE_KNOWN (decl) = 1;
4042           return error_mark_node;
4043         }
4044     }
4045
4046   DECL_TEMPLATE_RESULT (tmpl) = decl;
4047   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4048
4049   /* Push template declarations for global functions and types.  Note
4050      that we do not try to push a global template friend declared in a
4051      template class; such a thing may well depend on the template
4052      parameters of the class.  */
4053   if (new_template_p && !ctx
4054       && !(is_friend && template_class_depth (current_class_type) > 0))
4055     {
4056       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4057       if (tmpl == error_mark_node)
4058         return error_mark_node;
4059
4060       /* Hide template friend classes that haven't been declared yet.  */
4061       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4062         {
4063           DECL_ANTICIPATED (tmpl) = 1;
4064           DECL_FRIEND_P (tmpl) = 1;
4065         }
4066     }
4067
4068   if (primary)
4069     {
4070       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4071       int i;
4072
4073       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4074       if (DECL_CONV_FN_P (tmpl))
4075         {
4076           int depth = TMPL_PARMS_DEPTH (parms);
4077
4078           /* It is a conversion operator. See if the type converted to
4079              depends on innermost template operands.  */
4080
4081           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4082                                          depth))
4083             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4084         }
4085
4086       /* Give template template parms a DECL_CONTEXT of the template
4087          for which they are a parameter.  */
4088       parms = INNERMOST_TEMPLATE_PARMS (parms);
4089       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4090         {
4091           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4092           if (TREE_CODE (parm) == TEMPLATE_DECL)
4093             DECL_CONTEXT (parm) = tmpl;
4094         }
4095     }
4096
4097   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4098      back to its most general template.  If TMPL is a specialization,
4099      ARGS may only have the innermost set of arguments.  Add the missing
4100      argument levels if necessary.  */
4101   if (DECL_TEMPLATE_INFO (tmpl))
4102     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4103
4104   info = tree_cons (tmpl, args, NULL_TREE);
4105
4106   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4107     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4108   else if (DECL_LANG_SPECIFIC (decl))
4109     DECL_TEMPLATE_INFO (decl) = info;
4110
4111   return DECL_TEMPLATE_RESULT (tmpl);
4112 }
4113
4114 tree
4115 push_template_decl (tree decl)
4116 {
4117   return push_template_decl_real (decl, false);
4118 }
4119
4120 /* Called when a class template TYPE is redeclared with the indicated
4121    template PARMS, e.g.:
4122
4123      template <class T> struct S;
4124      template <class T> struct S {};  */
4125
4126 bool
4127 redeclare_class_template (tree type, tree parms)
4128 {
4129   tree tmpl;
4130   tree tmpl_parms;
4131   int i;
4132
4133   if (!TYPE_TEMPLATE_INFO (type))
4134     {
4135       error ("%qT is not a template type", type);
4136       return false;
4137     }
4138
4139   tmpl = TYPE_TI_TEMPLATE (type);
4140   if (!PRIMARY_TEMPLATE_P (tmpl))
4141     /* The type is nested in some template class.  Nothing to worry
4142        about here; there are no new template parameters for the nested
4143        type.  */
4144     return true;
4145
4146   if (!parms)
4147     {
4148       error ("template specifiers not specified in declaration of %qD",
4149              tmpl);
4150       return false;
4151     }
4152
4153   parms = INNERMOST_TEMPLATE_PARMS (parms);
4154   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4155
4156   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4157     {
4158       error ("redeclared with %d template parameter(s)", 
4159              TREE_VEC_LENGTH (parms));
4160       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4161              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4162       return false;
4163     }
4164
4165   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4166     {
4167       tree tmpl_parm;
4168       tree parm;
4169       tree tmpl_default;
4170       tree parm_default;
4171
4172       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4173           || TREE_VEC_ELT (parms, i) == error_mark_node)
4174         continue;
4175
4176       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4177       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4178       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4179       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4180
4181       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4182          TEMPLATE_DECL.  */
4183       if (tmpl_parm != error_mark_node
4184           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4185               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4186                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4187               || (TREE_CODE (tmpl_parm) != PARM_DECL
4188                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4189                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4190               || (TREE_CODE (tmpl_parm) == PARM_DECL
4191                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4192                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4193         {
4194           error ("template parameter %q+#D", tmpl_parm);
4195           error ("redeclared here as %q#D", parm);
4196           return false;
4197         }
4198
4199       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4200         {
4201           /* We have in [temp.param]:
4202
4203              A template-parameter may not be given default arguments
4204              by two different declarations in the same scope.  */
4205           error ("redefinition of default argument for %q#D", parm);
4206           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4207           return false;
4208         }
4209
4210       if (parm_default != NULL_TREE)
4211         /* Update the previous template parameters (which are the ones
4212            that will really count) with the new default value.  */
4213         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4214       else if (tmpl_default != NULL_TREE)
4215         /* Update the new parameters, too; they'll be used as the
4216            parameters for any members.  */
4217         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4218     }
4219
4220     return true;
4221 }
4222
4223 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4224    (possibly simplified) expression.  */
4225
4226 tree
4227 fold_non_dependent_expr (tree expr)
4228 {
4229   if (expr == NULL_TREE)
4230     return NULL_TREE;
4231
4232   /* If we're in a template, but EXPR isn't value dependent, simplify
4233      it.  We're supposed to treat:
4234
4235        template <typename T> void f(T[1 + 1]);
4236        template <typename T> void f(T[2]);
4237
4238      as two declarations of the same function, for example.  */
4239   if (processing_template_decl
4240       && !type_dependent_expression_p (expr)
4241       && !value_dependent_expression_p (expr))
4242     {
4243       HOST_WIDE_INT saved_processing_template_decl;
4244
4245       saved_processing_template_decl = processing_template_decl;
4246       processing_template_decl = 0;
4247       expr = tsubst_copy_and_build (expr,
4248                                     /*args=*/NULL_TREE,
4249                                     tf_error,
4250                                     /*in_decl=*/NULL_TREE,
4251                                     /*function_p=*/false,
4252                                     /*integral_constant_expression_p=*/true);
4253       processing_template_decl = saved_processing_template_decl;
4254     }
4255   return expr;
4256 }
4257
4258 /* EXPR is an expression which is used in a constant-expression context.
4259    For instance, it could be a VAR_DECL with a constant initializer.
4260    Extract the innermost constant expression.
4261
4262    This is basically a more powerful version of
4263    integral_constant_value, which can be used also in templates where
4264    initializers can maintain a syntactic rather than semantic form
4265    (even if they are non-dependent, for access-checking purposes).  */
4266
4267 static tree
4268 fold_decl_constant_value (tree expr)
4269 {
4270   tree const_expr = expr;
4271   do
4272     {
4273       expr = fold_non_dependent_expr (const_expr);
4274       const_expr = integral_constant_value (expr);
4275     }
4276   while (expr != const_expr);
4277
4278   return expr;
4279 }
4280
4281 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4282    must be a function or a pointer-to-function type, as specified
4283    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4284    and check that the resulting function has external linkage.  */
4285
4286 static tree
4287 convert_nontype_argument_function (tree type, tree expr)
4288 {
4289   tree fns = expr;
4290   tree fn, fn_no_ptr;
4291
4292   fn = instantiate_type (type, fns, tf_none);
4293   if (fn == error_mark_node)
4294     return error_mark_node;
4295
4296   fn_no_ptr = fn;
4297   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4298     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4299   if (TREE_CODE (fn_no_ptr) == BASELINK)
4300     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4301  
4302   /* [temp.arg.nontype]/1
4303
4304      A template-argument for a non-type, non-template template-parameter
4305      shall be one of:
4306      [...]
4307      -- the address of an object or function with external linkage.  */
4308   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4309     {
4310       error ("%qE is not a valid template argument for type %qT "
4311              "because function %qD has not external linkage",
4312              expr, type, fn_no_ptr);
4313       return NULL_TREE;
4314     }
4315
4316   return fn;
4317 }
4318
4319 /* Attempt to convert the non-type template parameter EXPR to the
4320    indicated TYPE.  If the conversion is successful, return the
4321    converted value.  If the conversion is unsuccessful, return
4322    NULL_TREE if we issued an error message, or error_mark_node if we
4323    did not.  We issue error messages for out-and-out bad template
4324    parameters, but not simply because the conversion failed, since we
4325    might be just trying to do argument deduction.  Both TYPE and EXPR
4326    must be non-dependent.
4327
4328    The conversion follows the special rules described in
4329    [temp.arg.nontype], and it is much more strict than an implicit
4330    conversion.
4331
4332    This function is called twice for each template argument (see
4333    lookup_template_class for a more accurate description of this
4334    problem). This means that we need to handle expressions which
4335    are not valid in a C++ source, but can be created from the
4336    first call (for instance, casts to perform conversions). These
4337    hacks can go away after we fix the double coercion problem.  */
4338
4339 static tree
4340 convert_nontype_argument (tree type, tree expr)
4341 {
4342   tree expr_type;
4343
4344   /* Detect immediately string literals as invalid non-type argument.
4345      This special-case is not needed for correctness (we would easily
4346      catch this later), but only to provide better diagnostic for this
4347      common user mistake. As suggested by DR 100, we do not mention
4348      linkage issues in the diagnostic as this is not the point.  */
4349   if (TREE_CODE (expr) == STRING_CST)
4350     {
4351       error ("%qE is not a valid template argument for type %qT "
4352              "because string literals can never be used in this context",
4353              expr, type);
4354       return NULL_TREE;
4355     }
4356
4357   /* If we are in a template, EXPR may be non-dependent, but still
4358      have a syntactic, rather than semantic, form.  For example, EXPR
4359      might be a SCOPE_REF, rather than the VAR_DECL to which the
4360      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4361      so that access checking can be performed when the template is
4362      instantiated -- but here we need the resolved form so that we can
4363      convert the argument.  */
4364   expr = fold_non_dependent_expr (expr);
4365   if (error_operand_p (expr))
4366     return error_mark_node;
4367   expr_type = TREE_TYPE (expr);
4368
4369   /* HACK: Due to double coercion, we can get a
4370      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4371      which is the tree that we built on the first call (see
4372      below when coercing to reference to object or to reference to
4373      function). We just strip everything and get to the arg.
4374      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4375      for examples.  */
4376   if (TREE_CODE (expr) == NOP_EXPR)
4377     {
4378       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4379         {
4380           /* ??? Maybe we could use convert_from_reference here, but we
4381              would need to relax its constraints because the NOP_EXPR
4382              could actually change the type to something more cv-qualified,
4383              and this is not folded by convert_from_reference.  */
4384           tree addr = TREE_OPERAND (expr, 0);
4385           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4386           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4387           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4388           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4389                       (TREE_TYPE (expr_type),
4390                        TREE_TYPE (TREE_TYPE (addr))));
4391
4392           expr = TREE_OPERAND (addr, 0);
4393           expr_type = TREE_TYPE (expr);
4394         }
4395
4396       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4397          parameter is a pointer to object, through decay and
4398          qualification conversion. Let's strip everything.  */
4399       else if (TYPE_PTROBV_P (type))
4400         {
4401           STRIP_NOPS (expr);
4402           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4403           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4404           /* Skip the ADDR_EXPR only if it is part of the decay for
4405              an array. Otherwise, it is part of the original argument
4406              in the source code.  */
4407           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4408             expr = TREE_OPERAND (expr, 0);
4409           expr_type = TREE_TYPE (expr);
4410         }
4411     }
4412
4413   /* [temp.arg.nontype]/5, bullet 1
4414
4415      For a non-type template-parameter of integral or enumeration type,
4416      integral promotions (_conv.prom_) and integral conversions
4417      (_conv.integral_) are applied.  */
4418   if (INTEGRAL_TYPE_P (type))
4419     {
4420       if (!INTEGRAL_TYPE_P (expr_type))
4421         return error_mark_node;
4422
4423       expr = fold_decl_constant_value (expr);
4424       /* Notice that there are constant expressions like '4 % 0' which
4425          do not fold into integer constants.  */
4426       if (TREE_CODE (expr) != INTEGER_CST)
4427         {
4428           error ("%qE is not a valid template argument for type %qT "
4429                  "because it is a non-constant expression", expr, type);
4430           return NULL_TREE;
4431         }
4432
4433       /* At this point, an implicit conversion does what we want,
4434          because we already know that the expression is of integral
4435          type.  */
4436       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4437       if (expr == error_mark_node)
4438         return error_mark_node;
4439
4440       /* Conversion was allowed: fold it to a bare integer constant.  */
4441       expr = fold (expr);
4442     }
4443   /* [temp.arg.nontype]/5, bullet 2
4444
4445      For a non-type template-parameter of type pointer to object,
4446      qualification conversions (_conv.qual_) and the array-to-pointer
4447      conversion (_conv.array_) are applied.  */
4448   else if (TYPE_PTROBV_P (type))
4449     {
4450       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4451
4452          A template-argument for a non-type, non-template template-parameter
4453          shall be one of: [...]
4454
4455          -- the name of a non-type template-parameter;
4456          -- the address of an object or function with external linkage, [...]
4457             expressed as "& id-expression" where the & is optional if the name
4458             refers to a function or array, or if the corresponding
4459             template-parameter is a reference.
4460
4461         Here, we do not care about functions, as they are invalid anyway
4462         for a parameter of type pointer-to-object.  */
4463
4464       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4465         /* Non-type template parameters are OK.  */
4466         ;
4467       else if (TREE_CODE (expr) != ADDR_EXPR
4468                && TREE_CODE (expr_type) != ARRAY_TYPE)
4469         {
4470           if (TREE_CODE (expr) == VAR_DECL)
4471             {
4472               error ("%qD is not a valid template argument "
4473                      "because %qD is a variable, not the address of "
4474                      "a variable",
4475                      expr, expr);
4476               return NULL_TREE;
4477             }
4478           /* Other values, like integer constants, might be valid
4479              non-type arguments of some other type.  */
4480           return error_mark_node;
4481         }
4482       else
4483         {
4484           tree decl;
4485
4486           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4487                   ? TREE_OPERAND (expr, 0) : expr);
4488           if (TREE_CODE (decl) != VAR_DECL)
4489             {
4490               error ("%qE is not a valid template argument of type %qT "
4491                      "because %qE is not a variable",
4492                      expr, type, decl);
4493               return NULL_TREE;
4494             }
4495           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4496             {
4497               error ("%qE is not a valid template argument of type %qT "
4498                      "because %qD does not have external linkage",
4499                      expr, type, decl);
4500               return NULL_TREE;
4501             }
4502         }
4503
4504       expr = decay_conversion (expr);
4505       if (expr == error_mark_node)
4506         return error_mark_node;
4507
4508       expr = perform_qualification_conversions (type, expr);
4509       if (expr == error_mark_node)
4510         return error_mark_node;
4511     }
4512   /* [temp.arg.nontype]/5, bullet 3
4513
4514      For a non-type template-parameter of type reference to object, no
4515      conversions apply. The type referred to by the reference may be more
4516      cv-qualified than the (otherwise identical) type of the
4517      template-argument. The template-parameter is bound directly to the
4518      template-argument, which must be an lvalue.  */
4519   else if (TYPE_REF_OBJ_P (type))
4520     {
4521       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4522                                                       expr_type))
4523         return error_mark_node;
4524
4525       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4526         {
4527           error ("%qE is not a valid template argument for type %qT "
4528                  "because of conflicts in cv-qualification", expr, type);
4529           return NULL_TREE;
4530         }
4531
4532       if (!real_lvalue_p (expr))
4533         {
4534           error ("%qE is not a valid template argument for type %qT "
4535                  "because it is not an lvalue", expr, type);
4536           return NULL_TREE;
4537         }
4538
4539       /* [temp.arg.nontype]/1
4540
4541          A template-argument for a non-type, non-template template-parameter
4542          shall be one of: [...]
4543
4544          -- the address of an object or function with external linkage.  */
4545       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4546         {
4547           error ("%qE is not a valid template argument for type %qT "
4548                  "because object %qD has not external linkage",
4549                  expr, type, expr);
4550           return NULL_TREE;
4551         }
4552
4553       expr = build_nop (type, build_address (expr));
4554     }
4555   /* [temp.arg.nontype]/5, bullet 4
4556
4557      For a non-type template-parameter of type pointer to function, only
4558      the function-to-pointer conversion (_conv.func_) is applied. If the
4559      template-argument represents a set of overloaded functions (or a
4560      pointer to such), the matching function is selected from the set
4561      (_over.over_).  */
4562   else if (TYPE_PTRFN_P (type))
4563     {
4564       /* If the argument is a template-id, we might not have enough
4565          context information to decay the pointer.  */
4566       if (!type_unknown_p (expr_type))
4567         {
4568           expr = decay_conversion (expr);
4569           if (expr == error_mark_node)
4570             return error_mark_node;
4571         }
4572
4573       expr = convert_nontype_argument_function (type, expr);
4574       if (!expr || expr == error_mark_node)
4575         return expr;
4576
4577       if (TREE_CODE (expr) != ADDR_EXPR)
4578         {
4579           error ("%qE is not a valid template argument for type %qT", expr, type);
4580           error ("it must be the address of a function with external linkage");
4581           return NULL_TREE;
4582         }
4583     }
4584   /* [temp.arg.nontype]/5, bullet 5
4585
4586      For a non-type template-parameter of type reference to function, no
4587      conversions apply. If the template-argument represents a set of
4588      overloaded functions, the matching function is selected from the set
4589      (_over.over_).  */
4590   else if (TYPE_REFFN_P (type))
4591     {
4592       if (TREE_CODE (expr) == ADDR_EXPR)
4593         {
4594           error ("%qE is not a valid template argument for type %qT "
4595                  "because it is a pointer", expr, type);
4596           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4597           return NULL_TREE;
4598         }
4599
4600       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4601       if (!expr || expr == error_mark_node)
4602         return expr;
4603
4604       expr = build_nop (type, build_address (expr));
4605     }
4606   /* [temp.arg.nontype]/5, bullet 6
4607
4608      For a non-type template-parameter of type pointer to member function,
4609      no conversions apply. If the template-argument represents a set of
4610      overloaded member functions, the matching member function is selected
4611      from the set (_over.over_).  */
4612   else if (TYPE_PTRMEMFUNC_P (type))
4613     {
4614       expr = instantiate_type (type, expr, tf_none);
4615       if (expr == error_mark_node)
4616         return error_mark_node;
4617
4618       /* There is no way to disable standard conversions in
4619          resolve_address_of_overloaded_function (called by
4620          instantiate_type). It is possible that the call succeeded by
4621          converting &B::I to &D::I (where B is a base of D), so we need
4622          to reject this conversion here.
4623
4624          Actually, even if there was a way to disable standard conversions,
4625          it would still be better to reject them here so that we can
4626          provide a superior diagnostic.  */
4627       if (!same_type_p (TREE_TYPE (expr), type))
4628         {
4629           /* Make sure we are just one standard conversion off.  */
4630           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4631           error ("%qE is not a valid template argument for type %qT "
4632                  "because it is of type %qT", expr, type,
4633                  TREE_TYPE (expr));
4634           inform (input_location, "standard conversions are not allowed in this context");
4635           return NULL_TREE;
4636         }
4637     }
4638   /* [temp.arg.nontype]/5, bullet 7
4639
4640      For a non-type template-parameter of type pointer to data member,
4641      qualification conversions (_conv.qual_) are applied.  */
4642   else if (TYPE_PTRMEM_P (type))
4643     {
4644       expr = perform_qualification_conversions (type, expr);
4645       if (expr == error_mark_node)
4646         return expr;
4647     }
4648   /* A template non-type parameter must be one of the above.  */
4649   else
4650     gcc_unreachable ();
4651
4652   /* Sanity check: did we actually convert the argument to the
4653      right type?  */
4654   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4655   return expr;
4656 }
4657
4658 /* Subroutine of coerce_template_template_parms, which returns 1 if
4659    PARM_PARM and ARG_PARM match using the rule for the template
4660    parameters of template template parameters. Both PARM and ARG are
4661    template parameters; the rest of the arguments are the same as for
4662    coerce_template_template_parms.
4663  */
4664 static int
4665 coerce_template_template_parm (tree parm,
4666                               tree arg,
4667                               tsubst_flags_t complain,
4668                               tree in_decl,
4669                               tree outer_args)
4670 {
4671   if (arg == NULL_TREE || arg == error_mark_node
4672       || parm == NULL_TREE || parm == error_mark_node)
4673     return 0;
4674   
4675   if (TREE_CODE (arg) != TREE_CODE (parm))
4676     return 0;
4677   
4678   switch (TREE_CODE (parm))
4679     {
4680     case TEMPLATE_DECL:
4681       /* We encounter instantiations of templates like
4682          template <template <template <class> class> class TT>
4683          class C;  */
4684       {
4685         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4686         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4687         
4688         if (!coerce_template_template_parms
4689             (parmparm, argparm, complain, in_decl, outer_args))
4690           return 0;
4691       }
4692       /* Fall through.  */
4693       
4694     case TYPE_DECL:
4695       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4696           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4697         /* Argument is a parameter pack but parameter is not.  */
4698         return 0;
4699       break;
4700       
4701     case PARM_DECL:
4702       /* The tsubst call is used to handle cases such as
4703          
4704            template <int> class C {};
4705            template <class T, template <T> class TT> class D {};
4706            D<int, C> d;
4707
4708          i.e. the parameter list of TT depends on earlier parameters.  */
4709       if (!uses_template_parms (TREE_TYPE (arg))
4710           && !same_type_p
4711                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4712                  TREE_TYPE (arg)))
4713         return 0;
4714       
4715       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4716           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4717         /* Argument is a parameter pack but parameter is not.  */
4718         return 0;
4719       
4720       break;
4721
4722     default:
4723       gcc_unreachable ();
4724     }
4725
4726   return 1;
4727 }
4728
4729
4730 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4731    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4732    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4733    or PARM_DECL.
4734
4735    Consider the example:
4736      template <class T> class A;
4737      template<template <class U> class TT> class B;
4738
4739    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4740    the parameters to A, and OUTER_ARGS contains A.  */
4741
4742 static int
4743 coerce_template_template_parms (tree parm_parms,
4744                                 tree arg_parms,
4745                                 tsubst_flags_t complain,
4746                                 tree in_decl,
4747                                 tree outer_args)
4748 {
4749   int nparms, nargs, i;
4750   tree parm, arg;
4751   int variadic_p = 0;
4752
4753   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4754   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4755
4756   nparms = TREE_VEC_LENGTH (parm_parms);
4757   nargs = TREE_VEC_LENGTH (arg_parms);
4758
4759   /* Determine whether we have a parameter pack at the end of the
4760      template template parameter's template parameter list.  */
4761   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4762     {
4763       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4764       
4765       if (parm == error_mark_node)
4766         return 0;
4767
4768       switch (TREE_CODE (parm))
4769         {
4770         case TEMPLATE_DECL:
4771         case TYPE_DECL:
4772           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4773             variadic_p = 1;
4774           break;
4775           
4776         case PARM_DECL:
4777           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4778             variadic_p = 1;
4779           break;
4780           
4781         default:
4782           gcc_unreachable ();
4783         }
4784     }
4785  
4786   if (nargs != nparms
4787       && !(variadic_p && nargs >= nparms - 1))
4788     return 0;
4789
4790   /* Check all of the template parameters except the parameter pack at
4791      the end (if any).  */
4792   for (i = 0; i < nparms - variadic_p; ++i)
4793     {
4794       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4795           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4796         continue;
4797
4798       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4799       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4800
4801       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4802                                           outer_args))
4803         return 0;
4804
4805     }
4806
4807   if (variadic_p)
4808     {
4809       /* Check each of the template parameters in the template
4810          argument against the template parameter pack at the end of
4811          the template template parameter.  */
4812       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4813         return 0;
4814
4815       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4816
4817       for (; i < nargs; ++i)
4818         {
4819           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4820             continue;
4821  
4822           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4823  
4824           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4825                                               outer_args))
4826             return 0;
4827         }
4828     }
4829
4830   return 1;
4831 }
4832
4833 /* Verifies that the deduced template arguments (in TARGS) for the
4834    template template parameters (in TPARMS) represent valid bindings,
4835    by comparing the template parameter list of each template argument
4836    to the template parameter list of its corresponding template
4837    template parameter, in accordance with DR150. This
4838    routine can only be called after all template arguments have been
4839    deduced. It will return TRUE if all of the template template
4840    parameter bindings are okay, FALSE otherwise.  */
4841 bool 
4842 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4843 {
4844   int i, ntparms = TREE_VEC_LENGTH (tparms);
4845   bool ret = true;
4846
4847   /* We're dealing with template parms in this process.  */
4848   ++processing_template_decl;
4849
4850   targs = INNERMOST_TEMPLATE_ARGS (targs);
4851
4852   for (i = 0; i < ntparms; ++i)
4853     {
4854       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4855       tree targ = TREE_VEC_ELT (targs, i);
4856
4857       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4858         {
4859           tree packed_args = NULL_TREE;
4860           int idx, len = 1;
4861
4862           if (ARGUMENT_PACK_P (targ))
4863             {
4864               /* Look inside the argument pack.  */
4865               packed_args = ARGUMENT_PACK_ARGS (targ);
4866               len = TREE_VEC_LENGTH (packed_args);
4867             }
4868
4869           for (idx = 0; idx < len; ++idx)
4870             {
4871               tree targ_parms = NULL_TREE;
4872
4873               if (packed_args)
4874                 /* Extract the next argument from the argument
4875                    pack.  */
4876                 targ = TREE_VEC_ELT (packed_args, idx);
4877
4878               if (PACK_EXPANSION_P (targ))
4879                 /* Look at the pattern of the pack expansion.  */
4880                 targ = PACK_EXPANSION_PATTERN (targ);
4881
4882               /* Extract the template parameters from the template
4883                  argument.  */
4884               if (TREE_CODE (targ) == TEMPLATE_DECL)
4885                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4886               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4887                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4888
4889               /* Verify that we can coerce the template template
4890                  parameters from the template argument to the template
4891                  parameter.  This requires an exact match.  */
4892               if (targ_parms
4893                   && !coerce_template_template_parms
4894                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4895                         targ_parms,
4896                         tf_none,
4897                         tparm,
4898                         targs))
4899                 {
4900                   ret = false;
4901                   goto out;
4902                 }
4903             }
4904         }
4905     }
4906
4907  out:
4908
4909   --processing_template_decl;
4910   return ret;
4911 }
4912
4913 /* Convert the indicated template ARG as necessary to match the
4914    indicated template PARM.  Returns the converted ARG, or
4915    error_mark_node if the conversion was unsuccessful.  Error and
4916    warning messages are issued under control of COMPLAIN.  This
4917    conversion is for the Ith parameter in the parameter list.  ARGS is
4918    the full set of template arguments deduced so far.  */
4919
4920 static tree
4921 convert_template_argument (tree parm,
4922                            tree arg,
4923                            tree args,
4924                            tsubst_flags_t complain,
4925                            int i,
4926                            tree in_decl)
4927 {
4928   tree orig_arg;
4929   tree val;
4930   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4931
4932   if (TREE_CODE (arg) == TREE_LIST
4933       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4934     {
4935       /* The template argument was the name of some
4936          member function.  That's usually
4937          invalid, but static members are OK.  In any
4938          case, grab the underlying fields/functions
4939          and issue an error later if required.  */
4940       orig_arg = TREE_VALUE (arg);
4941       TREE_TYPE (arg) = unknown_type_node;
4942     }
4943
4944   orig_arg = arg;
4945
4946   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4947   requires_type = (TREE_CODE (parm) == TYPE_DECL
4948                    || requires_tmpl_type);
4949
4950   /* When determining whether an argument pack expansion is a template,
4951      look at the pattern.  */
4952   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4953     arg = PACK_EXPANSION_PATTERN (arg);
4954
4955   is_tmpl_type = 
4956     ((TREE_CODE (arg) == TEMPLATE_DECL
4957       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4958      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4959      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4960
4961   if (is_tmpl_type
4962       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4963           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4964     arg = TYPE_STUB_DECL (arg);
4965
4966   is_type = TYPE_P (arg) || is_tmpl_type;
4967
4968   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4969       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4970     {
4971       permerror (input_location, "to refer to a type member of a template parameter, "
4972                  "use %<typename %E%>", orig_arg);
4973
4974       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4975                                      TREE_OPERAND (arg, 1),
4976                                      typename_type,
4977                                      complain & tf_error);
4978       arg = orig_arg;
4979       is_type = 1;
4980     }
4981   if (is_type != requires_type)
4982     {
4983       if (in_decl)
4984         {
4985           if (complain & tf_error)
4986             {
4987               error ("type/value mismatch at argument %d in template "
4988                      "parameter list for %qD",
4989                      i + 1, in_decl);
4990               if (is_type)
4991                 error ("  expected a constant of type %qT, got %qT",
4992                        TREE_TYPE (parm),
4993                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4994               else if (requires_tmpl_type)
4995                 error ("  expected a class template, got %qE", orig_arg);
4996               else
4997                 error ("  expected a type, got %qE", orig_arg);
4998             }
4999         }
5000       return error_mark_node;
5001     }
5002   if (is_tmpl_type ^ requires_tmpl_type)
5003     {
5004       if (in_decl && (complain & tf_error))
5005         {
5006           error ("type/value mismatch at argument %d in template "
5007                  "parameter list for %qD",
5008                  i + 1, in_decl);
5009           if (is_tmpl_type)
5010             error ("  expected a type, got %qT", DECL_NAME (arg));
5011           else
5012             error ("  expected a class template, got %qT", orig_arg);
5013         }
5014       return error_mark_node;
5015     }
5016
5017   if (is_type)
5018     {
5019       if (requires_tmpl_type)
5020         {
5021           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5022             /* The number of argument required is not known yet.
5023                Just accept it for now.  */
5024             val = TREE_TYPE (arg);
5025           else
5026             {
5027               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5028               tree argparm;
5029
5030               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5031
5032               if (coerce_template_template_parms (parmparm, argparm,
5033                                                   complain, in_decl,
5034                                                   args))
5035                 {
5036                   val = orig_arg;
5037
5038                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5039                      TEMPLATE_DECL.  */
5040                   if (val != error_mark_node)
5041                     {
5042                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5043                         val = TREE_TYPE (val);
5044                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5045                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5046                         {
5047                           val = TREE_TYPE (arg);
5048                           val = make_pack_expansion (val);
5049                         }
5050                     }
5051                 }
5052               else
5053                 {
5054                   if (in_decl && (complain & tf_error))
5055                     {
5056                       error ("type/value mismatch at argument %d in "
5057                              "template parameter list for %qD",
5058                              i + 1, in_decl);
5059                       error ("  expected a template of type %qD, got %qD",
5060                              parm, orig_arg);
5061                     }
5062
5063                   val = error_mark_node;
5064                 }
5065             }
5066         }
5067       else
5068         val = orig_arg;
5069       /* We only form one instance of each template specialization.
5070          Therefore, if we use a non-canonical variant (i.e., a
5071          typedef), any future messages referring to the type will use
5072          the typedef, which is confusing if those future uses do not
5073          themselves also use the typedef.  */
5074       if (TYPE_P (val))
5075         val = canonical_type_variant (val);
5076     }
5077   else
5078     {
5079       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5080
5081       if (invalid_nontype_parm_type_p (t, complain))
5082         return error_mark_node;
5083
5084       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5085         {
5086           if (same_type_p (t, TREE_TYPE (orig_arg)))
5087             val = orig_arg;
5088           else
5089             {
5090               /* Not sure if this is reachable, but it doesn't hurt
5091                  to be robust.  */
5092               error ("type mismatch in nontype parameter pack");
5093               val = error_mark_node;
5094             }
5095         }
5096       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5097         /* We used to call digest_init here.  However, digest_init
5098            will report errors, which we don't want when complain
5099            is zero.  More importantly, digest_init will try too
5100            hard to convert things: for example, `0' should not be
5101            converted to pointer type at this point according to
5102            the standard.  Accepting this is not merely an
5103            extension, since deciding whether or not these
5104            conversions can occur is part of determining which
5105            function template to call, or whether a given explicit
5106            argument specification is valid.  */
5107         val = convert_nontype_argument (t, orig_arg);
5108       else
5109         val = orig_arg;
5110
5111       if (val == NULL_TREE)
5112         val = error_mark_node;
5113       else if (val == error_mark_node && (complain & tf_error))
5114         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5115     }
5116
5117   return val;
5118 }
5119
5120 /* Coerces the remaining template arguments in INNER_ARGS (from
5121    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5122    Returns the coerced argument pack. PARM_IDX is the position of this
5123    parameter in the template parameter list. ARGS is the original
5124    template argument list.  */
5125 static tree
5126 coerce_template_parameter_pack (tree parms,
5127                                 int parm_idx,
5128                                 tree args,
5129                                 tree inner_args,
5130                                 int arg_idx,
5131                                 tree new_args,
5132                                 int* lost,
5133                                 tree in_decl,
5134                                 tsubst_flags_t complain)
5135 {
5136   tree parm = TREE_VEC_ELT (parms, parm_idx);
5137   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5138   tree packed_args;
5139   tree argument_pack;
5140   tree packed_types = NULL_TREE;
5141
5142   if (arg_idx > nargs)
5143     arg_idx = nargs;
5144
5145   packed_args = make_tree_vec (nargs - arg_idx);
5146
5147   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5148       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5149     {
5150       /* When the template parameter is a non-type template
5151          parameter pack whose type uses parameter packs, we need
5152          to look at each of the template arguments
5153          separately. Build a vector of the types for these
5154          non-type template parameters in PACKED_TYPES.  */
5155       tree expansion 
5156         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5157       packed_types = tsubst_pack_expansion (expansion, args,
5158                                             complain, in_decl);
5159
5160       if (packed_types == error_mark_node)
5161         return error_mark_node;
5162
5163       /* Check that we have the right number of arguments.  */
5164       if (arg_idx < nargs
5165           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5166           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5167         {
5168           int needed_parms 
5169             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5170           error ("wrong number of template arguments (%d, should be %d)",
5171                  nargs, needed_parms);
5172           return error_mark_node;
5173         }
5174
5175       /* If we aren't able to check the actual arguments now
5176          (because they haven't been expanded yet), we can at least
5177          verify that all of the types used for the non-type
5178          template parameter pack are, in fact, valid for non-type
5179          template parameters.  */
5180       if (arg_idx < nargs 
5181           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5182         {
5183           int j, len = TREE_VEC_LENGTH (packed_types);
5184           for (j = 0; j < len; ++j)
5185             {
5186               tree t = TREE_VEC_ELT (packed_types, j);
5187               if (invalid_nontype_parm_type_p (t, complain))
5188                 return error_mark_node;
5189             }
5190         }
5191     }
5192
5193   /* Convert the remaining arguments, which will be a part of the
5194      parameter pack "parm".  */
5195   for (; arg_idx < nargs; ++arg_idx)
5196     {
5197       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5198       tree actual_parm = TREE_VALUE (parm);
5199
5200       if (packed_types && !PACK_EXPANSION_P (arg))
5201         {
5202           /* When we have a vector of types (corresponding to the
5203              non-type template parameter pack that uses parameter
5204              packs in its type, as mention above), and the
5205              argument is not an expansion (which expands to a
5206              currently unknown number of arguments), clone the
5207              parm and give it the next type in PACKED_TYPES.  */
5208           actual_parm = copy_node (actual_parm);
5209           TREE_TYPE (actual_parm) = 
5210             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5211         }
5212
5213       if (arg != error_mark_node)
5214         arg = convert_template_argument (actual_parm, 
5215                                          arg, new_args, complain, parm_idx,
5216                                          in_decl);
5217       if (arg == error_mark_node)
5218         (*lost)++;
5219       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5220     }
5221
5222   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5223       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5224     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5225   else
5226     {
5227       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5228       TREE_TYPE (argument_pack) 
5229         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5230       TREE_CONSTANT (argument_pack) = 1;
5231     }
5232
5233   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5234   return argument_pack;
5235 }
5236
5237 /* Convert all template arguments to their appropriate types, and
5238    return a vector containing the innermost resulting template
5239    arguments.  If any error occurs, return error_mark_node. Error and
5240    warning messages are issued under control of COMPLAIN.
5241
5242    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5243    for arguments not specified in ARGS.  Otherwise, if
5244    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5245    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5246    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5247    ARGS.  */
5248
5249 static tree
5250 coerce_template_parms (tree parms,
5251                        tree args,
5252                        tree in_decl,
5253                        tsubst_flags_t complain,
5254                        bool require_all_args,
5255                        bool use_default_args)
5256 {
5257   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5258   tree inner_args;
5259   tree new_args;
5260   tree new_inner_args;
5261   bool saved_skip_evaluation;
5262
5263   /* When used as a boolean value, indicates whether this is a
5264      variadic template parameter list. Since it's an int, we can also
5265      subtract it from nparms to get the number of non-variadic
5266      parameters.  */
5267   int variadic_p = 0;
5268
5269   nparms = TREE_VEC_LENGTH (parms);
5270
5271   /* Determine if there are any parameter packs.  */
5272   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5273     {
5274       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5275       if (template_parameter_pack_p (tparm))
5276         ++variadic_p;
5277     }
5278
5279   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5280   /* If there are 0 or 1 parameter packs, we need to expand any argument
5281      packs so that we can deduce a parameter pack from some non-packed args
5282      followed by an argument pack, as in variadic85.C.  If there are more
5283      than that, we need to leave argument packs intact so the arguments are
5284      assigned to the right parameter packs.  This should only happen when
5285      dealing with a nested class inside a partial specialization of a class
5286      template, as in variadic92.C.  */
5287   if (variadic_p <= 1)
5288     inner_args = expand_template_argument_pack (inner_args);
5289
5290   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5291   if ((nargs > nparms && !variadic_p)
5292       || (nargs < nparms - variadic_p
5293           && require_all_args
5294           && (!use_default_args
5295               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5296                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5297     {
5298       if (complain & tf_error)
5299         {
5300           const char *or_more = "";
5301           if (variadic_p)
5302             {
5303               or_more = " or more";
5304               --nparms;
5305             }
5306
5307           error ("wrong number of template arguments (%d, should be %d%s)",
5308                  nargs, nparms, or_more);
5309
5310           if (in_decl)
5311             error ("provided for %q+D", in_decl);
5312         }
5313
5314       return error_mark_node;
5315     }
5316
5317   /* We need to evaluate the template arguments, even though this
5318      template-id may be nested within a "sizeof".  */
5319   saved_skip_evaluation = skip_evaluation;
5320   skip_evaluation = false;
5321   new_inner_args = make_tree_vec (nparms);
5322   new_args = add_outermost_template_args (args, new_inner_args);
5323   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5324     {
5325       tree arg;
5326       tree parm;
5327
5328       /* Get the Ith template parameter.  */
5329       parm = TREE_VEC_ELT (parms, parm_idx);
5330  
5331       if (parm == error_mark_node)
5332       {
5333         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5334         continue;
5335       }
5336
5337       /* Calculate the next argument.  */
5338       if (arg_idx < nargs)
5339         arg = TREE_VEC_ELT (inner_args, arg_idx);
5340       else
5341         arg = NULL_TREE;
5342
5343       if (template_parameter_pack_p (TREE_VALUE (parm))
5344           && !(arg && ARGUMENT_PACK_P (arg)))
5345         {
5346           /* All remaining arguments will be placed in the
5347              template parameter pack PARM.  */
5348           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5349                                                 inner_args, arg_idx,
5350                                                 new_args, &lost,
5351                                                 in_decl, complain);
5352
5353           /* Store this argument.  */
5354           if (arg == error_mark_node)
5355             lost++;
5356           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5357
5358           /* We are done with all of the arguments.  */
5359           arg_idx = nargs;
5360           
5361           continue;
5362         }
5363       else if (arg)
5364         {
5365           if (PACK_EXPANSION_P (arg))
5366             {
5367               if (complain & tf_error)
5368                 {
5369                   /* FIXME this restriction was removed by N2555; see
5370                      bug 35722.  */
5371                   /* If ARG is a pack expansion, but PARM is not a
5372                      template parameter pack (if it were, we would have
5373                      handled it above), we're trying to expand into a
5374                      fixed-length argument list.  */
5375                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5376                     sorry ("cannot expand %<%E%> into a fixed-length "
5377                            "argument list", arg);
5378                   else
5379                     sorry ("cannot expand %<%T%> into a fixed-length "
5380                            "argument list", arg);
5381                 }
5382               return error_mark_node;
5383             }
5384         }
5385       else if (require_all_args)
5386         /* There must be a default arg in this case.  */
5387         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5388                                    complain, in_decl);
5389       else
5390         break;
5391
5392       if (arg == error_mark_node)
5393         {
5394           if (complain & tf_error)
5395             error ("template argument %d is invalid", arg_idx + 1);
5396         }
5397       else if (!arg)
5398         /* This only occurs if there was an error in the template
5399            parameter list itself (which we would already have
5400            reported) that we are trying to recover from, e.g., a class
5401            template with a parameter list such as
5402            template<typename..., typename>.  */
5403         return error_mark_node;
5404       else
5405         arg = convert_template_argument (TREE_VALUE (parm),
5406                                          arg, new_args, complain, 
5407                                          parm_idx, in_decl);
5408
5409       if (arg == error_mark_node)
5410         lost++;
5411       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5412     }
5413   skip_evaluation = saved_skip_evaluation;
5414
5415   if (lost)
5416     return error_mark_node;
5417
5418   return new_inner_args;
5419 }
5420
5421 /* Returns 1 if template args OT and NT are equivalent.  */
5422
5423 static int
5424 template_args_equal (tree ot, tree nt)
5425 {
5426   if (nt == ot)
5427     return 1;
5428
5429   if (TREE_CODE (nt) == TREE_VEC)
5430     /* For member templates */
5431     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5432   else if (PACK_EXPANSION_P (ot))
5433     return PACK_EXPANSION_P (nt) 
5434       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5435                               PACK_EXPANSION_PATTERN (nt));
5436   else if (ARGUMENT_PACK_P (ot))
5437     {
5438       int i, len;
5439       tree opack, npack;
5440
5441       if (!ARGUMENT_PACK_P (nt))
5442         return 0;
5443
5444       opack = ARGUMENT_PACK_ARGS (ot);
5445       npack = ARGUMENT_PACK_ARGS (nt);
5446       len = TREE_VEC_LENGTH (opack);
5447       if (TREE_VEC_LENGTH (npack) != len)
5448         return 0;
5449       for (i = 0; i < len; ++i)
5450         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5451                                   TREE_VEC_ELT (npack, i)))
5452           return 0;
5453       return 1;
5454     }
5455   else if (TYPE_P (nt))
5456     return TYPE_P (ot) && same_type_p (ot, nt);
5457   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5458     return 0;
5459   else
5460     return cp_tree_equal (ot, nt);
5461 }
5462
5463 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5464    of template arguments.  Returns 0 otherwise.  */
5465
5466 int
5467 comp_template_args (tree oldargs, tree newargs)
5468 {
5469   int i;
5470
5471   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5472     return 0;
5473
5474   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5475     {
5476       tree nt = TREE_VEC_ELT (newargs, i);
5477       tree ot = TREE_VEC_ELT (oldargs, i);
5478
5479       if (! template_args_equal (ot, nt))
5480         return 0;
5481     }
5482   return 1;
5483 }
5484
5485 static void
5486 add_pending_template (tree d)
5487 {
5488   tree ti = (TYPE_P (d)
5489              ? CLASSTYPE_TEMPLATE_INFO (d)
5490              : DECL_TEMPLATE_INFO (d));
5491   struct pending_template *pt;
5492   int level;
5493
5494   if (TI_PENDING_TEMPLATE_FLAG (ti))
5495     return;
5496
5497   /* We are called both from instantiate_decl, where we've already had a
5498      tinst_level pushed, and instantiate_template, where we haven't.
5499      Compensate.  */
5500   level = !current_tinst_level || current_tinst_level->decl != d;
5501
5502   if (level)
5503     push_tinst_level (d);
5504
5505   pt = GGC_NEW (struct pending_template);
5506   pt->next = NULL;
5507   pt->tinst = current_tinst_level;
5508   if (last_pending_template)
5509     last_pending_template->next = pt;
5510   else
5511     pending_templates = pt;
5512
5513   last_pending_template = pt;
5514
5515   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5516
5517   if (level)
5518     pop_tinst_level ();
5519 }
5520
5521
5522 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5523    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5524    documentation for TEMPLATE_ID_EXPR.  */
5525
5526 tree
5527 lookup_template_function (tree fns, tree arglist)
5528 {
5529   tree type;
5530
5531   if (fns == error_mark_node || arglist == error_mark_node)
5532     return error_mark_node;
5533
5534   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5535   gcc_assert (fns && (is_overloaded_fn (fns)
5536                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5537
5538   if (BASELINK_P (fns))
5539     {
5540       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5541                                          unknown_type_node,
5542                                          BASELINK_FUNCTIONS (fns),
5543                                          arglist);
5544       return fns;
5545     }
5546
5547   type = TREE_TYPE (fns);
5548   if (TREE_CODE (fns) == OVERLOAD || !type)
5549     type = unknown_type_node;
5550
5551   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5552 }
5553
5554 /* Within the scope of a template class S<T>, the name S gets bound
5555    (in build_self_reference) to a TYPE_DECL for the class, not a
5556    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5557    or one of its enclosing classes, and that type is a template,
5558    return the associated TEMPLATE_DECL.  Otherwise, the original
5559    DECL is returned.  */
5560
5561 tree
5562 maybe_get_template_decl_from_type_decl (tree decl)
5563 {
5564   return (decl != NULL_TREE
5565           && TREE_CODE (decl) == TYPE_DECL
5566           && DECL_ARTIFICIAL (decl)
5567           && CLASS_TYPE_P (TREE_TYPE (decl))
5568           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5569     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5570 }
5571
5572 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5573    parameters, find the desired type.
5574
5575    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5576
5577    IN_DECL, if non-NULL, is the template declaration we are trying to
5578    instantiate.
5579
5580    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5581    the class we are looking up.
5582
5583    Issue error and warning messages under control of COMPLAIN.
5584
5585    If the template class is really a local class in a template
5586    function, then the FUNCTION_CONTEXT is the function in which it is
5587    being instantiated.
5588
5589    ??? Note that this function is currently called *twice* for each
5590    template-id: the first time from the parser, while creating the
5591    incomplete type (finish_template_type), and the second type during the
5592    real instantiation (instantiate_template_class). This is surely something
5593    that we want to avoid. It also causes some problems with argument
5594    coercion (see convert_nontype_argument for more information on this).  */
5595
5596 tree
5597 lookup_template_class (tree d1,
5598                        tree arglist,
5599                        tree in_decl,
5600                        tree context,
5601                        int entering_scope,
5602                        tsubst_flags_t complain)
5603 {
5604   tree templ = NULL_TREE, parmlist;
5605   tree t;
5606
5607   timevar_push (TV_NAME_LOOKUP);
5608
5609   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5610     {
5611       tree value = innermost_non_namespace_value (d1);
5612       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5613         templ = value;
5614       else
5615         {
5616           if (context)
5617             push_decl_namespace (context);
5618           templ = lookup_name (d1);
5619           templ = maybe_get_template_decl_from_type_decl (templ);
5620           if (context)
5621             pop_decl_namespace ();
5622         }
5623       if (templ)
5624         context = DECL_CONTEXT (templ);
5625     }
5626   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5627     {
5628       tree type = TREE_TYPE (d1);
5629
5630       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5631          an implicit typename for the second A.  Deal with it.  */
5632       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5633         type = TREE_TYPE (type);
5634
5635       if (CLASSTYPE_TEMPLATE_INFO (type))
5636         {
5637           templ = CLASSTYPE_TI_TEMPLATE (type);
5638           d1 = DECL_NAME (templ);
5639         }
5640     }
5641   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5642            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5643     {
5644       templ = TYPE_TI_TEMPLATE (d1);
5645       d1 = DECL_NAME (templ);
5646     }
5647   else if (TREE_CODE (d1) == TEMPLATE_DECL
5648            && DECL_TEMPLATE_RESULT (d1)
5649            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5650     {
5651       templ = d1;
5652       d1 = DECL_NAME (templ);
5653       context = DECL_CONTEXT (templ);
5654     }
5655
5656   /* Issue an error message if we didn't find a template.  */
5657   if (! templ)
5658     {
5659       if (complain & tf_error)
5660         error ("%qT is not a template", d1);
5661       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5662     }
5663
5664   if (TREE_CODE (templ) != TEMPLATE_DECL
5665          /* Make sure it's a user visible template, if it was named by
5666             the user.  */
5667       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5668           && !PRIMARY_TEMPLATE_P (templ)))
5669     {
5670       if (complain & tf_error)
5671         {
5672           error ("non-template type %qT used as a template", d1);
5673           if (in_decl)
5674             error ("for template declaration %q+D", in_decl);
5675         }
5676       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5677     }
5678
5679   complain &= ~tf_user;
5680
5681   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5682     {
5683       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5684          template arguments */
5685
5686       tree parm;
5687       tree arglist2;
5688       tree outer;
5689
5690       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5691
5692       /* Consider an example where a template template parameter declared as
5693
5694            template <class T, class U = std::allocator<T> > class TT
5695
5696          The template parameter level of T and U are one level larger than
5697          of TT.  To proper process the default argument of U, say when an
5698          instantiation `TT<int>' is seen, we need to build the full
5699          arguments containing {int} as the innermost level.  Outer levels,
5700          available when not appearing as default template argument, can be
5701          obtained from the arguments of the enclosing template.
5702
5703          Suppose that TT is later substituted with std::vector.  The above
5704          instantiation is `TT<int, std::allocator<T> >' with TT at
5705          level 1, and T at level 2, while the template arguments at level 1
5706          becomes {std::vector} and the inner level 2 is {int}.  */
5707
5708       outer = DECL_CONTEXT (templ);
5709       if (outer)
5710         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5711       else if (current_template_parms)
5712         /* This is an argument of the current template, so we haven't set
5713            DECL_CONTEXT yet.  */
5714         outer = current_template_args ();
5715
5716       if (outer)
5717         arglist = add_to_template_args (outer, arglist);
5718
5719       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5720                                         complain,
5721                                         /*require_all_args=*/true,
5722                                         /*use_default_args=*/true);
5723       if (arglist2 == error_mark_node
5724           || (!uses_template_parms (arglist2)
5725               && check_instantiated_args (templ, arglist2, complain)))
5726         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5727
5728       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5729       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5730     }
5731   else
5732     {
5733       tree template_type = TREE_TYPE (templ);
5734       tree gen_tmpl;
5735       tree type_decl;
5736       tree found = NULL_TREE;
5737       int arg_depth;
5738       int parm_depth;
5739       int is_partial_instantiation;
5740
5741       gen_tmpl = most_general_template (templ);
5742       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5743       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5744       arg_depth = TMPL_ARGS_DEPTH (arglist);
5745
5746       if (arg_depth == 1 && parm_depth > 1)
5747         {
5748           /* We've been given an incomplete set of template arguments.
5749              For example, given:
5750
5751                template <class T> struct S1 {
5752                  template <class U> struct S2 {};
5753                  template <class U> struct S2<U*> {};
5754                 };
5755
5756              we will be called with an ARGLIST of `U*', but the
5757              TEMPLATE will be `template <class T> template
5758              <class U> struct S1<T>::S2'.  We must fill in the missing
5759              arguments.  */
5760           arglist
5761             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5762                                            arglist);
5763           arg_depth = TMPL_ARGS_DEPTH (arglist);
5764         }
5765
5766       /* Now we should have enough arguments.  */
5767       gcc_assert (parm_depth == arg_depth);
5768
5769       /* From here on, we're only interested in the most general
5770          template.  */
5771       templ = gen_tmpl;
5772
5773       /* Calculate the BOUND_ARGS.  These will be the args that are
5774          actually tsubst'd into the definition to create the
5775          instantiation.  */
5776       if (parm_depth > 1)
5777         {
5778           /* We have multiple levels of arguments to coerce, at once.  */
5779           int i;
5780           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5781
5782           tree bound_args = make_tree_vec (parm_depth);
5783
5784           for (i = saved_depth,
5785                  t = DECL_TEMPLATE_PARMS (templ);
5786                i > 0 && t != NULL_TREE;
5787                --i, t = TREE_CHAIN (t))
5788             {
5789               tree a = coerce_template_parms (TREE_VALUE (t),
5790                                               arglist, templ,
5791                                               complain,
5792                                               /*require_all_args=*/true,
5793                                               /*use_default_args=*/true);
5794
5795               /* Don't process further if one of the levels fails.  */
5796               if (a == error_mark_node)
5797                 {
5798                   /* Restore the ARGLIST to its full size.  */
5799                   TREE_VEC_LENGTH (arglist) = saved_depth;
5800                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5801                 }
5802
5803               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5804
5805               /* We temporarily reduce the length of the ARGLIST so
5806                  that coerce_template_parms will see only the arguments
5807                  corresponding to the template parameters it is
5808                  examining.  */
5809               TREE_VEC_LENGTH (arglist)--;
5810             }
5811
5812           /* Restore the ARGLIST to its full size.  */
5813           TREE_VEC_LENGTH (arglist) = saved_depth;
5814
5815           arglist = bound_args;
5816         }
5817       else
5818         arglist
5819           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5820                                    INNERMOST_TEMPLATE_ARGS (arglist),
5821                                    templ,
5822                                    complain,
5823                                    /*require_all_args=*/true,
5824                                    /*use_default_args=*/true);
5825
5826       if (arglist == error_mark_node)
5827         /* We were unable to bind the arguments.  */
5828         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5829
5830       /* In the scope of a template class, explicit references to the
5831          template class refer to the type of the template, not any
5832          instantiation of it.  For example, in:
5833
5834            template <class T> class C { void f(C<T>); }
5835
5836          the `C<T>' is just the same as `C'.  Outside of the
5837          class, however, such a reference is an instantiation.  */
5838       if (comp_template_args (TYPE_TI_ARGS (template_type),
5839                               arglist))
5840         {
5841           found = template_type;
5842
5843           if (!entering_scope && PRIMARY_TEMPLATE_P (templ))
5844             {
5845               tree ctx;
5846
5847               for (ctx = current_class_type;
5848                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5849                    ctx = (TYPE_P (ctx)
5850                           ? TYPE_CONTEXT (ctx)
5851                           : DECL_CONTEXT (ctx)))
5852                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5853                   goto found_ctx;
5854
5855               /* We're not in the scope of the class, so the
5856                  TEMPLATE_TYPE is not the type we want after all.  */
5857               found = NULL_TREE;
5858             found_ctx:;
5859             }
5860         }
5861       if (found)
5862         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5863
5864       /* If we already have this specialization, return it.  */
5865       found = retrieve_specialization (templ, arglist,
5866                                        /*class_specializations_p=*/false);
5867       if (found)
5868         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5869
5870       /* This type is a "partial instantiation" if any of the template
5871          arguments still involve template parameters.  Note that we set
5872          IS_PARTIAL_INSTANTIATION for partial specializations as
5873          well.  */
5874       is_partial_instantiation = uses_template_parms (arglist);
5875
5876       /* If the deduced arguments are invalid, then the binding
5877          failed.  */
5878       if (!is_partial_instantiation
5879           && check_instantiated_args (templ,
5880                                       INNERMOST_TEMPLATE_ARGS (arglist),
5881                                       complain))
5882         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5883
5884       if (!is_partial_instantiation
5885           && !PRIMARY_TEMPLATE_P (templ)
5886           && TREE_CODE (CP_DECL_CONTEXT (templ)) == NAMESPACE_DECL)
5887         {
5888           found = xref_tag_from_type (TREE_TYPE (templ),
5889                                       DECL_NAME (templ),
5890                                       /*tag_scope=*/ts_global);
5891           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5892         }
5893
5894       context = tsubst (DECL_CONTEXT (templ), arglist,
5895                         complain, in_decl);
5896       if (!context)
5897         context = global_namespace;
5898
5899       /* Create the type.  */
5900       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5901         {
5902           if (!is_partial_instantiation)
5903             {
5904               set_current_access_from_decl (TYPE_NAME (template_type));
5905               t = start_enum (TYPE_IDENTIFIER (template_type),
5906                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
5907                                       arglist, complain, in_decl),
5908                               SCOPED_ENUM_P (template_type));
5909             }
5910           else
5911             {
5912               /* We don't want to call start_enum for this type, since
5913                  the values for the enumeration constants may involve
5914                  template parameters.  And, no one should be interested
5915                  in the enumeration constants for such a type.  */
5916               t = make_node (ENUMERAL_TYPE);
5917               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
5918             }
5919         }
5920       else
5921         {
5922           t = make_class_type (TREE_CODE (template_type));
5923           CLASSTYPE_DECLARED_CLASS (t)
5924             = CLASSTYPE_DECLARED_CLASS (template_type);
5925           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5926           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5927
5928           /* A local class.  Make sure the decl gets registered properly.  */
5929           if (context == current_function_decl)
5930             pushtag (DECL_NAME (templ), t, /*tag_scope=*/ts_current);
5931
5932           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5933             /* This instantiation is another name for the primary
5934                template type. Set the TYPE_CANONICAL field
5935                appropriately. */
5936             TYPE_CANONICAL (t) = template_type;
5937           else if (any_template_arguments_need_structural_equality_p (arglist))
5938             /* Some of the template arguments require structural
5939                equality testing, so this template class requires
5940                structural equality testing. */
5941             SET_TYPE_STRUCTURAL_EQUALITY (t);
5942         }
5943
5944       /* If we called start_enum or pushtag above, this information
5945          will already be set up.  */
5946       if (!TYPE_NAME (t))
5947         {
5948           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5949
5950           type_decl = create_implicit_typedef (DECL_NAME (templ), t);
5951           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5952           TYPE_STUB_DECL (t) = type_decl;
5953           DECL_SOURCE_LOCATION (type_decl)
5954             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5955         }
5956       else
5957         type_decl = TYPE_NAME (t);
5958
5959       TREE_PRIVATE (type_decl)
5960         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5961       TREE_PROTECTED (type_decl)
5962         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5963       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5964         {
5965           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5966           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5967         }
5968
5969       /* Set up the template information.  We have to figure out which
5970          template is the immediate parent if this is a full
5971          instantiation.  */
5972       if (parm_depth == 1 || is_partial_instantiation
5973           || !PRIMARY_TEMPLATE_P (templ))
5974         /* This case is easy; there are no member templates involved.  */
5975         found = templ;
5976       else
5977         {
5978           /* This is a full instantiation of a member template.  Look
5979              for a partial instantiation of which this is an instance.  */
5980
5981           for (found = DECL_TEMPLATE_INSTANTIATIONS (templ);
5982                found; found = TREE_CHAIN (found))
5983             {
5984               int success;
5985               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5986
5987               /* We only want partial instantiations, here, not
5988                  specializations or full instantiations.  */
5989               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5990                   || !uses_template_parms (TREE_VALUE (found)))
5991                 continue;
5992
5993               /* Temporarily reduce by one the number of levels in the
5994                  ARGLIST and in FOUND so as to avoid comparing the
5995                  last set of arguments.  */
5996               TREE_VEC_LENGTH (arglist)--;
5997               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5998
5999               /* See if the arguments match.  If they do, then TMPL is
6000                  the partial instantiation we want.  */
6001               success = comp_template_args (TREE_PURPOSE (found), arglist);
6002
6003               /* Restore the argument vectors to their full size.  */
6004               TREE_VEC_LENGTH (arglist)++;
6005               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
6006
6007               if (success)
6008                 {
6009                   found = tmpl;
6010                   break;
6011                 }
6012             }
6013
6014           if (!found)
6015             {
6016               /* There was no partial instantiation. This happens
6017                  where C<T> is a member template of A<T> and it's used
6018                  in something like
6019
6020                   template <typename T> struct B { A<T>::C<int> m; };
6021                   B<float>;
6022
6023                  Create the partial instantiation.
6024                */
6025               TREE_VEC_LENGTH (arglist)--;
6026               found = tsubst (templ, arglist, complain, NULL_TREE);
6027               TREE_VEC_LENGTH (arglist)++;
6028             }
6029         }
6030
6031       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6032       DECL_TEMPLATE_INSTANTIATIONS (templ)
6033         = tree_cons (arglist, t,
6034                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6035
6036       if (TREE_CODE (t) == ENUMERAL_TYPE
6037           && !is_partial_instantiation)
6038         /* Now that the type has been registered on the instantiations
6039            list, we set up the enumerators.  Because the enumeration
6040            constants may involve the enumeration type itself, we make
6041            sure to register the type first, and then create the
6042            constants.  That way, doing tsubst_expr for the enumeration
6043            constants won't result in recursive calls here; we'll find
6044            the instantiation and exit above.  */
6045         tsubst_enum (template_type, t, arglist);
6046
6047       if (is_partial_instantiation)
6048         /* If the type makes use of template parameters, the
6049            code that generates debugging information will crash.  */
6050         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6051
6052       /* Possibly limit visibility based on template args.  */
6053       TREE_PUBLIC (type_decl) = 1;
6054       determine_visibility (type_decl);
6055
6056       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6057     }
6058   timevar_pop (TV_NAME_LOOKUP);
6059 }
6060 \f
6061 struct pair_fn_data
6062 {
6063   tree_fn_t fn;
6064   void *data;
6065   /* True when we should also visit template parameters that occur in
6066      non-deduced contexts.  */
6067   bool include_nondeduced_p;
6068   struct pointer_set_t *visited;
6069 };
6070
6071 /* Called from for_each_template_parm via walk_tree.  */
6072
6073 static tree
6074 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6075 {
6076   tree t = *tp;
6077   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6078   tree_fn_t fn = pfd->fn;
6079   void *data = pfd->data;
6080
6081   if (TYPE_P (t)
6082       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6083       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6084                                  pfd->include_nondeduced_p))
6085     return error_mark_node;
6086
6087   switch (TREE_CODE (t))
6088     {
6089     case RECORD_TYPE:
6090       if (TYPE_PTRMEMFUNC_P (t))
6091         break;
6092       /* Fall through.  */
6093
6094     case UNION_TYPE:
6095     case ENUMERAL_TYPE:
6096       if (!TYPE_TEMPLATE_INFO (t))
6097         *walk_subtrees = 0;
6098       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6099                                        fn, data, pfd->visited, 
6100                                        pfd->include_nondeduced_p))
6101         return error_mark_node;
6102       break;
6103
6104     case INTEGER_TYPE:
6105       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6106                                   fn, data, pfd->visited, 
6107                                   pfd->include_nondeduced_p)
6108           || for_each_template_parm (TYPE_MAX_VALUE (t),
6109                                      fn, data, pfd->visited,
6110                                      pfd->include_nondeduced_p))
6111         return error_mark_node;
6112       break;
6113
6114     case METHOD_TYPE:
6115       /* Since we're not going to walk subtrees, we have to do this
6116          explicitly here.  */
6117       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6118                                   pfd->visited, pfd->include_nondeduced_p))
6119         return error_mark_node;
6120       /* Fall through.  */
6121
6122     case FUNCTION_TYPE:
6123       /* Check the return type.  */
6124       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6125                                   pfd->include_nondeduced_p))
6126         return error_mark_node;
6127
6128       /* Check the parameter types.  Since default arguments are not
6129          instantiated until they are needed, the TYPE_ARG_TYPES may
6130          contain expressions that involve template parameters.  But,
6131          no-one should be looking at them yet.  And, once they're
6132          instantiated, they don't contain template parameters, so
6133          there's no point in looking at them then, either.  */
6134       {
6135         tree parm;
6136
6137         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6138           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6139                                       pfd->visited, pfd->include_nondeduced_p))
6140             return error_mark_node;
6141
6142         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6143            want walk_tree walking into them itself.  */
6144         *walk_subtrees = 0;
6145       }
6146       break;
6147
6148     case TYPEOF_TYPE:
6149       if (pfd->include_nondeduced_p
6150           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6151                                      pfd->visited, 
6152                                      pfd->include_nondeduced_p))
6153         return error_mark_node;
6154       break;
6155
6156     case FUNCTION_DECL:
6157     case VAR_DECL:
6158       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6159           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6160                                      pfd->visited, pfd->include_nondeduced_p))
6161         return error_mark_node;
6162       /* Fall through.  */
6163
6164     case PARM_DECL:
6165     case CONST_DECL:
6166       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6167           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6168                                      pfd->visited, pfd->include_nondeduced_p))
6169         return error_mark_node;
6170       if (DECL_CONTEXT (t)
6171           && pfd->include_nondeduced_p
6172           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6173                                      pfd->visited, pfd->include_nondeduced_p))
6174         return error_mark_node;
6175       break;
6176
6177     case BOUND_TEMPLATE_TEMPLATE_PARM:
6178       /* Record template parameters such as `T' inside `TT<T>'.  */
6179       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6180                                   pfd->include_nondeduced_p))
6181         return error_mark_node;
6182       /* Fall through.  */
6183
6184     case TEMPLATE_TEMPLATE_PARM:
6185     case TEMPLATE_TYPE_PARM:
6186     case TEMPLATE_PARM_INDEX:
6187       if (fn && (*fn)(t, data))
6188         return error_mark_node;
6189       else if (!fn)
6190         return error_mark_node;
6191       break;
6192
6193     case TEMPLATE_DECL:
6194       /* A template template parameter is encountered.  */
6195       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6196           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6197                                      pfd->include_nondeduced_p))
6198         return error_mark_node;
6199
6200       /* Already substituted template template parameter */
6201       *walk_subtrees = 0;
6202       break;
6203
6204     case TYPENAME_TYPE:
6205       if (!fn
6206           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6207                                      data, pfd->visited, 
6208                                      pfd->include_nondeduced_p))
6209         return error_mark_node;
6210       break;
6211
6212     case CONSTRUCTOR:
6213       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6214           && pfd->include_nondeduced_p
6215           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6216                                      (TREE_TYPE (t)), fn, data,
6217                                      pfd->visited, pfd->include_nondeduced_p))
6218         return error_mark_node;
6219       break;
6220
6221     case INDIRECT_REF:
6222     case COMPONENT_REF:
6223       /* If there's no type, then this thing must be some expression
6224          involving template parameters.  */
6225       if (!fn && !TREE_TYPE (t))
6226         return error_mark_node;
6227       break;
6228
6229     case MODOP_EXPR:
6230     case CAST_EXPR:
6231     case REINTERPRET_CAST_EXPR:
6232     case CONST_CAST_EXPR:
6233     case STATIC_CAST_EXPR:
6234     case DYNAMIC_CAST_EXPR:
6235     case ARROW_EXPR:
6236     case DOTSTAR_EXPR:
6237     case TYPEID_EXPR:
6238     case PSEUDO_DTOR_EXPR:
6239       if (!fn)
6240         return error_mark_node;
6241       break;
6242
6243     default:
6244       break;
6245     }
6246
6247   /* We didn't find any template parameters we liked.  */
6248   return NULL_TREE;
6249 }
6250
6251 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6252    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6253    call FN with the parameter and the DATA.
6254    If FN returns nonzero, the iteration is terminated, and
6255    for_each_template_parm returns 1.  Otherwise, the iteration
6256    continues.  If FN never returns a nonzero value, the value
6257    returned by for_each_template_parm is 0.  If FN is NULL, it is
6258    considered to be the function which always returns 1.
6259
6260    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6261    parameters that occur in non-deduced contexts.  When false, only
6262    visits those template parameters that can be deduced.  */
6263
6264 static int
6265 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6266                         struct pointer_set_t *visited,
6267                         bool include_nondeduced_p)
6268 {
6269   struct pair_fn_data pfd;
6270   int result;
6271
6272   /* Set up.  */
6273   pfd.fn = fn;
6274   pfd.data = data;
6275   pfd.include_nondeduced_p = include_nondeduced_p;
6276
6277   /* Walk the tree.  (Conceptually, we would like to walk without
6278      duplicates, but for_each_template_parm_r recursively calls
6279      for_each_template_parm, so we would need to reorganize a fair
6280      bit to use walk_tree_without_duplicates, so we keep our own
6281      visited list.)  */
6282   if (visited)
6283     pfd.visited = visited;
6284   else
6285     pfd.visited = pointer_set_create ();
6286   result = cp_walk_tree (&t,
6287                          for_each_template_parm_r,
6288                          &pfd,
6289                          pfd.visited) != NULL_TREE;
6290
6291   /* Clean up.  */
6292   if (!visited)
6293     {
6294       pointer_set_destroy (pfd.visited);
6295       pfd.visited = 0;
6296     }
6297
6298   return result;
6299 }
6300
6301 /* Returns true if T depends on any template parameter.  */
6302
6303 int
6304 uses_template_parms (tree t)
6305 {
6306   bool dependent_p;
6307   int saved_processing_template_decl;
6308
6309   saved_processing_template_decl = processing_template_decl;
6310   if (!saved_processing_template_decl)
6311     processing_template_decl = 1;
6312   if (TYPE_P (t))
6313     dependent_p = dependent_type_p (t);
6314   else if (TREE_CODE (t) == TREE_VEC)
6315     dependent_p = any_dependent_template_arguments_p (t);
6316   else if (TREE_CODE (t) == TREE_LIST)
6317     dependent_p = (uses_template_parms (TREE_VALUE (t))
6318                    || uses_template_parms (TREE_CHAIN (t)));
6319   else if (TREE_CODE (t) == TYPE_DECL)
6320     dependent_p = dependent_type_p (TREE_TYPE (t));
6321   else if (DECL_P (t)
6322            || EXPR_P (t)
6323            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6324            || TREE_CODE (t) == OVERLOAD
6325            || TREE_CODE (t) == BASELINK
6326            || TREE_CODE (t) == IDENTIFIER_NODE
6327            || TREE_CODE (t) == TRAIT_EXPR
6328            || TREE_CODE (t) == CONSTRUCTOR
6329            || CONSTANT_CLASS_P (t))
6330     dependent_p = (type_dependent_expression_p (t)
6331                    || value_dependent_expression_p (t));
6332   else
6333     {
6334       gcc_assert (t == error_mark_node);
6335       dependent_p = false;
6336     }
6337
6338   processing_template_decl = saved_processing_template_decl;
6339
6340   return dependent_p;
6341 }
6342
6343 /* Returns true if T depends on any template parameter with level LEVEL.  */
6344
6345 int
6346 uses_template_parms_level (tree t, int level)
6347 {
6348   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6349                                  /*include_nondeduced_p=*/true);
6350 }
6351
6352 static int tinst_depth;
6353 extern int max_tinst_depth;
6354 #ifdef GATHER_STATISTICS
6355 int depth_reached;
6356 #endif
6357 static int tinst_level_tick;
6358 static int last_template_error_tick;
6359
6360 /* We're starting to instantiate D; record the template instantiation context
6361    for diagnostics and to restore it later.  */
6362
6363 static int
6364 push_tinst_level (tree d)
6365 {
6366   struct tinst_level *new_level;
6367
6368   if (tinst_depth >= max_tinst_depth)
6369     {
6370       /* If the instantiation in question still has unbound template parms,
6371          we don't really care if we can't instantiate it, so just return.
6372          This happens with base instantiation for implicit `typename'.  */
6373       if (uses_template_parms (d))
6374         return 0;
6375
6376       last_template_error_tick = tinst_level_tick;
6377       error ("template instantiation depth exceeds maximum of %d (use "
6378              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6379              max_tinst_depth, d);
6380
6381       print_instantiation_context ();
6382
6383       return 0;
6384     }
6385
6386   new_level = GGC_NEW (struct tinst_level);
6387   new_level->decl = d;
6388   new_level->locus = input_location;
6389   new_level->in_system_header_p = in_system_header;
6390   new_level->next = current_tinst_level;
6391   current_tinst_level = new_level;
6392
6393   ++tinst_depth;
6394 #ifdef GATHER_STATISTICS
6395   if (tinst_depth > depth_reached)
6396     depth_reached = tinst_depth;
6397 #endif
6398
6399   ++tinst_level_tick;
6400   return 1;
6401 }
6402
6403 /* We're done instantiating this template; return to the instantiation
6404    context.  */
6405
6406 static void
6407 pop_tinst_level (void)
6408 {
6409   /* Restore the filename and line number stashed away when we started
6410      this instantiation.  */
6411   input_location = current_tinst_level->locus;
6412   current_tinst_level = current_tinst_level->next;
6413   --tinst_depth;
6414   ++tinst_level_tick;
6415 }
6416
6417 /* We're instantiating a deferred template; restore the template
6418    instantiation context in which the instantiation was requested, which
6419    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6420
6421 static tree
6422 reopen_tinst_level (struct tinst_level *level)
6423 {
6424   struct tinst_level *t;
6425
6426   tinst_depth = 0;
6427   for (t = level; t; t = t->next)
6428     ++tinst_depth;
6429
6430   current_tinst_level = level;
6431   pop_tinst_level ();
6432   return level->decl;
6433 }
6434
6435 /* Returns the TINST_LEVEL which gives the original instantiation
6436    context.  */
6437
6438 struct tinst_level *
6439 outermost_tinst_level (void)
6440 {
6441   struct tinst_level *level = current_tinst_level;
6442   if (level)
6443     while (level->next)
6444       level = level->next;
6445   return level;
6446 }
6447
6448 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6449
6450 bool
6451 parameter_of_template_p (tree parm, tree templ)
6452 {
6453   tree parms;
6454   int i;
6455
6456   if (!parm || !templ)
6457     return false;
6458
6459   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6460   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6461
6462   parms = DECL_TEMPLATE_PARMS (templ);
6463   parms = INNERMOST_TEMPLATE_PARMS (parms);
6464
6465   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6466     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6467       return true;
6468
6469   return false;
6470 }
6471
6472 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6473    vector of template arguments, as for tsubst.
6474
6475    Returns an appropriate tsubst'd friend declaration.  */
6476
6477 static tree
6478 tsubst_friend_function (tree decl, tree args)
6479 {
6480   tree new_friend;
6481
6482   if (TREE_CODE (decl) == FUNCTION_DECL
6483       && DECL_TEMPLATE_INSTANTIATION (decl)
6484       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6485     /* This was a friend declared with an explicit template
6486        argument list, e.g.:
6487
6488        friend void f<>(T);
6489
6490        to indicate that f was a template instantiation, not a new
6491        function declaration.  Now, we have to figure out what
6492        instantiation of what template.  */
6493     {
6494       tree template_id, arglist, fns;
6495       tree new_args;
6496       tree tmpl;
6497       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6498
6499       /* Friend functions are looked up in the containing namespace scope.
6500          We must enter that scope, to avoid finding member functions of the
6501          current class with same name.  */
6502       push_nested_namespace (ns);
6503       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6504                          tf_warning_or_error, NULL_TREE,
6505                          /*integral_constant_expression_p=*/false);
6506       pop_nested_namespace (ns);
6507       arglist = tsubst (DECL_TI_ARGS (decl), args,
6508                         tf_warning_or_error, NULL_TREE);
6509       template_id = lookup_template_function (fns, arglist);
6510
6511       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6512       tmpl = determine_specialization (template_id, new_friend,
6513                                        &new_args,
6514                                        /*need_member_template=*/0,
6515                                        TREE_VEC_LENGTH (args),
6516                                        tsk_none);
6517       return instantiate_template (tmpl, new_args, tf_error);
6518     }
6519
6520   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6521
6522   /* The NEW_FRIEND will look like an instantiation, to the
6523      compiler, but is not an instantiation from the point of view of
6524      the language.  For example, we might have had:
6525
6526      template <class T> struct S {
6527        template <class U> friend void f(T, U);
6528      };
6529
6530      Then, in S<int>, template <class U> void f(int, U) is not an
6531      instantiation of anything.  */
6532   if (new_friend == error_mark_node)
6533     return error_mark_node;
6534
6535   DECL_USE_TEMPLATE (new_friend) = 0;
6536   if (TREE_CODE (decl) == TEMPLATE_DECL)
6537     {
6538       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6539       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6540         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6541     }
6542
6543   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6544      is not a template instantiation and should not be mangled like
6545      one.  Therefore, we forget the mangling here; we'll recompute it
6546      later if we need it.  */
6547   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6548     {
6549       SET_DECL_RTL (new_friend, NULL_RTX);
6550       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6551     }
6552
6553   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6554     {
6555       tree old_decl;
6556       tree new_friend_template_info;
6557       tree new_friend_result_template_info;
6558       tree ns;
6559       int  new_friend_is_defn;
6560
6561       /* We must save some information from NEW_FRIEND before calling
6562          duplicate decls since that function will free NEW_FRIEND if
6563          possible.  */
6564       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6565       new_friend_is_defn =
6566             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6567                            (template_for_substitution (new_friend)))
6568              != NULL_TREE);
6569       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6570         {
6571           /* This declaration is a `primary' template.  */
6572           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6573
6574           new_friend_result_template_info
6575             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6576         }
6577       else
6578         new_friend_result_template_info = NULL_TREE;
6579
6580       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6581       if (new_friend_is_defn)
6582         DECL_INITIAL (new_friend) = error_mark_node;
6583
6584       /* Inside pushdecl_namespace_level, we will push into the
6585          current namespace. However, the friend function should go
6586          into the namespace of the template.  */
6587       ns = decl_namespace_context (new_friend);
6588       push_nested_namespace (ns);
6589       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6590       pop_nested_namespace (ns);
6591
6592       if (old_decl == error_mark_node)
6593         return error_mark_node;
6594
6595       if (old_decl != new_friend)
6596         {
6597           /* This new friend declaration matched an existing
6598              declaration.  For example, given:
6599
6600                template <class T> void f(T);
6601                template <class U> class C {
6602                  template <class T> friend void f(T) {}
6603                };
6604
6605              the friend declaration actually provides the definition
6606              of `f', once C has been instantiated for some type.  So,
6607              old_decl will be the out-of-class template declaration,
6608              while new_friend is the in-class definition.
6609
6610              But, if `f' was called before this point, the
6611              instantiation of `f' will have DECL_TI_ARGS corresponding
6612              to `T' but not to `U', references to which might appear
6613              in the definition of `f'.  Previously, the most general
6614              template for an instantiation of `f' was the out-of-class
6615              version; now it is the in-class version.  Therefore, we
6616              run through all specialization of `f', adding to their
6617              DECL_TI_ARGS appropriately.  In particular, they need a
6618              new set of outer arguments, corresponding to the
6619              arguments for this class instantiation.
6620
6621              The same situation can arise with something like this:
6622
6623                friend void f(int);
6624                template <class T> class C {
6625                  friend void f(T) {}
6626                };
6627
6628              when `C<int>' is instantiated.  Now, `f(int)' is defined
6629              in the class.  */
6630
6631           if (!new_friend_is_defn)
6632             /* On the other hand, if the in-class declaration does
6633                *not* provide a definition, then we don't want to alter
6634                existing definitions.  We can just leave everything
6635                alone.  */
6636             ;
6637           else
6638             {
6639               /* Overwrite whatever template info was there before, if
6640                  any, with the new template information pertaining to
6641                  the declaration.  */
6642               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6643
6644               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6645                 reregister_specialization (new_friend,
6646                                            most_general_template (old_decl),
6647                                            old_decl);
6648               else
6649                 {
6650                   tree t;
6651                   tree new_friend_args;
6652
6653                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6654                     = new_friend_result_template_info;
6655
6656                   new_friend_args = TI_ARGS (new_friend_template_info);
6657                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6658                        t != NULL_TREE;
6659                        t = TREE_CHAIN (t))
6660                     {
6661                       tree spec = TREE_VALUE (t);
6662
6663                       DECL_TI_ARGS (spec)
6664                         = add_outermost_template_args (new_friend_args,
6665                                                        DECL_TI_ARGS (spec));
6666                     }
6667
6668                   /* Now, since specializations are always supposed to
6669                      hang off of the most general template, we must move
6670                      them.  */
6671                   t = most_general_template (old_decl);
6672                   if (t != old_decl)
6673                     {
6674                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6675                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6676                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6677                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6678                     }
6679                 }
6680             }
6681
6682           /* The information from NEW_FRIEND has been merged into OLD_DECL
6683              by duplicate_decls.  */
6684           new_friend = old_decl;
6685         }
6686     }
6687   else
6688     {
6689       tree context = DECL_CONTEXT (new_friend);
6690       bool dependent_p;
6691
6692       /* In the code
6693            template <class T> class C {
6694              template <class U> friend void C1<U>::f (); // case 1
6695              friend void C2<T>::f ();                    // case 2
6696            };
6697          we only need to make sure CONTEXT is a complete type for
6698          case 2.  To distinguish between the two cases, we note that
6699          CONTEXT of case 1 remains dependent type after tsubst while
6700          this isn't true for case 2.  */
6701       ++processing_template_decl;
6702       dependent_p = dependent_type_p (context);
6703       --processing_template_decl;
6704
6705       if (!dependent_p
6706           && !complete_type_or_else (context, NULL_TREE))
6707         return error_mark_node;
6708
6709       if (COMPLETE_TYPE_P (context))
6710         {
6711           /* Check to see that the declaration is really present, and,
6712              possibly obtain an improved declaration.  */
6713           tree fn = check_classfn (context,
6714                                    new_friend, NULL_TREE);
6715
6716           if (fn)
6717             new_friend = fn;
6718         }
6719     }
6720
6721   return new_friend;
6722 }
6723
6724 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6725    template arguments, as for tsubst.
6726
6727    Returns an appropriate tsubst'd friend type or error_mark_node on
6728    failure.  */
6729
6730 static tree
6731 tsubst_friend_class (tree friend_tmpl, tree args)
6732 {
6733   tree friend_type;
6734   tree tmpl;
6735   tree context;
6736
6737   context = DECL_CONTEXT (friend_tmpl);
6738
6739   if (context)
6740     {
6741       if (TREE_CODE (context) == NAMESPACE_DECL)
6742         push_nested_namespace (context);
6743       else
6744         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6745     }
6746
6747   /* Look for a class template declaration.  We look for hidden names
6748      because two friend declarations of the same template are the
6749      same.  For example, in:
6750
6751        struct A { 
6752          template <typename> friend class F;
6753        };
6754        template <typename> struct B { 
6755          template <typename> friend class F;
6756        };
6757
6758      both F templates are the same.  */
6759   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6760                            /*block_p=*/true, 0, 
6761                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6762
6763   /* But, if we don't find one, it might be because we're in a
6764      situation like this:
6765
6766        template <class T>
6767        struct S {
6768          template <class U>
6769          friend struct S;
6770        };
6771
6772      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6773      for `S<int>', not the TEMPLATE_DECL.  */
6774   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6775     {
6776       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6777       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6778     }
6779
6780   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6781     {
6782       /* The friend template has already been declared.  Just
6783          check to see that the declarations match, and install any new
6784          default parameters.  We must tsubst the default parameters,
6785          of course.  We only need the innermost template parameters
6786          because that is all that redeclare_class_template will look
6787          at.  */
6788       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6789           > TMPL_ARGS_DEPTH (args))
6790         {
6791           tree parms;
6792           location_t saved_input_location;
6793           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6794                                          args, tf_warning_or_error);
6795
6796           saved_input_location = input_location;
6797           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6798           redeclare_class_template (TREE_TYPE (tmpl), parms);
6799           input_location = saved_input_location;
6800           
6801         }
6802
6803       friend_type = TREE_TYPE (tmpl);
6804     }
6805   else
6806     {
6807       /* The friend template has not already been declared.  In this
6808          case, the instantiation of the template class will cause the
6809          injection of this template into the global scope.  */
6810       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6811       if (tmpl == error_mark_node)
6812         return error_mark_node;
6813
6814       /* The new TMPL is not an instantiation of anything, so we
6815          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6816          the new type because that is supposed to be the corresponding
6817          template decl, i.e., TMPL.  */
6818       DECL_USE_TEMPLATE (tmpl) = 0;
6819       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6820       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6821       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6822         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6823
6824       /* Inject this template into the global scope.  */
6825       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6826     }
6827
6828   if (context)
6829     {
6830       if (TREE_CODE (context) == NAMESPACE_DECL)
6831         pop_nested_namespace (context);
6832       else
6833         pop_nested_class ();
6834     }
6835
6836   return friend_type;
6837 }
6838
6839 /* Returns zero if TYPE cannot be completed later due to circularity.
6840    Otherwise returns one.  */
6841
6842 static int
6843 can_complete_type_without_circularity (tree type)
6844 {
6845   if (type == NULL_TREE || type == error_mark_node)
6846     return 0;
6847   else if (COMPLETE_TYPE_P (type))
6848     return 1;
6849   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6850     return can_complete_type_without_circularity (TREE_TYPE (type));
6851   else if (CLASS_TYPE_P (type)
6852            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6853     return 0;
6854   else
6855     return 1;
6856 }
6857
6858 /* Apply any attributes which had to be deferred until instantiation
6859    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6860    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6861
6862 static void
6863 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6864                                 tree args, tsubst_flags_t complain, tree in_decl)
6865 {
6866   tree last_dep = NULL_TREE;
6867   tree t;
6868   tree *p;
6869
6870   for (t = attributes; t; t = TREE_CHAIN (t))
6871     if (ATTR_IS_DEPENDENT (t))
6872       {
6873         last_dep = t;
6874         attributes = copy_list (attributes);
6875         break;
6876       }
6877
6878   if (DECL_P (*decl_p))
6879     {
6880       if (TREE_TYPE (*decl_p) == error_mark_node)
6881         return;
6882       p = &DECL_ATTRIBUTES (*decl_p);
6883     }
6884   else
6885     p = &TYPE_ATTRIBUTES (*decl_p);
6886
6887   if (last_dep)
6888     {
6889       tree late_attrs = NULL_TREE;
6890       tree *q = &late_attrs;
6891
6892       for (*p = attributes; *p; )
6893         {
6894           t = *p;
6895           if (ATTR_IS_DEPENDENT (t))
6896             {
6897               *p = TREE_CHAIN (t);
6898               TREE_CHAIN (t) = NULL_TREE;
6899               /* If the first attribute argument is an identifier, don't
6900                  pass it through tsubst.  Attributes like mode, format,
6901                  cleanup and several target specific attributes expect it
6902                  unmodified.  */
6903               if (TREE_VALUE (t)
6904                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6905                   && TREE_VALUE (TREE_VALUE (t))
6906                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6907                       == IDENTIFIER_NODE))
6908                 {
6909                   tree chain
6910                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6911                                    in_decl,
6912                                    /*integral_constant_expression_p=*/false);
6913                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6914                     TREE_VALUE (t)
6915                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6916                                    chain);
6917                 }
6918               else
6919                 TREE_VALUE (t)
6920                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6921                                  /*integral_constant_expression_p=*/false);
6922               *q = t;
6923               q = &TREE_CHAIN (t);
6924             }
6925           else
6926             p = &TREE_CHAIN (t);
6927         }
6928
6929       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6930     }
6931 }
6932
6933 /* Perform (or defer) access check for typedefs that were referenced
6934    from within the template TMPL code.
6935    This is a subroutine of instantiate_template and instantiate_class_template.
6936    TMPL is the template to consider and TARGS is the list of arguments of
6937    that template.  */
6938
6939 static void
6940 perform_typedefs_access_check (tree tmpl, tree targs)
6941 {
6942   tree t;
6943
6944   if (!tmpl || TREE_CODE (tmpl) != TEMPLATE_DECL)
6945     return;
6946
6947   for (t = MEMBER_TYPES_NEEDING_ACCESS_CHECK (tmpl); t; t = TREE_CHAIN (t))
6948     {
6949       tree type_decl = TREE_PURPOSE (t);
6950       tree type_scope = TREE_VALUE (t);
6951
6952       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
6953         continue;
6954
6955       if (uses_template_parms (type_decl))
6956         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
6957       if (uses_template_parms (type_scope))
6958         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
6959
6960       perform_or_defer_access_check (TYPE_BINFO (type_scope), type_decl, type_decl);
6961     }
6962 }
6963
6964 tree
6965 instantiate_class_template (tree type)
6966 {
6967   tree templ, args, pattern, t, member;
6968   tree typedecl;
6969   tree pbinfo;
6970   tree base_list;
6971
6972   if (type == error_mark_node)
6973     return error_mark_node;
6974
6975   if (TYPE_BEING_DEFINED (type)
6976       || COMPLETE_TYPE_P (type)
6977       || dependent_type_p (type))
6978     return type;
6979
6980   /* Figure out which template is being instantiated.  */
6981   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6982   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6983
6984   /* Determine what specialization of the original template to
6985      instantiate.  */
6986   t = most_specialized_class (type, templ);
6987   if (t == error_mark_node)
6988     {
6989       TYPE_BEING_DEFINED (type) = 1;
6990       return error_mark_node;
6991     }
6992   else if (t)
6993     {
6994       /* This TYPE is actually an instantiation of a partial
6995          specialization.  We replace the innermost set of ARGS with
6996          the arguments appropriate for substitution.  For example,
6997          given:
6998
6999            template <class T> struct S {};
7000            template <class T> struct S<T*> {};
7001
7002          and supposing that we are instantiating S<int*>, ARGS will
7003          presently be {int*} -- but we need {int}.  */
7004       pattern = TREE_TYPE (t);
7005       args = TREE_PURPOSE (t);
7006     }
7007   else
7008     {
7009       pattern = TREE_TYPE (templ);
7010       args = CLASSTYPE_TI_ARGS (type);
7011     }
7012
7013   /* If the template we're instantiating is incomplete, then clearly
7014      there's nothing we can do.  */
7015   if (!COMPLETE_TYPE_P (pattern))
7016     return type;
7017
7018   /* If we've recursively instantiated too many templates, stop.  */
7019   if (! push_tinst_level (type))
7020     return type;
7021
7022   /* Now we're really doing the instantiation.  Mark the type as in
7023      the process of being defined.  */
7024   TYPE_BEING_DEFINED (type) = 1;
7025
7026   /* We may be in the middle of deferred access check.  Disable
7027      it now.  */
7028   push_deferring_access_checks (dk_no_deferred);
7029
7030   push_to_top_level ();
7031
7032   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7033
7034   /* Set the input location to the template definition. This is needed
7035      if tsubsting causes an error.  */
7036   typedecl = TYPE_MAIN_DECL (type);
7037   input_location = DECL_SOURCE_LOCATION (typedecl);
7038
7039   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7040   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7041   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7042   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7043   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7044   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7045   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7046   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7047   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7048   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7049   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7050   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7051   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7052   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7053   if (ANON_AGGR_TYPE_P (pattern))
7054     SET_ANON_AGGR_TYPE_P (type);
7055   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7056     {
7057       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7058       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7059     }
7060
7061   pbinfo = TYPE_BINFO (pattern);
7062
7063   /* We should never instantiate a nested class before its enclosing
7064      class; we need to look up the nested class by name before we can
7065      instantiate it, and that lookup should instantiate the enclosing
7066      class.  */
7067   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7068               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7069               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7070
7071   base_list = NULL_TREE;
7072   if (BINFO_N_BASE_BINFOS (pbinfo))
7073     {
7074       tree pbase_binfo;
7075       tree context = TYPE_CONTEXT (type);
7076       tree pushed_scope;
7077       int i;
7078
7079       /* We must enter the scope containing the type, as that is where
7080          the accessibility of types named in dependent bases are
7081          looked up from.  */
7082       pushed_scope = push_scope (context ? context : global_namespace);
7083
7084       /* Substitute into each of the bases to determine the actual
7085          basetypes.  */
7086       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7087         {
7088           tree base;
7089           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7090           tree expanded_bases = NULL_TREE;
7091           int idx, len = 1;
7092
7093           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7094             {
7095               expanded_bases = 
7096                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7097                                        args, tf_error, NULL_TREE);
7098               if (expanded_bases == error_mark_node)
7099                 continue;
7100
7101               len = TREE_VEC_LENGTH (expanded_bases);
7102             }
7103
7104           for (idx = 0; idx < len; idx++)
7105             {
7106               if (expanded_bases)
7107                 /* Extract the already-expanded base class.  */
7108                 base = TREE_VEC_ELT (expanded_bases, idx);
7109               else
7110                 /* Substitute to figure out the base class.  */
7111                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7112                                NULL_TREE);
7113
7114               if (base == error_mark_node)
7115                 continue;
7116
7117               base_list = tree_cons (access, base, base_list);
7118               if (BINFO_VIRTUAL_P (pbase_binfo))
7119                 TREE_TYPE (base_list) = integer_type_node;
7120             }
7121         }
7122
7123       /* The list is now in reverse order; correct that.  */
7124       base_list = nreverse (base_list);
7125
7126       if (pushed_scope)
7127         pop_scope (pushed_scope);
7128     }
7129   /* Now call xref_basetypes to set up all the base-class
7130      information.  */
7131   xref_basetypes (type, base_list);
7132
7133   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7134                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7135                                   args, tf_error, NULL_TREE);
7136
7137   /* Now that our base classes are set up, enter the scope of the
7138      class, so that name lookups into base classes, etc. will work
7139      correctly.  This is precisely analogous to what we do in
7140      begin_class_definition when defining an ordinary non-template
7141      class, except we also need to push the enclosing classes.  */
7142   push_nested_class (type);
7143
7144   /* Now members are processed in the order of declaration.  */
7145   for (member = CLASSTYPE_DECL_LIST (pattern);
7146        member; member = TREE_CHAIN (member))
7147     {
7148       tree t = TREE_VALUE (member);
7149
7150       if (TREE_PURPOSE (member))
7151         {
7152           if (TYPE_P (t))
7153             {
7154               /* Build new CLASSTYPE_NESTED_UTDS.  */
7155
7156               tree newtag;
7157               bool class_template_p;
7158
7159               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7160                                   && TYPE_LANG_SPECIFIC (t)
7161                                   && CLASSTYPE_IS_TEMPLATE (t));
7162               /* If the member is a class template, then -- even after
7163                  substitution -- there may be dependent types in the
7164                  template argument list for the class.  We increment
7165                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7166                  that function will assume that no types are dependent
7167                  when outside of a template.  */
7168               if (class_template_p)
7169                 ++processing_template_decl;
7170               newtag = tsubst (t, args, tf_error, NULL_TREE);
7171               if (class_template_p)
7172                 --processing_template_decl;
7173               if (newtag == error_mark_node)
7174                 continue;
7175
7176               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7177                 {
7178                   tree name = TYPE_IDENTIFIER (t);
7179
7180                   if (class_template_p)
7181                     /* Unfortunately, lookup_template_class sets
7182                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7183                        instantiation (i.e., for the type of a member
7184                        template class nested within a template class.)
7185                        This behavior is required for
7186                        maybe_process_partial_specialization to work
7187                        correctly, but is not accurate in this case;
7188                        the TAG is not an instantiation of anything.
7189                        (The corresponding TEMPLATE_DECL is an
7190                        instantiation, but the TYPE is not.) */
7191                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7192
7193                   /* Now, we call pushtag to put this NEWTAG into the scope of
7194                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7195                      pushtag calling push_template_decl.  We don't have to do
7196                      this for enums because it will already have been done in
7197                      tsubst_enum.  */
7198                   if (name)
7199                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7200                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7201                 }
7202             }
7203           else if (TREE_CODE (t) == FUNCTION_DECL
7204                    || DECL_FUNCTION_TEMPLATE_P (t))
7205             {
7206               /* Build new TYPE_METHODS.  */
7207               tree r;
7208
7209               if (TREE_CODE (t) == TEMPLATE_DECL)
7210                 ++processing_template_decl;
7211               r = tsubst (t, args, tf_error, NULL_TREE);
7212               if (TREE_CODE (t) == TEMPLATE_DECL)
7213                 --processing_template_decl;
7214               set_current_access_from_decl (r);
7215               finish_member_declaration (r);
7216             }
7217           else
7218             {
7219               /* Build new TYPE_FIELDS.  */
7220               if (TREE_CODE (t) == STATIC_ASSERT)
7221                 {
7222                   tree condition = 
7223                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7224                                  tf_warning_or_error, NULL_TREE,
7225                                  /*integral_constant_expression_p=*/true);
7226                   finish_static_assert (condition,
7227                                         STATIC_ASSERT_MESSAGE (t), 
7228                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7229                                         /*member_p=*/true);
7230                 }
7231               else if (TREE_CODE (t) != CONST_DECL)
7232                 {
7233                   tree r;
7234
7235                   /* The file and line for this declaration, to
7236                      assist in error message reporting.  Since we
7237                      called push_tinst_level above, we don't need to
7238                      restore these.  */
7239                   input_location = DECL_SOURCE_LOCATION (t);
7240
7241                   if (TREE_CODE (t) == TEMPLATE_DECL)
7242                     ++processing_template_decl;
7243                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7244                   if (TREE_CODE (t) == TEMPLATE_DECL)
7245                     --processing_template_decl;
7246                   if (TREE_CODE (r) == VAR_DECL)
7247                     {
7248                       /* In [temp.inst]:
7249
7250                            [t]he initialization (and any associated
7251                            side-effects) of a static data member does
7252                            not occur unless the static data member is
7253                            itself used in a way that requires the
7254                            definition of the static data member to
7255                            exist.
7256
7257                          Therefore, we do not substitute into the
7258                          initialized for the static data member here.  */
7259                       finish_static_data_member_decl
7260                         (r,
7261                          /*init=*/NULL_TREE,
7262                          /*init_const_expr_p=*/false,
7263                          /*asmspec_tree=*/NULL_TREE,
7264                          /*flags=*/0);
7265                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7266                         check_static_variable_definition (r, TREE_TYPE (r));
7267                     }
7268                   else if (TREE_CODE (r) == FIELD_DECL)
7269                     {
7270                       /* Determine whether R has a valid type and can be
7271                          completed later.  If R is invalid, then it is
7272                          replaced by error_mark_node so that it will not be
7273                          added to TYPE_FIELDS.  */
7274                       tree rtype = TREE_TYPE (r);
7275                       if (can_complete_type_without_circularity (rtype))
7276                         complete_type (rtype);
7277
7278                       if (!COMPLETE_TYPE_P (rtype))
7279                         {
7280                           cxx_incomplete_type_error (r, rtype);
7281                           r = error_mark_node;
7282                         }
7283                     }
7284
7285                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7286                      such a thing will already have been added to the field
7287                      list by tsubst_enum in finish_member_declaration in the
7288                      CLASSTYPE_NESTED_UTDS case above.  */
7289                   if (!(TREE_CODE (r) == TYPE_DECL
7290                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7291                         && DECL_ARTIFICIAL (r)))
7292                     {
7293                       set_current_access_from_decl (r);
7294                       finish_member_declaration (r);
7295                     }
7296                 }
7297             }
7298         }
7299       else
7300         {
7301           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7302             {
7303               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7304
7305               tree friend_type = t;
7306               bool adjust_processing_template_decl = false;
7307
7308               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7309                 {
7310                   /* template <class T> friend class C;  */
7311                   friend_type = tsubst_friend_class (friend_type, args);
7312                   adjust_processing_template_decl = true;
7313                 }
7314               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7315                 {
7316                   /* template <class T> friend class C::D;  */
7317                   friend_type = tsubst (friend_type, args,
7318                                         tf_warning_or_error, NULL_TREE);
7319                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7320                     friend_type = TREE_TYPE (friend_type);
7321                   adjust_processing_template_decl = true;
7322                 }
7323               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7324                 {
7325                   /* This could be either
7326
7327                        friend class T::C;
7328
7329                      when dependent_type_p is false or
7330
7331                        template <class U> friend class T::C;
7332
7333                      otherwise.  */
7334                   friend_type = tsubst (friend_type, args,
7335                                         tf_warning_or_error, NULL_TREE);
7336                   /* Bump processing_template_decl for correct
7337                      dependent_type_p calculation.  */
7338                   ++processing_template_decl;
7339                   if (dependent_type_p (friend_type))
7340                     adjust_processing_template_decl = true;
7341                   --processing_template_decl;
7342                 }
7343               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7344                        && hidden_name_p (TYPE_NAME (friend_type)))
7345                 {
7346                   /* friend class C;
7347
7348                      where C hasn't been declared yet.  Let's lookup name
7349                      from namespace scope directly, bypassing any name that
7350                      come from dependent base class.  */
7351                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7352
7353                   /* The call to xref_tag_from_type does injection for friend
7354                      classes.  */
7355                   push_nested_namespace (ns);
7356                   friend_type =
7357                     xref_tag_from_type (friend_type, NULL_TREE,
7358                                         /*tag_scope=*/ts_current);
7359                   pop_nested_namespace (ns);
7360                 }
7361               else if (uses_template_parms (friend_type))
7362                 /* friend class C<T>;  */
7363                 friend_type = tsubst (friend_type, args,
7364                                       tf_warning_or_error, NULL_TREE);
7365               /* Otherwise it's
7366
7367                    friend class C;
7368
7369                  where C is already declared or
7370
7371                    friend class C<int>;
7372
7373                  We don't have to do anything in these cases.  */
7374
7375               if (adjust_processing_template_decl)
7376                 /* Trick make_friend_class into realizing that the friend
7377                    we're adding is a template, not an ordinary class.  It's
7378                    important that we use make_friend_class since it will
7379                    perform some error-checking and output cross-reference
7380                    information.  */
7381                 ++processing_template_decl;
7382
7383               if (friend_type != error_mark_node)
7384                 make_friend_class (type, friend_type, /*complain=*/false);
7385
7386               if (adjust_processing_template_decl)
7387                 --processing_template_decl;
7388             }
7389           else
7390             {
7391               /* Build new DECL_FRIENDLIST.  */
7392               tree r;
7393
7394               /* The file and line for this declaration, to
7395                  assist in error message reporting.  Since we
7396                  called push_tinst_level above, we don't need to
7397                  restore these.  */
7398               input_location = DECL_SOURCE_LOCATION (t);
7399
7400               if (TREE_CODE (t) == TEMPLATE_DECL)
7401                 {
7402                   ++processing_template_decl;
7403                   push_deferring_access_checks (dk_no_check);
7404                 }
7405
7406               r = tsubst_friend_function (t, args);
7407               add_friend (type, r, /*complain=*/false);
7408               if (TREE_CODE (t) == TEMPLATE_DECL)
7409                 {
7410                   pop_deferring_access_checks ();
7411                   --processing_template_decl;
7412                 }
7413             }
7414         }
7415     }
7416
7417   /* Set the file and line number information to whatever is given for
7418      the class itself.  This puts error messages involving generated
7419      implicit functions at a predictable point, and the same point
7420      that would be used for non-template classes.  */
7421   input_location = DECL_SOURCE_LOCATION (typedecl);
7422
7423   unreverse_member_declarations (type);
7424   finish_struct_1 (type);
7425   TYPE_BEING_DEFINED (type) = 0;
7426
7427   /* Now that the class is complete, instantiate default arguments for
7428      any member functions.  We don't do this earlier because the
7429      default arguments may reference members of the class.  */
7430   if (!PRIMARY_TEMPLATE_P (templ))
7431     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7432       if (TREE_CODE (t) == FUNCTION_DECL
7433           /* Implicitly generated member functions will not have template
7434              information; they are not instantiations, but instead are
7435              created "fresh" for each instantiation.  */
7436           && DECL_TEMPLATE_INFO (t))
7437         tsubst_default_arguments (t);
7438
7439   /* Some typedefs referenced from within the template code need to be access
7440      checked at template instantiation time, i.e now. These types were
7441      added to the template at parsing time. Let's get those and perform
7442      the acces checks then.  */
7443   perform_typedefs_access_check (templ, args);
7444   perform_deferred_access_checks ();
7445   pop_nested_class ();
7446   pop_from_top_level ();
7447   pop_deferring_access_checks ();
7448   pop_tinst_level ();
7449
7450   /* The vtable for a template class can be emitted in any translation
7451      unit in which the class is instantiated.  When there is no key
7452      method, however, finish_struct_1 will already have added TYPE to
7453      the keyed_classes list.  */
7454   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7455     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7456
7457   return type;
7458 }
7459
7460 static tree
7461 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7462 {
7463   tree r;
7464
7465   if (!t)
7466     r = t;
7467   else if (TYPE_P (t))
7468     r = tsubst (t, args, complain, in_decl);
7469   else
7470     {
7471       r = tsubst_expr (t, args, complain, in_decl,
7472                        /*integral_constant_expression_p=*/true);
7473       r = fold_non_dependent_expr (r);
7474     }
7475   return r;
7476 }
7477
7478 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7479    NONTYPE_ARGUMENT_PACK.  */
7480
7481 static tree
7482 make_fnparm_pack (tree spec_parm)
7483 {
7484   /* Collect all of the extra "packed" parameters into an
7485      argument pack.  */
7486   tree parmvec;
7487   tree parmtypevec;
7488   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7489   tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
7490   int i, len = list_length (spec_parm);
7491
7492   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7493   parmvec = make_tree_vec (len);
7494   parmtypevec = make_tree_vec (len);
7495   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7496     {
7497       TREE_VEC_ELT (parmvec, i) = spec_parm;
7498       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7499     }
7500
7501   /* Build the argument packs.  */
7502   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7503   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7504   TREE_TYPE (argpack) = argtypepack;
7505
7506   return argpack;
7507 }        
7508
7509 /* Substitute ARGS into T, which is an pack expansion
7510    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7511    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7512    (if only a partial substitution could be performed) or
7513    ERROR_MARK_NODE if there was an error.  */
7514 tree
7515 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7516                        tree in_decl)
7517 {
7518   tree pattern;
7519   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7520   tree first_arg_pack; int i, len = -1;
7521   tree result;
7522   int incomplete = 0;
7523   bool very_local_specializations = false;
7524
7525   gcc_assert (PACK_EXPANSION_P (t));
7526   pattern = PACK_EXPANSION_PATTERN (t);
7527
7528   /* Determine the argument packs that will instantiate the parameter
7529      packs used in the expansion expression. While we're at it,
7530      compute the number of arguments to be expanded and make sure it
7531      is consistent.  */
7532   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7533        pack = TREE_CHAIN (pack))
7534     {
7535       tree parm_pack = TREE_VALUE (pack);
7536       tree arg_pack = NULL_TREE;
7537       tree orig_arg = NULL_TREE;
7538
7539       if (TREE_CODE (parm_pack) == PARM_DECL)
7540         {
7541           arg_pack = retrieve_local_specialization (parm_pack);
7542           if (arg_pack == NULL_TREE)
7543             {
7544               /* This can happen for a parameter name used later in a function
7545                  declaration (such as in a late-specified return type).  Just
7546                  make a dummy decl, since it's only used for its type.  */
7547               gcc_assert (skip_evaluation);
7548               arg_pack = tsubst_decl (parm_pack, args, complain);
7549               arg_pack = make_fnparm_pack (arg_pack);
7550             }
7551         }
7552       else
7553         {
7554           int level, idx, levels;
7555           template_parm_level_and_index (parm_pack, &level, &idx);
7556
7557           levels = TMPL_ARGS_DEPTH (args);
7558           if (level <= levels)
7559             arg_pack = TMPL_ARG (args, level, idx);
7560         }
7561
7562       orig_arg = arg_pack;
7563       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7564         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7565       
7566       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7567         /* This can only happen if we forget to expand an argument
7568            pack somewhere else. Just return an error, silently.  */
7569         {
7570           result = make_tree_vec (1);
7571           TREE_VEC_ELT (result, 0) = error_mark_node;
7572           return result;
7573         }
7574
7575       if (arg_pack
7576           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7577           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7578         {
7579           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7580           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7581           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7582               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7583             /* The argument pack that the parameter maps to is just an
7584                expansion of the parameter itself, such as one would
7585                find in the implicit typedef of a class inside the
7586                class itself.  Consider this parameter "unsubstituted",
7587                so that we will maintain the outer pack expansion.  */
7588             arg_pack = NULL_TREE;
7589         }
7590           
7591       if (arg_pack)
7592         {
7593           int my_len = 
7594             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7595
7596           /* It's all-or-nothing with incomplete argument packs.  */
7597           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7598             return error_mark_node;
7599           
7600           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7601             incomplete = 1;
7602
7603           if (len < 0)
7604             {
7605               len = my_len;
7606               first_arg_pack = arg_pack;
7607             }
7608           else if (len != my_len)
7609             {
7610               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7611                 error ("mismatched argument pack lengths while expanding "
7612                        "%<%T%>",
7613                        pattern);
7614               else
7615                 error ("mismatched argument pack lengths while expanding "
7616                        "%<%E%>",
7617                        pattern);
7618               return error_mark_node;
7619             }
7620
7621           /* Keep track of the parameter packs and their corresponding
7622              argument packs.  */
7623           packs = tree_cons (parm_pack, arg_pack, packs);
7624           TREE_TYPE (packs) = orig_arg;
7625         }
7626       else
7627         /* We can't substitute for this parameter pack.  */
7628         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7629                                          TREE_VALUE (pack),
7630                                          unsubstituted_packs);
7631     }
7632
7633   /* We cannot expand this expansion expression, because we don't have
7634      all of the argument packs we need. Substitute into the pattern
7635      and return a PACK_EXPANSION_*. The caller will need to deal with
7636      that.  */
7637   if (unsubstituted_packs)
7638     return make_pack_expansion (tsubst (pattern, args, complain, 
7639                                         in_decl));
7640
7641   /* We could not find any argument packs that work.  */
7642   if (len < 0)
7643     return error_mark_node;
7644
7645   if (!local_specializations)
7646     {
7647       /* We're in a late-specified return type, so we don't have a local
7648          specializations table.  Create one for doing this expansion.  */
7649       very_local_specializations = true;
7650       local_specializations = htab_create (37,
7651                                            hash_local_specialization,
7652                                            eq_local_specializations,
7653                                            NULL);
7654     }
7655
7656   /* For each argument in each argument pack, substitute into the
7657      pattern.  */
7658   result = make_tree_vec (len + incomplete);
7659   for (i = 0; i < len + incomplete; ++i)
7660     {
7661       /* For parameter pack, change the substitution of the parameter
7662          pack to the ith argument in its argument pack, then expand
7663          the pattern.  */
7664       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7665         {
7666           tree parm = TREE_PURPOSE (pack);
7667
7668           if (TREE_CODE (parm) == PARM_DECL)
7669             {
7670               /* Select the Ith argument from the pack.  */
7671               tree arg = make_node (ARGUMENT_PACK_SELECT);
7672               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7673               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7674               mark_used (parm);
7675               register_local_specialization (arg, parm);
7676             }
7677           else
7678             {
7679               tree value = parm;
7680               int idx, level;
7681               template_parm_level_and_index (parm, &level, &idx);
7682               
7683               if (i < len) 
7684                 {
7685                   /* Select the Ith argument from the pack. */
7686                   value = make_node (ARGUMENT_PACK_SELECT);
7687                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7688                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7689                 }
7690
7691               /* Update the corresponding argument.  */
7692               TMPL_ARG (args, level, idx) = value;
7693             }
7694         }
7695
7696       /* Substitute into the PATTERN with the altered arguments.  */
7697       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7698         TREE_VEC_ELT (result, i) = 
7699           tsubst_expr (pattern, args, complain, in_decl,
7700                        /*integral_constant_expression_p=*/false);
7701       else
7702         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7703
7704       if (i == len)
7705         /* When we have incomplete argument packs, the last "expanded"
7706            result is itself a pack expansion, which allows us
7707            to deduce more arguments.  */
7708         TREE_VEC_ELT (result, i) = 
7709           make_pack_expansion (TREE_VEC_ELT (result, i));
7710
7711       if (TREE_VEC_ELT (result, i) == error_mark_node)
7712         {
7713           result = error_mark_node;
7714           break;
7715         }
7716     }
7717
7718   /* Update ARGS to restore the substitution from parameter packs to
7719      their argument packs.  */
7720   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7721     {
7722       tree parm = TREE_PURPOSE (pack);
7723
7724       if (TREE_CODE (parm) == PARM_DECL)
7725         register_local_specialization (TREE_TYPE (pack), parm);
7726       else
7727         {
7728           int idx, level;
7729           template_parm_level_and_index (parm, &level, &idx);
7730           
7731           /* Update the corresponding argument.  */
7732           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7733             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7734               TREE_TYPE (pack);
7735           else
7736             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7737         }
7738     }
7739
7740   if (very_local_specializations)
7741     {
7742       htab_delete (local_specializations);
7743       local_specializations = NULL;
7744     }
7745   
7746   return result;
7747 }
7748
7749 /* Substitute ARGS into the vector or list of template arguments T.  */
7750
7751 static tree
7752 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7753 {
7754   tree orig_t = t;
7755   int len = TREE_VEC_LENGTH (t);
7756   int need_new = 0, i, expanded_len_adjust = 0, out;
7757   tree *elts = (tree *) alloca (len * sizeof (tree));
7758
7759   for (i = 0; i < len; i++)
7760     {
7761       tree orig_arg = TREE_VEC_ELT (t, i);
7762       tree new_arg;
7763
7764       if (TREE_CODE (orig_arg) == TREE_VEC)
7765         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7766       else if (PACK_EXPANSION_P (orig_arg))
7767         {
7768           /* Substitute into an expansion expression.  */
7769           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7770
7771           if (TREE_CODE (new_arg) == TREE_VEC)
7772             /* Add to the expanded length adjustment the number of
7773                expanded arguments. We subtract one from this
7774                measurement, because the argument pack expression
7775                itself is already counted as 1 in
7776                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7777                the argument pack is empty.  */
7778             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7779         }
7780       else if (ARGUMENT_PACK_P (orig_arg))
7781         {
7782           /* Substitute into each of the arguments.  */
7783           new_arg = make_node (TREE_CODE (orig_arg));
7784           
7785           SET_ARGUMENT_PACK_ARGS (
7786             new_arg,
7787             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7788                                   args, complain, in_decl));
7789
7790           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7791             new_arg = error_mark_node;
7792
7793           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7794             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7795                                           complain, in_decl);
7796             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7797
7798             if (TREE_TYPE (new_arg) == error_mark_node)
7799               new_arg = error_mark_node;
7800           }
7801         }
7802       else
7803         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7804
7805       if (new_arg == error_mark_node)
7806         return error_mark_node;
7807
7808       elts[i] = new_arg;
7809       if (new_arg != orig_arg)
7810         need_new = 1;
7811     }
7812
7813   if (!need_new)
7814     return t;
7815
7816   /* Make space for the expanded arguments coming from template
7817      argument packs.  */
7818   t = make_tree_vec (len + expanded_len_adjust);
7819   for (i = 0, out = 0; i < len; i++)
7820     {
7821       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7822            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7823           && TREE_CODE (elts[i]) == TREE_VEC)
7824         {
7825           int idx;
7826
7827           /* Now expand the template argument pack "in place".  */
7828           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7829             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7830         }
7831       else
7832         {
7833           TREE_VEC_ELT (t, out) = elts[i];
7834           out++;
7835         }
7836     }
7837
7838   return t;
7839 }
7840
7841 /* Return the result of substituting ARGS into the template parameters
7842    given by PARMS.  If there are m levels of ARGS and m + n levels of
7843    PARMS, then the result will contain n levels of PARMS.  For
7844    example, if PARMS is `template <class T> template <class U>
7845    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7846    result will be `template <int*, double, class V>'.  */
7847
7848 static tree
7849 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7850 {
7851   tree r = NULL_TREE;
7852   tree* new_parms;
7853
7854   /* When substituting into a template, we must set
7855      PROCESSING_TEMPLATE_DECL as the template parameters may be
7856      dependent if they are based on one-another, and the dependency
7857      predicates are short-circuit outside of templates.  */
7858   ++processing_template_decl;
7859
7860   for (new_parms = &r;
7861        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7862        new_parms = &(TREE_CHAIN (*new_parms)),
7863          parms = TREE_CHAIN (parms))
7864     {
7865       tree new_vec =
7866         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7867       int i;
7868
7869       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7870         {
7871           tree tuple;
7872           tree default_value;
7873           tree parm_decl;
7874
7875           if (parms == error_mark_node)
7876             continue;
7877
7878           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7879
7880           if (tuple == error_mark_node)
7881             continue;
7882
7883           default_value = TREE_PURPOSE (tuple);
7884           parm_decl = TREE_VALUE (tuple);
7885
7886           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7887           if (TREE_CODE (parm_decl) == PARM_DECL
7888               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7889             parm_decl = error_mark_node;
7890           default_value = tsubst_template_arg (default_value, args,
7891                                                complain, NULL_TREE);
7892
7893           tuple = build_tree_list (default_value, parm_decl);
7894           TREE_VEC_ELT (new_vec, i) = tuple;
7895         }
7896
7897       *new_parms =
7898         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7899                              - TMPL_ARGS_DEPTH (args)),
7900                    new_vec, NULL_TREE);
7901     }
7902
7903   --processing_template_decl;
7904
7905   return r;
7906 }
7907
7908 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7909    type T.  If T is not an aggregate or enumeration type, it is
7910    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7911    ENTERING_SCOPE is nonzero, T is the context for a template which
7912    we are presently tsubst'ing.  Return the substituted value.  */
7913
7914 static tree
7915 tsubst_aggr_type (tree t,
7916                   tree args,
7917                   tsubst_flags_t complain,
7918                   tree in_decl,
7919                   int entering_scope)
7920 {
7921   if (t == NULL_TREE)
7922     return NULL_TREE;
7923
7924   switch (TREE_CODE (t))
7925     {
7926     case RECORD_TYPE:
7927       if (TYPE_PTRMEMFUNC_P (t))
7928         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7929
7930       /* Else fall through.  */
7931     case ENUMERAL_TYPE:
7932     case UNION_TYPE:
7933       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7934         {
7935           tree argvec;
7936           tree context;
7937           tree r;
7938           bool saved_skip_evaluation;
7939
7940           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7941           saved_skip_evaluation = skip_evaluation;
7942           skip_evaluation = false;
7943
7944           /* First, determine the context for the type we are looking
7945              up.  */
7946           context = TYPE_CONTEXT (t);
7947           if (context)
7948             {
7949               context = tsubst_aggr_type (context, args, complain,
7950                                           in_decl, /*entering_scope=*/1);
7951               /* If context is a nested class inside a class template,
7952                  it may still need to be instantiated (c++/33959).  */
7953               if (TYPE_P (context))
7954                 context = complete_type (context);
7955             }
7956
7957           /* Then, figure out what arguments are appropriate for the
7958              type we are trying to find.  For example, given:
7959
7960                template <class T> struct S;
7961                template <class T, class U> void f(T, U) { S<U> su; }
7962
7963              and supposing that we are instantiating f<int, double>,
7964              then our ARGS will be {int, double}, but, when looking up
7965              S we only want {double}.  */
7966           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7967                                          complain, in_decl);
7968           if (argvec == error_mark_node)
7969             r = error_mark_node;
7970           else
7971             {
7972               r = lookup_template_class (t, argvec, in_decl, context,
7973                                          entering_scope, complain);
7974               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7975             }
7976
7977           skip_evaluation = saved_skip_evaluation;
7978
7979           return r;
7980         }
7981       else
7982         /* This is not a template type, so there's nothing to do.  */
7983         return t;
7984
7985     default:
7986       return tsubst (t, args, complain, in_decl);
7987     }
7988 }
7989
7990 /* Substitute into the default argument ARG (a default argument for
7991    FN), which has the indicated TYPE.  */
7992
7993 tree
7994 tsubst_default_argument (tree fn, tree type, tree arg)
7995 {
7996   tree saved_class_ptr = NULL_TREE;
7997   tree saved_class_ref = NULL_TREE;
7998
7999   /* This default argument came from a template.  Instantiate the
8000      default argument here, not in tsubst.  In the case of
8001      something like:
8002
8003        template <class T>
8004        struct S {
8005          static T t();
8006          void f(T = t());
8007        };
8008
8009      we must be careful to do name lookup in the scope of S<T>,
8010      rather than in the current class.  */
8011   push_access_scope (fn);
8012   /* The "this" pointer is not valid in a default argument.  */
8013   if (cfun)
8014     {
8015       saved_class_ptr = current_class_ptr;
8016       cp_function_chain->x_current_class_ptr = NULL_TREE;
8017       saved_class_ref = current_class_ref;
8018       cp_function_chain->x_current_class_ref = NULL_TREE;
8019     }
8020
8021   push_deferring_access_checks(dk_no_deferred);
8022   /* The default argument expression may cause implicitly defined
8023      member functions to be synthesized, which will result in garbage
8024      collection.  We must treat this situation as if we were within
8025      the body of function so as to avoid collecting live data on the
8026      stack.  */
8027   ++function_depth;
8028   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8029                      tf_warning_or_error, NULL_TREE,
8030                      /*integral_constant_expression_p=*/false);
8031   --function_depth;
8032   pop_deferring_access_checks();
8033
8034   /* Restore the "this" pointer.  */
8035   if (cfun)
8036     {
8037       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8038       cp_function_chain->x_current_class_ref = saved_class_ref;
8039     }
8040
8041   pop_access_scope (fn);
8042
8043   /* Make sure the default argument is reasonable.  */
8044   arg = check_default_argument (type, arg);
8045
8046   return arg;
8047 }
8048
8049 /* Substitute into all the default arguments for FN.  */
8050
8051 static void
8052 tsubst_default_arguments (tree fn)
8053 {
8054   tree arg;
8055   tree tmpl_args;
8056
8057   tmpl_args = DECL_TI_ARGS (fn);
8058
8059   /* If this function is not yet instantiated, we certainly don't need
8060      its default arguments.  */
8061   if (uses_template_parms (tmpl_args))
8062     return;
8063
8064   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8065        arg;
8066        arg = TREE_CHAIN (arg))
8067     if (TREE_PURPOSE (arg))
8068       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8069                                                     TREE_VALUE (arg),
8070                                                     TREE_PURPOSE (arg));
8071 }
8072
8073 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8074    result of the substitution.  Issue error and warning messages under
8075    control of COMPLAIN.  */
8076
8077 static tree
8078 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8079 {
8080   location_t saved_loc;
8081   tree r = NULL_TREE;
8082   tree in_decl = t;
8083
8084   /* Set the filename and linenumber to improve error-reporting.  */
8085   saved_loc = input_location;
8086   input_location = DECL_SOURCE_LOCATION (t);
8087
8088   switch (TREE_CODE (t))
8089     {
8090     case TEMPLATE_DECL:
8091       {
8092         /* We can get here when processing a member function template,
8093            member class template, and template template parameter of
8094            a template class.  */
8095         tree decl = DECL_TEMPLATE_RESULT (t);
8096         tree spec;
8097         tree tmpl_args;
8098         tree full_args;
8099
8100         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8101           {
8102             /* Template template parameter is treated here.  */
8103             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8104             if (new_type == error_mark_node)
8105               return error_mark_node;
8106
8107             r = copy_decl (t);
8108             TREE_CHAIN (r) = NULL_TREE;
8109             TREE_TYPE (r) = new_type;
8110             DECL_TEMPLATE_RESULT (r)
8111               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
8112             DECL_TEMPLATE_PARMS (r)
8113               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8114                                        complain);
8115             TYPE_NAME (new_type) = r;
8116             break;
8117           }
8118
8119         /* We might already have an instance of this template.
8120            The ARGS are for the surrounding class type, so the
8121            full args contain the tsubst'd args for the context,
8122            plus the innermost args from the template decl.  */
8123         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8124           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8125           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8126         /* Because this is a template, the arguments will still be
8127            dependent, even after substitution.  If
8128            PROCESSING_TEMPLATE_DECL is not set, the dependency
8129            predicates will short-circuit.  */
8130         ++processing_template_decl;
8131         full_args = tsubst_template_args (tmpl_args, args,
8132                                           complain, in_decl);
8133         --processing_template_decl;
8134         if (full_args == error_mark_node)
8135           return error_mark_node;
8136
8137         /* tsubst_template_args doesn't copy the vector if
8138            nothing changed.  But, *something* should have
8139            changed.  */
8140         gcc_assert (full_args != tmpl_args);
8141
8142         spec = retrieve_specialization (t, full_args,
8143                                         /*class_specializations_p=*/true);
8144         if (spec != NULL_TREE)
8145           {
8146             r = spec;
8147             break;
8148           }
8149
8150         /* Make a new template decl.  It will be similar to the
8151            original, but will record the current template arguments.
8152            We also create a new function declaration, which is just
8153            like the old one, but points to this new template, rather
8154            than the old one.  */
8155         r = copy_decl (t);
8156         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8157         TREE_CHAIN (r) = NULL_TREE;
8158
8159         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8160
8161         if (TREE_CODE (decl) == TYPE_DECL)
8162           {
8163             tree new_type;
8164             ++processing_template_decl;
8165             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8166             --processing_template_decl;
8167             if (new_type == error_mark_node)
8168               return error_mark_node;
8169
8170             TREE_TYPE (r) = new_type;
8171             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8172             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8173             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8174             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8175           }
8176         else
8177           {
8178             tree new_decl;
8179             ++processing_template_decl;
8180             new_decl = tsubst (decl, args, complain, in_decl);
8181             --processing_template_decl;
8182             if (new_decl == error_mark_node)
8183               return error_mark_node;
8184
8185             DECL_TEMPLATE_RESULT (r) = new_decl;
8186             DECL_TI_TEMPLATE (new_decl) = r;
8187             TREE_TYPE (r) = TREE_TYPE (new_decl);
8188             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8189             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8190           }
8191
8192         SET_DECL_IMPLICIT_INSTANTIATION (r);
8193         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8194         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8195
8196         /* The template parameters for this new template are all the
8197            template parameters for the old template, except the
8198            outermost level of parameters.  */
8199         DECL_TEMPLATE_PARMS (r)
8200           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8201                                    complain);
8202
8203         if (PRIMARY_TEMPLATE_P (t))
8204           DECL_PRIMARY_TEMPLATE (r) = r;
8205
8206         if (TREE_CODE (decl) != TYPE_DECL)
8207           /* Record this non-type partial instantiation.  */
8208           register_specialization (r, t,
8209                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8210                                    false);
8211       }
8212       break;
8213
8214     case FUNCTION_DECL:
8215       {
8216         tree ctx;
8217         tree argvec = NULL_TREE;
8218         tree *friends;
8219         tree gen_tmpl;
8220         tree type;
8221         int member;
8222         int args_depth;
8223         int parms_depth;
8224
8225         /* Nobody should be tsubst'ing into non-template functions.  */
8226         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8227
8228         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8229           {
8230             tree spec;
8231             bool dependent_p;
8232
8233             /* If T is not dependent, just return it.  We have to
8234                increment PROCESSING_TEMPLATE_DECL because
8235                value_dependent_expression_p assumes that nothing is
8236                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8237             ++processing_template_decl;
8238             dependent_p = value_dependent_expression_p (t);
8239             --processing_template_decl;
8240             if (!dependent_p)
8241               return t;
8242
8243             /* Calculate the most general template of which R is a
8244                specialization, and the complete set of arguments used to
8245                specialize R.  */
8246             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8247             argvec = tsubst_template_args (DECL_TI_ARGS
8248                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8249                                            args, complain, in_decl);
8250
8251             /* Check to see if we already have this specialization.  */
8252             spec = retrieve_specialization (gen_tmpl, argvec,
8253                                             /*class_specializations_p=*/false);
8254
8255             if (spec)
8256               {
8257                 r = spec;
8258                 break;
8259               }
8260
8261             /* We can see more levels of arguments than parameters if
8262                there was a specialization of a member template, like
8263                this:
8264
8265                  template <class T> struct S { template <class U> void f(); }
8266                  template <> template <class U> void S<int>::f(U);
8267
8268                Here, we'll be substituting into the specialization,
8269                because that's where we can find the code we actually
8270                want to generate, but we'll have enough arguments for
8271                the most general template.
8272
8273                We also deal with the peculiar case:
8274
8275                  template <class T> struct S {
8276                    template <class U> friend void f();
8277                  };
8278                  template <class U> void f() {}
8279                  template S<int>;
8280                  template void f<double>();
8281
8282                Here, the ARGS for the instantiation of will be {int,
8283                double}.  But, we only need as many ARGS as there are
8284                levels of template parameters in CODE_PATTERN.  We are
8285                careful not to get fooled into reducing the ARGS in
8286                situations like:
8287
8288                  template <class T> struct S { template <class U> void f(U); }
8289                  template <class T> template <> void S<T>::f(int) {}
8290
8291                which we can spot because the pattern will be a
8292                specialization in this case.  */
8293             args_depth = TMPL_ARGS_DEPTH (args);
8294             parms_depth =
8295               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8296             if (args_depth > parms_depth
8297                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8298               args = get_innermost_template_args (args, parms_depth);
8299           }
8300         else
8301           {
8302             /* This special case arises when we have something like this:
8303
8304                  template <class T> struct S {
8305                    friend void f<int>(int, double);
8306                  };
8307
8308                Here, the DECL_TI_TEMPLATE for the friend declaration
8309                will be an IDENTIFIER_NODE.  We are being called from
8310                tsubst_friend_function, and we want only to create a
8311                new decl (R) with appropriate types so that we can call
8312                determine_specialization.  */
8313             gen_tmpl = NULL_TREE;
8314           }
8315
8316         if (DECL_CLASS_SCOPE_P (t))
8317           {
8318             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8319               member = 2;
8320             else
8321               member = 1;
8322             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8323                                     complain, t, /*entering_scope=*/1);
8324           }
8325         else
8326           {
8327             member = 0;
8328             ctx = DECL_CONTEXT (t);
8329           }
8330         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8331         if (type == error_mark_node)
8332           return error_mark_node;
8333
8334         /* We do NOT check for matching decls pushed separately at this
8335            point, as they may not represent instantiations of this
8336            template, and in any case are considered separate under the
8337            discrete model.  */
8338         r = copy_decl (t);
8339         DECL_USE_TEMPLATE (r) = 0;
8340         TREE_TYPE (r) = type;
8341         /* Clear out the mangled name and RTL for the instantiation.  */
8342         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8343         SET_DECL_RTL (r, NULL_RTX);
8344         /* Leave DECL_INITIAL set on deleted instantiations.  */
8345         if (!DECL_DELETED_FN (r))
8346           DECL_INITIAL (r) = NULL_TREE;
8347         DECL_CONTEXT (r) = ctx;
8348
8349         if (member && DECL_CONV_FN_P (r))
8350           /* Type-conversion operator.  Reconstruct the name, in
8351              case it's the name of one of the template's parameters.  */
8352           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8353
8354         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8355                                      complain, t);
8356         DECL_RESULT (r) = NULL_TREE;
8357
8358         TREE_STATIC (r) = 0;
8359         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8360         DECL_EXTERNAL (r) = 1;
8361         /* If this is an instantiation of a function with internal
8362            linkage, we already know what object file linkage will be
8363            assigned to the instantiation.  */
8364         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8365         DECL_DEFER_OUTPUT (r) = 0;
8366         TREE_CHAIN (r) = NULL_TREE;
8367         DECL_PENDING_INLINE_INFO (r) = 0;
8368         DECL_PENDING_INLINE_P (r) = 0;
8369         DECL_SAVED_TREE (r) = NULL_TREE;
8370         DECL_STRUCT_FUNCTION (r) = NULL;
8371         TREE_USED (r) = 0;
8372         if (DECL_CLONED_FUNCTION (r))
8373           {
8374             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8375                                                args, complain, t);
8376             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8377             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8378           }
8379
8380         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8381            this in the special friend case mentioned above where
8382            GEN_TMPL is NULL.  */
8383         if (gen_tmpl)
8384           {
8385             DECL_TEMPLATE_INFO (r)
8386               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8387             SET_DECL_IMPLICIT_INSTANTIATION (r);
8388             register_specialization (r, gen_tmpl, argvec, false);
8389
8390             /* We're not supposed to instantiate default arguments
8391                until they are called, for a template.  But, for a
8392                declaration like:
8393
8394                  template <class T> void f ()
8395                  { extern void g(int i = T()); }
8396
8397                we should do the substitution when the template is
8398                instantiated.  We handle the member function case in
8399                instantiate_class_template since the default arguments
8400                might refer to other members of the class.  */
8401             if (!member
8402                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8403                 && !uses_template_parms (argvec))
8404               tsubst_default_arguments (r);
8405           }
8406         else
8407           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8408
8409         /* Copy the list of befriending classes.  */
8410         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8411              *friends;
8412              friends = &TREE_CHAIN (*friends))
8413           {
8414             *friends = copy_node (*friends);
8415             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8416                                             args, complain,
8417                                             in_decl);
8418           }
8419
8420         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8421           {
8422             maybe_retrofit_in_chrg (r);
8423             if (DECL_CONSTRUCTOR_P (r))
8424               grok_ctor_properties (ctx, r);
8425             /* If this is an instantiation of a member template, clone it.
8426                If it isn't, that'll be handled by
8427                clone_constructors_and_destructors.  */
8428             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8429               clone_function_decl (r, /*update_method_vec_p=*/0);
8430           }
8431         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8432                  && !grok_op_properties (r, (complain & tf_error) != 0))
8433           return error_mark_node;
8434
8435         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8436           SET_DECL_FRIEND_CONTEXT (r,
8437                                    tsubst (DECL_FRIEND_CONTEXT (t),
8438                                             args, complain, in_decl));
8439
8440         /* Possibly limit visibility based on template args.  */
8441         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8442         if (DECL_VISIBILITY_SPECIFIED (t))
8443           {
8444             DECL_VISIBILITY_SPECIFIED (r) = 0;
8445             DECL_ATTRIBUTES (r)
8446               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8447           }
8448         determine_visibility (r);
8449
8450         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8451                                         args, complain, in_decl);
8452       }
8453       break;
8454
8455     case PARM_DECL:
8456       {
8457         tree type = NULL_TREE;
8458         int i, len = 1;
8459         tree expanded_types = NULL_TREE;
8460         tree prev_r = NULL_TREE;
8461         tree first_r = NULL_TREE;
8462
8463         if (FUNCTION_PARAMETER_PACK_P (t))
8464           {
8465             /* If there is a local specialization that isn't a
8466                parameter pack, it means that we're doing a "simple"
8467                substitution from inside tsubst_pack_expansion. Just
8468                return the local specialization (which will be a single
8469                parm).  */
8470             tree spec = retrieve_local_specialization (t);
8471             if (spec 
8472                 && TREE_CODE (spec) == PARM_DECL
8473                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8474               return spec;
8475
8476             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8477                the parameters in this function parameter pack.  */
8478             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8479                                                     complain, in_decl);
8480             if (TREE_CODE (expanded_types) == TREE_VEC)
8481               {
8482                 len = TREE_VEC_LENGTH (expanded_types);
8483
8484                 /* Zero-length parameter packs are boring. Just substitute
8485                    into the chain.  */
8486                 if (len == 0)
8487                   return tsubst (TREE_CHAIN (t), args, complain, 
8488                                  TREE_CHAIN (t));
8489               }
8490             else
8491               {
8492                 /* All we did was update the type. Make a note of that.  */
8493                 type = expanded_types;
8494                 expanded_types = NULL_TREE;
8495               }
8496           }
8497
8498         /* Loop through all of the parameter's we'll build. When T is
8499            a function parameter pack, LEN is the number of expanded
8500            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8501         r = NULL_TREE;
8502         for (i = 0; i < len; ++i)
8503           {
8504             prev_r = r;
8505             r = copy_node (t);
8506             if (DECL_TEMPLATE_PARM_P (t))
8507               SET_DECL_TEMPLATE_PARM_P (r);
8508
8509             if (expanded_types)
8510               /* We're on the Ith parameter of the function parameter
8511                  pack.  */
8512               {
8513                 /* Get the Ith type.  */
8514                 type = TREE_VEC_ELT (expanded_types, i);
8515
8516                 if (DECL_NAME (r))
8517                   /* Rename the parameter to include the index.  */
8518                   DECL_NAME (r) =
8519                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8520               }
8521             else if (!type)
8522               /* We're dealing with a normal parameter.  */
8523               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8524
8525             type = type_decays_to (type);
8526             TREE_TYPE (r) = type;
8527             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8528
8529             if (DECL_INITIAL (r))
8530               {
8531                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8532                   DECL_INITIAL (r) = TREE_TYPE (r);
8533                 else
8534                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8535                                              complain, in_decl);
8536               }
8537
8538             DECL_CONTEXT (r) = NULL_TREE;
8539
8540             if (!DECL_TEMPLATE_PARM_P (r))
8541               DECL_ARG_TYPE (r) = type_passed_as (type);
8542
8543             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8544                                             args, complain, in_decl);
8545
8546             /* Keep track of the first new parameter we
8547                generate. That's what will be returned to the
8548                caller.  */
8549             if (!first_r)
8550               first_r = r;
8551
8552             /* Build a proper chain of parameters when substituting
8553                into a function parameter pack.  */
8554             if (prev_r)
8555               TREE_CHAIN (prev_r) = r;
8556           }
8557
8558         if (TREE_CHAIN (t))
8559           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8560                                    complain, TREE_CHAIN (t));
8561
8562         /* FIRST_R contains the start of the chain we've built.  */
8563         r = first_r;
8564       }
8565       break;
8566
8567     case FIELD_DECL:
8568       {
8569         tree type;
8570
8571         r = copy_decl (t);
8572         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8573         if (type == error_mark_node)
8574           return error_mark_node;
8575         TREE_TYPE (r) = type;
8576         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8577
8578         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8579         DECL_INITIAL (r)
8580           = tsubst_expr (DECL_INITIAL (t), args,
8581                          complain, in_decl,
8582                          /*integral_constant_expression_p=*/true);
8583         /* We don't have to set DECL_CONTEXT here; it is set by
8584            finish_member_declaration.  */
8585         TREE_CHAIN (r) = NULL_TREE;
8586         if (VOID_TYPE_P (type))
8587           error ("instantiation of %q+D as type %qT", r, type);
8588
8589         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8590                                         args, complain, in_decl);
8591       }
8592       break;
8593
8594     case USING_DECL:
8595       /* We reach here only for member using decls.  */
8596       if (DECL_DEPENDENT_P (t))
8597         {
8598           r = do_class_using_decl
8599             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8600              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8601           if (!r)
8602             r = error_mark_node;
8603           else
8604             {
8605               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8606               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8607             }
8608         }
8609       else
8610         {
8611           r = copy_node (t);
8612           TREE_CHAIN (r) = NULL_TREE;
8613         }
8614       break;
8615
8616     case TYPE_DECL:
8617     case VAR_DECL:
8618       {
8619         tree argvec = NULL_TREE;
8620         tree gen_tmpl = NULL_TREE;
8621         tree spec;
8622         tree tmpl = NULL_TREE;
8623         tree ctx;
8624         tree type = NULL_TREE;
8625         bool local_p;
8626
8627         if (TREE_CODE (t) == TYPE_DECL
8628             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8629           {
8630             /* If this is the canonical decl, we don't have to
8631                mess with instantiations, and often we can't (for
8632                typename, template type parms and such).  Note that
8633                TYPE_NAME is not correct for the above test if
8634                we've copied the type for a typedef.  */
8635             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8636             if (type == error_mark_node)
8637               return error_mark_node;
8638             r = TYPE_NAME (type);
8639             break;
8640           }
8641
8642         /* Check to see if we already have the specialization we
8643            need.  */
8644         spec = NULL_TREE;
8645         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8646           {
8647             /* T is a static data member or namespace-scope entity.
8648                We have to substitute into namespace-scope variables
8649                (even though such entities are never templates) because
8650                of cases like:
8651                
8652                  template <class T> void f() { extern T t; }
8653
8654                where the entity referenced is not known until
8655                instantiation time.  */
8656             local_p = false;
8657             ctx = DECL_CONTEXT (t);
8658             if (DECL_CLASS_SCOPE_P (t))
8659               {
8660                 ctx = tsubst_aggr_type (ctx, args,
8661                                         complain,
8662                                         in_decl, /*entering_scope=*/1);
8663                 /* If CTX is unchanged, then T is in fact the
8664                    specialization we want.  That situation occurs when
8665                    referencing a static data member within in its own
8666                    class.  We can use pointer equality, rather than
8667                    same_type_p, because DECL_CONTEXT is always
8668                    canonical.  */
8669                 if (ctx == DECL_CONTEXT (t))
8670                   spec = t;
8671               }
8672
8673             if (!spec)
8674               {
8675                 tmpl = DECL_TI_TEMPLATE (t);
8676                 gen_tmpl = most_general_template (tmpl);
8677                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8678                 spec = (retrieve_specialization 
8679                         (gen_tmpl, argvec,
8680                          /*class_specializations_p=*/false));
8681               }
8682           }
8683         else
8684           {
8685             /* A local variable.  */
8686             local_p = true;
8687             /* Subsequent calls to pushdecl will fill this in.  */
8688             ctx = NULL_TREE;
8689             spec = retrieve_local_specialization (t);
8690           }
8691         /* If we already have the specialization we need, there is
8692            nothing more to do.  */ 
8693         if (spec)
8694           {
8695             r = spec;
8696             break;
8697           }
8698
8699         /* Create a new node for the specialization we need.  */
8700         r = copy_decl (t);
8701         if (type == NULL_TREE)
8702           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8703         if (TREE_CODE (r) == VAR_DECL)
8704           {
8705             /* Even if the original location is out of scope, the
8706                newly substituted one is not.  */
8707             DECL_DEAD_FOR_LOCAL (r) = 0;
8708             DECL_INITIALIZED_P (r) = 0;
8709             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8710             if (type == error_mark_node)
8711               return error_mark_node;
8712             if (TREE_CODE (type) == FUNCTION_TYPE)
8713               {
8714                 /* It may seem that this case cannot occur, since:
8715
8716                      typedef void f();
8717                      void g() { f x; }
8718
8719                    declares a function, not a variable.  However:
8720       
8721                      typedef void f();
8722                      template <typename T> void g() { T t; }
8723                      template void g<f>();
8724
8725                    is an attempt to declare a variable with function
8726                    type.  */
8727                 error ("variable %qD has function type",
8728                        /* R is not yet sufficiently initialized, so we
8729                           just use its name.  */
8730                        DECL_NAME (r));
8731                 return error_mark_node;
8732               }
8733             type = complete_type (type);
8734             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8735               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8736             type = check_var_type (DECL_NAME (r), type);
8737
8738             if (DECL_HAS_VALUE_EXPR_P (t))
8739               {
8740                 tree ve = DECL_VALUE_EXPR (t);
8741                 ve = tsubst_expr (ve, args, complain, in_decl,
8742                                   /*constant_expression_p=*/false);
8743                 SET_DECL_VALUE_EXPR (r, ve);
8744               }
8745           }
8746         else if (DECL_SELF_REFERENCE_P (t))
8747           SET_DECL_SELF_REFERENCE_P (r);
8748         TREE_TYPE (r) = type;
8749         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8750         DECL_CONTEXT (r) = ctx;
8751         /* Clear out the mangled name and RTL for the instantiation.  */
8752         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8753         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8754           SET_DECL_RTL (r, NULL_RTX);
8755         /* The initializer must not be expanded until it is required;
8756            see [temp.inst].  */
8757         DECL_INITIAL (r) = NULL_TREE;
8758         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8759           SET_DECL_RTL (r, NULL_RTX);
8760         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8761         if (TREE_CODE (r) == VAR_DECL)
8762           {
8763             /* Possibly limit visibility based on template args.  */
8764             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8765             if (DECL_VISIBILITY_SPECIFIED (t))
8766               {
8767                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8768                 DECL_ATTRIBUTES (r)
8769                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8770               }
8771             determine_visibility (r);
8772           }
8773         /* Preserve a typedef that names a type.  */
8774         else if (TREE_CODE (r) == TYPE_DECL
8775                  && DECL_ORIGINAL_TYPE (t)
8776                  && type != error_mark_node)
8777           {
8778             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8779                                              args, complain, in_decl);
8780             TREE_TYPE (r) = type = build_variant_type_copy (type);
8781             TYPE_NAME (type) = r;
8782           }
8783
8784         if (!local_p)
8785           {
8786             /* A static data member declaration is always marked
8787                external when it is declared in-class, even if an
8788                initializer is present.  We mimic the non-template
8789                processing here.  */
8790             DECL_EXTERNAL (r) = 1;
8791
8792             register_specialization (r, gen_tmpl, argvec, false);
8793             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8794             SET_DECL_IMPLICIT_INSTANTIATION (r);
8795           }
8796         else
8797           register_local_specialization (r, t);
8798
8799         TREE_CHAIN (r) = NULL_TREE;
8800
8801         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8802                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8803                                         args, complain, in_decl);
8804         layout_decl (r, 0);
8805       }
8806       break;
8807
8808     default:
8809       gcc_unreachable ();
8810     }
8811
8812   /* Restore the file and line information.  */
8813   input_location = saved_loc;
8814
8815   return r;
8816 }
8817
8818 /* Substitute into the ARG_TYPES of a function type.  */
8819
8820 static tree
8821 tsubst_arg_types (tree arg_types,
8822                   tree args,
8823                   tsubst_flags_t complain,
8824                   tree in_decl)
8825 {
8826   tree remaining_arg_types;
8827   tree type = NULL_TREE;
8828   int i = 1;
8829   tree expanded_args = NULL_TREE;
8830   tree default_arg;
8831
8832   if (!arg_types || arg_types == void_list_node)
8833     return arg_types;
8834
8835   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8836                                           args, complain, in_decl);
8837   if (remaining_arg_types == error_mark_node)
8838     return error_mark_node;
8839
8840   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8841     {
8842       /* For a pack expansion, perform substitution on the
8843          entire expression. Later on, we'll handle the arguments
8844          one-by-one.  */
8845       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8846                                             args, complain, in_decl);
8847
8848       if (TREE_CODE (expanded_args) == TREE_VEC)
8849         /* So that we'll spin through the parameters, one by one.  */
8850         i = TREE_VEC_LENGTH (expanded_args);
8851       else
8852         {
8853           /* We only partially substituted into the parameter
8854              pack. Our type is TYPE_PACK_EXPANSION.  */
8855           type = expanded_args;
8856           expanded_args = NULL_TREE;
8857         }
8858     }
8859
8860   while (i > 0) {
8861     --i;
8862     
8863     if (expanded_args)
8864       type = TREE_VEC_ELT (expanded_args, i);
8865     else if (!type)
8866       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8867
8868     if (type == error_mark_node)
8869       return error_mark_node;
8870     if (VOID_TYPE_P (type))
8871       {
8872         if (complain & tf_error)
8873           {
8874             error ("invalid parameter type %qT", type);
8875             if (in_decl)
8876               error ("in declaration %q+D", in_decl);
8877           }
8878         return error_mark_node;
8879     }
8880     
8881     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8882        top-level qualifiers as required.  */
8883     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8884
8885     /* We do not substitute into default arguments here.  The standard
8886        mandates that they be instantiated only when needed, which is
8887        done in build_over_call.  */
8888     default_arg = TREE_PURPOSE (arg_types);
8889
8890     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8891       {
8892         /* We've instantiated a template before its default arguments
8893            have been parsed.  This can happen for a nested template
8894            class, and is not an error unless we require the default
8895            argument in a call of this function.  */
8896         remaining_arg_types = 
8897           tree_cons (default_arg, type, remaining_arg_types);
8898         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8899                        remaining_arg_types);
8900       }
8901     else
8902       remaining_arg_types = 
8903         hash_tree_cons (default_arg, type, remaining_arg_types);
8904   }
8905         
8906   return remaining_arg_types;
8907 }
8908
8909 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8910    *not* handle the exception-specification for FNTYPE, because the
8911    initial substitution of explicitly provided template parameters
8912    during argument deduction forbids substitution into the
8913    exception-specification:
8914
8915      [temp.deduct]
8916
8917      All references in the function type of the function template to  the
8918      corresponding template parameters are replaced by the specified tem-
8919      plate argument values.  If a substitution in a template parameter or
8920      in  the function type of the function template results in an invalid
8921      type, type deduction fails.  [Note: The equivalent  substitution  in
8922      exception specifications is done only when the function is instanti-
8923      ated, at which point a program is  ill-formed  if  the  substitution
8924      results in an invalid type.]  */
8925
8926 static tree
8927 tsubst_function_type (tree t,
8928                       tree args,
8929                       tsubst_flags_t complain,
8930                       tree in_decl)
8931 {
8932   tree return_type;
8933   tree arg_types;
8934   tree fntype;
8935
8936   /* The TYPE_CONTEXT is not used for function/method types.  */
8937   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8938
8939   /* Substitute the return type.  */
8940   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8941   if (return_type == error_mark_node)
8942     return error_mark_node;
8943   /* The standard does not presently indicate that creation of a
8944      function type with an invalid return type is a deduction failure.
8945      However, that is clearly analogous to creating an array of "void"
8946      or a reference to a reference.  This is core issue #486.  */
8947   if (TREE_CODE (return_type) == ARRAY_TYPE
8948       || TREE_CODE (return_type) == FUNCTION_TYPE)
8949     {
8950       if (complain & tf_error)
8951         {
8952           if (TREE_CODE (return_type) == ARRAY_TYPE)
8953             error ("function returning an array");
8954           else
8955             error ("function returning a function");
8956         }
8957       return error_mark_node;
8958     }
8959
8960   /* Substitute the argument types.  */
8961   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8962                                 complain, in_decl);
8963   if (arg_types == error_mark_node)
8964     return error_mark_node;
8965
8966   /* Construct a new type node and return it.  */
8967   if (TREE_CODE (t) == FUNCTION_TYPE)
8968     fntype = build_function_type (return_type, arg_types);
8969   else
8970     {
8971       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8972       if (! MAYBE_CLASS_TYPE_P (r))
8973         {
8974           /* [temp.deduct]
8975
8976              Type deduction may fail for any of the following
8977              reasons:
8978
8979              -- Attempting to create "pointer to member of T" when T
8980              is not a class type.  */
8981           if (complain & tf_error)
8982             error ("creating pointer to member function of non-class type %qT",
8983                       r);
8984           return error_mark_node;
8985         }
8986
8987       fntype = build_method_type_directly (r, return_type,
8988                                            TREE_CHAIN (arg_types));
8989     }
8990   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8991   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8992
8993   return fntype;
8994 }
8995
8996 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8997    ARGS into that specification, and return the substituted
8998    specification.  If there is no specification, return NULL_TREE.  */
8999
9000 static tree
9001 tsubst_exception_specification (tree fntype,
9002                                 tree args,
9003                                 tsubst_flags_t complain,
9004                                 tree in_decl)
9005 {
9006   tree specs;
9007   tree new_specs;
9008
9009   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9010   new_specs = NULL_TREE;
9011   if (specs)
9012     {
9013       if (! TREE_VALUE (specs))
9014         new_specs = specs;
9015       else
9016         while (specs)
9017           {
9018             tree spec;
9019             int i, len = 1;
9020             tree expanded_specs = NULL_TREE;
9021
9022             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9023               {
9024                 /* Expand the pack expansion type.  */
9025                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9026                                                        args, complain,
9027                                                        in_decl);
9028
9029                 if (expanded_specs == error_mark_node)
9030                   return error_mark_node;
9031                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9032                   len = TREE_VEC_LENGTH (expanded_specs);
9033                 else
9034                   {
9035                     /* We're substituting into a member template, so
9036                        we got a TYPE_PACK_EXPANSION back.  Add that
9037                        expansion and move on.  */
9038                     gcc_assert (TREE_CODE (expanded_specs) 
9039                                 == TYPE_PACK_EXPANSION);
9040                     new_specs = add_exception_specifier (new_specs,
9041                                                          expanded_specs,
9042                                                          complain);
9043                     specs = TREE_CHAIN (specs);
9044                     continue;
9045                   }
9046               }
9047
9048             for (i = 0; i < len; ++i)
9049               {
9050                 if (expanded_specs)
9051                   spec = TREE_VEC_ELT (expanded_specs, i);
9052                 else
9053                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9054                 if (spec == error_mark_node)
9055                   return spec;
9056                 new_specs = add_exception_specifier (new_specs, spec, 
9057                                                      complain);
9058               }
9059
9060             specs = TREE_CHAIN (specs);
9061           }
9062     }
9063   return new_specs;
9064 }
9065
9066 /* Take the tree structure T and replace template parameters used
9067    therein with the argument vector ARGS.  IN_DECL is an associated
9068    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9069    Issue error and warning messages under control of COMPLAIN.  Note
9070    that we must be relatively non-tolerant of extensions here, in
9071    order to preserve conformance; if we allow substitutions that
9072    should not be allowed, we may allow argument deductions that should
9073    not succeed, and therefore report ambiguous overload situations
9074    where there are none.  In theory, we could allow the substitution,
9075    but indicate that it should have failed, and allow our caller to
9076    make sure that the right thing happens, but we don't try to do this
9077    yet.
9078
9079    This function is used for dealing with types, decls and the like;
9080    for expressions, use tsubst_expr or tsubst_copy.  */
9081
9082 tree
9083 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9084 {
9085   tree type, r;
9086
9087   if (t == NULL_TREE || t == error_mark_node
9088       || t == integer_type_node
9089       || t == void_type_node
9090       || t == char_type_node
9091       || t == unknown_type_node
9092       || TREE_CODE (t) == NAMESPACE_DECL)
9093     return t;
9094
9095   if (DECL_P (t))
9096     return tsubst_decl (t, args, complain);
9097
9098   if (args == NULL_TREE)
9099     return t;
9100
9101   if (TREE_CODE (t) == IDENTIFIER_NODE)
9102     type = IDENTIFIER_TYPE_VALUE (t);
9103   else
9104     type = TREE_TYPE (t);
9105
9106   gcc_assert (type != unknown_type_node);
9107
9108   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9109      such as attribute aligned.  */
9110   if (TYPE_P (t)
9111       && TYPE_NAME (t)
9112       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9113     {
9114       tree decl = TYPE_NAME (t);
9115       
9116       if (DECL_CLASS_SCOPE_P (decl)
9117           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9118           && uses_template_parms (DECL_CONTEXT (decl)))
9119         {
9120           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9121           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9122           r = retrieve_specialization (tmpl, gen_args, false);
9123         }
9124       else if (DECL_FUNCTION_SCOPE_P (decl)
9125                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9126                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9127         r = retrieve_local_specialization (decl);
9128       else
9129         /* The typedef is from a non-template context.  */
9130         return t;
9131
9132       if (r)
9133         {
9134           r = TREE_TYPE (r);
9135           r = cp_build_qualified_type_real
9136             (r, cp_type_quals (t) | cp_type_quals (r),
9137              complain | tf_ignore_bad_quals);
9138           return r;
9139         }
9140       /* Else we must be instantiating the typedef, so fall through.  */
9141     }
9142
9143   if (type
9144       && TREE_CODE (t) != TYPENAME_TYPE
9145       && TREE_CODE (t) != IDENTIFIER_NODE
9146       && TREE_CODE (t) != FUNCTION_TYPE
9147       && TREE_CODE (t) != METHOD_TYPE)
9148     type = tsubst (type, args, complain, in_decl);
9149   if (type == error_mark_node)
9150     return error_mark_node;
9151
9152   switch (TREE_CODE (t))
9153     {
9154     case RECORD_TYPE:
9155     case UNION_TYPE:
9156     case ENUMERAL_TYPE:
9157       return tsubst_aggr_type (t, args, complain, in_decl,
9158                                /*entering_scope=*/0);
9159
9160     case ERROR_MARK:
9161     case IDENTIFIER_NODE:
9162     case VOID_TYPE:
9163     case REAL_TYPE:
9164     case COMPLEX_TYPE:
9165     case VECTOR_TYPE:
9166     case BOOLEAN_TYPE:
9167     case INTEGER_CST:
9168     case REAL_CST:
9169     case STRING_CST:
9170       return t;
9171
9172     case INTEGER_TYPE:
9173       if (t == integer_type_node)
9174         return t;
9175
9176       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9177           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9178         return t;
9179
9180       {
9181         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9182
9183         max = tsubst_expr (omax, args, complain, in_decl,
9184                            /*integral_constant_expression_p=*/false);
9185
9186         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9187            needed.  */
9188         if (TREE_CODE (max) == NOP_EXPR
9189             && TREE_SIDE_EFFECTS (omax)
9190             && !TREE_TYPE (max))
9191           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9192
9193         max = fold_decl_constant_value (max);
9194
9195         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9196            with TREE_SIDE_EFFECTS that indicates this is not an integral
9197            constant expression.  */
9198         if (processing_template_decl
9199             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9200           {
9201             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9202             TREE_SIDE_EFFECTS (max) = 1;
9203           }
9204
9205         if (TREE_CODE (max) != INTEGER_CST
9206             && !at_function_scope_p ()
9207             && !TREE_SIDE_EFFECTS (max)
9208             && !value_dependent_expression_p (max))
9209           {
9210             if (complain & tf_error)
9211               error ("array bound is not an integer constant");
9212             return error_mark_node;
9213           }
9214
9215         /* [temp.deduct]
9216
9217            Type deduction may fail for any of the following
9218            reasons:
9219
9220              Attempting to create an array with a size that is
9221              zero or negative.  */
9222         if (integer_zerop (max) && !(complain & tf_error))
9223           /* We must fail if performing argument deduction (as
9224              indicated by the state of complain), so that
9225              another substitution can be found.  */
9226           return error_mark_node;
9227         else if (TREE_CODE (max) == INTEGER_CST
9228                  && INT_CST_LT (max, integer_zero_node))
9229           {
9230             if (complain & tf_error)
9231               error ("creating array with negative size (%qE)", max);
9232
9233             return error_mark_node;
9234           }
9235
9236         return compute_array_index_type (NULL_TREE, max);
9237       }
9238
9239     case TEMPLATE_TYPE_PARM:
9240     case TEMPLATE_TEMPLATE_PARM:
9241     case BOUND_TEMPLATE_TEMPLATE_PARM:
9242     case TEMPLATE_PARM_INDEX:
9243       {
9244         int idx;
9245         int level;
9246         int levels;
9247         tree arg = NULL_TREE;
9248
9249         r = NULL_TREE;
9250
9251         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9252         template_parm_level_and_index (t, &level, &idx); 
9253
9254         levels = TMPL_ARGS_DEPTH (args);
9255         if (level <= levels)
9256           {
9257             arg = TMPL_ARG (args, level, idx);
9258
9259             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9260               /* See through ARGUMENT_PACK_SELECT arguments. */
9261               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9262           }
9263
9264         if (arg == error_mark_node)
9265           return error_mark_node;
9266         else if (arg != NULL_TREE)
9267           {
9268             if (ARGUMENT_PACK_P (arg))
9269               /* If ARG is an argument pack, we don't actually want to
9270                  perform a substitution here, because substitutions
9271                  for argument packs are only done
9272                  element-by-element. We can get to this point when
9273                  substituting the type of a non-type template
9274                  parameter pack, when that type actually contains
9275                  template parameter packs from an outer template, e.g.,
9276
9277                  template<typename... Types> struct A {
9278                    template<Types... Values> struct B { };
9279                  };  */
9280               return t;
9281
9282             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9283               {
9284                 int quals;
9285                 gcc_assert (TYPE_P (arg));
9286
9287                 /* cv-quals from the template are discarded when
9288                    substituting in a function or reference type.  */
9289                 if (TREE_CODE (arg) == FUNCTION_TYPE
9290                     || TREE_CODE (arg) == METHOD_TYPE
9291                     || TREE_CODE (arg) == REFERENCE_TYPE)
9292                   quals = cp_type_quals (arg);
9293                 else
9294                   quals = cp_type_quals (arg) | cp_type_quals (t);
9295                   
9296                 return cp_build_qualified_type_real
9297                   (arg, quals, complain | tf_ignore_bad_quals);
9298               }
9299             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9300               {
9301                 /* We are processing a type constructed from a
9302                    template template parameter.  */
9303                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9304                                       args, complain, in_decl);
9305                 if (argvec == error_mark_node)
9306                   return error_mark_node;
9307
9308                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9309                    are resolving nested-types in the signature of a
9310                    member function templates.  Otherwise ARG is a
9311                    TEMPLATE_DECL and is the real template to be
9312                    instantiated.  */
9313                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9314                   arg = TYPE_NAME (arg);
9315
9316                 r = lookup_template_class (arg,
9317                                            argvec, in_decl,
9318                                            DECL_CONTEXT (arg),
9319                                             /*entering_scope=*/0,
9320                                            complain);
9321                 return cp_build_qualified_type_real
9322                   (r, TYPE_QUALS (t), complain);
9323               }
9324             else
9325               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9326               return arg;
9327           }
9328
9329         if (level == 1)
9330           /* This can happen during the attempted tsubst'ing in
9331              unify.  This means that we don't yet have any information
9332              about the template parameter in question.  */
9333           return t;
9334
9335         /* If we get here, we must have been looking at a parm for a
9336            more deeply nested template.  Make a new version of this
9337            template parameter, but with a lower level.  */
9338         switch (TREE_CODE (t))
9339           {
9340           case TEMPLATE_TYPE_PARM:
9341           case TEMPLATE_TEMPLATE_PARM:
9342           case BOUND_TEMPLATE_TEMPLATE_PARM:
9343             if (cp_type_quals (t))
9344               {
9345                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9346                 r = cp_build_qualified_type_real
9347                   (r, cp_type_quals (t),
9348                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9349                                ? tf_ignore_bad_quals : 0));
9350               }
9351             else
9352               {
9353                 r = copy_type (t);
9354                 TEMPLATE_TYPE_PARM_INDEX (r)
9355                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9356                                                 r, levels, args, complain);
9357                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9358                 TYPE_MAIN_VARIANT (r) = r;
9359                 TYPE_POINTER_TO (r) = NULL_TREE;
9360                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9361
9362                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9363                   /* We have reduced the level of the template
9364                      template parameter, but not the levels of its
9365                      template parameters, so canonical_type_parameter
9366                      will not be able to find the canonical template
9367                      template parameter for this level. Thus, we
9368                      require structural equality checking to compare
9369                      TEMPLATE_TEMPLATE_PARMs. */
9370                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9371                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9372                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9373                 else
9374                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9375
9376                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9377                   {
9378                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9379                                           complain, in_decl);
9380                     if (argvec == error_mark_node)
9381                       return error_mark_node;
9382
9383                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9384                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9385                   }
9386               }
9387             break;
9388
9389           case TEMPLATE_PARM_INDEX:
9390             r = reduce_template_parm_level (t, type, levels, args, complain);
9391             break;
9392
9393           default:
9394             gcc_unreachable ();
9395           }
9396
9397         return r;
9398       }
9399
9400     case TREE_LIST:
9401       {
9402         tree purpose, value, chain;
9403
9404         if (t == void_list_node)
9405           return t;
9406
9407         purpose = TREE_PURPOSE (t);
9408         if (purpose)
9409           {
9410             purpose = tsubst (purpose, args, complain, in_decl);
9411             if (purpose == error_mark_node)
9412               return error_mark_node;
9413           }
9414         value = TREE_VALUE (t);
9415         if (value)
9416           {
9417             value = tsubst (value, args, complain, in_decl);
9418             if (value == error_mark_node)
9419               return error_mark_node;
9420           }
9421         chain = TREE_CHAIN (t);
9422         if (chain && chain != void_type_node)
9423           {
9424             chain = tsubst (chain, args, complain, in_decl);
9425             if (chain == error_mark_node)
9426               return error_mark_node;
9427           }
9428         if (purpose == TREE_PURPOSE (t)
9429             && value == TREE_VALUE (t)
9430             && chain == TREE_CHAIN (t))
9431           return t;
9432         return hash_tree_cons (purpose, value, chain);
9433       }
9434
9435     case TREE_BINFO:
9436       /* We should never be tsubsting a binfo.  */
9437       gcc_unreachable ();
9438
9439     case TREE_VEC:
9440       /* A vector of template arguments.  */
9441       gcc_assert (!type);
9442       return tsubst_template_args (t, args, complain, in_decl);
9443
9444     case POINTER_TYPE:
9445     case REFERENCE_TYPE:
9446       {
9447         enum tree_code code;
9448
9449         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9450           return t;
9451
9452         code = TREE_CODE (t);
9453
9454
9455         /* [temp.deduct]
9456
9457            Type deduction may fail for any of the following
9458            reasons:
9459
9460            -- Attempting to create a pointer to reference type.
9461            -- Attempting to create a reference to a reference type or
9462               a reference to void.
9463
9464           Core issue 106 says that creating a reference to a reference
9465           during instantiation is no longer a cause for failure. We
9466           only enforce this check in strict C++98 mode.  */
9467         if ((TREE_CODE (type) == REFERENCE_TYPE
9468              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9469             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9470           {
9471             static location_t last_loc;
9472
9473             /* We keep track of the last time we issued this error
9474                message to avoid spewing a ton of messages during a
9475                single bad template instantiation.  */
9476             if (complain & tf_error
9477                 && last_loc != input_location)
9478               {
9479                 if (TREE_CODE (type) == VOID_TYPE)
9480                   error ("forming reference to void");
9481                 else
9482                   error ("forming %s to reference type %qT",
9483                          (code == POINTER_TYPE) ? "pointer" : "reference",
9484                          type);
9485                 last_loc = input_location;
9486               }
9487
9488             return error_mark_node;
9489           }
9490         else if (code == POINTER_TYPE)
9491           {
9492             r = build_pointer_type (type);
9493             if (TREE_CODE (type) == METHOD_TYPE)
9494               r = build_ptrmemfunc_type (r);
9495           }
9496         else if (TREE_CODE (type) == REFERENCE_TYPE)
9497           /* In C++0x, during template argument substitution, when there is an
9498              attempt to create a reference to a reference type, reference
9499              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9500
9501              "If a template-argument for a template-parameter T names a type
9502              that is a reference to a type A, an attempt to create the type
9503              'lvalue reference to cv T' creates the type 'lvalue reference to
9504              A,' while an attempt to create the type type rvalue reference to
9505              cv T' creates the type T"
9506           */
9507           r = cp_build_reference_type
9508               (TREE_TYPE (type),
9509                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9510         else
9511           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9512         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9513
9514         if (r != error_mark_node)
9515           /* Will this ever be needed for TYPE_..._TO values?  */
9516           layout_type (r);
9517
9518         return r;
9519       }
9520     case OFFSET_TYPE:
9521       {
9522         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9523         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9524           {
9525             /* [temp.deduct]
9526
9527                Type deduction may fail for any of the following
9528                reasons:
9529
9530                -- Attempting to create "pointer to member of T" when T
9531                   is not a class type.  */
9532             if (complain & tf_error)
9533               error ("creating pointer to member of non-class type %qT", r);
9534             return error_mark_node;
9535           }
9536         if (TREE_CODE (type) == REFERENCE_TYPE)
9537           {
9538             if (complain & tf_error)
9539               error ("creating pointer to member reference type %qT", type);
9540             return error_mark_node;
9541           }
9542         if (TREE_CODE (type) == VOID_TYPE)
9543           {
9544             if (complain & tf_error)
9545               error ("creating pointer to member of type void");
9546             return error_mark_node;
9547           }
9548         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9549         if (TREE_CODE (type) == FUNCTION_TYPE)
9550           {
9551             /* The type of the implicit object parameter gets its
9552                cv-qualifiers from the FUNCTION_TYPE. */
9553             tree method_type;
9554             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9555                                                       cp_type_quals (type));
9556             tree memptr;
9557             method_type = build_method_type_directly (this_type,
9558                                                       TREE_TYPE (type),
9559                                                       TYPE_ARG_TYPES (type));
9560             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9561             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9562                                                  complain);
9563           }
9564         else
9565           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9566                                                TYPE_QUALS (t),
9567                                                complain);
9568       }
9569     case FUNCTION_TYPE:
9570     case METHOD_TYPE:
9571       {
9572         tree fntype;
9573         tree specs;
9574         fntype = tsubst_function_type (t, args, complain, in_decl);
9575         if (fntype == error_mark_node)
9576           return error_mark_node;
9577
9578         /* Substitute the exception specification.  */
9579         specs = tsubst_exception_specification (t, args, complain,
9580                                                 in_decl);
9581         if (specs == error_mark_node)
9582           return error_mark_node;
9583         if (specs)
9584           fntype = build_exception_variant (fntype, specs);
9585         return fntype;
9586       }
9587     case ARRAY_TYPE:
9588       {
9589         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9590         if (domain == error_mark_node)
9591           return error_mark_node;
9592
9593         /* As an optimization, we avoid regenerating the array type if
9594            it will obviously be the same as T.  */
9595         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9596           return t;
9597
9598         /* These checks should match the ones in grokdeclarator.
9599
9600            [temp.deduct]
9601
9602            The deduction may fail for any of the following reasons:
9603
9604            -- Attempting to create an array with an element type that
9605               is void, a function type, or a reference type, or [DR337]
9606               an abstract class type.  */
9607         if (TREE_CODE (type) == VOID_TYPE
9608             || TREE_CODE (type) == FUNCTION_TYPE
9609             || TREE_CODE (type) == REFERENCE_TYPE)
9610           {
9611             if (complain & tf_error)
9612               error ("creating array of %qT", type);
9613             return error_mark_node;
9614           }
9615         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9616           {
9617             if (complain & tf_error)
9618               error ("creating array of %qT, which is an abstract class type",
9619                      type);
9620             return error_mark_node;
9621           }
9622
9623         r = build_cplus_array_type (type, domain);
9624
9625         if (TYPE_USER_ALIGN (t))
9626           {
9627             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9628             TYPE_USER_ALIGN (r) = 1;
9629           }
9630
9631         return r;
9632       }
9633
9634     case PLUS_EXPR:
9635     case MINUS_EXPR:
9636       {
9637         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9638         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9639
9640         if (e1 == error_mark_node || e2 == error_mark_node)
9641           return error_mark_node;
9642
9643         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9644       }
9645
9646     case NEGATE_EXPR:
9647     case NOP_EXPR:
9648       {
9649         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9650         if (e == error_mark_node)
9651           return error_mark_node;
9652
9653         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9654       }
9655
9656     case TYPENAME_TYPE:
9657       {
9658         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9659                                      in_decl, /*entering_scope=*/1);
9660         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9661                               complain, in_decl);
9662
9663         if (ctx == error_mark_node || f == error_mark_node)
9664           return error_mark_node;
9665
9666         if (!MAYBE_CLASS_TYPE_P (ctx))
9667           {
9668             if (complain & tf_error)
9669               error ("%qT is not a class, struct, or union type", ctx);
9670             return error_mark_node;
9671           }
9672         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9673           {
9674             /* Normally, make_typename_type does not require that the CTX
9675                have complete type in order to allow things like:
9676
9677                  template <class T> struct S { typename S<T>::X Y; };
9678
9679                But, such constructs have already been resolved by this
9680                point, so here CTX really should have complete type, unless
9681                it's a partial instantiation.  */
9682             ctx = complete_type (ctx);
9683             if (!COMPLETE_TYPE_P (ctx))
9684               {
9685                 if (complain & tf_error)
9686                   cxx_incomplete_type_error (NULL_TREE, ctx);
9687                 return error_mark_node;
9688               }
9689           }
9690
9691         f = make_typename_type (ctx, f, typename_type,
9692                                 (complain & tf_error) | tf_keep_type_decl);
9693         if (f == error_mark_node)
9694           return f;
9695         if (TREE_CODE (f) == TYPE_DECL)
9696           {
9697             complain |= tf_ignore_bad_quals;
9698             f = TREE_TYPE (f);
9699           }
9700
9701         if (TREE_CODE (f) != TYPENAME_TYPE)
9702           {
9703             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9704               error ("%qT resolves to %qT, which is not an enumeration type",
9705                      t, f);
9706             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9707               error ("%qT resolves to %qT, which is is not a class type",
9708                      t, f);
9709           }
9710
9711         return cp_build_qualified_type_real
9712           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9713       }
9714
9715     case UNBOUND_CLASS_TEMPLATE:
9716       {
9717         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9718                                      in_decl, /*entering_scope=*/1);
9719         tree name = TYPE_IDENTIFIER (t);
9720         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9721
9722         if (ctx == error_mark_node || name == error_mark_node)
9723           return error_mark_node;
9724
9725         if (parm_list)
9726           parm_list = tsubst_template_parms (parm_list, args, complain);
9727         return make_unbound_class_template (ctx, name, parm_list, complain);
9728       }
9729
9730     case INDIRECT_REF:
9731     case ADDR_EXPR:
9732     case CALL_EXPR:
9733       gcc_unreachable ();
9734
9735     case ARRAY_REF:
9736       {
9737         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9738         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9739                                /*integral_constant_expression_p=*/false);
9740         if (e1 == error_mark_node || e2 == error_mark_node)
9741           return error_mark_node;
9742
9743         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9744       }
9745
9746     case SCOPE_REF:
9747       {
9748         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9749         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9750         if (e1 == error_mark_node || e2 == error_mark_node)
9751           return error_mark_node;
9752
9753         return build_qualified_name (/*type=*/NULL_TREE,
9754                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9755       }
9756
9757     case TYPEOF_TYPE:
9758       {
9759         tree type;
9760
9761         type = finish_typeof (tsubst_expr 
9762                               (TYPEOF_TYPE_EXPR (t), args,
9763                                complain, in_decl,
9764                                /*integral_constant_expression_p=*/false));
9765         return cp_build_qualified_type_real (type,
9766                                              cp_type_quals (t)
9767                                              | cp_type_quals (type),
9768                                              complain);
9769       }
9770
9771     case DECLTYPE_TYPE:
9772       {
9773         tree type;
9774
9775         ++skip_evaluation;
9776
9777         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9778                             complain, in_decl,
9779                             /*integral_constant_expression_p=*/false);
9780
9781         --skip_evaluation;
9782
9783         type =
9784           finish_decltype_type (type,
9785                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9786         return cp_build_qualified_type_real (type,
9787                                              cp_type_quals (t)
9788                                              | cp_type_quals (type),
9789                                              complain);
9790       }
9791
9792     case TYPE_ARGUMENT_PACK:
9793     case NONTYPE_ARGUMENT_PACK:
9794       {
9795         tree r = make_node (TREE_CODE (t));
9796         tree packed_out = 
9797           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9798                                 args,
9799                                 complain,
9800                                 in_decl);
9801         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9802
9803         /* For template nontype argument packs, also substitute into
9804            the type.  */
9805         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9806           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9807
9808         return r;
9809       }
9810       break;
9811
9812     default:
9813       sorry ("use of %qs in template",
9814              tree_code_name [(int) TREE_CODE (t)]);
9815       return error_mark_node;
9816     }
9817 }
9818
9819 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9820    type of the expression on the left-hand side of the "." or "->"
9821    operator.  */
9822
9823 static tree
9824 tsubst_baselink (tree baselink, tree object_type,
9825                  tree args, tsubst_flags_t complain, tree in_decl)
9826 {
9827     tree name;
9828     tree qualifying_scope;
9829     tree fns;
9830     tree optype;
9831     tree template_args = 0;
9832     bool template_id_p = false;
9833
9834     /* A baselink indicates a function from a base class.  Both the
9835        BASELINK_ACCESS_BINFO and the base class referenced may
9836        indicate bases of the template class, rather than the
9837        instantiated class.  In addition, lookups that were not
9838        ambiguous before may be ambiguous now.  Therefore, we perform
9839        the lookup again.  */
9840     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9841     qualifying_scope = tsubst (qualifying_scope, args,
9842                                complain, in_decl);
9843     fns = BASELINK_FUNCTIONS (baselink);
9844     optype = BASELINK_OPTYPE (baselink);
9845     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9846       {
9847         template_id_p = true;
9848         template_args = TREE_OPERAND (fns, 1);
9849         fns = TREE_OPERAND (fns, 0);
9850         if (template_args)
9851           template_args = tsubst_template_args (template_args, args,
9852                                                 complain, in_decl);
9853       }
9854     name = DECL_NAME (get_first_fn (fns));
9855     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9856
9857     /* If lookup found a single function, mark it as used at this
9858        point.  (If it lookup found multiple functions the one selected
9859        later by overload resolution will be marked as used at that
9860        point.)  */
9861     if (BASELINK_P (baselink))
9862       fns = BASELINK_FUNCTIONS (baselink);
9863     if (!template_id_p && !really_overloaded_fn (fns))
9864       mark_used (OVL_CURRENT (fns));
9865
9866     /* Add back the template arguments, if present.  */
9867     if (BASELINK_P (baselink) && template_id_p)
9868       BASELINK_FUNCTIONS (baselink)
9869         = build_nt (TEMPLATE_ID_EXPR,
9870                     BASELINK_FUNCTIONS (baselink),
9871                     template_args);
9872     /* Update the conversion operator type.  */
9873     BASELINK_OPTYPE (baselink) 
9874       = tsubst (optype, args, complain, in_decl);
9875
9876     if (!object_type)
9877       object_type = current_class_type;
9878     return adjust_result_of_qualified_name_lookup (baselink,
9879                                                    qualifying_scope,
9880                                                    object_type);
9881 }
9882
9883 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9884    true if the qualified-id will be a postfix-expression in-and-of
9885    itself; false if more of the postfix-expression follows the
9886    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9887    of "&".  */
9888
9889 static tree
9890 tsubst_qualified_id (tree qualified_id, tree args,
9891                      tsubst_flags_t complain, tree in_decl,
9892                      bool done, bool address_p)
9893 {
9894   tree expr;
9895   tree scope;
9896   tree name;
9897   bool is_template;
9898   tree template_args;
9899
9900   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9901
9902   /* Figure out what name to look up.  */
9903   name = TREE_OPERAND (qualified_id, 1);
9904   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9905     {
9906       is_template = true;
9907       template_args = TREE_OPERAND (name, 1);
9908       if (template_args)
9909         template_args = tsubst_template_args (template_args, args,
9910                                               complain, in_decl);
9911       name = TREE_OPERAND (name, 0);
9912     }
9913   else
9914     {
9915       is_template = false;
9916       template_args = NULL_TREE;
9917     }
9918
9919   /* Substitute into the qualifying scope.  When there are no ARGS, we
9920      are just trying to simplify a non-dependent expression.  In that
9921      case the qualifying scope may be dependent, and, in any case,
9922      substituting will not help.  */
9923   scope = TREE_OPERAND (qualified_id, 0);
9924   if (args)
9925     {
9926       scope = tsubst (scope, args, complain, in_decl);
9927       expr = tsubst_copy (name, args, complain, in_decl);
9928     }
9929   else
9930     expr = name;
9931
9932   if (dependent_type_p (scope))
9933     return build_qualified_name (/*type=*/NULL_TREE,
9934                                  scope, expr,
9935                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9936
9937   if (!BASELINK_P (name) && !DECL_P (expr))
9938     {
9939       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9940         /* If this were actually a destructor call, it would have been
9941            parsed as such by the parser.  */
9942         expr = error_mark_node;
9943       else
9944         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9945       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9946                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9947         {
9948           if (complain & tf_error)
9949             {
9950               error ("dependent-name %qE is parsed as a non-type, but "
9951                      "instantiation yields a type", qualified_id);
9952               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
9953             }
9954           return error_mark_node;
9955         }
9956     }
9957
9958   if (DECL_P (expr))
9959     {
9960       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9961                                            scope);
9962       /* Remember that there was a reference to this entity.  */
9963       mark_used (expr);
9964     }
9965
9966   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9967     {
9968       if (complain & tf_error)
9969         qualified_name_lookup_error (scope,
9970                                      TREE_OPERAND (qualified_id, 1),
9971                                      expr, input_location);
9972       return error_mark_node;
9973     }
9974
9975   if (is_template)
9976     expr = lookup_template_function (expr, template_args);
9977
9978   if (expr == error_mark_node && complain & tf_error)
9979     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9980                                  expr, input_location);
9981   else if (TYPE_P (scope))
9982     {
9983       expr = (adjust_result_of_qualified_name_lookup
9984               (expr, scope, current_class_type));
9985       expr = (finish_qualified_id_expr
9986               (scope, expr, done, address_p,
9987                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9988                /*template_arg_p=*/false));
9989     }
9990
9991   /* Expressions do not generally have reference type.  */
9992   if (TREE_CODE (expr) != SCOPE_REF
9993       /* However, if we're about to form a pointer-to-member, we just
9994          want the referenced member referenced.  */
9995       && TREE_CODE (expr) != OFFSET_REF)
9996     expr = convert_from_reference (expr);
9997
9998   return expr;
9999 }
10000
10001 /* Like tsubst, but deals with expressions.  This function just replaces
10002    template parms; to finish processing the resultant expression, use
10003    tsubst_expr.  */
10004
10005 static tree
10006 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10007 {
10008   enum tree_code code;
10009   tree r;
10010
10011   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10012     return t;
10013
10014   code = TREE_CODE (t);
10015
10016   switch (code)
10017     {
10018     case PARM_DECL:
10019       r = retrieve_local_specialization (t);
10020
10021       if (r == NULL)
10022         {
10023           tree c;
10024           /* This can happen for a parameter name used later in a function
10025              declaration (such as in a late-specified return type).  Just
10026              make a dummy decl, since it's only used for its type.  */
10027           gcc_assert (skip_evaluation);   
10028           /* We copy T because want to tsubst the PARM_DECL only,
10029              not the following PARM_DECLs that are chained to T.  */
10030           c = copy_node (t);
10031           r = tsubst_decl (c, args, complain);
10032           /* Give it the template pattern as its context; its true context
10033              hasn't been instantiated yet and this is good enough for
10034              mangling.  */
10035           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10036         }
10037       
10038       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10039         r = ARGUMENT_PACK_SELECT_ARG (r);
10040       mark_used (r);
10041       return r;
10042
10043     case CONST_DECL:
10044       {
10045         tree enum_type;
10046         tree v;
10047
10048         if (DECL_TEMPLATE_PARM_P (t))
10049           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10050         /* There is no need to substitute into namespace-scope
10051            enumerators.  */
10052         if (DECL_NAMESPACE_SCOPE_P (t))
10053           return t;
10054         /* If ARGS is NULL, then T is known to be non-dependent.  */
10055         if (args == NULL_TREE)
10056           return integral_constant_value (t);
10057
10058         /* Unfortunately, we cannot just call lookup_name here.
10059            Consider:
10060
10061              template <int I> int f() {
10062              enum E { a = I };
10063              struct S { void g() { E e = a; } };
10064              };
10065
10066            When we instantiate f<7>::S::g(), say, lookup_name is not
10067            clever enough to find f<7>::a.  */
10068         enum_type
10069           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10070                               /*entering_scope=*/0);
10071
10072         for (v = TYPE_VALUES (enum_type);
10073              v != NULL_TREE;
10074              v = TREE_CHAIN (v))
10075           if (TREE_PURPOSE (v) == DECL_NAME (t))
10076             return TREE_VALUE (v);
10077
10078           /* We didn't find the name.  That should never happen; if
10079              name-lookup found it during preliminary parsing, we
10080              should find it again here during instantiation.  */
10081         gcc_unreachable ();
10082       }
10083       return t;
10084
10085     case FIELD_DECL:
10086       if (DECL_CONTEXT (t))
10087         {
10088           tree ctx;
10089
10090           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10091                                   /*entering_scope=*/1);
10092           if (ctx != DECL_CONTEXT (t))
10093             {
10094               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10095               if (!r)
10096                 {
10097                   if (complain & tf_error)
10098                     error ("using invalid field %qD", t);
10099                   return error_mark_node;
10100                 }
10101               return r;
10102             }
10103         }
10104
10105       return t;
10106
10107     case VAR_DECL:
10108     case FUNCTION_DECL:
10109       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10110           || local_variable_p (t))
10111         t = tsubst (t, args, complain, in_decl);
10112       mark_used (t);
10113       return t;
10114
10115     case BASELINK:
10116       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10117
10118     case TEMPLATE_DECL:
10119       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10120         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10121                        args, complain, in_decl);
10122       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10123         return tsubst (t, args, complain, in_decl);
10124       else if (DECL_CLASS_SCOPE_P (t)
10125                && uses_template_parms (DECL_CONTEXT (t)))
10126         {
10127           /* Template template argument like the following example need
10128              special treatment:
10129
10130                template <template <class> class TT> struct C {};
10131                template <class T> struct D {
10132                  template <class U> struct E {};
10133                  C<E> c;                                // #1
10134                };
10135                D<int> d;                                // #2
10136
10137              We are processing the template argument `E' in #1 for
10138              the template instantiation #2.  Originally, `E' is a
10139              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10140              have to substitute this with one having context `D<int>'.  */
10141
10142           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10143           return lookup_field (context, DECL_NAME(t), 0, false);
10144         }
10145       else
10146         /* Ordinary template template argument.  */
10147         return t;
10148
10149     case CAST_EXPR:
10150     case REINTERPRET_CAST_EXPR:
10151     case CONST_CAST_EXPR:
10152     case STATIC_CAST_EXPR:
10153     case DYNAMIC_CAST_EXPR:
10154     case NOP_EXPR:
10155       return build1
10156         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10157          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10158
10159     case SIZEOF_EXPR:
10160       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10161         {
10162           /* We only want to compute the number of arguments.  */
10163           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10164                                                 complain, in_decl);
10165           int len = 0;
10166
10167           if (TREE_CODE (expanded) == TREE_VEC)
10168             len = TREE_VEC_LENGTH (expanded);
10169
10170           if (expanded == error_mark_node)
10171             return error_mark_node;
10172           else if (PACK_EXPANSION_P (expanded)
10173                    || (TREE_CODE (expanded) == TREE_VEC
10174                        && len > 0
10175                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10176             {
10177               if (TREE_CODE (expanded) == TREE_VEC)
10178                 expanded = TREE_VEC_ELT (expanded, len - 1);
10179
10180               if (TYPE_P (expanded))
10181                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10182                                                    complain & tf_error);
10183               else
10184                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10185                                                    complain & tf_error);
10186             }
10187           else
10188             return build_int_cst (size_type_node, len);
10189         }
10190       /* Fall through */
10191
10192     case INDIRECT_REF:
10193     case NEGATE_EXPR:
10194     case TRUTH_NOT_EXPR:
10195     case BIT_NOT_EXPR:
10196     case ADDR_EXPR:
10197     case UNARY_PLUS_EXPR:      /* Unary + */
10198     case ALIGNOF_EXPR:
10199     case ARROW_EXPR:
10200     case THROW_EXPR:
10201     case TYPEID_EXPR:
10202     case REALPART_EXPR:
10203     case IMAGPART_EXPR:
10204       return build1
10205         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10206          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10207
10208     case COMPONENT_REF:
10209       {
10210         tree object;
10211         tree name;
10212
10213         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10214         name = TREE_OPERAND (t, 1);
10215         if (TREE_CODE (name) == BIT_NOT_EXPR)
10216           {
10217             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10218                                 complain, in_decl);
10219             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10220           }
10221         else if (TREE_CODE (name) == SCOPE_REF
10222                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10223           {
10224             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10225                                      complain, in_decl);
10226             name = TREE_OPERAND (name, 1);
10227             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10228                                 complain, in_decl);
10229             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10230             name = build_qualified_name (/*type=*/NULL_TREE,
10231                                          base, name,
10232                                          /*template_p=*/false);
10233           }
10234         else if (TREE_CODE (name) == BASELINK)
10235           name = tsubst_baselink (name,
10236                                   non_reference (TREE_TYPE (object)),
10237                                   args, complain,
10238                                   in_decl);
10239         else
10240           name = tsubst_copy (name, args, complain, in_decl);
10241         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10242       }
10243
10244     case PLUS_EXPR:
10245     case MINUS_EXPR:
10246     case MULT_EXPR:
10247     case TRUNC_DIV_EXPR:
10248     case CEIL_DIV_EXPR:
10249     case FLOOR_DIV_EXPR:
10250     case ROUND_DIV_EXPR:
10251     case EXACT_DIV_EXPR:
10252     case BIT_AND_EXPR:
10253     case BIT_IOR_EXPR:
10254     case BIT_XOR_EXPR:
10255     case TRUNC_MOD_EXPR:
10256     case FLOOR_MOD_EXPR:
10257     case TRUTH_ANDIF_EXPR:
10258     case TRUTH_ORIF_EXPR:
10259     case TRUTH_AND_EXPR:
10260     case TRUTH_OR_EXPR:
10261     case RSHIFT_EXPR:
10262     case LSHIFT_EXPR:
10263     case RROTATE_EXPR:
10264     case LROTATE_EXPR:
10265     case EQ_EXPR:
10266     case NE_EXPR:
10267     case MAX_EXPR:
10268     case MIN_EXPR:
10269     case LE_EXPR:
10270     case GE_EXPR:
10271     case LT_EXPR:
10272     case GT_EXPR:
10273     case COMPOUND_EXPR:
10274     case DOTSTAR_EXPR:
10275     case MEMBER_REF:
10276     case PREDECREMENT_EXPR:
10277     case PREINCREMENT_EXPR:
10278     case POSTDECREMENT_EXPR:
10279     case POSTINCREMENT_EXPR:
10280       return build_nt
10281         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10282          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10283
10284     case SCOPE_REF:
10285       return build_qualified_name (/*type=*/NULL_TREE,
10286                                    tsubst_copy (TREE_OPERAND (t, 0),
10287                                                 args, complain, in_decl),
10288                                    tsubst_copy (TREE_OPERAND (t, 1),
10289                                                 args, complain, in_decl),
10290                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10291
10292     case ARRAY_REF:
10293       return build_nt
10294         (ARRAY_REF,
10295          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10296          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10297          NULL_TREE, NULL_TREE);
10298
10299     case CALL_EXPR:
10300       {
10301         int n = VL_EXP_OPERAND_LENGTH (t);
10302         tree result = build_vl_exp (CALL_EXPR, n);
10303         int i;
10304         for (i = 0; i < n; i++)
10305           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10306                                              complain, in_decl);
10307         return result;
10308       }
10309
10310     case COND_EXPR:
10311     case MODOP_EXPR:
10312     case PSEUDO_DTOR_EXPR:
10313       {
10314         r = build_nt
10315           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10316            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10317            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10318         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10319         return r;
10320       }
10321
10322     case NEW_EXPR:
10323       {
10324         r = build_nt
10325         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10326          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10327          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10328         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10329         return r;
10330       }
10331
10332     case DELETE_EXPR:
10333       {
10334         r = build_nt
10335         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10336          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10337         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10338         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10339         return r;
10340       }
10341
10342     case TEMPLATE_ID_EXPR:
10343       {
10344         /* Substituted template arguments */
10345         tree fn = TREE_OPERAND (t, 0);
10346         tree targs = TREE_OPERAND (t, 1);
10347
10348         fn = tsubst_copy (fn, args, complain, in_decl);
10349         if (targs)
10350           targs = tsubst_template_args (targs, args, complain, in_decl);
10351
10352         return lookup_template_function (fn, targs);
10353       }
10354
10355     case TREE_LIST:
10356       {
10357         tree purpose, value, chain;
10358
10359         if (t == void_list_node)
10360           return t;
10361
10362         purpose = TREE_PURPOSE (t);
10363         if (purpose)
10364           purpose = tsubst_copy (purpose, args, complain, in_decl);
10365         value = TREE_VALUE (t);
10366         if (value)
10367           value = tsubst_copy (value, args, complain, in_decl);
10368         chain = TREE_CHAIN (t);
10369         if (chain && chain != void_type_node)
10370           chain = tsubst_copy (chain, args, complain, in_decl);
10371         if (purpose == TREE_PURPOSE (t)
10372             && value == TREE_VALUE (t)
10373             && chain == TREE_CHAIN (t))
10374           return t;
10375         return tree_cons (purpose, value, chain);
10376       }
10377
10378     case RECORD_TYPE:
10379     case UNION_TYPE:
10380     case ENUMERAL_TYPE:
10381     case INTEGER_TYPE:
10382     case TEMPLATE_TYPE_PARM:
10383     case TEMPLATE_TEMPLATE_PARM:
10384     case BOUND_TEMPLATE_TEMPLATE_PARM:
10385     case TEMPLATE_PARM_INDEX:
10386     case POINTER_TYPE:
10387     case REFERENCE_TYPE:
10388     case OFFSET_TYPE:
10389     case FUNCTION_TYPE:
10390     case METHOD_TYPE:
10391     case ARRAY_TYPE:
10392     case TYPENAME_TYPE:
10393     case UNBOUND_CLASS_TEMPLATE:
10394     case TYPEOF_TYPE:
10395     case DECLTYPE_TYPE:
10396     case TYPE_DECL:
10397       return tsubst (t, args, complain, in_decl);
10398
10399     case IDENTIFIER_NODE:
10400       if (IDENTIFIER_TYPENAME_P (t))
10401         {
10402           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10403           return mangle_conv_op_name_for_type (new_type);
10404         }
10405       else
10406         return t;
10407
10408     case CONSTRUCTOR:
10409       /* This is handled by tsubst_copy_and_build.  */
10410       gcc_unreachable ();
10411
10412     case VA_ARG_EXPR:
10413       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10414                                           in_decl),
10415                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10416
10417     case CLEANUP_POINT_EXPR:
10418       /* We shouldn't have built any of these during initial template
10419          generation.  Instead, they should be built during instantiation
10420          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10421       gcc_unreachable ();
10422
10423     case OFFSET_REF:
10424       mark_used (TREE_OPERAND (t, 1));
10425       return t;
10426
10427     case EXPR_PACK_EXPANSION:
10428       error ("invalid use of pack expansion expression");
10429       return error_mark_node;
10430
10431     case NONTYPE_ARGUMENT_PACK:
10432       error ("use %<...%> to expand argument pack");
10433       return error_mark_node;
10434
10435     default:
10436       return t;
10437     }
10438 }
10439
10440 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10441
10442 static tree
10443 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10444                     tree in_decl)
10445 {
10446   tree new_clauses = NULL, nc, oc;
10447
10448   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10449     {
10450       nc = copy_node (oc);
10451       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10452       new_clauses = nc;
10453
10454       switch (OMP_CLAUSE_CODE (nc))
10455         {
10456         case OMP_CLAUSE_LASTPRIVATE:
10457           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10458             {
10459               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10460               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10461                            in_decl, /*integral_constant_expression_p=*/false);
10462               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10463                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10464             }
10465           /* FALLTHRU */
10466         case OMP_CLAUSE_PRIVATE:
10467         case OMP_CLAUSE_SHARED:
10468         case OMP_CLAUSE_FIRSTPRIVATE:
10469         case OMP_CLAUSE_REDUCTION:
10470         case OMP_CLAUSE_COPYIN:
10471         case OMP_CLAUSE_COPYPRIVATE:
10472         case OMP_CLAUSE_IF:
10473         case OMP_CLAUSE_NUM_THREADS:
10474         case OMP_CLAUSE_SCHEDULE:
10475         case OMP_CLAUSE_COLLAPSE:
10476           OMP_CLAUSE_OPERAND (nc, 0)
10477             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10478                            in_decl, /*integral_constant_expression_p=*/false);
10479           break;
10480         case OMP_CLAUSE_NOWAIT:
10481         case OMP_CLAUSE_ORDERED:
10482         case OMP_CLAUSE_DEFAULT:
10483         case OMP_CLAUSE_UNTIED:
10484           break;
10485         default:
10486           gcc_unreachable ();
10487         }
10488     }
10489
10490   return finish_omp_clauses (nreverse (new_clauses));
10491 }
10492
10493 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10494
10495 static tree
10496 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10497                           tree in_decl)
10498 {
10499 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10500
10501   tree purpose, value, chain;
10502
10503   if (t == NULL)
10504     return t;
10505
10506   if (TREE_CODE (t) != TREE_LIST)
10507     return tsubst_copy_and_build (t, args, complain, in_decl,
10508                                   /*function_p=*/false,
10509                                   /*integral_constant_expression_p=*/false);
10510
10511   if (t == void_list_node)
10512     return t;
10513
10514   purpose = TREE_PURPOSE (t);
10515   if (purpose)
10516     purpose = RECUR (purpose);
10517   value = TREE_VALUE (t);
10518   if (value)
10519     value = RECUR (value);
10520   chain = TREE_CHAIN (t);
10521   if (chain && chain != void_type_node)
10522     chain = RECUR (chain);
10523   return tree_cons (purpose, value, chain);
10524 #undef RECUR
10525 }
10526
10527 /* Substitute one OMP_FOR iterator.  */
10528
10529 static void
10530 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10531                          tree condv, tree incrv, tree *clauses,
10532                          tree args, tsubst_flags_t complain, tree in_decl,
10533                          bool integral_constant_expression_p)
10534 {
10535 #define RECUR(NODE)                             \
10536   tsubst_expr ((NODE), args, complain, in_decl, \
10537                integral_constant_expression_p)
10538   tree decl, init, cond, incr, auto_node;
10539
10540   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10541   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10542   decl = RECUR (TREE_OPERAND (init, 0));
10543   init = TREE_OPERAND (init, 1);
10544   auto_node = type_uses_auto (TREE_TYPE (decl));
10545   if (auto_node && init)
10546     {
10547       tree init_expr = init;
10548       if (TREE_CODE (init_expr) == DECL_EXPR)
10549         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10550       init_expr = RECUR (init_expr);
10551       TREE_TYPE (decl)
10552         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10553     }
10554   gcc_assert (!type_dependent_expression_p (decl));
10555
10556   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10557     {
10558       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10559       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10560       if (TREE_CODE (incr) == MODIFY_EXPR)
10561         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10562                                     RECUR (TREE_OPERAND (incr, 1)),
10563                                     complain);
10564       else
10565         incr = RECUR (incr);
10566       TREE_VEC_ELT (declv, i) = decl;
10567       TREE_VEC_ELT (initv, i) = init;
10568       TREE_VEC_ELT (condv, i) = cond;
10569       TREE_VEC_ELT (incrv, i) = incr;
10570       return;
10571     }
10572
10573   if (init && TREE_CODE (init) != DECL_EXPR)
10574     {
10575       tree c;
10576       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10577         {
10578           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10579                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10580               && OMP_CLAUSE_DECL (c) == decl)
10581             break;
10582           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10583                    && OMP_CLAUSE_DECL (c) == decl)
10584             error ("iteration variable %qD should not be firstprivate", decl);
10585           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10586                    && OMP_CLAUSE_DECL (c) == decl)
10587             error ("iteration variable %qD should not be reduction", decl);
10588         }
10589       if (c == NULL)
10590         {
10591           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10592           OMP_CLAUSE_DECL (c) = decl;
10593           c = finish_omp_clauses (c);
10594           if (c)
10595             {
10596               OMP_CLAUSE_CHAIN (c) = *clauses;
10597               *clauses = c;
10598             }
10599         }
10600     }
10601   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10602   if (COMPARISON_CLASS_P (cond))
10603     cond = build2 (TREE_CODE (cond), boolean_type_node,
10604                    RECUR (TREE_OPERAND (cond, 0)),
10605                    RECUR (TREE_OPERAND (cond, 1)));
10606   else
10607     cond = RECUR (cond);
10608   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10609   switch (TREE_CODE (incr))
10610     {
10611     case PREINCREMENT_EXPR:
10612     case PREDECREMENT_EXPR:
10613     case POSTINCREMENT_EXPR:
10614     case POSTDECREMENT_EXPR:
10615       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10616                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10617       break;
10618     case MODIFY_EXPR:
10619       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10620           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10621         {
10622           tree rhs = TREE_OPERAND (incr, 1);
10623           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10624                          RECUR (TREE_OPERAND (incr, 0)),
10625                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10626                                  RECUR (TREE_OPERAND (rhs, 0)),
10627                                  RECUR (TREE_OPERAND (rhs, 1))));
10628         }
10629       else
10630         incr = RECUR (incr);
10631       break;
10632     case MODOP_EXPR:
10633       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10634           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10635         {
10636           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10637           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10638                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10639                                  TREE_TYPE (decl), lhs,
10640                                  RECUR (TREE_OPERAND (incr, 2))));
10641         }
10642       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10643                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10644                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10645         {
10646           tree rhs = TREE_OPERAND (incr, 2);
10647           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10648                          RECUR (TREE_OPERAND (incr, 0)),
10649                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10650                                  RECUR (TREE_OPERAND (rhs, 0)),
10651                                  RECUR (TREE_OPERAND (rhs, 1))));
10652         }
10653       else
10654         incr = RECUR (incr);
10655       break;
10656     default:
10657       incr = RECUR (incr);
10658       break;
10659     }
10660
10661   TREE_VEC_ELT (declv, i) = decl;
10662   TREE_VEC_ELT (initv, i) = init;
10663   TREE_VEC_ELT (condv, i) = cond;
10664   TREE_VEC_ELT (incrv, i) = incr;
10665 #undef RECUR
10666 }
10667
10668 /* Like tsubst_copy for expressions, etc. but also does semantic
10669    processing.  */
10670
10671 static tree
10672 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10673              bool integral_constant_expression_p)
10674 {
10675 #define RECUR(NODE)                             \
10676   tsubst_expr ((NODE), args, complain, in_decl, \
10677                integral_constant_expression_p)
10678
10679   tree stmt, tmp;
10680
10681   if (t == NULL_TREE || t == error_mark_node)
10682     return t;
10683
10684   if (EXPR_HAS_LOCATION (t))
10685     input_location = EXPR_LOCATION (t);
10686   if (STATEMENT_CODE_P (TREE_CODE (t)))
10687     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10688
10689   switch (TREE_CODE (t))
10690     {
10691     case STATEMENT_LIST:
10692       {
10693         tree_stmt_iterator i;
10694         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10695           RECUR (tsi_stmt (i));
10696         break;
10697       }
10698
10699     case CTOR_INITIALIZER:
10700       finish_mem_initializers (tsubst_initializer_list
10701                                (TREE_OPERAND (t, 0), args));
10702       break;
10703
10704     case RETURN_EXPR:
10705       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10706       break;
10707
10708     case EXPR_STMT:
10709       tmp = RECUR (EXPR_STMT_EXPR (t));
10710       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10711         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10712       else
10713         finish_expr_stmt (tmp);
10714       break;
10715
10716     case USING_STMT:
10717       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10718       break;
10719
10720     case DECL_EXPR:
10721       {
10722         tree decl;
10723         tree init;
10724
10725         decl = DECL_EXPR_DECL (t);
10726         if (TREE_CODE (decl) == LABEL_DECL)
10727           finish_label_decl (DECL_NAME (decl));
10728         else if (TREE_CODE (decl) == USING_DECL)
10729           {
10730             tree scope = USING_DECL_SCOPE (decl);
10731             tree name = DECL_NAME (decl);
10732             tree decl;
10733
10734             scope = RECUR (scope);
10735             decl = lookup_qualified_name (scope, name,
10736                                           /*is_type_p=*/false,
10737                                           /*complain=*/false);
10738             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10739               qualified_name_lookup_error (scope, name, decl, input_location);
10740             else
10741               do_local_using_decl (decl, scope, name);
10742           }
10743         else
10744           {
10745             init = DECL_INITIAL (decl);
10746             decl = tsubst (decl, args, complain, in_decl);
10747             if (decl != error_mark_node)
10748               {
10749                 /* By marking the declaration as instantiated, we avoid
10750                    trying to instantiate it.  Since instantiate_decl can't
10751                    handle local variables, and since we've already done
10752                    all that needs to be done, that's the right thing to
10753                    do.  */
10754                 if (TREE_CODE (decl) == VAR_DECL)
10755                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10756                 if (TREE_CODE (decl) == VAR_DECL
10757                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10758                   /* Anonymous aggregates are a special case.  */
10759                   finish_anon_union (decl);
10760                 else
10761                   {
10762                     maybe_push_decl (decl);
10763                     if (TREE_CODE (decl) == VAR_DECL
10764                         && DECL_PRETTY_FUNCTION_P (decl))
10765                       {
10766                         /* For __PRETTY_FUNCTION__ we have to adjust the
10767                            initializer.  */
10768                         const char *const name
10769                           = cxx_printable_name (current_function_decl, 2);
10770                         init = cp_fname_init (name, &TREE_TYPE (decl));
10771                       }
10772                     else
10773                       {
10774                         tree t = RECUR (init);
10775
10776                         if (init && !t)
10777                           /* If we had an initializer but it
10778                              instantiated to nothing,
10779                              value-initialize the object.  This will
10780                              only occur when the initializer was a
10781                              pack expansion where the parameter packs
10782                              used in that expansion were of length
10783                              zero.  */
10784                           init = build_value_init (TREE_TYPE (decl));
10785                         else
10786                           init = t;
10787                       }
10788
10789                     finish_decl (decl, init, NULL_TREE, NULL_TREE);
10790                   }
10791               }
10792           }
10793
10794         /* A DECL_EXPR can also be used as an expression, in the condition
10795            clause of an if/for/while construct.  */
10796         return decl;
10797       }
10798
10799     case FOR_STMT:
10800       stmt = begin_for_stmt ();
10801                           RECUR (FOR_INIT_STMT (t));
10802       finish_for_init_stmt (stmt);
10803       tmp = RECUR (FOR_COND (t));
10804       finish_for_cond (tmp, stmt);
10805       tmp = RECUR (FOR_EXPR (t));
10806       finish_for_expr (tmp, stmt);
10807       RECUR (FOR_BODY (t));
10808       finish_for_stmt (stmt);
10809       break;
10810
10811     case WHILE_STMT:
10812       stmt = begin_while_stmt ();
10813       tmp = RECUR (WHILE_COND (t));
10814       finish_while_stmt_cond (tmp, stmt);
10815       RECUR (WHILE_BODY (t));
10816       finish_while_stmt (stmt);
10817       break;
10818
10819     case DO_STMT:
10820       stmt = begin_do_stmt ();
10821       RECUR (DO_BODY (t));
10822       finish_do_body (stmt);
10823       tmp = RECUR (DO_COND (t));
10824       finish_do_stmt (tmp, stmt);
10825       break;
10826
10827     case IF_STMT:
10828       stmt = begin_if_stmt ();
10829       tmp = RECUR (IF_COND (t));
10830       finish_if_stmt_cond (tmp, stmt);
10831       RECUR (THEN_CLAUSE (t));
10832       finish_then_clause (stmt);
10833
10834       if (ELSE_CLAUSE (t))
10835         {
10836           begin_else_clause (stmt);
10837           RECUR (ELSE_CLAUSE (t));
10838           finish_else_clause (stmt);
10839         }
10840
10841       finish_if_stmt (stmt);
10842       break;
10843
10844     case BIND_EXPR:
10845       if (BIND_EXPR_BODY_BLOCK (t))
10846         stmt = begin_function_body ();
10847       else
10848         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10849                                     ? BCS_TRY_BLOCK : 0);
10850
10851       RECUR (BIND_EXPR_BODY (t));
10852
10853       if (BIND_EXPR_BODY_BLOCK (t))
10854         finish_function_body (stmt);
10855       else
10856         finish_compound_stmt (stmt);
10857       break;
10858
10859     case BREAK_STMT:
10860       finish_break_stmt ();
10861       break;
10862
10863     case CONTINUE_STMT:
10864       finish_continue_stmt ();
10865       break;
10866
10867     case SWITCH_STMT:
10868       stmt = begin_switch_stmt ();
10869       tmp = RECUR (SWITCH_STMT_COND (t));
10870       finish_switch_cond (tmp, stmt);
10871       RECUR (SWITCH_STMT_BODY (t));
10872       finish_switch_stmt (stmt);
10873       break;
10874
10875     case CASE_LABEL_EXPR:
10876       finish_case_label (RECUR (CASE_LOW (t)),
10877                          RECUR (CASE_HIGH (t)));
10878       break;
10879
10880     case LABEL_EXPR:
10881       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10882       break;
10883
10884     case GOTO_EXPR:
10885       tmp = GOTO_DESTINATION (t);
10886       if (TREE_CODE (tmp) != LABEL_DECL)
10887         /* Computed goto's must be tsubst'd into.  On the other hand,
10888            non-computed gotos must not be; the identifier in question
10889            will have no binding.  */
10890         tmp = RECUR (tmp);
10891       else
10892         tmp = DECL_NAME (tmp);
10893       finish_goto_stmt (tmp);
10894       break;
10895
10896     case ASM_EXPR:
10897       tmp = finish_asm_stmt
10898         (ASM_VOLATILE_P (t),
10899          RECUR (ASM_STRING (t)),
10900          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10901          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10902          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10903       {
10904         tree asm_expr = tmp;
10905         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10906           asm_expr = TREE_OPERAND (asm_expr, 0);
10907         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10908       }
10909       break;
10910
10911     case TRY_BLOCK:
10912       if (CLEANUP_P (t))
10913         {
10914           stmt = begin_try_block ();
10915           RECUR (TRY_STMTS (t));
10916           finish_cleanup_try_block (stmt);
10917           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10918         }
10919       else
10920         {
10921           tree compound_stmt = NULL_TREE;
10922
10923           if (FN_TRY_BLOCK_P (t))
10924             stmt = begin_function_try_block (&compound_stmt);
10925           else
10926             stmt = begin_try_block ();
10927
10928           RECUR (TRY_STMTS (t));
10929
10930           if (FN_TRY_BLOCK_P (t))
10931             finish_function_try_block (stmt);
10932           else
10933             finish_try_block (stmt);
10934
10935           RECUR (TRY_HANDLERS (t));
10936           if (FN_TRY_BLOCK_P (t))
10937             finish_function_handler_sequence (stmt, compound_stmt);
10938           else
10939             finish_handler_sequence (stmt);
10940         }
10941       break;
10942
10943     case HANDLER:
10944       {
10945         tree decl = HANDLER_PARMS (t);
10946
10947         if (decl)
10948           {
10949             decl = tsubst (decl, args, complain, in_decl);
10950             /* Prevent instantiate_decl from trying to instantiate
10951                this variable.  We've already done all that needs to be
10952                done.  */
10953             if (decl != error_mark_node)
10954               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10955           }
10956         stmt = begin_handler ();
10957         finish_handler_parms (decl, stmt);
10958         RECUR (HANDLER_BODY (t));
10959         finish_handler (stmt);
10960       }
10961       break;
10962
10963     case TAG_DEFN:
10964       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10965       break;
10966
10967     case STATIC_ASSERT:
10968       {
10969         tree condition = 
10970           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10971                        args,
10972                        complain, in_decl,
10973                        /*integral_constant_expression_p=*/true);
10974         finish_static_assert (condition,
10975                               STATIC_ASSERT_MESSAGE (t),
10976                               STATIC_ASSERT_SOURCE_LOCATION (t),
10977                               /*member_p=*/false);
10978       }
10979       break;
10980
10981     case OMP_PARALLEL:
10982       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10983                                 args, complain, in_decl);
10984       stmt = begin_omp_parallel ();
10985       RECUR (OMP_PARALLEL_BODY (t));
10986       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10987         = OMP_PARALLEL_COMBINED (t);
10988       break;
10989
10990     case OMP_TASK:
10991       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
10992                                 args, complain, in_decl);
10993       stmt = begin_omp_task ();
10994       RECUR (OMP_TASK_BODY (t));
10995       finish_omp_task (tmp, stmt);
10996       break;
10997
10998     case OMP_FOR:
10999       {
11000         tree clauses, body, pre_body;
11001         tree declv, initv, condv, incrv;
11002         int i;
11003
11004         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11005                                       args, complain, in_decl);
11006         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11007         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11008         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11009         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11010
11011         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11012           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11013                                    &clauses, args, complain, in_decl,
11014                                    integral_constant_expression_p);
11015
11016         stmt = begin_omp_structured_block ();
11017
11018         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11019           if (TREE_VEC_ELT (initv, i) == NULL
11020               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11021             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11022           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11023             {
11024               tree init = RECUR (TREE_VEC_ELT (initv, i));
11025               gcc_assert (init == TREE_VEC_ELT (declv, i));
11026               TREE_VEC_ELT (initv, i) = NULL_TREE;
11027             }
11028           else
11029             {
11030               tree decl_expr = TREE_VEC_ELT (initv, i);
11031               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11032               gcc_assert (init != NULL);
11033               TREE_VEC_ELT (initv, i) = RECUR (init);
11034               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11035               RECUR (decl_expr);
11036               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11037             }
11038
11039         pre_body = push_stmt_list ();
11040         RECUR (OMP_FOR_PRE_BODY (t));
11041         pre_body = pop_stmt_list (pre_body);
11042
11043         body = push_stmt_list ();
11044         RECUR (OMP_FOR_BODY (t));
11045         body = pop_stmt_list (body);
11046
11047         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11048                             body, pre_body, clauses);
11049
11050         add_stmt (finish_omp_structured_block (stmt));
11051       }
11052       break;
11053
11054     case OMP_SECTIONS:
11055     case OMP_SINGLE:
11056       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11057       stmt = push_stmt_list ();
11058       RECUR (OMP_BODY (t));
11059       stmt = pop_stmt_list (stmt);
11060
11061       t = copy_node (t);
11062       OMP_BODY (t) = stmt;
11063       OMP_CLAUSES (t) = tmp;
11064       add_stmt (t);
11065       break;
11066
11067     case OMP_SECTION:
11068     case OMP_CRITICAL:
11069     case OMP_MASTER:
11070     case OMP_ORDERED:
11071       stmt = push_stmt_list ();
11072       RECUR (OMP_BODY (t));
11073       stmt = pop_stmt_list (stmt);
11074
11075       t = copy_node (t);
11076       OMP_BODY (t) = stmt;
11077       add_stmt (t);
11078       break;
11079
11080     case OMP_ATOMIC:
11081       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11082       {
11083         tree op1 = TREE_OPERAND (t, 1);
11084         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11085         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11086         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11087       }
11088       break;
11089
11090     case EXPR_PACK_EXPANSION:
11091       error ("invalid use of pack expansion expression");
11092       return error_mark_node;
11093
11094     case NONTYPE_ARGUMENT_PACK:
11095       error ("use %<...%> to expand argument pack");
11096       return error_mark_node;
11097
11098     default:
11099       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11100
11101       return tsubst_copy_and_build (t, args, complain, in_decl,
11102                                     /*function_p=*/false,
11103                                     integral_constant_expression_p);
11104     }
11105
11106   return NULL_TREE;
11107 #undef RECUR
11108 }
11109
11110 /* T is a postfix-expression that is not being used in a function
11111    call.  Return the substituted version of T.  */
11112
11113 static tree
11114 tsubst_non_call_postfix_expression (tree t, tree args,
11115                                     tsubst_flags_t complain,
11116                                     tree in_decl)
11117 {
11118   if (TREE_CODE (t) == SCOPE_REF)
11119     t = tsubst_qualified_id (t, args, complain, in_decl,
11120                              /*done=*/false, /*address_p=*/false);
11121   else
11122     t = tsubst_copy_and_build (t, args, complain, in_decl,
11123                                /*function_p=*/false,
11124                                /*integral_constant_expression_p=*/false);
11125
11126   return t;
11127 }
11128
11129 /* Like tsubst but deals with expressions and performs semantic
11130    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11131
11132 tree
11133 tsubst_copy_and_build (tree t,
11134                        tree args,
11135                        tsubst_flags_t complain,
11136                        tree in_decl,
11137                        bool function_p,
11138                        bool integral_constant_expression_p)
11139 {
11140 #define RECUR(NODE)                                             \
11141   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11142                          /*function_p=*/false,                  \
11143                          integral_constant_expression_p)
11144
11145   tree op1;
11146
11147   if (t == NULL_TREE || t == error_mark_node)
11148     return t;
11149
11150   switch (TREE_CODE (t))
11151     {
11152     case USING_DECL:
11153       t = DECL_NAME (t);
11154       /* Fall through.  */
11155     case IDENTIFIER_NODE:
11156       {
11157         tree decl;
11158         cp_id_kind idk;
11159         bool non_integral_constant_expression_p;
11160         const char *error_msg;
11161
11162         if (IDENTIFIER_TYPENAME_P (t))
11163           {
11164             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11165             t = mangle_conv_op_name_for_type (new_type);
11166           }
11167
11168         /* Look up the name.  */
11169         decl = lookup_name (t);
11170
11171         /* By convention, expressions use ERROR_MARK_NODE to indicate
11172            failure, not NULL_TREE.  */
11173         if (decl == NULL_TREE)
11174           decl = error_mark_node;
11175
11176         decl = finish_id_expression (t, decl, NULL_TREE,
11177                                      &idk,
11178                                      integral_constant_expression_p,
11179                                      /*allow_non_integral_constant_expression_p=*/false,
11180                                      &non_integral_constant_expression_p,
11181                                      /*template_p=*/false,
11182                                      /*done=*/true,
11183                                      /*address_p=*/false,
11184                                      /*template_arg_p=*/false,
11185                                      &error_msg,
11186                                      input_location);
11187         if (error_msg)
11188           error (error_msg);
11189         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11190           decl = unqualified_name_lookup_error (decl);
11191         return decl;
11192       }
11193
11194     case TEMPLATE_ID_EXPR:
11195       {
11196         tree object;
11197         tree templ = RECUR (TREE_OPERAND (t, 0));
11198         tree targs = TREE_OPERAND (t, 1);
11199
11200         if (targs)
11201           targs = tsubst_template_args (targs, args, complain, in_decl);
11202
11203         if (TREE_CODE (templ) == COMPONENT_REF)
11204           {
11205             object = TREE_OPERAND (templ, 0);
11206             templ = TREE_OPERAND (templ, 1);
11207           }
11208         else
11209           object = NULL_TREE;
11210         templ = lookup_template_function (templ, targs);
11211
11212         if (object)
11213           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11214                          object, templ, NULL_TREE);
11215         else
11216           return baselink_for_fns (templ);
11217       }
11218
11219     case INDIRECT_REF:
11220       {
11221         tree r = RECUR (TREE_OPERAND (t, 0));
11222
11223         if (REFERENCE_REF_P (t))
11224           {
11225             /* A type conversion to reference type will be enclosed in
11226                such an indirect ref, but the substitution of the cast
11227                will have also added such an indirect ref.  */
11228             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11229               r = convert_from_reference (r);
11230           }
11231         else
11232           r = build_x_indirect_ref (r, "unary *", complain);
11233         return r;
11234       }
11235
11236     case NOP_EXPR:
11237       return build_nop
11238         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11239          RECUR (TREE_OPERAND (t, 0)));
11240
11241     case CAST_EXPR:
11242     case REINTERPRET_CAST_EXPR:
11243     case CONST_CAST_EXPR:
11244     case DYNAMIC_CAST_EXPR:
11245     case STATIC_CAST_EXPR:
11246       {
11247         tree type;
11248         tree op;
11249
11250         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11251         if (integral_constant_expression_p
11252             && !cast_valid_in_integral_constant_expression_p (type))
11253           {
11254             if (complain & tf_error)
11255               error ("a cast to a type other than an integral or "
11256                      "enumeration type cannot appear in a constant-expression");
11257             return error_mark_node; 
11258           }
11259
11260         op = RECUR (TREE_OPERAND (t, 0));
11261
11262         switch (TREE_CODE (t))
11263           {
11264           case CAST_EXPR:
11265             return build_functional_cast (type, op, complain);
11266           case REINTERPRET_CAST_EXPR:
11267             return build_reinterpret_cast (type, op, complain);
11268           case CONST_CAST_EXPR:
11269             return build_const_cast (type, op, complain);
11270           case DYNAMIC_CAST_EXPR:
11271             return build_dynamic_cast (type, op, complain);
11272           case STATIC_CAST_EXPR:
11273             return build_static_cast (type, op, complain);
11274           default:
11275             gcc_unreachable ();
11276           }
11277       }
11278
11279     case POSTDECREMENT_EXPR:
11280     case POSTINCREMENT_EXPR:
11281       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11282                                                 args, complain, in_decl);
11283       return build_x_unary_op (TREE_CODE (t), op1, complain);
11284
11285     case PREDECREMENT_EXPR:
11286     case PREINCREMENT_EXPR:
11287     case NEGATE_EXPR:
11288     case BIT_NOT_EXPR:
11289     case ABS_EXPR:
11290     case TRUTH_NOT_EXPR:
11291     case UNARY_PLUS_EXPR:  /* Unary + */
11292     case REALPART_EXPR:
11293     case IMAGPART_EXPR:
11294       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11295                                complain);
11296
11297     case ADDR_EXPR:
11298       op1 = TREE_OPERAND (t, 0);
11299       if (TREE_CODE (op1) == SCOPE_REF)
11300         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11301                                    /*done=*/true, /*address_p=*/true);
11302       else
11303         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11304                                                   in_decl);
11305       if (TREE_CODE (op1) == LABEL_DECL)
11306         return finish_label_address_expr (DECL_NAME (op1),
11307                                           EXPR_LOCATION (op1));
11308       return build_x_unary_op (ADDR_EXPR, op1, complain);
11309
11310     case PLUS_EXPR:
11311     case MINUS_EXPR:
11312     case MULT_EXPR:
11313     case TRUNC_DIV_EXPR:
11314     case CEIL_DIV_EXPR:
11315     case FLOOR_DIV_EXPR:
11316     case ROUND_DIV_EXPR:
11317     case EXACT_DIV_EXPR:
11318     case BIT_AND_EXPR:
11319     case BIT_IOR_EXPR:
11320     case BIT_XOR_EXPR:
11321     case TRUNC_MOD_EXPR:
11322     case FLOOR_MOD_EXPR:
11323     case TRUTH_ANDIF_EXPR:
11324     case TRUTH_ORIF_EXPR:
11325     case TRUTH_AND_EXPR:
11326     case TRUTH_OR_EXPR:
11327     case RSHIFT_EXPR:
11328     case LSHIFT_EXPR:
11329     case RROTATE_EXPR:
11330     case LROTATE_EXPR:
11331     case EQ_EXPR:
11332     case NE_EXPR:
11333     case MAX_EXPR:
11334     case MIN_EXPR:
11335     case LE_EXPR:
11336     case GE_EXPR:
11337     case LT_EXPR:
11338     case GT_EXPR:
11339     case MEMBER_REF:
11340     case DOTSTAR_EXPR:
11341       return build_x_binary_op
11342         (TREE_CODE (t),
11343          RECUR (TREE_OPERAND (t, 0)),
11344          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11345           ? ERROR_MARK
11346           : TREE_CODE (TREE_OPERAND (t, 0))),
11347          RECUR (TREE_OPERAND (t, 1)),
11348          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11349           ? ERROR_MARK
11350           : TREE_CODE (TREE_OPERAND (t, 1))),
11351          /*overloaded_p=*/NULL,
11352          complain);
11353
11354     case SCOPE_REF:
11355       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11356                                   /*address_p=*/false);
11357     case ARRAY_REF:
11358       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11359                                                 args, complain, in_decl);
11360       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11361
11362     case SIZEOF_EXPR:
11363       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11364         return tsubst_copy (t, args, complain, in_decl);
11365       /* Fall through */
11366       
11367     case ALIGNOF_EXPR:
11368       op1 = TREE_OPERAND (t, 0);
11369       if (!args)
11370         {
11371           /* When there are no ARGS, we are trying to evaluate a
11372              non-dependent expression from the parser.  Trying to do
11373              the substitutions may not work.  */
11374           if (!TYPE_P (op1))
11375             op1 = TREE_TYPE (op1);
11376         }
11377       else
11378         {
11379           ++skip_evaluation;
11380           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11381                                        /*function_p=*/false,
11382                                        /*integral_constant_expression_p=*/false);
11383           --skip_evaluation;
11384         }
11385       if (TYPE_P (op1))
11386         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11387                                            complain & tf_error);
11388       else
11389         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11390                                            complain & tf_error);
11391
11392     case MODOP_EXPR:
11393       {
11394         tree r = build_x_modify_expr
11395           (RECUR (TREE_OPERAND (t, 0)),
11396            TREE_CODE (TREE_OPERAND (t, 1)),
11397            RECUR (TREE_OPERAND (t, 2)),
11398            complain);
11399         /* TREE_NO_WARNING must be set if either the expression was
11400            parenthesized or it uses an operator such as >>= rather
11401            than plain assignment.  In the former case, it was already
11402            set and must be copied.  In the latter case,
11403            build_x_modify_expr sets it and it must not be reset
11404            here.  */
11405         if (TREE_NO_WARNING (t))
11406           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11407         return r;
11408       }
11409
11410     case ARROW_EXPR:
11411       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11412                                                 args, complain, in_decl);
11413       /* Remember that there was a reference to this entity.  */
11414       if (DECL_P (op1))
11415         mark_used (op1);
11416       return build_x_arrow (op1);
11417
11418     case NEW_EXPR:
11419       {
11420         tree init = RECUR (TREE_OPERAND (t, 3));
11421
11422         if (TREE_OPERAND (t, 3) && !init)
11423           /* If there was an initializer in the original tree, but
11424              it instantiated to an empty list, then we should pass on
11425              VOID_ZERO_NODE to tell build_new that it was an empty
11426              initializer () rather than no initializer.  This can only
11427              happen when the initializer is a pack expansion whose
11428              parameter packs are of length zero.  */
11429           init = void_zero_node;
11430
11431         return build_new
11432           (RECUR (TREE_OPERAND (t, 0)),
11433            RECUR (TREE_OPERAND (t, 1)),
11434            RECUR (TREE_OPERAND (t, 2)),
11435            init,
11436            NEW_EXPR_USE_GLOBAL (t),
11437            complain);
11438       }
11439
11440     case DELETE_EXPR:
11441      return delete_sanity
11442        (RECUR (TREE_OPERAND (t, 0)),
11443         RECUR (TREE_OPERAND (t, 1)),
11444         DELETE_EXPR_USE_VEC (t),
11445         DELETE_EXPR_USE_GLOBAL (t));
11446
11447     case COMPOUND_EXPR:
11448       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11449                                     RECUR (TREE_OPERAND (t, 1)),
11450                                     complain);
11451
11452     case CALL_EXPR:
11453       {
11454         tree function;
11455         tree call_args;
11456         bool qualified_p;
11457         bool koenig_p;
11458
11459         function = CALL_EXPR_FN (t);
11460         /* When we parsed the expression,  we determined whether or
11461            not Koenig lookup should be performed.  */
11462         koenig_p = KOENIG_LOOKUP_P (t);
11463         if (TREE_CODE (function) == SCOPE_REF)
11464           {
11465             qualified_p = true;
11466             function = tsubst_qualified_id (function, args, complain, in_decl,
11467                                             /*done=*/false,
11468                                             /*address_p=*/false);
11469           }
11470         else
11471           {
11472             if (TREE_CODE (function) == COMPONENT_REF)
11473               {
11474                 tree op = TREE_OPERAND (function, 1);
11475
11476                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11477                                || (BASELINK_P (op)
11478                                    && BASELINK_QUALIFIED_P (op)));
11479               }
11480             else
11481               qualified_p = false;
11482
11483             function = tsubst_copy_and_build (function, args, complain,
11484                                               in_decl,
11485                                               !qualified_p,
11486                                               integral_constant_expression_p);
11487
11488             if (BASELINK_P (function))
11489               qualified_p = true;
11490           }
11491
11492         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11493         call_args = RECUR (CALL_EXPR_ARGS (t));
11494
11495         /* We do not perform argument-dependent lookup if normal
11496            lookup finds a non-function, in accordance with the
11497            expected resolution of DR 218.  */
11498         if (koenig_p
11499             && ((is_overloaded_fn (function)
11500                  /* If lookup found a member function, the Koenig lookup is
11501                     not appropriate, even if an unqualified-name was used
11502                     to denote the function.  */
11503                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11504                 || TREE_CODE (function) == IDENTIFIER_NODE)
11505             /* Only do this when substitution turns a dependent call
11506                into a non-dependent call.  */
11507             && type_dependent_expression_p_push (t)
11508             && !any_type_dependent_arguments_p (call_args))
11509           function = perform_koenig_lookup (function, call_args);
11510
11511         if (TREE_CODE (function) == IDENTIFIER_NODE)
11512           {
11513             unqualified_name_lookup_error (function);
11514             return error_mark_node;
11515           }
11516
11517         /* Remember that there was a reference to this entity.  */
11518         if (DECL_P (function))
11519           mark_used (function);
11520
11521         if (TREE_CODE (function) == OFFSET_REF)
11522           return build_offset_ref_call_from_tree (function, call_args);
11523         if (TREE_CODE (function) == COMPONENT_REF)
11524           {
11525             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11526               return finish_call_expr (function, call_args,
11527                                        /*disallow_virtual=*/false,
11528                                        /*koenig_p=*/false,
11529                                        complain);
11530             else
11531               return (build_new_method_call
11532                       (TREE_OPERAND (function, 0),
11533                        TREE_OPERAND (function, 1),
11534                        call_args, NULL_TREE,
11535                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11536                        /*fn_p=*/NULL,
11537                        complain));
11538           }
11539         return finish_call_expr (function, call_args,
11540                                  /*disallow_virtual=*/qualified_p,
11541                                  koenig_p,
11542                                  complain);
11543       }
11544
11545     case COND_EXPR:
11546       return build_x_conditional_expr
11547         (RECUR (TREE_OPERAND (t, 0)),
11548          RECUR (TREE_OPERAND (t, 1)),
11549          RECUR (TREE_OPERAND (t, 2)),
11550          complain);
11551
11552     case PSEUDO_DTOR_EXPR:
11553       return finish_pseudo_destructor_expr
11554         (RECUR (TREE_OPERAND (t, 0)),
11555          RECUR (TREE_OPERAND (t, 1)),
11556          RECUR (TREE_OPERAND (t, 2)));
11557
11558     case TREE_LIST:
11559       {
11560         tree purpose, value, chain;
11561
11562         if (t == void_list_node)
11563           return t;
11564
11565         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11566             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11567           {
11568             /* We have pack expansions, so expand those and
11569                create a new list out of it.  */
11570             tree purposevec = NULL_TREE;
11571             tree valuevec = NULL_TREE;
11572             tree chain;
11573             int i, len = -1;
11574
11575             /* Expand the argument expressions.  */
11576             if (TREE_PURPOSE (t))
11577               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11578                                                  complain, in_decl);
11579             if (TREE_VALUE (t))
11580               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11581                                                complain, in_decl);
11582
11583             /* Build the rest of the list.  */
11584             chain = TREE_CHAIN (t);
11585             if (chain && chain != void_type_node)
11586               chain = RECUR (chain);
11587
11588             /* Determine the number of arguments.  */
11589             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11590               {
11591                 len = TREE_VEC_LENGTH (purposevec);
11592                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11593               }
11594             else if (TREE_CODE (valuevec) == TREE_VEC)
11595               len = TREE_VEC_LENGTH (valuevec);
11596             else
11597               {
11598                 /* Since we only performed a partial substitution into
11599                    the argument pack, we only return a single list
11600                    node.  */
11601                 if (purposevec == TREE_PURPOSE (t)
11602                     && valuevec == TREE_VALUE (t)
11603                     && chain == TREE_CHAIN (t))
11604                   return t;
11605
11606                 return tree_cons (purposevec, valuevec, chain);
11607               }
11608             
11609             /* Convert the argument vectors into a TREE_LIST */
11610             i = len;
11611             while (i > 0)
11612               {
11613                 /* Grab the Ith values.  */
11614                 i--;
11615                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11616                                      : NULL_TREE;
11617                 value 
11618                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11619                              : NULL_TREE;
11620
11621                 /* Build the list (backwards).  */
11622                 chain = tree_cons (purpose, value, chain);
11623               }
11624
11625             return chain;
11626           }
11627
11628         purpose = TREE_PURPOSE (t);
11629         if (purpose)
11630           purpose = RECUR (purpose);
11631         value = TREE_VALUE (t);
11632         if (value)
11633           value = RECUR (value);
11634         chain = TREE_CHAIN (t);
11635         if (chain && chain != void_type_node)
11636           chain = RECUR (chain);
11637         if (purpose == TREE_PURPOSE (t)
11638             && value == TREE_VALUE (t)
11639             && chain == TREE_CHAIN (t))
11640           return t;
11641         return tree_cons (purpose, value, chain);
11642       }
11643
11644     case COMPONENT_REF:
11645       {
11646         tree object;
11647         tree object_type;
11648         tree member;
11649
11650         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11651                                                      args, complain, in_decl);
11652         /* Remember that there was a reference to this entity.  */
11653         if (DECL_P (object))
11654           mark_used (object);
11655         object_type = TREE_TYPE (object);
11656
11657         member = TREE_OPERAND (t, 1);
11658         if (BASELINK_P (member))
11659           member = tsubst_baselink (member,
11660                                     non_reference (TREE_TYPE (object)),
11661                                     args, complain, in_decl);
11662         else
11663           member = tsubst_copy (member, args, complain, in_decl);
11664         if (member == error_mark_node)
11665           return error_mark_node;
11666
11667         if (object_type && !CLASS_TYPE_P (object_type))
11668           {
11669             if (SCALAR_TYPE_P (object_type))
11670               {
11671                 tree s = NULL_TREE;
11672                 tree dtor = member;
11673
11674                 if (TREE_CODE (dtor) == SCOPE_REF)
11675                   {
11676                     s = TREE_OPERAND (dtor, 0);
11677                     dtor = TREE_OPERAND (dtor, 1);
11678                   }
11679                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11680                   {
11681                     dtor = TREE_OPERAND (dtor, 0);
11682                     if (TYPE_P (dtor))
11683                       return finish_pseudo_destructor_expr (object, s, dtor);
11684                   }
11685               }
11686           }
11687         else if (TREE_CODE (member) == SCOPE_REF
11688                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11689           {
11690             tree tmpl;
11691             tree args;
11692
11693             /* Lookup the template functions now that we know what the
11694                scope is.  */
11695             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11696             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11697             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11698                                             /*is_type_p=*/false,
11699                                             /*complain=*/false);
11700             if (BASELINK_P (member))
11701               {
11702                 BASELINK_FUNCTIONS (member)
11703                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11704                               args);
11705                 member = (adjust_result_of_qualified_name_lookup
11706                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11707                            object_type));
11708               }
11709             else
11710               {
11711                 qualified_name_lookup_error (object_type, tmpl, member,
11712                                              input_location);
11713                 return error_mark_node;
11714               }
11715           }
11716         else if (TREE_CODE (member) == SCOPE_REF
11717                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11718                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11719           {
11720             if (complain & tf_error)
11721               {
11722                 if (TYPE_P (TREE_OPERAND (member, 0)))
11723                   error ("%qT is not a class or namespace",
11724                          TREE_OPERAND (member, 0));
11725                 else
11726                   error ("%qD is not a class or namespace",
11727                          TREE_OPERAND (member, 0));
11728               }
11729             return error_mark_node;
11730           }
11731         else if (TREE_CODE (member) == FIELD_DECL)
11732           return finish_non_static_data_member (member, object, NULL_TREE);
11733
11734         return finish_class_member_access_expr (object, member,
11735                                                 /*template_p=*/false,
11736                                                 complain);
11737       }
11738
11739     case THROW_EXPR:
11740       return build_throw
11741         (RECUR (TREE_OPERAND (t, 0)));
11742
11743     case CONSTRUCTOR:
11744       {
11745         VEC(constructor_elt,gc) *n;
11746         constructor_elt *ce;
11747         unsigned HOST_WIDE_INT idx;
11748         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11749         bool process_index_p;
11750         int newlen;
11751         bool need_copy_p = false;
11752         tree r;
11753
11754         if (type == error_mark_node)
11755           return error_mark_node;
11756
11757         /* digest_init will do the wrong thing if we let it.  */
11758         if (type && TYPE_PTRMEMFUNC_P (type))
11759           return t;
11760
11761         /* We do not want to process the index of aggregate
11762            initializers as they are identifier nodes which will be
11763            looked up by digest_init.  */
11764         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11765
11766         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11767         newlen = VEC_length (constructor_elt, n);
11768         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11769           {
11770             if (ce->index && process_index_p)
11771               ce->index = RECUR (ce->index);
11772
11773             if (PACK_EXPANSION_P (ce->value))
11774               {
11775                 /* Substitute into the pack expansion.  */
11776                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11777                                                   in_decl);
11778
11779                 if (ce->value == error_mark_node)
11780                   ;
11781                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11782                   /* Just move the argument into place.  */
11783                   ce->value = TREE_VEC_ELT (ce->value, 0);
11784                 else
11785                   {
11786                     /* Update the length of the final CONSTRUCTOR
11787                        arguments vector, and note that we will need to
11788                        copy.*/
11789                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11790                     need_copy_p = true;
11791                   }
11792               }
11793             else
11794               ce->value = RECUR (ce->value);
11795           }
11796
11797         if (need_copy_p)
11798           {
11799             VEC(constructor_elt,gc) *old_n = n;
11800
11801             n = VEC_alloc (constructor_elt, gc, newlen);
11802             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11803                  idx++)
11804               {
11805                 if (TREE_CODE (ce->value) == TREE_VEC)
11806                   {
11807                     int i, len = TREE_VEC_LENGTH (ce->value);
11808                     for (i = 0; i < len; ++i)
11809                       CONSTRUCTOR_APPEND_ELT (n, 0,
11810                                               TREE_VEC_ELT (ce->value, i));
11811                   }
11812                 else
11813                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11814               }
11815           }
11816
11817         r = build_constructor (init_list_type_node, n);
11818         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11819
11820         if (TREE_HAS_CONSTRUCTOR (t))
11821           return finish_compound_literal (type, r);
11822
11823         return r;
11824       }
11825
11826     case TYPEID_EXPR:
11827       {
11828         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11829         if (TYPE_P (operand_0))
11830           return get_typeid (operand_0);
11831         return build_typeid (operand_0);
11832       }
11833
11834     case VAR_DECL:
11835       if (!args)
11836         return t;
11837       /* Fall through */
11838
11839     case PARM_DECL:
11840       {
11841         tree r = tsubst_copy (t, args, complain, in_decl);
11842
11843         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11844           /* If the original type was a reference, we'll be wrapped in
11845              the appropriate INDIRECT_REF.  */
11846           r = convert_from_reference (r);
11847         return r;
11848       }
11849
11850     case VA_ARG_EXPR:
11851       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11852                              tsubst_copy (TREE_TYPE (t), args, complain,
11853                                           in_decl));
11854
11855     case OFFSETOF_EXPR:
11856       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11857
11858     case TRAIT_EXPR:
11859       {
11860         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11861                                   complain, in_decl);
11862
11863         tree type2 = TRAIT_EXPR_TYPE2 (t);
11864         if (type2)
11865           type2 = tsubst_copy (type2, args, complain, in_decl);
11866         
11867         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11868       }
11869
11870     case STMT_EXPR:
11871       {
11872         tree old_stmt_expr = cur_stmt_expr;
11873         tree stmt_expr = begin_stmt_expr ();
11874
11875         cur_stmt_expr = stmt_expr;
11876         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11877                      integral_constant_expression_p);
11878         stmt_expr = finish_stmt_expr (stmt_expr, false);
11879         cur_stmt_expr = old_stmt_expr;
11880
11881         return stmt_expr;
11882       }
11883
11884     case CONST_DECL:
11885       t = tsubst_copy (t, args, complain, in_decl);
11886       /* As in finish_id_expression, we resolve enumeration constants
11887          to their underlying values.  */
11888       if (TREE_CODE (t) == CONST_DECL)
11889         {
11890           used_types_insert (TREE_TYPE (t));
11891           return DECL_INITIAL (t);
11892         }
11893       return t;
11894
11895     default:
11896       /* Handle Objective-C++ constructs, if appropriate.  */
11897       {
11898         tree subst
11899           = objcp_tsubst_copy_and_build (t, args, complain,
11900                                          in_decl, /*function_p=*/false);
11901         if (subst)
11902           return subst;
11903       }
11904       return tsubst_copy (t, args, complain, in_decl);
11905     }
11906
11907 #undef RECUR
11908 }
11909
11910 /* Verify that the instantiated ARGS are valid. For type arguments,
11911    make sure that the type's linkage is ok. For non-type arguments,
11912    make sure they are constants if they are integral or enumerations.
11913    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11914
11915 static bool
11916 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
11917 {
11918   if (ARGUMENT_PACK_P (t))
11919     {
11920       tree vec = ARGUMENT_PACK_ARGS (t);
11921       int len = TREE_VEC_LENGTH (vec);
11922       bool result = false;
11923       int i;
11924
11925       for (i = 0; i < len; ++i)
11926         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
11927           result = true;
11928       return result;
11929     }
11930   else if (TYPE_P (t))
11931     {
11932       /* [basic.link]: A name with no linkage (notably, the name
11933          of a class or enumeration declared in a local scope)
11934          shall not be used to declare an entity with linkage.
11935          This implies that names with no linkage cannot be used as
11936          template arguments.  */
11937       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11938
11939       if (nt)
11940         {
11941           /* DR 488 makes use of a type with no linkage cause
11942              type deduction to fail.  */
11943           if (complain & tf_error)
11944             {
11945               if (TYPE_ANONYMOUS_P (nt))
11946                 error ("%qT is/uses anonymous type", t);
11947               else
11948                 error ("template argument for %qD uses local type %qT",
11949                        tmpl, t);
11950             }
11951           return true;
11952         }
11953       /* In order to avoid all sorts of complications, we do not
11954          allow variably-modified types as template arguments.  */
11955       else if (variably_modified_type_p (t, NULL_TREE))
11956         {
11957           if (complain & tf_error)
11958             error ("%qT is a variably modified type", t);
11959           return true;
11960         }
11961     }
11962   /* A non-type argument of integral or enumerated type must be a
11963      constant.  */
11964   else if (TREE_TYPE (t)
11965            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11966            && !TREE_CONSTANT (t))
11967     {
11968       if (complain & tf_error)
11969         error ("integral expression %qE is not constant", t);
11970       return true;
11971     }
11972   return false;
11973 }
11974
11975 static bool
11976 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11977 {
11978   int ix, len = DECL_NTPARMS (tmpl);
11979   bool result = false;
11980
11981   for (ix = 0; ix != len; ix++)
11982     {
11983       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
11984         result = true;
11985     }
11986   if (result && (complain & tf_error))
11987     error ("  trying to instantiate %qD", tmpl);
11988   return result;
11989 }
11990
11991 /* Instantiate the indicated variable or function template TMPL with
11992    the template arguments in TARG_PTR.  */
11993
11994 tree
11995 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11996 {
11997   tree fndecl;
11998   tree gen_tmpl;
11999   tree spec;
12000   HOST_WIDE_INT saved_processing_template_decl;
12001
12002   if (tmpl == error_mark_node)
12003     return error_mark_node;
12004
12005   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12006
12007   /* If this function is a clone, handle it specially.  */
12008   if (DECL_CLONED_FUNCTION_P (tmpl))
12009     {
12010       tree spec;
12011       tree clone;
12012
12013       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
12014                                    complain);
12015       if (spec == error_mark_node)
12016         return error_mark_node;
12017
12018       /* Look for the clone.  */
12019       FOR_EACH_CLONE (clone, spec)
12020         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12021           return clone;
12022       /* We should always have found the clone by now.  */
12023       gcc_unreachable ();
12024       return NULL_TREE;
12025     }
12026
12027   /* Check to see if we already have this specialization.  */
12028   spec = retrieve_specialization (tmpl, targ_ptr,
12029                                   /*class_specializations_p=*/false);
12030   if (spec != NULL_TREE)
12031     return spec;
12032
12033   gen_tmpl = most_general_template (tmpl);
12034   if (tmpl != gen_tmpl)
12035     {
12036       /* The TMPL is a partial instantiation.  To get a full set of
12037          arguments we must add the arguments used to perform the
12038          partial instantiation.  */
12039       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12040                                               targ_ptr);
12041
12042       /* Check to see if we already have this specialization.  */
12043       spec = retrieve_specialization (gen_tmpl, targ_ptr,
12044                                       /*class_specializations_p=*/false);
12045       if (spec != NULL_TREE)
12046         return spec;
12047     }
12048
12049   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12050                                complain))
12051     return error_mark_node;
12052
12053   /* We are building a FUNCTION_DECL, during which the access of its
12054      parameters and return types have to be checked.  However this
12055      FUNCTION_DECL which is the desired context for access checking
12056      is not built yet.  We solve this chicken-and-egg problem by
12057      deferring all checks until we have the FUNCTION_DECL.  */
12058   push_deferring_access_checks (dk_deferred);
12059
12060   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12061      (because, for example, we have encountered a non-dependent
12062      function call in the body of a template function and must now
12063      determine which of several overloaded functions will be called),
12064      within the instantiation itself we are not processing a
12065      template.  */  
12066   saved_processing_template_decl = processing_template_decl;
12067   processing_template_decl = 0;
12068   /* Substitute template parameters to obtain the specialization.  */
12069   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12070                    targ_ptr, complain, gen_tmpl);
12071   processing_template_decl = saved_processing_template_decl;
12072   if (fndecl == error_mark_node)
12073     return error_mark_node;
12074
12075   /* Now we know the specialization, compute access previously
12076      deferred.  */
12077   push_access_scope (fndecl);
12078
12079   /* Some typedefs referenced from within the template code need to be access
12080      checked at template instantiation time, i.e now. These types were
12081      added to the template at parsing time. Let's get those and perfom
12082      the acces checks then.  */
12083   perform_typedefs_access_check (tmpl, targ_ptr);
12084   perform_deferred_access_checks ();
12085   pop_access_scope (fndecl);
12086   pop_deferring_access_checks ();
12087
12088   /* The DECL_TI_TEMPLATE should always be the immediate parent
12089      template, not the most general template.  */
12090   DECL_TI_TEMPLATE (fndecl) = tmpl;
12091
12092   /* If we've just instantiated the main entry point for a function,
12093      instantiate all the alternate entry points as well.  We do this
12094      by cloning the instantiation of the main entry point, not by
12095      instantiating the template clones.  */
12096   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12097     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12098
12099   return fndecl;
12100 }
12101
12102 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
12103    arguments that are being used when calling it.  TARGS is a vector
12104    into which the deduced template arguments are placed.
12105
12106    Return zero for success, 2 for an incomplete match that doesn't resolve
12107    all the types, and 1 for complete failure.  An error message will be
12108    printed only for an incomplete match.
12109
12110    If FN is a conversion operator, or we are trying to produce a specific
12111    specialization, RETURN_TYPE is the return type desired.
12112
12113    The EXPLICIT_TARGS are explicit template arguments provided via a
12114    template-id.
12115
12116    The parameter STRICT is one of:
12117
12118    DEDUCE_CALL:
12119      We are deducing arguments for a function call, as in
12120      [temp.deduct.call].
12121
12122    DEDUCE_CONV:
12123      We are deducing arguments for a conversion function, as in
12124      [temp.deduct.conv].
12125
12126    DEDUCE_EXACT:
12127      We are deducing arguments when doing an explicit instantiation
12128      as in [temp.explicit], when determining an explicit specialization
12129      as in [temp.expl.spec], or when taking the address of a function
12130      template, as in [temp.deduct.funcaddr].  */
12131
12132 int
12133 fn_type_unification (tree fn,
12134                      tree explicit_targs,
12135                      tree targs,
12136                      tree args,
12137                      tree return_type,
12138                      unification_kind_t strict,
12139                      int flags)
12140 {
12141   tree parms;
12142   tree fntype;
12143   int result;
12144   bool incomplete_argument_packs_p = false;
12145
12146   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12147
12148   fntype = TREE_TYPE (fn);
12149   if (explicit_targs)
12150     {
12151       /* [temp.deduct]
12152
12153          The specified template arguments must match the template
12154          parameters in kind (i.e., type, nontype, template), and there
12155          must not be more arguments than there are parameters;
12156          otherwise type deduction fails.
12157
12158          Nontype arguments must match the types of the corresponding
12159          nontype template parameters, or must be convertible to the
12160          types of the corresponding nontype parameters as specified in
12161          _temp.arg.nontype_, otherwise type deduction fails.
12162
12163          All references in the function type of the function template
12164          to the corresponding template parameters are replaced by the
12165          specified template argument values.  If a substitution in a
12166          template parameter or in the function type of the function
12167          template results in an invalid type, type deduction fails.  */
12168       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12169       int i, len = TREE_VEC_LENGTH (tparms);
12170       tree converted_args;
12171       bool incomplete = false;
12172
12173       if (explicit_targs == error_mark_node)
12174         return 1;
12175
12176       converted_args
12177         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12178                                   /*require_all_args=*/false,
12179                                   /*use_default_args=*/false));
12180       if (converted_args == error_mark_node)
12181         return 1;
12182
12183       /* Substitute the explicit args into the function type.  This is
12184          necessary so that, for instance, explicitly declared function
12185          arguments can match null pointed constants.  If we were given
12186          an incomplete set of explicit args, we must not do semantic
12187          processing during substitution as we could create partial
12188          instantiations.  */
12189       for (i = 0; i < len; i++)
12190         {
12191           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12192           bool parameter_pack = false;
12193
12194           /* Dig out the actual parm.  */
12195           if (TREE_CODE (parm) == TYPE_DECL
12196               || TREE_CODE (parm) == TEMPLATE_DECL)
12197             {
12198               parm = TREE_TYPE (parm);
12199               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12200             }
12201           else if (TREE_CODE (parm) == PARM_DECL)
12202             {
12203               parm = DECL_INITIAL (parm);
12204               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12205             }
12206
12207           if (parameter_pack)
12208             {
12209               int level, idx;
12210               tree targ;
12211               template_parm_level_and_index (parm, &level, &idx);
12212
12213               /* Mark the argument pack as "incomplete". We could
12214                  still deduce more arguments during unification.  */
12215               targ = TMPL_ARG (converted_args, level, idx);
12216               if (targ)
12217                 {
12218                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12219                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12220                     = ARGUMENT_PACK_ARGS (targ);
12221                 }
12222
12223               /* We have some incomplete argument packs.  */
12224               incomplete_argument_packs_p = true;
12225             }
12226         }
12227
12228       if (incomplete_argument_packs_p)
12229         /* Any substitution is guaranteed to be incomplete if there
12230            are incomplete argument packs, because we can still deduce
12231            more arguments.  */
12232         incomplete = 1;
12233       else
12234         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12235
12236       processing_template_decl += incomplete;
12237       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12238       processing_template_decl -= incomplete;
12239
12240       if (fntype == error_mark_node)
12241         return 1;
12242
12243       /* Place the explicitly specified arguments in TARGS.  */
12244       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12245         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12246     }
12247
12248   /* Never do unification on the 'this' parameter.  */
12249   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12250
12251   if (return_type)
12252     {
12253       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12254       args = tree_cons (NULL_TREE, return_type, args);
12255     }
12256
12257   /* We allow incomplete unification without an error message here
12258      because the standard doesn't seem to explicitly prohibit it.  Our
12259      callers must be ready to deal with unification failures in any
12260      event.  */
12261   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12262                                   targs, parms, args, /*subr=*/0,
12263                                   strict, flags);
12264
12265   if (result == 0 && incomplete_argument_packs_p)
12266     {
12267       int i, len = NUM_TMPL_ARGS (targs);
12268
12269       /* Clear the "incomplete" flags on all argument packs.  */
12270       for (i = 0; i < len; i++)
12271         {
12272           tree arg = TREE_VEC_ELT (targs, i);
12273           if (ARGUMENT_PACK_P (arg))
12274             {
12275               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12276               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12277             }
12278         }
12279     }
12280
12281   /* Now that we have bindings for all of the template arguments,
12282      ensure that the arguments deduced for the template template
12283      parameters have compatible template parameter lists.  We cannot
12284      check this property before we have deduced all template
12285      arguments, because the template parameter types of a template
12286      template parameter might depend on prior template parameters
12287      deduced after the template template parameter.  The following
12288      ill-formed example illustrates this issue:
12289
12290        template<typename T, template<T> class C> void f(C<5>, T);
12291
12292        template<int N> struct X {};
12293
12294        void g() {
12295          f(X<5>(), 5l); // error: template argument deduction fails
12296        }
12297
12298      The template parameter list of 'C' depends on the template type
12299      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12300      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12301      time that we deduce 'C'.  */
12302   if (result == 0
12303       && !template_template_parm_bindings_ok_p 
12304            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12305     return 1;
12306
12307   if (result == 0)
12308     /* All is well so far.  Now, check:
12309
12310        [temp.deduct]
12311
12312        When all template arguments have been deduced, all uses of
12313        template parameters in nondeduced contexts are replaced with
12314        the corresponding deduced argument values.  If the
12315        substitution results in an invalid type, as described above,
12316        type deduction fails.  */
12317     {
12318       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12319       if (substed == error_mark_node)
12320         return 1;
12321
12322       /* If we're looking for an exact match, check that what we got
12323          is indeed an exact match.  It might not be if some template
12324          parameters are used in non-deduced contexts.  */
12325       if (strict == DEDUCE_EXACT)
12326         {
12327           tree sarg
12328             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12329           tree arg = args;
12330           if (return_type)
12331             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12332           for (; arg && sarg;
12333                arg = TREE_CHAIN (arg), sarg = TREE_CHAIN (sarg))
12334             if (!same_type_p (TREE_VALUE (arg), TREE_VALUE (sarg)))
12335               return 1;
12336         }
12337     }
12338
12339   return result;
12340 }
12341
12342 /* Adjust types before performing type deduction, as described in
12343    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12344    sections are symmetric.  PARM is the type of a function parameter
12345    or the return type of the conversion function.  ARG is the type of
12346    the argument passed to the call, or the type of the value
12347    initialized with the result of the conversion function.
12348    ARG_EXPR is the original argument expression, which may be null.  */
12349
12350 static int
12351 maybe_adjust_types_for_deduction (unification_kind_t strict,
12352                                   tree* parm,
12353                                   tree* arg,
12354                                   tree arg_expr)
12355 {
12356   int result = 0;
12357
12358   switch (strict)
12359     {
12360     case DEDUCE_CALL:
12361       break;
12362
12363     case DEDUCE_CONV:
12364       {
12365         /* Swap PARM and ARG throughout the remainder of this
12366            function; the handling is precisely symmetric since PARM
12367            will initialize ARG rather than vice versa.  */
12368         tree* temp = parm;
12369         parm = arg;
12370         arg = temp;
12371         break;
12372       }
12373
12374     case DEDUCE_EXACT:
12375       /* There is nothing to do in this case.  */
12376       return 0;
12377
12378     default:
12379       gcc_unreachable ();
12380     }
12381
12382   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12383     {
12384       /* [temp.deduct.call]
12385
12386          If P is not a reference type:
12387
12388          --If A is an array type, the pointer type produced by the
12389          array-to-pointer standard conversion (_conv.array_) is
12390          used in place of A for type deduction; otherwise,
12391
12392          --If A is a function type, the pointer type produced by
12393          the function-to-pointer standard conversion
12394          (_conv.func_) is used in place of A for type deduction;
12395          otherwise,
12396
12397          --If A is a cv-qualified type, the top level
12398          cv-qualifiers of A's type are ignored for type
12399          deduction.  */
12400       if (TREE_CODE (*arg) == ARRAY_TYPE)
12401         *arg = build_pointer_type (TREE_TYPE (*arg));
12402       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12403         *arg = build_pointer_type (*arg);
12404       else
12405         *arg = TYPE_MAIN_VARIANT (*arg);
12406     }
12407
12408   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12409      of the form T&&, where T is a template parameter, and the argument
12410      is an lvalue, T is deduced as A& */
12411   if (TREE_CODE (*parm) == REFERENCE_TYPE
12412       && TYPE_REF_IS_RVALUE (*parm)
12413       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12414       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12415       && arg_expr && real_lvalue_p (arg_expr))
12416     *arg = build_reference_type (*arg);
12417
12418   /* [temp.deduct.call]
12419
12420      If P is a cv-qualified type, the top level cv-qualifiers
12421      of P's type are ignored for type deduction.  If P is a
12422      reference type, the type referred to by P is used for
12423      type deduction.  */
12424   *parm = TYPE_MAIN_VARIANT (*parm);
12425   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12426     {
12427       *parm = TREE_TYPE (*parm);
12428       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12429     }
12430
12431   /* DR 322. For conversion deduction, remove a reference type on parm
12432      too (which has been swapped into ARG).  */
12433   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12434     *arg = TREE_TYPE (*arg);
12435
12436   return result;
12437 }
12438
12439 /* Most parms like fn_type_unification.
12440
12441    If SUBR is 1, we're being called recursively (to unify the
12442    arguments of a function or method parameter of a function
12443    template). */
12444
12445 static int
12446 type_unification_real (tree tparms,
12447                        tree targs,
12448                        tree xparms,
12449                        tree xargs,
12450                        int subr,
12451                        unification_kind_t strict,
12452                        int flags)
12453 {
12454   tree parm, arg, arg_expr;
12455   int i;
12456   int ntparms = TREE_VEC_LENGTH (tparms);
12457   int sub_strict;
12458   int saw_undeduced = 0;
12459   tree parms, args;
12460
12461   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12462   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12463   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
12464   gcc_assert (ntparms > 0);
12465
12466   switch (strict)
12467     {
12468     case DEDUCE_CALL:
12469       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12470                     | UNIFY_ALLOW_DERIVED);
12471       break;
12472
12473     case DEDUCE_CONV:
12474       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12475       break;
12476
12477     case DEDUCE_EXACT:
12478       sub_strict = UNIFY_ALLOW_NONE;
12479       break;
12480
12481     default:
12482       gcc_unreachable ();
12483     }
12484
12485  again:
12486   parms = xparms;
12487   args = xargs;
12488
12489   while (parms && parms != void_list_node
12490          && args && args != void_list_node)
12491     {
12492       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12493         break;
12494
12495       parm = TREE_VALUE (parms);
12496       parms = TREE_CHAIN (parms);
12497       arg = TREE_VALUE (args);
12498       args = TREE_CHAIN (args);
12499       arg_expr = NULL;
12500
12501       if (arg == error_mark_node)
12502         return 1;
12503       if (arg == unknown_type_node)
12504         /* We can't deduce anything from this, but we might get all the
12505            template args from other function args.  */
12506         continue;
12507
12508       /* Conversions will be performed on a function argument that
12509          corresponds with a function parameter that contains only
12510          non-deducible template parameters and explicitly specified
12511          template parameters.  */
12512       if (!uses_template_parms (parm))
12513         {
12514           tree type;
12515
12516           if (!TYPE_P (arg))
12517             type = TREE_TYPE (arg);
12518           else
12519             type = arg;
12520
12521           if (same_type_p (parm, type))
12522             continue;
12523           if (strict != DEDUCE_EXACT
12524               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12525                                   flags))
12526             continue;
12527
12528           return 1;
12529         }
12530
12531       if (!TYPE_P (arg))
12532         {
12533           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12534           if (type_unknown_p (arg))
12535             {
12536               /* [temp.deduct.type] 
12537
12538                  A template-argument can be deduced from a pointer to
12539                  function or pointer to member function argument if
12540                  the set of overloaded functions does not contain
12541                  function templates and at most one of a set of
12542                  overloaded functions provides a unique match.  */
12543               if (resolve_overloaded_unification
12544                   (tparms, targs, parm, arg, strict, sub_strict))
12545                 continue;
12546
12547               return 1;
12548             }
12549           arg_expr = arg;
12550           arg = unlowered_expr_type (arg);
12551           if (arg == error_mark_node)
12552             return 1;
12553         }
12554
12555       {
12556         int arg_strict = sub_strict;
12557
12558         if (!subr)
12559           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12560                                                           arg_expr);
12561
12562         if (arg == init_list_type_node && arg_expr)
12563           arg = arg_expr;
12564         if (unify (tparms, targs, parm, arg, arg_strict))
12565           return 1;
12566       }
12567     }
12568
12569
12570   if (parms 
12571       && parms != void_list_node
12572       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12573     {
12574       /* Unify the remaining arguments with the pack expansion type.  */
12575       tree argvec;
12576       tree parmvec = make_tree_vec (1);
12577       int len = 0;
12578       tree t;
12579
12580       /* Count the number of arguments that remain.  */
12581       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12582         len++;
12583         
12584       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12585       argvec = make_tree_vec (len);
12586       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12587         {
12588           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12589           ++i;
12590         }
12591
12592       /* Copy the parameter into parmvec.  */
12593       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12594       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12595                                 /*call_args_p=*/true, /*subr=*/subr))
12596         return 1;
12597
12598       /* Advance to the end of the list of parameters.  */
12599       parms = TREE_CHAIN (parms);
12600     }
12601
12602   /* Fail if we've reached the end of the parm list, and more args
12603      are present, and the parm list isn't variadic.  */
12604   if (args && args != void_list_node && parms == void_list_node)
12605     return 1;
12606   /* Fail if parms are left and they don't have default values.  */
12607   if (parms && parms != void_list_node
12608       && TREE_PURPOSE (parms) == NULL_TREE)
12609     return 1;
12610
12611   if (!subr)
12612     for (i = 0; i < ntparms; i++)
12613       if (!TREE_VEC_ELT (targs, i))
12614         {
12615           tree tparm;
12616
12617           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12618             continue;
12619
12620           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12621
12622           /* If this is an undeduced nontype parameter that depends on
12623              a type parameter, try another pass; its type may have been
12624              deduced from a later argument than the one from which
12625              this parameter can be deduced.  */
12626           if (TREE_CODE (tparm) == PARM_DECL
12627               && uses_template_parms (TREE_TYPE (tparm))
12628               && !saw_undeduced++)
12629             goto again;
12630
12631           /* Core issue #226 (C++0x) [temp.deduct]:
12632
12633                If a template argument has not been deduced, its
12634                default template argument, if any, is used. 
12635
12636              When we are in C++98 mode, TREE_PURPOSE will either
12637              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12638              to explicitly check cxx_dialect here.  */
12639           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12640             {
12641               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12642                                  targs, tf_none, NULL_TREE);
12643               if (arg == error_mark_node)
12644                 return 1;
12645               else
12646                 {
12647                   TREE_VEC_ELT (targs, i) = arg;
12648                   continue;
12649                 }
12650             }
12651
12652           /* If the type parameter is a parameter pack, then it will
12653              be deduced to an empty parameter pack.  */
12654           if (template_parameter_pack_p (tparm))
12655             {
12656               tree arg;
12657
12658               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12659                 {
12660                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12661                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12662                   TREE_CONSTANT (arg) = 1;
12663                 }
12664               else
12665                 arg = make_node (TYPE_ARGUMENT_PACK);
12666
12667               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12668
12669               TREE_VEC_ELT (targs, i) = arg;
12670               continue;
12671             }
12672
12673           return 2;
12674         }
12675
12676   return 0;
12677 }
12678
12679 /* Subroutine of type_unification_real.  Args are like the variables
12680    at the call site.  ARG is an overloaded function (or template-id);
12681    we try deducing template args from each of the overloads, and if
12682    only one succeeds, we go with that.  Modifies TARGS and returns
12683    true on success.  */
12684
12685 static bool
12686 resolve_overloaded_unification (tree tparms,
12687                                 tree targs,
12688                                 tree parm,
12689                                 tree arg,
12690                                 unification_kind_t strict,
12691                                 int sub_strict)
12692 {
12693   tree tempargs = copy_node (targs);
12694   int good = 0;
12695   tree goodfn = NULL_TREE;
12696   bool addr_p;
12697
12698   if (TREE_CODE (arg) == ADDR_EXPR)
12699     {
12700       arg = TREE_OPERAND (arg, 0);
12701       addr_p = true;
12702     }
12703   else
12704     addr_p = false;
12705
12706   if (TREE_CODE (arg) == COMPONENT_REF)
12707     /* Handle `&x' where `x' is some static or non-static member
12708        function name.  */
12709     arg = TREE_OPERAND (arg, 1);
12710
12711   if (TREE_CODE (arg) == OFFSET_REF)
12712     arg = TREE_OPERAND (arg, 1);
12713
12714   /* Strip baselink information.  */
12715   if (BASELINK_P (arg))
12716     arg = BASELINK_FUNCTIONS (arg);
12717
12718   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12719     {
12720       /* If we got some explicit template args, we need to plug them into
12721          the affected templates before we try to unify, in case the
12722          explicit args will completely resolve the templates in question.  */
12723
12724       tree expl_subargs = TREE_OPERAND (arg, 1);
12725       arg = TREE_OPERAND (arg, 0);
12726
12727       for (; arg; arg = OVL_NEXT (arg))
12728         {
12729           tree fn = OVL_CURRENT (arg);
12730           tree subargs, elem;
12731
12732           if (TREE_CODE (fn) != TEMPLATE_DECL)
12733             continue;
12734
12735           ++processing_template_decl;
12736           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12737                                   expl_subargs, /*check_ret=*/false);
12738           if (subargs)
12739             {
12740               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12741               if (try_one_overload (tparms, targs, tempargs, parm,
12742                                     elem, strict, sub_strict, addr_p)
12743                   && (!goodfn || !decls_match (goodfn, elem)))
12744                 {
12745                   goodfn = elem;
12746                   ++good;
12747                 }
12748             }
12749           --processing_template_decl;
12750         }
12751     }
12752   else if (TREE_CODE (arg) != OVERLOAD
12753            && TREE_CODE (arg) != FUNCTION_DECL)
12754     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12755        -- but the deduction does not succeed because the expression is
12756        not just the function on its own.  */
12757     return false;
12758   else
12759     for (; arg; arg = OVL_NEXT (arg))
12760       if (try_one_overload (tparms, targs, tempargs, parm,
12761                             TREE_TYPE (OVL_CURRENT (arg)),
12762                             strict, sub_strict, addr_p)
12763           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
12764         {
12765           goodfn = OVL_CURRENT (arg);
12766           ++good;
12767         }
12768
12769   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12770      to function or pointer to member function argument if the set of
12771      overloaded functions does not contain function templates and at most
12772      one of a set of overloaded functions provides a unique match.
12773
12774      So if we found multiple possibilities, we return success but don't
12775      deduce anything.  */
12776
12777   if (good == 1)
12778     {
12779       int i = TREE_VEC_LENGTH (targs);
12780       for (; i--; )
12781         if (TREE_VEC_ELT (tempargs, i))
12782           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12783     }
12784   if (good)
12785     return true;
12786
12787   return false;
12788 }
12789
12790 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12791    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12792    different overloads deduce different arguments for a given parm.
12793    ADDR_P is true if the expression for which deduction is being
12794    performed was of the form "& fn" rather than simply "fn".
12795
12796    Returns 1 on success.  */
12797
12798 static int
12799 try_one_overload (tree tparms,
12800                   tree orig_targs,
12801                   tree targs,
12802                   tree parm,
12803                   tree arg,
12804                   unification_kind_t strict,
12805                   int sub_strict,
12806                   bool addr_p)
12807 {
12808   int nargs;
12809   tree tempargs;
12810   int i;
12811
12812   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12813      to function or pointer to member function argument if the set of
12814      overloaded functions does not contain function templates and at most
12815      one of a set of overloaded functions provides a unique match.
12816
12817      So if this is a template, just return success.  */
12818
12819   if (uses_template_parms (arg))
12820     return 1;
12821
12822   if (TREE_CODE (arg) == METHOD_TYPE)
12823     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12824   else if (addr_p)
12825     arg = build_pointer_type (arg);
12826
12827   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12828
12829   /* We don't copy orig_targs for this because if we have already deduced
12830      some template args from previous args, unify would complain when we
12831      try to deduce a template parameter for the same argument, even though
12832      there isn't really a conflict.  */
12833   nargs = TREE_VEC_LENGTH (targs);
12834   tempargs = make_tree_vec (nargs);
12835
12836   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12837     return 0;
12838
12839   /* First make sure we didn't deduce anything that conflicts with
12840      explicitly specified args.  */
12841   for (i = nargs; i--; )
12842     {
12843       tree elt = TREE_VEC_ELT (tempargs, i);
12844       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12845
12846       if (!elt)
12847         /*NOP*/;
12848       else if (uses_template_parms (elt))
12849         /* Since we're unifying against ourselves, we will fill in
12850            template args used in the function parm list with our own
12851            template parms.  Discard them.  */
12852         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12853       else if (oldelt && !template_args_equal (oldelt, elt))
12854         return 0;
12855     }
12856
12857   for (i = nargs; i--; )
12858     {
12859       tree elt = TREE_VEC_ELT (tempargs, i);
12860
12861       if (elt)
12862         TREE_VEC_ELT (targs, i) = elt;
12863     }
12864
12865   return 1;
12866 }
12867
12868 /* PARM is a template class (perhaps with unbound template
12869    parameters).  ARG is a fully instantiated type.  If ARG can be
12870    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12871    TARGS are as for unify.  */
12872
12873 static tree
12874 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12875 {
12876   tree copy_of_targs;
12877
12878   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12879       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12880           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12881     return NULL_TREE;
12882
12883   /* We need to make a new template argument vector for the call to
12884      unify.  If we used TARGS, we'd clutter it up with the result of
12885      the attempted unification, even if this class didn't work out.
12886      We also don't want to commit ourselves to all the unifications
12887      we've already done, since unification is supposed to be done on
12888      an argument-by-argument basis.  In other words, consider the
12889      following pathological case:
12890
12891        template <int I, int J, int K>
12892        struct S {};
12893
12894        template <int I, int J>
12895        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12896
12897        template <int I, int J, int K>
12898        void f(S<I, J, K>, S<I, I, I>);
12899
12900        void g() {
12901          S<0, 0, 0> s0;
12902          S<0, 1, 2> s2;
12903
12904          f(s0, s2);
12905        }
12906
12907      Now, by the time we consider the unification involving `s2', we
12908      already know that we must have `f<0, 0, 0>'.  But, even though
12909      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12910      because there are two ways to unify base classes of S<0, 1, 2>
12911      with S<I, I, I>.  If we kept the already deduced knowledge, we
12912      would reject the possibility I=1.  */
12913   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12914
12915   /* If unification failed, we're done.  */
12916   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12917              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12918     return NULL_TREE;
12919
12920   return arg;
12921 }
12922
12923 /* Given a template type PARM and a class type ARG, find the unique
12924    base type in ARG that is an instance of PARM.  We do not examine
12925    ARG itself; only its base-classes.  If there is not exactly one
12926    appropriate base class, return NULL_TREE.  PARM may be the type of
12927    a partial specialization, as well as a plain template type.  Used
12928    by unify.  */
12929
12930 static tree
12931 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12932 {
12933   tree rval = NULL_TREE;
12934   tree binfo;
12935
12936   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
12937
12938   binfo = TYPE_BINFO (complete_type (arg));
12939   if (!binfo)
12940     /* The type could not be completed.  */
12941     return NULL_TREE;
12942
12943   /* Walk in inheritance graph order.  The search order is not
12944      important, and this avoids multiple walks of virtual bases.  */
12945   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12946     {
12947       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12948
12949       if (r)
12950         {
12951           /* If there is more than one satisfactory baseclass, then:
12952
12953                [temp.deduct.call]
12954
12955               If they yield more than one possible deduced A, the type
12956               deduction fails.
12957
12958              applies.  */
12959           if (rval && !same_type_p (r, rval))
12960             return NULL_TREE;
12961
12962           rval = r;
12963         }
12964     }
12965
12966   return rval;
12967 }
12968
12969 /* Returns the level of DECL, which declares a template parameter.  */
12970
12971 static int
12972 template_decl_level (tree decl)
12973 {
12974   switch (TREE_CODE (decl))
12975     {
12976     case TYPE_DECL:
12977     case TEMPLATE_DECL:
12978       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12979
12980     case PARM_DECL:
12981       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12982
12983     default:
12984       gcc_unreachable ();
12985     }
12986   return 0;
12987 }
12988
12989 /* Decide whether ARG can be unified with PARM, considering only the
12990    cv-qualifiers of each type, given STRICT as documented for unify.
12991    Returns nonzero iff the unification is OK on that basis.  */
12992
12993 static int
12994 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12995 {
12996   int arg_quals = cp_type_quals (arg);
12997   int parm_quals = cp_type_quals (parm);
12998
12999   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13000       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13001     {
13002       /*  Although a CVR qualifier is ignored when being applied to a
13003           substituted template parameter ([8.3.2]/1 for example), that
13004           does not apply during deduction [14.8.2.4]/1, (even though
13005           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13006           this).  Except when we're allowing additional CV qualifiers
13007           at the outer level [14.8.2.1]/3,1st bullet.  */
13008       if ((TREE_CODE (arg) == REFERENCE_TYPE
13009            || TREE_CODE (arg) == FUNCTION_TYPE
13010            || TREE_CODE (arg) == METHOD_TYPE)
13011           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13012         return 0;
13013
13014       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13015           && (parm_quals & TYPE_QUAL_RESTRICT))
13016         return 0;
13017     }
13018
13019   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13020       && (arg_quals & parm_quals) != parm_quals)
13021     return 0;
13022
13023   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13024       && (parm_quals & arg_quals) != arg_quals)
13025     return 0;
13026
13027   return 1;
13028 }
13029
13030 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13031 void 
13032 template_parm_level_and_index (tree parm, int* level, int* index)
13033 {
13034   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13035       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13036       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13037     {
13038       *index = TEMPLATE_TYPE_IDX (parm);
13039       *level = TEMPLATE_TYPE_LEVEL (parm);
13040     }
13041   else
13042     {
13043       *index = TEMPLATE_PARM_IDX (parm);
13044       *level = TEMPLATE_PARM_LEVEL (parm);
13045     }
13046 }
13047
13048 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13049    expansion at the end of PACKED_PARMS. Returns 0 if the type
13050    deduction succeeds, 1 otherwise. STRICT is the same as in
13051    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13052    call argument list. We'll need to adjust the arguments to make them
13053    types. SUBR tells us if this is from a recursive call to
13054    type_unification_real.  */
13055 int
13056 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13057                       tree packed_args, int strict, bool call_args_p,
13058                       bool subr)
13059 {
13060   tree parm 
13061     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13062   tree pattern = PACK_EXPANSION_PATTERN (parm);
13063   tree pack, packs = NULL_TREE;
13064   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13065   int len = TREE_VEC_LENGTH (packed_args);
13066
13067   /* Determine the parameter packs we will be deducing from the
13068      pattern, and record their current deductions.  */
13069   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13070        pack; pack = TREE_CHAIN (pack))
13071     {
13072       tree parm_pack = TREE_VALUE (pack);
13073       int idx, level;
13074
13075       /* Determine the index and level of this parameter pack.  */
13076       template_parm_level_and_index (parm_pack, &level, &idx);
13077
13078       /* Keep track of the parameter packs and their corresponding
13079          argument packs.  */
13080       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13081       TREE_TYPE (packs) = make_tree_vec (len - start);
13082     }
13083   
13084   /* Loop through all of the arguments that have not yet been
13085      unified and unify each with the pattern.  */
13086   for (i = start; i < len; i++)
13087     {
13088       tree parm = pattern;
13089
13090       /* For each parameter pack, clear out the deduced value so that
13091          we can deduce it again.  */
13092       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13093         {
13094           int idx, level;
13095           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13096
13097           TMPL_ARG (targs, level, idx) = NULL_TREE;
13098         }
13099
13100       /* Unify the pattern with the current argument.  */
13101       {
13102         tree arg = TREE_VEC_ELT (packed_args, i);
13103         tree arg_expr = NULL_TREE;
13104         int arg_strict = strict;
13105         bool skip_arg_p = false;
13106
13107         if (call_args_p)
13108           {
13109             int sub_strict;
13110
13111             /* This mirrors what we do in type_unification_real.  */
13112             switch (strict)
13113               {
13114               case DEDUCE_CALL:
13115                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13116                               | UNIFY_ALLOW_MORE_CV_QUAL
13117                               | UNIFY_ALLOW_DERIVED);
13118                 break;
13119                 
13120               case DEDUCE_CONV:
13121                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13122                 break;
13123                 
13124               case DEDUCE_EXACT:
13125                 sub_strict = UNIFY_ALLOW_NONE;
13126                 break;
13127                 
13128               default:
13129                 gcc_unreachable ();
13130               }
13131
13132             if (!TYPE_P (arg))
13133               {
13134                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13135                 if (type_unknown_p (arg))
13136                   {
13137                     /* [temp.deduct.type] A template-argument can be
13138                        deduced from a pointer to function or pointer
13139                        to member function argument if the set of
13140                        overloaded functions does not contain function
13141                        templates and at most one of a set of
13142                        overloaded functions provides a unique
13143                        match.  */
13144
13145                     if (resolve_overloaded_unification
13146                         (tparms, targs, parm, arg,
13147                          (unification_kind_t) strict,
13148                          sub_strict)
13149                         != 0)
13150                       return 1;
13151                     skip_arg_p = true;
13152                   }
13153
13154                 if (!skip_arg_p)
13155                   {
13156                     arg_expr = arg;
13157                     arg = unlowered_expr_type (arg);
13158                     if (arg == error_mark_node)
13159                       return 1;
13160                   }
13161               }
13162       
13163             arg_strict = sub_strict;
13164
13165             if (!subr)
13166               arg_strict |= 
13167                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13168                                                   &parm, &arg, arg_expr);
13169           }
13170
13171         if (!skip_arg_p)
13172           {
13173             if (unify (tparms, targs, parm, arg, arg_strict))
13174               return 1;
13175           }
13176       }
13177
13178       /* For each parameter pack, collect the deduced value.  */
13179       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13180         {
13181           int idx, level;
13182           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13183
13184           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13185             TMPL_ARG (targs, level, idx);
13186         }
13187     }
13188
13189   /* Verify that the results of unification with the parameter packs
13190      produce results consistent with what we've seen before, and make
13191      the deduced argument packs available.  */
13192   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13193     {
13194       tree old_pack = TREE_VALUE (pack);
13195       tree new_args = TREE_TYPE (pack);
13196       int i, len = TREE_VEC_LENGTH (new_args);
13197       bool nondeduced_p = false;
13198
13199       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13200          actually deduce anything.  */
13201       for (i = 0; i < len && !nondeduced_p; ++i)
13202         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13203           nondeduced_p = true;
13204       if (nondeduced_p)
13205         continue;
13206
13207       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13208         {
13209           /* Prepend the explicit arguments onto NEW_ARGS.  */
13210           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13211           tree old_args = new_args;
13212           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13213           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13214
13215           /* Copy the explicit arguments.  */
13216           new_args = make_tree_vec (len);
13217           for (i = 0; i < explicit_len; i++)
13218             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13219
13220           /* Copy the deduced arguments.  */
13221           for (; i < len; i++)
13222             TREE_VEC_ELT (new_args, i) =
13223               TREE_VEC_ELT (old_args, i - explicit_len);
13224         }
13225
13226       if (!old_pack)
13227         {
13228           tree result;
13229           int idx, level;
13230           
13231           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13232
13233           /* Build the deduced *_ARGUMENT_PACK.  */
13234           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13235             {
13236               result = make_node (NONTYPE_ARGUMENT_PACK);
13237               TREE_TYPE (result) = 
13238                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13239               TREE_CONSTANT (result) = 1;
13240             }
13241           else
13242             result = make_node (TYPE_ARGUMENT_PACK);
13243
13244           SET_ARGUMENT_PACK_ARGS (result, new_args);
13245
13246           /* Note the deduced argument packs for this parameter
13247              pack.  */
13248           TMPL_ARG (targs, level, idx) = result;
13249         }
13250       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13251                && (ARGUMENT_PACK_ARGS (old_pack) 
13252                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13253         {
13254           /* We only had the explicitly-provided arguments before, but
13255              now we have a complete set of arguments.  */
13256           int idx, level;
13257           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13258           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13259
13260           /* Keep the original deduced argument pack.  */
13261           TMPL_ARG (targs, level, idx) = old_pack;
13262
13263           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13264           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13265           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13266         }
13267       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13268                                     new_args))
13269         /* Inconsistent unification of this parameter pack.  */
13270         return 1;
13271       else
13272         {
13273           int idx, level;
13274           
13275           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13276
13277           /* Keep the original deduced argument pack.  */
13278           TMPL_ARG (targs, level, idx) = old_pack;
13279         }
13280     }
13281
13282   return 0;
13283 }
13284
13285 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13286    set of template parameters to a template.  TARGS is the bindings
13287    for those template parameters, as determined thus far; TARGS may
13288    include template arguments for outer levels of template parameters
13289    as well.  PARM is a parameter to a template function, or a
13290    subcomponent of that parameter; ARG is the corresponding argument.
13291    This function attempts to match PARM with ARG in a manner
13292    consistent with the existing assignments in TARGS.  If more values
13293    are deduced, then TARGS is updated.
13294
13295    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13296    parameter STRICT is a bitwise or of the following flags:
13297
13298      UNIFY_ALLOW_NONE:
13299        Require an exact match between PARM and ARG.
13300      UNIFY_ALLOW_MORE_CV_QUAL:
13301        Allow the deduced ARG to be more cv-qualified (by qualification
13302        conversion) than ARG.
13303      UNIFY_ALLOW_LESS_CV_QUAL:
13304        Allow the deduced ARG to be less cv-qualified than ARG.
13305      UNIFY_ALLOW_DERIVED:
13306        Allow the deduced ARG to be a template base class of ARG,
13307        or a pointer to a template base class of the type pointed to by
13308        ARG.
13309      UNIFY_ALLOW_INTEGER:
13310        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13311        case for more information.
13312      UNIFY_ALLOW_OUTER_LEVEL:
13313        This is the outermost level of a deduction. Used to determine validity
13314        of qualification conversions. A valid qualification conversion must
13315        have const qualified pointers leading up to the inner type which
13316        requires additional CV quals, except at the outer level, where const
13317        is not required [conv.qual]. It would be normal to set this flag in
13318        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13319      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13320        This is the outermost level of a deduction, and PARM can be more CV
13321        qualified at this point.
13322      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13323        This is the outermost level of a deduction, and PARM can be less CV
13324        qualified at this point.  */
13325
13326 static int
13327 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13328 {
13329   int idx;
13330   tree targ;
13331   tree tparm;
13332   int strict_in = strict;
13333
13334   /* I don't think this will do the right thing with respect to types.
13335      But the only case I've seen it in so far has been array bounds, where
13336      signedness is the only information lost, and I think that will be
13337      okay.  */
13338   while (TREE_CODE (parm) == NOP_EXPR)
13339     parm = TREE_OPERAND (parm, 0);
13340
13341   if (arg == error_mark_node)
13342     return 1;
13343   if (arg == unknown_type_node
13344       || arg == init_list_type_node)
13345     /* We can't deduce anything from this, but we might get all the
13346        template args from other function args.  */
13347     return 0;
13348
13349   /* If PARM uses template parameters, then we can't bail out here,
13350      even if ARG == PARM, since we won't record unifications for the
13351      template parameters.  We might need them if we're trying to
13352      figure out which of two things is more specialized.  */
13353   if (arg == parm && !uses_template_parms (parm))
13354     return 0;
13355
13356   /* Handle init lists early, so the rest of the function can assume
13357      we're dealing with a type. */
13358   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13359     {
13360       tree elt, elttype;
13361       unsigned i;
13362
13363       if (!is_std_init_list (parm))
13364         /* We can only deduce from an initializer list argument if the
13365            parameter is std::initializer_list; otherwise this is a
13366            non-deduced context. */
13367         return 0;
13368
13369       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13370
13371       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13372         {
13373           int elt_strict = strict;
13374           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13375             {
13376               tree type = TREE_TYPE (elt);
13377               /* It should only be possible to get here for a call.  */
13378               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13379               elt_strict |= maybe_adjust_types_for_deduction
13380                 (DEDUCE_CALL, &elttype, &type, elt);
13381               elt = type;
13382             }
13383
13384           if (unify (tparms, targs, elttype, elt, elt_strict))
13385             return 1;
13386         }
13387       return 0;
13388     }
13389
13390   /* Immediately reject some pairs that won't unify because of
13391      cv-qualification mismatches.  */
13392   if (TREE_CODE (arg) == TREE_CODE (parm)
13393       && TYPE_P (arg)
13394       /* It is the elements of the array which hold the cv quals of an array
13395          type, and the elements might be template type parms. We'll check
13396          when we recurse.  */
13397       && TREE_CODE (arg) != ARRAY_TYPE
13398       /* We check the cv-qualifiers when unifying with template type
13399          parameters below.  We want to allow ARG `const T' to unify with
13400          PARM `T' for example, when computing which of two templates
13401          is more specialized, for example.  */
13402       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13403       && !check_cv_quals_for_unify (strict_in, arg, parm))
13404     return 1;
13405
13406   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13407       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13408     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13409   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13410   strict &= ~UNIFY_ALLOW_DERIVED;
13411   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13412   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13413
13414   switch (TREE_CODE (parm))
13415     {
13416     case TYPENAME_TYPE:
13417     case SCOPE_REF:
13418     case UNBOUND_CLASS_TEMPLATE:
13419       /* In a type which contains a nested-name-specifier, template
13420          argument values cannot be deduced for template parameters used
13421          within the nested-name-specifier.  */
13422       return 0;
13423
13424     case TEMPLATE_TYPE_PARM:
13425     case TEMPLATE_TEMPLATE_PARM:
13426     case BOUND_TEMPLATE_TEMPLATE_PARM:
13427       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13428       if (tparm == error_mark_node)
13429         return 1;
13430
13431       if (TEMPLATE_TYPE_LEVEL (parm)
13432           != template_decl_level (tparm))
13433         /* The PARM is not one we're trying to unify.  Just check
13434            to see if it matches ARG.  */
13435         return (TREE_CODE (arg) == TREE_CODE (parm)
13436                 && same_type_p (parm, arg)) ? 0 : 1;
13437       idx = TEMPLATE_TYPE_IDX (parm);
13438       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13439       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13440
13441       /* Check for mixed types and values.  */
13442       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13443            && TREE_CODE (tparm) != TYPE_DECL)
13444           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13445               && TREE_CODE (tparm) != TEMPLATE_DECL))
13446         return 1;
13447
13448       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13449         {
13450           /* ARG must be constructed from a template class or a template
13451              template parameter.  */
13452           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13453               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13454             return 1;
13455
13456           {
13457             tree parmvec = TYPE_TI_ARGS (parm);
13458             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13459             tree parm_parms 
13460               = DECL_INNERMOST_TEMPLATE_PARMS
13461                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13462             int i, len;
13463             int parm_variadic_p = 0;
13464
13465             /* The resolution to DR150 makes clear that default
13466                arguments for an N-argument may not be used to bind T
13467                to a template template parameter with fewer than N
13468                parameters.  It is not safe to permit the binding of
13469                default arguments as an extension, as that may change
13470                the meaning of a conforming program.  Consider:
13471
13472                   struct Dense { static const unsigned int dim = 1; };
13473
13474                   template <template <typename> class View,
13475                             typename Block>
13476                   void operator+(float, View<Block> const&);
13477
13478                   template <typename Block,
13479                             unsigned int Dim = Block::dim>
13480                   struct Lvalue_proxy { operator float() const; };
13481
13482                   void
13483                   test_1d (void) {
13484                     Lvalue_proxy<Dense> p;
13485                     float b;
13486                     b + p;
13487                   }
13488
13489               Here, if Lvalue_proxy is permitted to bind to View, then
13490               the global operator+ will be used; if they are not, the
13491               Lvalue_proxy will be converted to float.  */
13492             if (coerce_template_parms (parm_parms,
13493                                        argvec,
13494                                        TYPE_TI_TEMPLATE (parm),
13495                                        tf_none,
13496                                        /*require_all_args=*/true,
13497                                        /*use_default_args=*/false)
13498                 == error_mark_node)
13499               return 1;
13500
13501             /* Deduce arguments T, i from TT<T> or TT<i>.
13502                We check each element of PARMVEC and ARGVEC individually
13503                rather than the whole TREE_VEC since they can have
13504                different number of elements.  */
13505
13506             parmvec = expand_template_argument_pack (parmvec);
13507             argvec = expand_template_argument_pack (argvec);
13508
13509             len = TREE_VEC_LENGTH (parmvec);
13510
13511             /* Check if the parameters end in a pack, making them
13512                variadic.  */
13513             if (len > 0
13514                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13515               parm_variadic_p = 1;
13516             
13517             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13518               return 1;
13519
13520              for (i = 0; i < len - parm_variadic_p; ++i)
13521               {
13522                 if (unify (tparms, targs,
13523                            TREE_VEC_ELT (parmvec, i),
13524                            TREE_VEC_ELT (argvec, i),
13525                            UNIFY_ALLOW_NONE))
13526                   return 1;
13527               }
13528
13529             if (parm_variadic_p
13530                 && unify_pack_expansion (tparms, targs,
13531                                          parmvec, argvec,
13532                                          UNIFY_ALLOW_NONE,
13533                                          /*call_args_p=*/false,
13534                                          /*subr=*/false))
13535               return 1;
13536           }
13537           arg = TYPE_TI_TEMPLATE (arg);
13538
13539           /* Fall through to deduce template name.  */
13540         }
13541
13542       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13543           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13544         {
13545           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13546
13547           /* Simple cases: Value already set, does match or doesn't.  */
13548           if (targ != NULL_TREE && template_args_equal (targ, arg))
13549             return 0;
13550           else if (targ)
13551             return 1;
13552         }
13553       else
13554         {
13555           /* If PARM is `const T' and ARG is only `int', we don't have
13556              a match unless we are allowing additional qualification.
13557              If ARG is `const int' and PARM is just `T' that's OK;
13558              that binds `const int' to `T'.  */
13559           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13560                                          arg, parm))
13561             return 1;
13562
13563           /* Consider the case where ARG is `const volatile int' and
13564              PARM is `const T'.  Then, T should be `volatile int'.  */
13565           arg = cp_build_qualified_type_real
13566             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13567           if (arg == error_mark_node)
13568             return 1;
13569
13570           /* Simple cases: Value already set, does match or doesn't.  */
13571           if (targ != NULL_TREE && same_type_p (targ, arg))
13572             return 0;
13573           else if (targ)
13574             return 1;
13575
13576           /* Make sure that ARG is not a variable-sized array.  (Note
13577              that were talking about variable-sized arrays (like
13578              `int[n]'), rather than arrays of unknown size (like
13579              `int[]').)  We'll get very confused by such a type since
13580              the bound of the array will not be computable in an
13581              instantiation.  Besides, such types are not allowed in
13582              ISO C++, so we can do as we please here.  */
13583           if (variably_modified_type_p (arg, NULL_TREE))
13584             return 1;
13585
13586           /* Strip typedefs as in convert_template_argument.  */
13587           arg = canonical_type_variant (arg);
13588         }
13589
13590       /* If ARG is a parameter pack or an expansion, we cannot unify
13591          against it unless PARM is also a parameter pack.  */
13592       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13593           && !template_parameter_pack_p (parm))
13594         return 1;
13595
13596       /* If the argument deduction results is a METHOD_TYPE,
13597          then there is a problem.
13598          METHOD_TYPE doesn't map to any real C++ type the result of
13599          the deduction can not be of that type.  */
13600       if (TREE_CODE (arg) == METHOD_TYPE)
13601         return 1;
13602
13603       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13604       return 0;
13605
13606     case TEMPLATE_PARM_INDEX:
13607       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13608       if (tparm == error_mark_node)
13609         return 1;
13610
13611       if (TEMPLATE_PARM_LEVEL (parm)
13612           != template_decl_level (tparm))
13613         /* The PARM is not one we're trying to unify.  Just check
13614            to see if it matches ARG.  */
13615         return !(TREE_CODE (arg) == TREE_CODE (parm)
13616                  && cp_tree_equal (parm, arg));
13617
13618       idx = TEMPLATE_PARM_IDX (parm);
13619       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13620
13621       if (targ)
13622         return !cp_tree_equal (targ, arg);
13623
13624       /* [temp.deduct.type] If, in the declaration of a function template
13625          with a non-type template-parameter, the non-type
13626          template-parameter is used in an expression in the function
13627          parameter-list and, if the corresponding template-argument is
13628          deduced, the template-argument type shall match the type of the
13629          template-parameter exactly, except that a template-argument
13630          deduced from an array bound may be of any integral type.
13631          The non-type parameter might use already deduced type parameters.  */
13632       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13633       if (!TREE_TYPE (arg))
13634         /* Template-parameter dependent expression.  Just accept it for now.
13635            It will later be processed in convert_template_argument.  */
13636         ;
13637       else if (same_type_p (TREE_TYPE (arg), tparm))
13638         /* OK */;
13639       else if ((strict & UNIFY_ALLOW_INTEGER)
13640                && (TREE_CODE (tparm) == INTEGER_TYPE
13641                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13642         /* Convert the ARG to the type of PARM; the deduced non-type
13643            template argument must exactly match the types of the
13644            corresponding parameter.  */
13645         arg = fold (build_nop (tparm, arg));
13646       else if (uses_template_parms (tparm))
13647         /* We haven't deduced the type of this parameter yet.  Try again
13648            later.  */
13649         return 0;
13650       else
13651         return 1;
13652
13653       /* If ARG is a parameter pack or an expansion, we cannot unify
13654          against it unless PARM is also a parameter pack.  */
13655       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13656           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13657         return 1;
13658
13659       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13660       return 0;
13661
13662     case PTRMEM_CST:
13663      {
13664         /* A pointer-to-member constant can be unified only with
13665          another constant.  */
13666       if (TREE_CODE (arg) != PTRMEM_CST)
13667         return 1;
13668
13669       /* Just unify the class member. It would be useless (and possibly
13670          wrong, depending on the strict flags) to unify also
13671          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13672          arg refer to the same variable, even if through different
13673          classes. For instance:
13674
13675          struct A { int x; };
13676          struct B : A { };
13677
13678          Unification of &A::x and &B::x must succeed.  */
13679       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13680                     PTRMEM_CST_MEMBER (arg), strict);
13681      }
13682
13683     case POINTER_TYPE:
13684       {
13685         if (TREE_CODE (arg) != POINTER_TYPE)
13686           return 1;
13687
13688         /* [temp.deduct.call]
13689
13690            A can be another pointer or pointer to member type that can
13691            be converted to the deduced A via a qualification
13692            conversion (_conv.qual_).
13693
13694            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13695            This will allow for additional cv-qualification of the
13696            pointed-to types if appropriate.  */
13697
13698         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13699           /* The derived-to-base conversion only persists through one
13700              level of pointers.  */
13701           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13702
13703         return unify (tparms, targs, TREE_TYPE (parm),
13704                       TREE_TYPE (arg), strict);
13705       }
13706
13707     case REFERENCE_TYPE:
13708       if (TREE_CODE (arg) != REFERENCE_TYPE)
13709         return 1;
13710       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13711                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13712
13713     case ARRAY_TYPE:
13714       if (TREE_CODE (arg) != ARRAY_TYPE)
13715         return 1;
13716       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13717           != (TYPE_DOMAIN (arg) == NULL_TREE))
13718         return 1;
13719       if (TYPE_DOMAIN (parm) != NULL_TREE)
13720         {
13721           tree parm_max;
13722           tree arg_max;
13723           bool parm_cst;
13724           bool arg_cst;
13725
13726           /* Our representation of array types uses "N - 1" as the
13727              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13728              not an integer constant.  We cannot unify arbitrarily
13729              complex expressions, so we eliminate the MINUS_EXPRs
13730              here.  */
13731           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13732           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13733           if (!parm_cst)
13734             {
13735               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13736               parm_max = TREE_OPERAND (parm_max, 0);
13737             }
13738           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13739           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13740           if (!arg_cst)
13741             {
13742               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13743                  trying to unify the type of a variable with the type
13744                  of a template parameter.  For example:
13745
13746                    template <unsigned int N>
13747                    void f (char (&) [N]);
13748                    int g(); 
13749                    void h(int i) {
13750                      char a[g(i)];
13751                      f(a); 
13752                    }
13753
13754                 Here, the type of the ARG will be "int [g(i)]", and
13755                 may be a SAVE_EXPR, etc.  */
13756               if (TREE_CODE (arg_max) != MINUS_EXPR)
13757                 return 1;
13758               arg_max = TREE_OPERAND (arg_max, 0);
13759             }
13760
13761           /* If only one of the bounds used a MINUS_EXPR, compensate
13762              by adding one to the other bound.  */
13763           if (parm_cst && !arg_cst)
13764             parm_max = fold_build2 (PLUS_EXPR,
13765                                     integer_type_node,
13766                                     parm_max,
13767                                     integer_one_node);
13768           else if (arg_cst && !parm_cst)
13769             arg_max = fold_build2 (PLUS_EXPR,
13770                                    integer_type_node,
13771                                    arg_max,
13772                                    integer_one_node);
13773
13774           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13775             return 1;
13776         }
13777       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13778                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13779
13780     case REAL_TYPE:
13781     case COMPLEX_TYPE:
13782     case VECTOR_TYPE:
13783     case INTEGER_TYPE:
13784     case BOOLEAN_TYPE:
13785     case ENUMERAL_TYPE:
13786     case VOID_TYPE:
13787       if (TREE_CODE (arg) != TREE_CODE (parm))
13788         return 1;
13789
13790       /* We have already checked cv-qualification at the top of the
13791          function.  */
13792       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13793         return 1;
13794
13795       /* As far as unification is concerned, this wins.  Later checks
13796          will invalidate it if necessary.  */
13797       return 0;
13798
13799       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13800       /* Type INTEGER_CST can come from ordinary constant template args.  */
13801     case INTEGER_CST:
13802       while (TREE_CODE (arg) == NOP_EXPR)
13803         arg = TREE_OPERAND (arg, 0);
13804
13805       if (TREE_CODE (arg) != INTEGER_CST)
13806         return 1;
13807       return !tree_int_cst_equal (parm, arg);
13808
13809     case TREE_VEC:
13810       {
13811         int i;
13812         if (TREE_CODE (arg) != TREE_VEC)
13813           return 1;
13814         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13815           return 1;
13816         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13817           if (unify (tparms, targs,
13818                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13819                      UNIFY_ALLOW_NONE))
13820             return 1;
13821         return 0;
13822       }
13823
13824     case RECORD_TYPE:
13825     case UNION_TYPE:
13826       if (TREE_CODE (arg) != TREE_CODE (parm))
13827         return 1;
13828
13829       if (TYPE_PTRMEMFUNC_P (parm))
13830         {
13831           if (!TYPE_PTRMEMFUNC_P (arg))
13832             return 1;
13833
13834           return unify (tparms, targs,
13835                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13836                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13837                         strict);
13838         }
13839
13840       if (CLASSTYPE_TEMPLATE_INFO (parm))
13841         {
13842           tree t = NULL_TREE;
13843
13844           if (strict_in & UNIFY_ALLOW_DERIVED)
13845             {
13846               /* First, we try to unify the PARM and ARG directly.  */
13847               t = try_class_unification (tparms, targs,
13848                                          parm, arg);
13849
13850               if (!t)
13851                 {
13852                   /* Fallback to the special case allowed in
13853                      [temp.deduct.call]:
13854
13855                        If P is a class, and P has the form
13856                        template-id, then A can be a derived class of
13857                        the deduced A.  Likewise, if P is a pointer to
13858                        a class of the form template-id, A can be a
13859                        pointer to a derived class pointed to by the
13860                        deduced A.  */
13861                   t = get_template_base (tparms, targs, parm, arg);
13862
13863                   if (!t)
13864                     return 1;
13865                 }
13866             }
13867           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13868                    && (CLASSTYPE_TI_TEMPLATE (parm)
13869                        == CLASSTYPE_TI_TEMPLATE (arg)))
13870             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13871                Then, we should unify `int' and `U'.  */
13872             t = arg;
13873           else
13874             /* There's no chance of unification succeeding.  */
13875             return 1;
13876
13877           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13878                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13879         }
13880       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13881         return 1;
13882       return 0;
13883
13884     case METHOD_TYPE:
13885     case FUNCTION_TYPE:
13886       if (TREE_CODE (arg) != TREE_CODE (parm))
13887         return 1;
13888
13889       /* CV qualifications for methods can never be deduced, they must
13890          match exactly.  We need to check them explicitly here,
13891          because type_unification_real treats them as any other
13892          cv-qualified parameter.  */
13893       if (TREE_CODE (parm) == METHOD_TYPE
13894           && (!check_cv_quals_for_unify
13895               (UNIFY_ALLOW_NONE,
13896                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13897                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13898         return 1;
13899
13900       if (unify (tparms, targs, TREE_TYPE (parm),
13901                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13902         return 1;
13903       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13904                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13905                                     LOOKUP_NORMAL);
13906
13907     case OFFSET_TYPE:
13908       /* Unify a pointer to member with a pointer to member function, which
13909          deduces the type of the member as a function type. */
13910       if (TYPE_PTRMEMFUNC_P (arg))
13911         {
13912           tree method_type;
13913           tree fntype;
13914           cp_cv_quals cv_quals;
13915
13916           /* Check top-level cv qualifiers */
13917           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13918             return 1;
13919
13920           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13921                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13922             return 1;
13923
13924           /* Determine the type of the function we are unifying against. */
13925           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13926           fntype =
13927             build_function_type (TREE_TYPE (method_type),
13928                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13929
13930           /* Extract the cv-qualifiers of the member function from the
13931              implicit object parameter and place them on the function
13932              type to be restored later. */
13933           cv_quals =
13934             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13935           fntype = build_qualified_type (fntype, cv_quals);
13936           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13937         }
13938
13939       if (TREE_CODE (arg) != OFFSET_TYPE)
13940         return 1;
13941       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13942                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13943         return 1;
13944       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13945                     strict);
13946
13947     case CONST_DECL:
13948       if (DECL_TEMPLATE_PARM_P (parm))
13949         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13950       if (arg != integral_constant_value (parm))
13951         return 1;
13952       return 0;
13953
13954     case FIELD_DECL:
13955     case TEMPLATE_DECL:
13956       /* Matched cases are handled by the ARG == PARM test above.  */
13957       return 1;
13958
13959     case TYPE_ARGUMENT_PACK:
13960     case NONTYPE_ARGUMENT_PACK:
13961       {
13962         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13963         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13964         int i, len = TREE_VEC_LENGTH (packed_parms);
13965         int argslen = TREE_VEC_LENGTH (packed_args);
13966         int parm_variadic_p = 0;
13967
13968         for (i = 0; i < len; ++i)
13969           {
13970             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13971               {
13972                 if (i == len - 1)
13973                   /* We can unify against something with a trailing
13974                      parameter pack.  */
13975                   parm_variadic_p = 1;
13976                 else
13977                   /* Since there is something following the pack
13978                      expansion, we cannot unify this template argument
13979                      list.  */
13980                   return 0;
13981               }
13982           }
13983           
13984
13985         /* If we don't have enough arguments to satisfy the parameters
13986            (not counting the pack expression at the end), or we have
13987            too many arguments for a parameter list that doesn't end in
13988            a pack expression, we can't unify.  */
13989         if (argslen < (len - parm_variadic_p)
13990             || (argslen > len && !parm_variadic_p))
13991           return 1;
13992
13993         /* Unify all of the parameters that precede the (optional)
13994            pack expression.  */
13995         for (i = 0; i < len - parm_variadic_p; ++i)
13996           {
13997             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13998                        TREE_VEC_ELT (packed_args, i), strict))
13999               return 1;
14000           }
14001
14002         if (parm_variadic_p)
14003           return unify_pack_expansion (tparms, targs, 
14004                                        packed_parms, packed_args,
14005                                        strict, /*call_args_p=*/false,
14006                                        /*subr=*/false);
14007         return 0;
14008       }
14009
14010       break;
14011
14012     case TYPEOF_TYPE:
14013     case DECLTYPE_TYPE:
14014       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14015          nodes.  */
14016       return 0;
14017
14018     case ERROR_MARK:
14019       /* Unification fails if we hit an error node.  */
14020       return 1;
14021
14022     default:
14023       gcc_assert (EXPR_P (parm));
14024
14025       /* We must be looking at an expression.  This can happen with
14026          something like:
14027
14028            template <int I>
14029            void foo(S<I>, S<I + 2>);
14030
14031          This is a "nondeduced context":
14032
14033            [deduct.type]
14034
14035            The nondeduced contexts are:
14036
14037            --A type that is a template-id in which one or more of
14038              the template-arguments is an expression that references
14039              a template-parameter.
14040
14041          In these cases, we assume deduction succeeded, but don't
14042          actually infer any unifications.  */
14043
14044       if (!uses_template_parms (parm)
14045           && !template_args_equal (parm, arg))
14046         return 1;
14047       else
14048         return 0;
14049     }
14050 }
14051 \f
14052 /* Note that DECL can be defined in this translation unit, if
14053    required.  */
14054
14055 static void
14056 mark_definable (tree decl)
14057 {
14058   tree clone;
14059   DECL_NOT_REALLY_EXTERN (decl) = 1;
14060   FOR_EACH_CLONE (clone, decl)
14061     DECL_NOT_REALLY_EXTERN (clone) = 1;
14062 }
14063
14064 /* Called if RESULT is explicitly instantiated, or is a member of an
14065    explicitly instantiated class.  */
14066
14067 void
14068 mark_decl_instantiated (tree result, int extern_p)
14069 {
14070   SET_DECL_EXPLICIT_INSTANTIATION (result);
14071
14072   /* If this entity has already been written out, it's too late to
14073      make any modifications.  */
14074   if (TREE_ASM_WRITTEN (result))
14075     return;
14076
14077   if (TREE_CODE (result) != FUNCTION_DECL)
14078     /* The TREE_PUBLIC flag for function declarations will have been
14079        set correctly by tsubst.  */
14080     TREE_PUBLIC (result) = 1;
14081
14082   /* This might have been set by an earlier implicit instantiation.  */
14083   DECL_COMDAT (result) = 0;
14084
14085   if (extern_p)
14086     DECL_NOT_REALLY_EXTERN (result) = 0;
14087   else
14088     {
14089       mark_definable (result);
14090       /* Always make artificials weak.  */
14091       if (DECL_ARTIFICIAL (result) && flag_weak)
14092         comdat_linkage (result);
14093       /* For WIN32 we also want to put explicit instantiations in
14094          linkonce sections.  */
14095       else if (TREE_PUBLIC (result))
14096         maybe_make_one_only (result);
14097     }
14098
14099   /* If EXTERN_P, then this function will not be emitted -- unless
14100      followed by an explicit instantiation, at which point its linkage
14101      will be adjusted.  If !EXTERN_P, then this function will be
14102      emitted here.  In neither circumstance do we want
14103      import_export_decl to adjust the linkage.  */
14104   DECL_INTERFACE_KNOWN (result) = 1;
14105 }
14106
14107 /* Given two function templates PAT1 and PAT2, return:
14108
14109    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14110    -1 if PAT2 is more specialized than PAT1.
14111    0 if neither is more specialized.
14112
14113    LEN indicates the number of parameters we should consider
14114    (defaulted parameters should not be considered).
14115
14116    The 1998 std underspecified function template partial ordering, and
14117    DR214 addresses the issue.  We take pairs of arguments, one from
14118    each of the templates, and deduce them against each other.  One of
14119    the templates will be more specialized if all the *other*
14120    template's arguments deduce against its arguments and at least one
14121    of its arguments *does* *not* deduce against the other template's
14122    corresponding argument.  Deduction is done as for class templates.
14123    The arguments used in deduction have reference and top level cv
14124    qualifiers removed.  Iff both arguments were originally reference
14125    types *and* deduction succeeds in both directions, the template
14126    with the more cv-qualified argument wins for that pairing (if
14127    neither is more cv-qualified, they both are equal).  Unlike regular
14128    deduction, after all the arguments have been deduced in this way,
14129    we do *not* verify the deduced template argument values can be
14130    substituted into non-deduced contexts, nor do we have to verify
14131    that all template arguments have been deduced.  */
14132
14133 int
14134 more_specialized_fn (tree pat1, tree pat2, int len)
14135 {
14136   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14137   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14138   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14139   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14140   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14141   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14142   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14143   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14144   int better1 = 0;
14145   int better2 = 0;
14146
14147   /* Remove the this parameter from non-static member functions.  If
14148      one is a non-static member function and the other is not a static
14149      member function, remove the first parameter from that function
14150      also.  This situation occurs for operator functions where we
14151      locate both a member function (with this pointer) and non-member
14152      operator (with explicit first operand).  */
14153   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14154     {
14155       len--; /* LEN is the number of significant arguments for DECL1 */
14156       args1 = TREE_CHAIN (args1);
14157       if (!DECL_STATIC_FUNCTION_P (decl2))
14158         args2 = TREE_CHAIN (args2);
14159     }
14160   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14161     {
14162       args2 = TREE_CHAIN (args2);
14163       if (!DECL_STATIC_FUNCTION_P (decl1))
14164         {
14165           len--;
14166           args1 = TREE_CHAIN (args1);
14167         }
14168     }
14169
14170   /* If only one is a conversion operator, they are unordered.  */
14171   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14172     return 0;
14173
14174   /* Consider the return type for a conversion function */
14175   if (DECL_CONV_FN_P (decl1))
14176     {
14177       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14178       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14179       len++;
14180     }
14181
14182   processing_template_decl++;
14183
14184   while (len--
14185          /* Stop when an ellipsis is seen.  */
14186          && args1 != NULL_TREE && args2 != NULL_TREE)
14187     {
14188       tree arg1 = TREE_VALUE (args1);
14189       tree arg2 = TREE_VALUE (args2);
14190       int deduce1, deduce2;
14191       int quals1 = -1;
14192       int quals2 = -1;
14193
14194       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14195           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14196         {
14197           /* When both arguments are pack expansions, we need only
14198              unify the patterns themselves.  */
14199           arg1 = PACK_EXPANSION_PATTERN (arg1);
14200           arg2 = PACK_EXPANSION_PATTERN (arg2);
14201
14202           /* This is the last comparison we need to do.  */
14203           len = 0;
14204         }
14205
14206       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14207         {
14208           arg1 = TREE_TYPE (arg1);
14209           quals1 = cp_type_quals (arg1);
14210         }
14211
14212       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14213         {
14214           arg2 = TREE_TYPE (arg2);
14215           quals2 = cp_type_quals (arg2);
14216         }
14217
14218       if ((quals1 < 0) != (quals2 < 0))
14219         {
14220           /* Only of the args is a reference, see if we should apply
14221              array/function pointer decay to it.  This is not part of
14222              DR214, but is, IMHO, consistent with the deduction rules
14223              for the function call itself, and with our earlier
14224              implementation of the underspecified partial ordering
14225              rules.  (nathan).  */
14226           if (quals1 >= 0)
14227             {
14228               switch (TREE_CODE (arg1))
14229                 {
14230                 case ARRAY_TYPE:
14231                   arg1 = TREE_TYPE (arg1);
14232                   /* FALLTHROUGH. */
14233                 case FUNCTION_TYPE:
14234                   arg1 = build_pointer_type (arg1);
14235                   break;
14236
14237                 default:
14238                   break;
14239                 }
14240             }
14241           else
14242             {
14243               switch (TREE_CODE (arg2))
14244                 {
14245                 case ARRAY_TYPE:
14246                   arg2 = TREE_TYPE (arg2);
14247                   /* FALLTHROUGH. */
14248                 case FUNCTION_TYPE:
14249                   arg2 = build_pointer_type (arg2);
14250                   break;
14251
14252                 default:
14253                   break;
14254                 }
14255             }
14256         }
14257
14258       arg1 = TYPE_MAIN_VARIANT (arg1);
14259       arg2 = TYPE_MAIN_VARIANT (arg2);
14260
14261       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14262         {
14263           int i, len2 = list_length (args2);
14264           tree parmvec = make_tree_vec (1);
14265           tree argvec = make_tree_vec (len2);
14266           tree ta = args2;
14267
14268           /* Setup the parameter vector, which contains only ARG1.  */
14269           TREE_VEC_ELT (parmvec, 0) = arg1;
14270
14271           /* Setup the argument vector, which contains the remaining
14272              arguments.  */
14273           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14274             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14275
14276           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14277                                            argvec, UNIFY_ALLOW_NONE, 
14278                                            /*call_args_p=*/false, 
14279                                            /*subr=*/0);
14280
14281           /* We cannot deduce in the other direction, because ARG1 is
14282              a pack expansion but ARG2 is not.  */
14283           deduce2 = 0;
14284         }
14285       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14286         {
14287           int i, len1 = list_length (args1);
14288           tree parmvec = make_tree_vec (1);
14289           tree argvec = make_tree_vec (len1);
14290           tree ta = args1;
14291
14292           /* Setup the parameter vector, which contains only ARG1.  */
14293           TREE_VEC_ELT (parmvec, 0) = arg2;
14294
14295           /* Setup the argument vector, which contains the remaining
14296              arguments.  */
14297           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14298             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14299
14300           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14301                                            argvec, UNIFY_ALLOW_NONE, 
14302                                            /*call_args_p=*/false, 
14303                                            /*subr=*/0);
14304
14305           /* We cannot deduce in the other direction, because ARG2 is
14306              a pack expansion but ARG1 is not.*/
14307           deduce1 = 0;
14308         }
14309
14310       else
14311         {
14312           /* The normal case, where neither argument is a pack
14313              expansion.  */
14314           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14315           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14316         }
14317
14318       if (!deduce1)
14319         better2 = -1;
14320       if (!deduce2)
14321         better1 = -1;
14322       if (better1 < 0 && better2 < 0)
14323         /* We've failed to deduce something in either direction.
14324            These must be unordered.  */
14325         break;
14326
14327       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14328         {
14329           /* Deduces in both directions, see if quals can
14330              disambiguate.  Pretend the worse one failed to deduce. */
14331           if ((quals1 & quals2) == quals2)
14332             deduce1 = 0;
14333           if ((quals1 & quals2) == quals1)
14334             deduce2 = 0;
14335         }
14336       if (deduce1 && !deduce2 && !better2)
14337         better2 = 1;
14338       if (deduce2 && !deduce1 && !better1)
14339         better1 = 1;
14340
14341       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14342           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14343         /* We have already processed all of the arguments in our
14344            handing of the pack expansion type.  */
14345         len = 0;
14346
14347       args1 = TREE_CHAIN (args1);
14348       args2 = TREE_CHAIN (args2);
14349     }
14350
14351   processing_template_decl--;
14352
14353   /* All things being equal, if the next argument is a pack expansion
14354      for one function but not for the other, prefer the
14355      non-variadic function.  */
14356   if ((better1 > 0) - (better2 > 0) == 0
14357       && args1 && TREE_VALUE (args1)
14358       && args2 && TREE_VALUE (args2))
14359     {
14360       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14361         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14362       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14363         return 1;
14364     }
14365
14366   return (better1 > 0) - (better2 > 0);
14367 }
14368
14369 /* Determine which of two partial specializations is more specialized.
14370
14371    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14372    to the first partial specialization.  The TREE_VALUE is the
14373    innermost set of template parameters for the partial
14374    specialization.  PAT2 is similar, but for the second template.
14375
14376    Return 1 if the first partial specialization is more specialized;
14377    -1 if the second is more specialized; 0 if neither is more
14378    specialized.
14379
14380    See [temp.class.order] for information about determining which of
14381    two templates is more specialized.  */
14382
14383 static int
14384 more_specialized_class (tree pat1, tree pat2)
14385 {
14386   tree targs;
14387   tree tmpl1, tmpl2;
14388   int winner = 0;
14389   bool any_deductions = false;
14390
14391   tmpl1 = TREE_TYPE (pat1);
14392   tmpl2 = TREE_TYPE (pat2);
14393
14394   /* Just like what happens for functions, if we are ordering between
14395      different class template specializations, we may encounter dependent
14396      types in the arguments, and we need our dependency check functions
14397      to behave correctly.  */
14398   ++processing_template_decl;
14399   targs = get_class_bindings (TREE_VALUE (pat1),
14400                               CLASSTYPE_TI_ARGS (tmpl1),
14401                               CLASSTYPE_TI_ARGS (tmpl2));
14402   if (targs)
14403     {
14404       --winner;
14405       any_deductions = true;
14406     }
14407
14408   targs = get_class_bindings (TREE_VALUE (pat2),
14409                               CLASSTYPE_TI_ARGS (tmpl2),
14410                               CLASSTYPE_TI_ARGS (tmpl1));
14411   if (targs)
14412     {
14413       ++winner;
14414       any_deductions = true;
14415     }
14416   --processing_template_decl;
14417
14418   /* In the case of a tie where at least one of the class templates
14419      has a parameter pack at the end, the template with the most
14420      non-packed parameters wins.  */
14421   if (winner == 0
14422       && any_deductions
14423       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14424           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14425     {
14426       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14427       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14428       int len1 = TREE_VEC_LENGTH (args1);
14429       int len2 = TREE_VEC_LENGTH (args2);
14430
14431       /* We don't count the pack expansion at the end.  */
14432       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14433         --len1;
14434       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14435         --len2;
14436
14437       if (len1 > len2)
14438         return 1;
14439       else if (len1 < len2)
14440         return -1;
14441     }
14442
14443   return winner;
14444 }
14445
14446 /* Return the template arguments that will produce the function signature
14447    DECL from the function template FN, with the explicit template
14448    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14449    also match.  Return NULL_TREE if no satisfactory arguments could be
14450    found.  */
14451
14452 static tree
14453 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14454 {
14455   int ntparms = DECL_NTPARMS (fn);
14456   tree targs = make_tree_vec (ntparms);
14457   tree decl_type;
14458   tree decl_arg_types;
14459
14460   /* Substitute the explicit template arguments into the type of DECL.
14461      The call to fn_type_unification will handle substitution into the
14462      FN.  */
14463   decl_type = TREE_TYPE (decl);
14464   if (explicit_args && uses_template_parms (decl_type))
14465     {
14466       tree tmpl;
14467       tree converted_args;
14468
14469       if (DECL_TEMPLATE_INFO (decl))
14470         tmpl = DECL_TI_TEMPLATE (decl);
14471       else
14472         /* We can get here for some invalid specializations.  */
14473         return NULL_TREE;
14474
14475       converted_args
14476         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14477                                  explicit_args, NULL_TREE,
14478                                  tf_none,
14479                                  /*require_all_args=*/false,
14480                                  /*use_default_args=*/false);
14481       if (converted_args == error_mark_node)
14482         return NULL_TREE;
14483
14484       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14485       if (decl_type == error_mark_node)
14486         return NULL_TREE;
14487     }
14488
14489   /* Never do unification on the 'this' parameter.  */
14490   decl_arg_types = skip_artificial_parms_for (decl, 
14491                                               TYPE_ARG_TYPES (decl_type));
14492
14493   if (fn_type_unification (fn, explicit_args, targs,
14494                            decl_arg_types,
14495                            (check_rettype || DECL_CONV_FN_P (fn)
14496                             ? TREE_TYPE (decl_type) : NULL_TREE),
14497                            DEDUCE_EXACT, LOOKUP_NORMAL))
14498     return NULL_TREE;
14499
14500   return targs;
14501 }
14502
14503 /* Return the innermost template arguments that, when applied to a
14504    template specialization whose innermost template parameters are
14505    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
14506    ARGS.
14507
14508    For example, suppose we have:
14509
14510      template <class T, class U> struct S {};
14511      template <class T> struct S<T*, int> {};
14512
14513    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14514    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14515    int}.  The resulting vector will be {double}, indicating that `T'
14516    is bound to `double'.  */
14517
14518 static tree
14519 get_class_bindings (tree tparms, tree spec_args, tree args)
14520 {
14521   int i, ntparms = TREE_VEC_LENGTH (tparms);
14522   tree deduced_args;
14523   tree innermost_deduced_args;
14524
14525   innermost_deduced_args = make_tree_vec (ntparms);
14526   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14527     {
14528       deduced_args = copy_node (args);
14529       SET_TMPL_ARGS_LEVEL (deduced_args,
14530                            TMPL_ARGS_DEPTH (deduced_args),
14531                            innermost_deduced_args);
14532     }
14533   else
14534     deduced_args = innermost_deduced_args;
14535
14536   if (unify (tparms, deduced_args,
14537              INNERMOST_TEMPLATE_ARGS (spec_args),
14538              INNERMOST_TEMPLATE_ARGS (args),
14539              UNIFY_ALLOW_NONE))
14540     return NULL_TREE;
14541
14542   for (i =  0; i < ntparms; ++i)
14543     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14544       return NULL_TREE;
14545
14546   /* Verify that nondeduced template arguments agree with the type
14547      obtained from argument deduction.
14548
14549      For example:
14550
14551        struct A { typedef int X; };
14552        template <class T, class U> struct C {};
14553        template <class T> struct C<T, typename T::X> {};
14554
14555      Then with the instantiation `C<A, int>', we can deduce that
14556      `T' is `A' but unify () does not check whether `typename T::X'
14557      is `int'.  */
14558   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14559   if (spec_args == error_mark_node
14560       /* We only need to check the innermost arguments; the other
14561          arguments will always agree.  */
14562       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14563                               INNERMOST_TEMPLATE_ARGS (args)))
14564     return NULL_TREE;
14565
14566   /* Now that we have bindings for all of the template arguments,
14567      ensure that the arguments deduced for the template template
14568      parameters have compatible template parameter lists.  See the use
14569      of template_template_parm_bindings_ok_p in fn_type_unification
14570      for more information.  */
14571   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14572     return NULL_TREE;
14573
14574   return deduced_args;
14575 }
14576
14577 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14578    Return the TREE_LIST node with the most specialized template, if
14579    any.  If there is no most specialized template, the error_mark_node
14580    is returned.
14581
14582    Note that this function does not look at, or modify, the
14583    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14584    returned is one of the elements of INSTANTIATIONS, callers may
14585    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14586    and retrieve it from the value returned.  */
14587
14588 tree
14589 most_specialized_instantiation (tree templates)
14590 {
14591   tree fn, champ;
14592
14593   ++processing_template_decl;
14594
14595   champ = templates;
14596   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14597     {
14598       int fate = 0;
14599
14600       if (get_bindings (TREE_VALUE (champ),
14601                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14602                         NULL_TREE, /*check_ret=*/false))
14603         fate--;
14604
14605       if (get_bindings (TREE_VALUE (fn),
14606                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14607                         NULL_TREE, /*check_ret=*/false))
14608         fate++;
14609
14610       if (fate == -1)
14611         champ = fn;
14612       else if (!fate)
14613         {
14614           /* Equally specialized, move to next function.  If there
14615              is no next function, nothing's most specialized.  */
14616           fn = TREE_CHAIN (fn);
14617           champ = fn;
14618           if (!fn)
14619             break;
14620         }
14621     }
14622
14623   if (champ)
14624     /* Now verify that champ is better than everything earlier in the
14625        instantiation list.  */
14626     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14627       if (get_bindings (TREE_VALUE (champ),
14628                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14629                         NULL_TREE, /*check_ret=*/false)
14630           || !get_bindings (TREE_VALUE (fn),
14631                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14632                             NULL_TREE, /*check_ret=*/false))
14633         {
14634           champ = NULL_TREE;
14635           break;
14636         }
14637
14638   processing_template_decl--;
14639
14640   if (!champ)
14641     return error_mark_node;
14642
14643   return champ;
14644 }
14645
14646 /* If DECL is a specialization of some template, return the most
14647    general such template.  Otherwise, returns NULL_TREE.
14648
14649    For example, given:
14650
14651      template <class T> struct S { template <class U> void f(U); };
14652
14653    if TMPL is `template <class U> void S<int>::f(U)' this will return
14654    the full template.  This function will not trace past partial
14655    specializations, however.  For example, given in addition:
14656
14657      template <class T> struct S<T*> { template <class U> void f(U); };
14658
14659    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14660    `template <class T> template <class U> S<T*>::f(U)'.  */
14661
14662 tree
14663 most_general_template (tree decl)
14664 {
14665   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14666      an immediate specialization.  */
14667   if (TREE_CODE (decl) == FUNCTION_DECL)
14668     {
14669       if (DECL_TEMPLATE_INFO (decl)) {
14670         decl = DECL_TI_TEMPLATE (decl);
14671
14672         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14673            template friend.  */
14674         if (TREE_CODE (decl) != TEMPLATE_DECL)
14675           return NULL_TREE;
14676       } else
14677         return NULL_TREE;
14678     }
14679
14680   /* Look for more and more general templates.  */
14681   while (DECL_TEMPLATE_INFO (decl))
14682     {
14683       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14684          (See cp-tree.h for details.)  */
14685       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14686         break;
14687
14688       if (CLASS_TYPE_P (TREE_TYPE (decl))
14689           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14690         break;
14691
14692       /* Stop if we run into an explicitly specialized class template.  */
14693       if (!DECL_NAMESPACE_SCOPE_P (decl)
14694           && DECL_CONTEXT (decl)
14695           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14696         break;
14697
14698       decl = DECL_TI_TEMPLATE (decl);
14699     }
14700
14701   return decl;
14702 }
14703
14704 /* Return the most specialized of the class template partial
14705    specializations of TMPL which can produce TYPE, a specialization of
14706    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14707    a _TYPE node corresponding to the partial specialization, while the
14708    TREE_PURPOSE is the set of template arguments that must be
14709    substituted into the TREE_TYPE in order to generate TYPE.
14710
14711    If the choice of partial specialization is ambiguous, a diagnostic
14712    is issued, and the error_mark_node is returned.  If there are no
14713    partial specializations of TMPL matching TYPE, then NULL_TREE is
14714    returned.  */
14715
14716 static tree
14717 most_specialized_class (tree type, tree tmpl)
14718 {
14719   tree list = NULL_TREE;
14720   tree t;
14721   tree champ;
14722   int fate;
14723   bool ambiguous_p;
14724   tree args;
14725   tree outer_args = NULL_TREE;
14726
14727   tmpl = most_general_template (tmpl);
14728   args = CLASSTYPE_TI_ARGS (type);
14729
14730   /* For determining which partial specialization to use, only the
14731      innermost args are interesting.  */
14732   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14733     {
14734       outer_args = strip_innermost_template_args (args, 1);
14735       args = INNERMOST_TEMPLATE_ARGS (args);
14736     }
14737
14738   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14739     {
14740       tree partial_spec_args;
14741       tree spec_args;
14742       tree parms = TREE_VALUE (t);
14743
14744       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14745       if (outer_args)
14746         {
14747           int i;
14748
14749           ++processing_template_decl;
14750
14751           /* Discard the outer levels of args, and then substitute in the
14752              template args from the enclosing class.  */
14753           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14754           partial_spec_args = tsubst_template_args
14755             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14756
14757           /* PARMS already refers to just the innermost parms, but the
14758              template parms in partial_spec_args had their levels lowered
14759              by tsubst, so we need to do the same for the parm list.  We
14760              can't just tsubst the TREE_VEC itself, as tsubst wants to
14761              treat a TREE_VEC as an argument vector.  */
14762           parms = copy_node (parms);
14763           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14764             TREE_VEC_ELT (parms, i) =
14765               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14766
14767           --processing_template_decl;
14768         }
14769       spec_args = get_class_bindings (parms,
14770                                       partial_spec_args,
14771                                       args);
14772       if (spec_args)
14773         {
14774           if (outer_args)
14775             spec_args = add_to_template_args (outer_args, spec_args);
14776           list = tree_cons (spec_args, TREE_VALUE (t), list);
14777           TREE_TYPE (list) = TREE_TYPE (t);
14778         }
14779     }
14780
14781   if (! list)
14782     return NULL_TREE;
14783
14784   ambiguous_p = false;
14785   t = list;
14786   champ = t;
14787   t = TREE_CHAIN (t);
14788   for (; t; t = TREE_CHAIN (t))
14789     {
14790       fate = more_specialized_class (champ, t);
14791       if (fate == 1)
14792         ;
14793       else
14794         {
14795           if (fate == 0)
14796             {
14797               t = TREE_CHAIN (t);
14798               if (! t)
14799                 {
14800                   ambiguous_p = true;
14801                   break;
14802                 }
14803             }
14804           champ = t;
14805         }
14806     }
14807
14808   if (!ambiguous_p)
14809     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14810       {
14811         fate = more_specialized_class (champ, t);
14812         if (fate != 1)
14813           {
14814             ambiguous_p = true;
14815             break;
14816           }
14817       }
14818
14819   if (ambiguous_p)
14820     {
14821       const char *str = "candidates are:";
14822       error ("ambiguous class template instantiation for %q#T", type);
14823       for (t = list; t; t = TREE_CHAIN (t))
14824         {
14825           error ("%s %+#T", str, TREE_TYPE (t));
14826           str = "               ";
14827         }
14828       return error_mark_node;
14829     }
14830
14831   return champ;
14832 }
14833
14834 /* Explicitly instantiate DECL.  */
14835
14836 void
14837 do_decl_instantiation (tree decl, tree storage)
14838 {
14839   tree result = NULL_TREE;
14840   int extern_p = 0;
14841
14842   if (!decl || decl == error_mark_node)
14843     /* An error occurred, for which grokdeclarator has already issued
14844        an appropriate message.  */
14845     return;
14846   else if (! DECL_LANG_SPECIFIC (decl))
14847     {
14848       error ("explicit instantiation of non-template %q#D", decl);
14849       return;
14850     }
14851   else if (TREE_CODE (decl) == VAR_DECL)
14852     {
14853       /* There is an asymmetry here in the way VAR_DECLs and
14854          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14855          the latter, the DECL we get back will be marked as a
14856          template instantiation, and the appropriate
14857          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14858          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14859          should handle VAR_DECLs as it currently handles
14860          FUNCTION_DECLs.  */
14861       if (!DECL_CLASS_SCOPE_P (decl))
14862         {
14863           error ("%qD is not a static data member of a class template", decl);
14864           return;
14865         }
14866       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14867       if (!result || TREE_CODE (result) != VAR_DECL)
14868         {
14869           error ("no matching template for %qD found", decl);
14870           return;
14871         }
14872       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14873         {
14874           error ("type %qT for explicit instantiation %qD does not match "
14875                  "declared type %qT", TREE_TYPE (result), decl,
14876                  TREE_TYPE (decl));
14877           return;
14878         }
14879     }
14880   else if (TREE_CODE (decl) != FUNCTION_DECL)
14881     {
14882       error ("explicit instantiation of %q#D", decl);
14883       return;
14884     }
14885   else
14886     result = decl;
14887
14888   /* Check for various error cases.  Note that if the explicit
14889      instantiation is valid the RESULT will currently be marked as an
14890      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14891      until we get here.  */
14892
14893   if (DECL_TEMPLATE_SPECIALIZATION (result))
14894     {
14895       /* DR 259 [temp.spec].
14896
14897          Both an explicit instantiation and a declaration of an explicit
14898          specialization shall not appear in a program unless the explicit
14899          instantiation follows a declaration of the explicit specialization.
14900
14901          For a given set of template parameters, if an explicit
14902          instantiation of a template appears after a declaration of an
14903          explicit specialization for that template, the explicit
14904          instantiation has no effect.  */
14905       return;
14906     }
14907   else if (DECL_EXPLICIT_INSTANTIATION (result))
14908     {
14909       /* [temp.spec]
14910
14911          No program shall explicitly instantiate any template more
14912          than once.
14913
14914          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14915          the first instantiation was `extern' and the second is not,
14916          and EXTERN_P for the opposite case.  */
14917       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14918         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
14919       /* If an "extern" explicit instantiation follows an ordinary
14920          explicit instantiation, the template is instantiated.  */
14921       if (extern_p)
14922         return;
14923     }
14924   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14925     {
14926       error ("no matching template for %qD found", result);
14927       return;
14928     }
14929   else if (!DECL_TEMPLATE_INFO (result))
14930     {
14931       permerror (input_location, "explicit instantiation of non-template %q#D", result);
14932       return;
14933     }
14934
14935   if (storage == NULL_TREE)
14936     ;
14937   else if (storage == ridpointers[(int) RID_EXTERN])
14938     {
14939       if (!in_system_header && (cxx_dialect == cxx98))
14940         pedwarn (input_location, OPT_pedantic, 
14941                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
14942                  "instantiations");
14943       extern_p = 1;
14944     }
14945   else
14946     error ("storage class %qD applied to template instantiation", storage);
14947
14948   check_explicit_instantiation_namespace (result);
14949   mark_decl_instantiated (result, extern_p);
14950   if (! extern_p)
14951     instantiate_decl (result, /*defer_ok=*/1,
14952                       /*expl_inst_class_mem_p=*/false);
14953 }
14954
14955 static void
14956 mark_class_instantiated (tree t, int extern_p)
14957 {
14958   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14959   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14960   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14961   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14962   if (! extern_p)
14963     {
14964       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14965       rest_of_type_compilation (t, 1);
14966     }
14967 }
14968
14969 /* Called from do_type_instantiation through binding_table_foreach to
14970    do recursive instantiation for the type bound in ENTRY.  */
14971 static void
14972 bt_instantiate_type_proc (binding_entry entry, void *data)
14973 {
14974   tree storage = *(tree *) data;
14975
14976   if (MAYBE_CLASS_TYPE_P (entry->type)
14977       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14978     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14979 }
14980
14981 /* Called from do_type_instantiation to instantiate a member
14982    (a member function or a static member variable) of an
14983    explicitly instantiated class template.  */
14984 static void
14985 instantiate_class_member (tree decl, int extern_p)
14986 {
14987   mark_decl_instantiated (decl, extern_p);
14988   if (! extern_p)
14989     instantiate_decl (decl, /*defer_ok=*/1,
14990                       /*expl_inst_class_mem_p=*/true);
14991 }
14992
14993 /* Perform an explicit instantiation of template class T.  STORAGE, if
14994    non-null, is the RID for extern, inline or static.  COMPLAIN is
14995    nonzero if this is called from the parser, zero if called recursively,
14996    since the standard is unclear (as detailed below).  */
14997
14998 void
14999 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15000 {
15001   int extern_p = 0;
15002   int nomem_p = 0;
15003   int static_p = 0;
15004   int previous_instantiation_extern_p = 0;
15005
15006   if (TREE_CODE (t) == TYPE_DECL)
15007     t = TREE_TYPE (t);
15008
15009   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15010     {
15011       error ("explicit instantiation of non-template type %qT", t);
15012       return;
15013     }
15014
15015   complete_type (t);
15016
15017   if (!COMPLETE_TYPE_P (t))
15018     {
15019       if (complain & tf_error)
15020         error ("explicit instantiation of %q#T before definition of template",
15021                t);
15022       return;
15023     }
15024
15025   if (storage != NULL_TREE)
15026     {
15027       if (!in_system_header)
15028         {
15029           if (storage == ridpointers[(int) RID_EXTERN])
15030             {
15031               if (cxx_dialect == cxx98)
15032                 pedwarn (input_location, OPT_pedantic, 
15033                          "ISO C++ 1998 forbids the use of %<extern%> on "
15034                          "explicit instantiations");
15035             }
15036           else
15037             pedwarn (input_location, OPT_pedantic, 
15038                      "ISO C++ forbids the use of %qE"
15039                      " on explicit instantiations", storage);
15040         }
15041
15042       if (storage == ridpointers[(int) RID_INLINE])
15043         nomem_p = 1;
15044       else if (storage == ridpointers[(int) RID_EXTERN])
15045         extern_p = 1;
15046       else if (storage == ridpointers[(int) RID_STATIC])
15047         static_p = 1;
15048       else
15049         {
15050           error ("storage class %qD applied to template instantiation",
15051                  storage);
15052           extern_p = 0;
15053         }
15054     }
15055
15056   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15057     {
15058       /* DR 259 [temp.spec].
15059
15060          Both an explicit instantiation and a declaration of an explicit
15061          specialization shall not appear in a program unless the explicit
15062          instantiation follows a declaration of the explicit specialization.
15063
15064          For a given set of template parameters, if an explicit
15065          instantiation of a template appears after a declaration of an
15066          explicit specialization for that template, the explicit
15067          instantiation has no effect.  */
15068       return;
15069     }
15070   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15071     {
15072       /* [temp.spec]
15073
15074          No program shall explicitly instantiate any template more
15075          than once.
15076
15077          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15078          instantiation was `extern'.  If EXTERN_P then the second is.
15079          These cases are OK.  */
15080       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15081
15082       if (!previous_instantiation_extern_p && !extern_p
15083           && (complain & tf_error))
15084         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15085
15086       /* If we've already instantiated the template, just return now.  */
15087       if (!CLASSTYPE_INTERFACE_ONLY (t))
15088         return;
15089     }
15090
15091   check_explicit_instantiation_namespace (TYPE_NAME (t));
15092   mark_class_instantiated (t, extern_p);
15093
15094   if (nomem_p)
15095     return;
15096
15097   {
15098     tree tmp;
15099
15100     /* In contrast to implicit instantiation, where only the
15101        declarations, and not the definitions, of members are
15102        instantiated, we have here:
15103
15104          [temp.explicit]
15105
15106          The explicit instantiation of a class template specialization
15107          implies the instantiation of all of its members not
15108          previously explicitly specialized in the translation unit
15109          containing the explicit instantiation.
15110
15111        Of course, we can't instantiate member template classes, since
15112        we don't have any arguments for them.  Note that the standard
15113        is unclear on whether the instantiation of the members are
15114        *explicit* instantiations or not.  However, the most natural
15115        interpretation is that it should be an explicit instantiation.  */
15116
15117     if (! static_p)
15118       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15119         if (TREE_CODE (tmp) == FUNCTION_DECL
15120             && DECL_TEMPLATE_INSTANTIATION (tmp))
15121           instantiate_class_member (tmp, extern_p);
15122
15123     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15124       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15125         instantiate_class_member (tmp, extern_p);
15126
15127     if (CLASSTYPE_NESTED_UTDS (t))
15128       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15129                              bt_instantiate_type_proc, &storage);
15130   }
15131 }
15132
15133 /* Given a function DECL, which is a specialization of TMPL, modify
15134    DECL to be a re-instantiation of TMPL with the same template
15135    arguments.  TMPL should be the template into which tsubst'ing
15136    should occur for DECL, not the most general template.
15137
15138    One reason for doing this is a scenario like this:
15139
15140      template <class T>
15141      void f(const T&, int i);
15142
15143      void g() { f(3, 7); }
15144
15145      template <class T>
15146      void f(const T& t, const int i) { }
15147
15148    Note that when the template is first instantiated, with
15149    instantiate_template, the resulting DECL will have no name for the
15150    first parameter, and the wrong type for the second.  So, when we go
15151    to instantiate the DECL, we regenerate it.  */
15152
15153 static void
15154 regenerate_decl_from_template (tree decl, tree tmpl)
15155 {
15156   /* The arguments used to instantiate DECL, from the most general
15157      template.  */
15158   tree args;
15159   tree code_pattern;
15160
15161   args = DECL_TI_ARGS (decl);
15162   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15163
15164   /* Make sure that we can see identifiers, and compute access
15165      correctly.  */
15166   push_access_scope (decl);
15167
15168   if (TREE_CODE (decl) == FUNCTION_DECL)
15169     {
15170       tree decl_parm;
15171       tree pattern_parm;
15172       tree specs;
15173       int args_depth;
15174       int parms_depth;
15175
15176       args_depth = TMPL_ARGS_DEPTH (args);
15177       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15178       if (args_depth > parms_depth)
15179         args = get_innermost_template_args (args, parms_depth);
15180
15181       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15182                                               args, tf_error, NULL_TREE);
15183       if (specs)
15184         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15185                                                     specs);
15186
15187       /* Merge parameter declarations.  */
15188       decl_parm = skip_artificial_parms_for (decl,
15189                                              DECL_ARGUMENTS (decl));
15190       pattern_parm
15191         = skip_artificial_parms_for (code_pattern,
15192                                      DECL_ARGUMENTS (code_pattern));
15193       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15194         {
15195           tree parm_type;
15196           tree attributes;
15197           
15198           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15199             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15200           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15201                               NULL_TREE);
15202           parm_type = type_decays_to (parm_type);
15203           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15204             TREE_TYPE (decl_parm) = parm_type;
15205           attributes = DECL_ATTRIBUTES (pattern_parm);
15206           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15207             {
15208               DECL_ATTRIBUTES (decl_parm) = attributes;
15209               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15210             }
15211           decl_parm = TREE_CHAIN (decl_parm);
15212           pattern_parm = TREE_CHAIN (pattern_parm);
15213         }
15214       /* Merge any parameters that match with the function parameter
15215          pack.  */
15216       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15217         {
15218           int i, len;
15219           tree expanded_types;
15220           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15221              the parameters in this function parameter pack.  */
15222           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15223                                                  args, tf_error, NULL_TREE);
15224           len = TREE_VEC_LENGTH (expanded_types);
15225           for (i = 0; i < len; i++)
15226             {
15227               tree parm_type;
15228               tree attributes;
15229           
15230               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15231                 /* Rename the parameter to include the index.  */
15232                 DECL_NAME (decl_parm) = 
15233                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15234               parm_type = TREE_VEC_ELT (expanded_types, i);
15235               parm_type = type_decays_to (parm_type);
15236               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15237                 TREE_TYPE (decl_parm) = parm_type;
15238               attributes = DECL_ATTRIBUTES (pattern_parm);
15239               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15240                 {
15241                   DECL_ATTRIBUTES (decl_parm) = attributes;
15242                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15243                 }
15244               decl_parm = TREE_CHAIN (decl_parm);
15245             }
15246         }
15247       /* Merge additional specifiers from the CODE_PATTERN.  */
15248       if (DECL_DECLARED_INLINE_P (code_pattern)
15249           && !DECL_DECLARED_INLINE_P (decl))
15250         DECL_DECLARED_INLINE_P (decl) = 1;
15251     }
15252   else if (TREE_CODE (decl) == VAR_DECL)
15253     DECL_INITIAL (decl) =
15254       tsubst_expr (DECL_INITIAL (code_pattern), args,
15255                    tf_error, DECL_TI_TEMPLATE (decl),
15256                    /*integral_constant_expression_p=*/false);
15257   else
15258     gcc_unreachable ();
15259
15260   pop_access_scope (decl);
15261 }
15262
15263 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15264    substituted to get DECL.  */
15265
15266 tree
15267 template_for_substitution (tree decl)
15268 {
15269   tree tmpl = DECL_TI_TEMPLATE (decl);
15270
15271   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15272      for the instantiation.  This is not always the most general
15273      template.  Consider, for example:
15274
15275         template <class T>
15276         struct S { template <class U> void f();
15277                    template <> void f<int>(); };
15278
15279      and an instantiation of S<double>::f<int>.  We want TD to be the
15280      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15281   while (/* An instantiation cannot have a definition, so we need a
15282             more general template.  */
15283          DECL_TEMPLATE_INSTANTIATION (tmpl)
15284            /* We must also deal with friend templates.  Given:
15285
15286                 template <class T> struct S {
15287                   template <class U> friend void f() {};
15288                 };
15289
15290               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15291               so far as the language is concerned, but that's still
15292               where we get the pattern for the instantiation from.  On
15293               other hand, if the definition comes outside the class, say:
15294
15295                 template <class T> struct S {
15296                   template <class U> friend void f();
15297                 };
15298                 template <class U> friend void f() {}
15299
15300               we don't need to look any further.  That's what the check for
15301               DECL_INITIAL is for.  */
15302           || (TREE_CODE (decl) == FUNCTION_DECL
15303               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15304               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15305     {
15306       /* The present template, TD, should not be a definition.  If it
15307          were a definition, we should be using it!  Note that we
15308          cannot restructure the loop to just keep going until we find
15309          a template with a definition, since that might go too far if
15310          a specialization was declared, but not defined.  */
15311       gcc_assert (TREE_CODE (decl) != VAR_DECL
15312                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15313
15314       /* Fetch the more general template.  */
15315       tmpl = DECL_TI_TEMPLATE (tmpl);
15316     }
15317
15318   return tmpl;
15319 }
15320
15321 /* Produce the definition of D, a _DECL generated from a template.  If
15322    DEFER_OK is nonzero, then we don't have to actually do the
15323    instantiation now; we just have to do it sometime.  Normally it is
15324    an error if this is an explicit instantiation but D is undefined.
15325    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15326    explicitly instantiated class template.  */
15327
15328 tree
15329 instantiate_decl (tree d, int defer_ok,
15330                   bool expl_inst_class_mem_p)
15331 {
15332   tree tmpl = DECL_TI_TEMPLATE (d);
15333   tree gen_args;
15334   tree args;
15335   tree td;
15336   tree code_pattern;
15337   tree spec;
15338   tree gen_tmpl;
15339   bool pattern_defined;
15340   int need_push;
15341   location_t saved_loc = input_location;
15342   bool external_p;
15343
15344   /* This function should only be used to instantiate templates for
15345      functions and static member variables.  */
15346   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15347               || TREE_CODE (d) == VAR_DECL);
15348
15349   /* Variables are never deferred; if instantiation is required, they
15350      are instantiated right away.  That allows for better code in the
15351      case that an expression refers to the value of the variable --
15352      if the variable has a constant value the referring expression can
15353      take advantage of that fact.  */
15354   if (TREE_CODE (d) == VAR_DECL)
15355     defer_ok = 0;
15356
15357   /* Don't instantiate cloned functions.  Instead, instantiate the
15358      functions they cloned.  */
15359   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15360     d = DECL_CLONED_FUNCTION (d);
15361
15362   if (DECL_TEMPLATE_INSTANTIATED (d))
15363     /* D has already been instantiated.  It might seem reasonable to
15364        check whether or not D is an explicit instantiation, and, if so,
15365        stop here.  But when an explicit instantiation is deferred
15366        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15367        is set, even though we still need to do the instantiation.  */
15368     return d;
15369
15370   /* If we already have a specialization of this declaration, then
15371      there's no reason to instantiate it.  Note that
15372      retrieve_specialization gives us both instantiations and
15373      specializations, so we must explicitly check
15374      DECL_TEMPLATE_SPECIALIZATION.  */
15375   gen_tmpl = most_general_template (tmpl);
15376   gen_args = DECL_TI_ARGS (d);
15377   spec = retrieve_specialization (gen_tmpl, gen_args,
15378                                   /*class_specializations_p=*/false);
15379   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15380     return spec;
15381
15382   /* This needs to happen before any tsubsting.  */
15383   if (! push_tinst_level (d))
15384     return d;
15385
15386   timevar_push (TV_PARSE);
15387
15388   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15389      for the instantiation.  */
15390   td = template_for_substitution (d);
15391   code_pattern = DECL_TEMPLATE_RESULT (td);
15392
15393   /* We should never be trying to instantiate a member of a class
15394      template or partial specialization.  */
15395   gcc_assert (d != code_pattern);
15396
15397   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15398       || DECL_TEMPLATE_SPECIALIZATION (td))
15399     /* In the case of a friend template whose definition is provided
15400        outside the class, we may have too many arguments.  Drop the
15401        ones we don't need.  The same is true for specializations.  */
15402     args = get_innermost_template_args
15403       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15404   else
15405     args = gen_args;
15406
15407   if (TREE_CODE (d) == FUNCTION_DECL)
15408     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15409   else
15410     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15411
15412   /* We may be in the middle of deferred access check.  Disable it now.  */
15413   push_deferring_access_checks (dk_no_deferred);
15414
15415   /* Unless an explicit instantiation directive has already determined
15416      the linkage of D, remember that a definition is available for
15417      this entity.  */
15418   if (pattern_defined
15419       && !DECL_INTERFACE_KNOWN (d)
15420       && !DECL_NOT_REALLY_EXTERN (d))
15421     mark_definable (d);
15422
15423   input_location = DECL_SOURCE_LOCATION (d);
15424
15425   /* If D is a member of an explicitly instantiated class template,
15426      and no definition is available, treat it like an implicit
15427      instantiation.  */
15428   if (!pattern_defined && expl_inst_class_mem_p
15429       && DECL_EXPLICIT_INSTANTIATION (d))
15430     {
15431       DECL_NOT_REALLY_EXTERN (d) = 0;
15432       DECL_INTERFACE_KNOWN (d) = 0;
15433       SET_DECL_IMPLICIT_INSTANTIATION (d);
15434     }
15435
15436   if (!defer_ok)
15437     {
15438       /* Recheck the substitutions to obtain any warning messages
15439          about ignoring cv qualifiers.  */
15440       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15441       tree type = TREE_TYPE (gen);
15442
15443       /* Make sure that we can see identifiers, and compute access
15444          correctly.  D is already the target FUNCTION_DECL with the
15445          right context.  */
15446       push_access_scope (d);
15447
15448       if (TREE_CODE (gen) == FUNCTION_DECL)
15449         {
15450           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15451           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15452                                           d);
15453           /* Don't simply tsubst the function type, as that will give
15454              duplicate warnings about poor parameter qualifications.
15455              The function arguments are the same as the decl_arguments
15456              without the top level cv qualifiers.  */
15457           type = TREE_TYPE (type);
15458         }
15459       tsubst (type, gen_args, tf_warning_or_error, d);
15460
15461       pop_access_scope (d);
15462     }
15463
15464   /* Check to see whether we know that this template will be
15465      instantiated in some other file, as with "extern template"
15466      extension.  */
15467   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15468   /* In general, we do not instantiate such templates...  */
15469   if (external_p
15470       /* ... but we instantiate inline functions so that we can inline
15471          them.  An explicit instantiation declaration prohibits implicit
15472          instantiation of non-inline functions.  With high levels of
15473          optimization, we would normally inline non-inline functions
15474          -- but we're not allowed to do that for "extern template" functions.
15475          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15476          possibly_inlined_p.  And ...  */
15477       && ! (TREE_CODE (d) == FUNCTION_DECL
15478             && DECL_DECLARED_INLINE_P (d))
15479       /* ... we instantiate static data members whose values are
15480          needed in integral constant expressions.  */
15481       && ! (TREE_CODE (d) == VAR_DECL
15482             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15483     goto out;
15484   /* Defer all other templates, unless we have been explicitly
15485      forbidden from doing so.  */
15486   if (/* If there is no definition, we cannot instantiate the
15487          template.  */
15488       ! pattern_defined
15489       /* If it's OK to postpone instantiation, do so.  */
15490       || defer_ok
15491       /* If this is a static data member that will be defined
15492          elsewhere, we don't want to instantiate the entire data
15493          member, but we do want to instantiate the initializer so that
15494          we can substitute that elsewhere.  */
15495       || (external_p && TREE_CODE (d) == VAR_DECL))
15496     {
15497       /* The definition of the static data member is now required so
15498          we must substitute the initializer.  */
15499       if (TREE_CODE (d) == VAR_DECL
15500           && !DECL_INITIAL (d)
15501           && DECL_INITIAL (code_pattern))
15502         {
15503           tree ns;
15504           tree init;
15505
15506           ns = decl_namespace_context (d);
15507           push_nested_namespace (ns);
15508           push_nested_class (DECL_CONTEXT (d));
15509           init = tsubst_expr (DECL_INITIAL (code_pattern),
15510                               args,
15511                               tf_warning_or_error, NULL_TREE,
15512                               /*integral_constant_expression_p=*/false);
15513           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15514                           /*asmspec_tree=*/NULL_TREE,
15515                           LOOKUP_ONLYCONVERTING);
15516           pop_nested_class ();
15517           pop_nested_namespace (ns);
15518         }
15519
15520       /* We restore the source position here because it's used by
15521          add_pending_template.  */
15522       input_location = saved_loc;
15523
15524       if (at_eof && !pattern_defined
15525           && DECL_EXPLICIT_INSTANTIATION (d)
15526           && DECL_NOT_REALLY_EXTERN (d))
15527         /* [temp.explicit]
15528
15529            The definition of a non-exported function template, a
15530            non-exported member function template, or a non-exported
15531            member function or static data member of a class template
15532            shall be present in every translation unit in which it is
15533            explicitly instantiated.  */
15534         permerror (input_location,  "explicit instantiation of %qD "
15535                    "but no definition available", d);
15536
15537       /* ??? Historically, we have instantiated inline functions, even
15538          when marked as "extern template".  */
15539       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15540         add_pending_template (d);
15541       goto out;
15542     }
15543   /* Tell the repository that D is available in this translation unit
15544      -- and see if it is supposed to be instantiated here.  */
15545   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15546     {
15547       /* In a PCH file, despite the fact that the repository hasn't
15548          requested instantiation in the PCH it is still possible that
15549          an instantiation will be required in a file that includes the
15550          PCH.  */
15551       if (pch_file)
15552         add_pending_template (d);
15553       /* Instantiate inline functions so that the inliner can do its
15554          job, even though we'll not be emitting a copy of this
15555          function.  */
15556       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15557         goto out;
15558     }
15559
15560   need_push = !cfun || !global_bindings_p ();
15561   if (need_push)
15562     push_to_top_level ();
15563
15564   /* Mark D as instantiated so that recursive calls to
15565      instantiate_decl do not try to instantiate it again.  */
15566   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15567
15568   /* Regenerate the declaration in case the template has been modified
15569      by a subsequent redeclaration.  */
15570   regenerate_decl_from_template (d, td);
15571
15572   /* We already set the file and line above.  Reset them now in case
15573      they changed as a result of calling regenerate_decl_from_template.  */
15574   input_location = DECL_SOURCE_LOCATION (d);
15575
15576   if (TREE_CODE (d) == VAR_DECL)
15577     {
15578       tree init;
15579
15580       /* Clear out DECL_RTL; whatever was there before may not be right
15581          since we've reset the type of the declaration.  */
15582       SET_DECL_RTL (d, NULL_RTX);
15583       DECL_IN_AGGR_P (d) = 0;
15584
15585       /* The initializer is placed in DECL_INITIAL by
15586          regenerate_decl_from_template.  Pull it out so that
15587          finish_decl can process it.  */
15588       init = DECL_INITIAL (d);
15589       DECL_INITIAL (d) = NULL_TREE;
15590       DECL_INITIALIZED_P (d) = 0;
15591
15592       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15593          initializer.  That function will defer actual emission until
15594          we have a chance to determine linkage.  */
15595       DECL_EXTERNAL (d) = 0;
15596
15597       /* Enter the scope of D so that access-checking works correctly.  */
15598       push_nested_class (DECL_CONTEXT (d));
15599       finish_decl (d, init, NULL_TREE, NULL_TREE);
15600       pop_nested_class ();
15601     }
15602   else if (TREE_CODE (d) == FUNCTION_DECL)
15603     {
15604       htab_t saved_local_specializations;
15605       tree subst_decl;
15606       tree tmpl_parm;
15607       tree spec_parm;
15608
15609       /* Save away the current list, in case we are instantiating one
15610          template from within the body of another.  */
15611       saved_local_specializations = local_specializations;
15612
15613       /* Set up the list of local specializations.  */
15614       local_specializations = htab_create (37,
15615                                            hash_local_specialization,
15616                                            eq_local_specializations,
15617                                            NULL);
15618
15619       /* Set up context.  */
15620       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15621
15622       /* Create substitution entries for the parameters.  */
15623       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15624       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15625       spec_parm = DECL_ARGUMENTS (d);
15626       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15627         {
15628           register_local_specialization (spec_parm, tmpl_parm);
15629           spec_parm = skip_artificial_parms_for (d, spec_parm);
15630           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15631         }
15632       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15633         {
15634           register_local_specialization (spec_parm, tmpl_parm);
15635           tmpl_parm = TREE_CHAIN (tmpl_parm);
15636           spec_parm = TREE_CHAIN (spec_parm);
15637         }
15638       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15639         {
15640           /* Register the (value) argument pack as a specialization of
15641              TMPL_PARM, then move on.  */
15642           tree argpack = make_fnparm_pack (spec_parm);
15643           register_local_specialization (argpack, tmpl_parm);
15644           tmpl_parm = TREE_CHAIN (tmpl_parm);
15645           spec_parm = NULL_TREE;
15646         }
15647       gcc_assert (!spec_parm);
15648
15649       /* Substitute into the body of the function.  */
15650       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15651                    tf_warning_or_error, tmpl,
15652                    /*integral_constant_expression_p=*/false);
15653
15654       /* Set the current input_location to the end of the function
15655          so that finish_function knows where we are.  */
15656       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15657
15658       /* We don't need the local specializations any more.  */
15659       htab_delete (local_specializations);
15660       local_specializations = saved_local_specializations;
15661
15662       /* Finish the function.  */
15663       d = finish_function (0);
15664       expand_or_defer_fn (d);
15665     }
15666
15667   /* We're not deferring instantiation any more.  */
15668   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15669
15670   if (need_push)
15671     pop_from_top_level ();
15672
15673 out:
15674   input_location = saved_loc;
15675   pop_deferring_access_checks ();
15676   pop_tinst_level ();
15677
15678   timevar_pop (TV_PARSE);
15679
15680   return d;
15681 }
15682
15683 /* Run through the list of templates that we wish we could
15684    instantiate, and instantiate any we can.  RETRIES is the
15685    number of times we retry pending template instantiation.  */
15686
15687 void
15688 instantiate_pending_templates (int retries)
15689 {
15690   int reconsider;
15691   location_t saved_loc = input_location;
15692
15693   /* Instantiating templates may trigger vtable generation.  This in turn
15694      may require further template instantiations.  We place a limit here
15695      to avoid infinite loop.  */
15696   if (pending_templates && retries >= max_tinst_depth)
15697     {
15698       tree decl = pending_templates->tinst->decl;
15699
15700       error ("template instantiation depth exceeds maximum of %d"
15701              " instantiating %q+D, possibly from virtual table generation"
15702              " (use -ftemplate-depth-NN to increase the maximum)",
15703              max_tinst_depth, decl);
15704       if (TREE_CODE (decl) == FUNCTION_DECL)
15705         /* Pretend that we defined it.  */
15706         DECL_INITIAL (decl) = error_mark_node;
15707       return;
15708     }
15709
15710   do
15711     {
15712       struct pending_template **t = &pending_templates;
15713       struct pending_template *last = NULL;
15714       reconsider = 0;
15715       while (*t)
15716         {
15717           tree instantiation = reopen_tinst_level ((*t)->tinst);
15718           bool complete = false;
15719
15720           if (TYPE_P (instantiation))
15721             {
15722               tree fn;
15723
15724               if (!COMPLETE_TYPE_P (instantiation))
15725                 {
15726                   instantiate_class_template (instantiation);
15727                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15728                     for (fn = TYPE_METHODS (instantiation);
15729                          fn;
15730                          fn = TREE_CHAIN (fn))
15731                       if (! DECL_ARTIFICIAL (fn))
15732                         instantiate_decl (fn,
15733                                           /*defer_ok=*/0,
15734                                           /*expl_inst_class_mem_p=*/false);
15735                   if (COMPLETE_TYPE_P (instantiation))
15736                     reconsider = 1;
15737                 }
15738
15739               complete = COMPLETE_TYPE_P (instantiation);
15740             }
15741           else
15742             {
15743               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15744                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15745                 {
15746                   instantiation
15747                     = instantiate_decl (instantiation,
15748                                         /*defer_ok=*/0,
15749                                         /*expl_inst_class_mem_p=*/false);
15750                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15751                     reconsider = 1;
15752                 }
15753
15754               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15755                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15756             }
15757
15758           if (complete)
15759             /* If INSTANTIATION has been instantiated, then we don't
15760                need to consider it again in the future.  */
15761             *t = (*t)->next;
15762           else
15763             {
15764               last = *t;
15765               t = &(*t)->next;
15766             }
15767           tinst_depth = 0;
15768           current_tinst_level = NULL;
15769         }
15770       last_pending_template = last;
15771     }
15772   while (reconsider);
15773
15774   input_location = saved_loc;
15775 }
15776
15777 /* Substitute ARGVEC into T, which is a list of initializers for
15778    either base class or a non-static data member.  The TREE_PURPOSEs
15779    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15780    instantiate_decl.  */
15781
15782 static tree
15783 tsubst_initializer_list (tree t, tree argvec)
15784 {
15785   tree inits = NULL_TREE;
15786
15787   for (; t; t = TREE_CHAIN (t))
15788     {
15789       tree decl;
15790       tree init;
15791       tree expanded_bases = NULL_TREE;
15792       tree expanded_arguments = NULL_TREE;
15793       int i, len = 1;
15794
15795       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15796         {
15797           tree expr;
15798           tree arg;
15799
15800           /* Expand the base class expansion type into separate base
15801              classes.  */
15802           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15803                                                  tf_warning_or_error,
15804                                                  NULL_TREE);
15805           if (expanded_bases == error_mark_node)
15806             continue;
15807           
15808           /* We'll be building separate TREE_LISTs of arguments for
15809              each base.  */
15810           len = TREE_VEC_LENGTH (expanded_bases);
15811           expanded_arguments = make_tree_vec (len);
15812           for (i = 0; i < len; i++)
15813             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15814
15815           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15816              expand each argument in the TREE_VALUE of t.  */
15817           expr = make_node (EXPR_PACK_EXPANSION);
15818           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15819             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15820
15821           if (TREE_VALUE (t) == void_type_node)
15822             /* VOID_TYPE_NODE is used to indicate
15823                value-initialization.  */
15824             {
15825               for (i = 0; i < len; i++)
15826                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15827             }
15828           else
15829             {
15830               /* Substitute parameter packs into each argument in the
15831                  TREE_LIST.  */
15832               in_base_initializer = 1;
15833               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15834                 {
15835                   tree expanded_exprs;
15836
15837                   /* Expand the argument.  */
15838                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15839                   expanded_exprs 
15840                     = tsubst_pack_expansion (expr, argvec,
15841                                              tf_warning_or_error,
15842                                              NULL_TREE);
15843                   if (expanded_exprs == error_mark_node)
15844                     continue;
15845
15846                   /* Prepend each of the expanded expressions to the
15847                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15848                   for (i = 0; i < len; i++)
15849                     {
15850                       TREE_VEC_ELT (expanded_arguments, i) = 
15851                         tree_cons (NULL_TREE, 
15852                                    TREE_VEC_ELT (expanded_exprs, i),
15853                                    TREE_VEC_ELT (expanded_arguments, i));
15854                     }
15855                 }
15856               in_base_initializer = 0;
15857
15858               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15859                  since we built them backwards.  */
15860               for (i = 0; i < len; i++)
15861                 {
15862                   TREE_VEC_ELT (expanded_arguments, i) = 
15863                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15864                 }
15865             }
15866         }
15867
15868       for (i = 0; i < len; ++i)
15869         {
15870           if (expanded_bases)
15871             {
15872               decl = TREE_VEC_ELT (expanded_bases, i);
15873               decl = expand_member_init (decl);
15874               init = TREE_VEC_ELT (expanded_arguments, i);
15875             }
15876           else
15877             {
15878               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15879                                   tf_warning_or_error, NULL_TREE);
15880
15881               decl = expand_member_init (decl);
15882               if (decl && !DECL_P (decl))
15883                 in_base_initializer = 1;
15884
15885               init = tsubst_expr (TREE_VALUE (t), argvec, 
15886                                   tf_warning_or_error, NULL_TREE,
15887                                   /*integral_constant_expression_p=*/false);
15888               in_base_initializer = 0;
15889             }
15890
15891           if (decl)
15892             {
15893               init = build_tree_list (decl, init);
15894               TREE_CHAIN (init) = inits;
15895               inits = init;
15896             }
15897         }
15898     }
15899   return inits;
15900 }
15901
15902 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15903
15904 static void
15905 set_current_access_from_decl (tree decl)
15906 {
15907   if (TREE_PRIVATE (decl))
15908     current_access_specifier = access_private_node;
15909   else if (TREE_PROTECTED (decl))
15910     current_access_specifier = access_protected_node;
15911   else
15912     current_access_specifier = access_public_node;
15913 }
15914
15915 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15916    is the instantiation (which should have been created with
15917    start_enum) and ARGS are the template arguments to use.  */
15918
15919 static void
15920 tsubst_enum (tree tag, tree newtag, tree args)
15921 {
15922   tree e;
15923
15924   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15925     {
15926       tree value;
15927       tree decl;
15928
15929       decl = TREE_VALUE (e);
15930       /* Note that in a template enum, the TREE_VALUE is the
15931          CONST_DECL, not the corresponding INTEGER_CST.  */
15932       value = tsubst_expr (DECL_INITIAL (decl),
15933                            args, tf_warning_or_error, NULL_TREE,
15934                            /*integral_constant_expression_p=*/true);
15935
15936       /* Give this enumeration constant the correct access.  */
15937       set_current_access_from_decl (decl);
15938
15939       /* Actually build the enumerator itself.  */
15940       build_enumerator (DECL_NAME (decl), value, newtag);
15941     }
15942
15943   finish_enum (newtag);
15944   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15945     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15946 }
15947
15948 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15949    its type -- but without substituting the innermost set of template
15950    arguments.  So, innermost set of template parameters will appear in
15951    the type.  */
15952
15953 tree
15954 get_mostly_instantiated_function_type (tree decl)
15955 {
15956   tree fn_type;
15957   tree tmpl;
15958   tree targs;
15959   tree tparms;
15960   int parm_depth;
15961
15962   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15963   targs = DECL_TI_ARGS (decl);
15964   tparms = DECL_TEMPLATE_PARMS (tmpl);
15965   parm_depth = TMPL_PARMS_DEPTH (tparms);
15966
15967   /* There should be as many levels of arguments as there are levels
15968      of parameters.  */
15969   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15970
15971   fn_type = TREE_TYPE (tmpl);
15972
15973   if (parm_depth == 1)
15974     /* No substitution is necessary.  */
15975     ;
15976   else
15977     {
15978       int i, save_access_control;
15979       tree partial_args;
15980
15981       /* Replace the innermost level of the TARGS with NULL_TREEs to
15982          let tsubst know not to substitute for those parameters.  */
15983       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15984       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15985         SET_TMPL_ARGS_LEVEL (partial_args, i,
15986                              TMPL_ARGS_LEVEL (targs, i));
15987       SET_TMPL_ARGS_LEVEL (partial_args,
15988                            TMPL_ARGS_DEPTH (targs),
15989                            make_tree_vec (DECL_NTPARMS (tmpl)));
15990
15991       /* Disable access control as this function is used only during
15992          name-mangling.  */
15993       save_access_control = flag_access_control;
15994       flag_access_control = 0;
15995
15996       ++processing_template_decl;
15997       /* Now, do the (partial) substitution to figure out the
15998          appropriate function type.  */
15999       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16000       --processing_template_decl;
16001
16002       /* Substitute into the template parameters to obtain the real
16003          innermost set of parameters.  This step is important if the
16004          innermost set of template parameters contains value
16005          parameters whose types depend on outer template parameters.  */
16006       TREE_VEC_LENGTH (partial_args)--;
16007       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16008
16009       flag_access_control = save_access_control;
16010     }
16011
16012   return fn_type;
16013 }
16014
16015 /* Return truthvalue if we're processing a template different from
16016    the last one involved in diagnostics.  */
16017 int
16018 problematic_instantiation_changed (void)
16019 {
16020   return last_template_error_tick != tinst_level_tick;
16021 }
16022
16023 /* Remember current template involved in diagnostics.  */
16024 void
16025 record_last_problematic_instantiation (void)
16026 {
16027   last_template_error_tick = tinst_level_tick;
16028 }
16029
16030 struct tinst_level *
16031 current_instantiation (void)
16032 {
16033   return current_tinst_level;
16034 }
16035
16036 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16037    type. Return zero for ok, nonzero for disallowed. Issue error and
16038    warning messages under control of COMPLAIN.  */
16039
16040 static int
16041 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16042 {
16043   if (INTEGRAL_TYPE_P (type))
16044     return 0;
16045   else if (POINTER_TYPE_P (type))
16046     return 0;
16047   else if (TYPE_PTR_TO_MEMBER_P (type))
16048     return 0;
16049   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16050     return 0;
16051   else if (TREE_CODE (type) == TYPENAME_TYPE)
16052     return 0;
16053
16054   if (complain & tf_error)
16055     error ("%q#T is not a valid type for a template constant parameter", type);
16056   return 1;
16057 }
16058
16059 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16060    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16061
16062 static bool
16063 dependent_type_p_r (tree type)
16064 {
16065   tree scope;
16066
16067   /* [temp.dep.type]
16068
16069      A type is dependent if it is:
16070
16071      -- a template parameter. Template template parameters are types
16072         for us (since TYPE_P holds true for them) so we handle
16073         them here.  */
16074   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16075       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16076     return true;
16077   /* -- a qualified-id with a nested-name-specifier which contains a
16078         class-name that names a dependent type or whose unqualified-id
16079         names a dependent type.  */
16080   if (TREE_CODE (type) == TYPENAME_TYPE)
16081     return true;
16082   /* -- a cv-qualified type where the cv-unqualified type is
16083         dependent.  */
16084   type = TYPE_MAIN_VARIANT (type);
16085   /* -- a compound type constructed from any dependent type.  */
16086   if (TYPE_PTR_TO_MEMBER_P (type))
16087     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16088             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16089                                            (type)));
16090   else if (TREE_CODE (type) == POINTER_TYPE
16091            || TREE_CODE (type) == REFERENCE_TYPE)
16092     return dependent_type_p (TREE_TYPE (type));
16093   else if (TREE_CODE (type) == FUNCTION_TYPE
16094            || TREE_CODE (type) == METHOD_TYPE)
16095     {
16096       tree arg_type;
16097
16098       if (dependent_type_p (TREE_TYPE (type)))
16099         return true;
16100       for (arg_type = TYPE_ARG_TYPES (type);
16101            arg_type;
16102            arg_type = TREE_CHAIN (arg_type))
16103         if (dependent_type_p (TREE_VALUE (arg_type)))
16104           return true;
16105       return false;
16106     }
16107   /* -- an array type constructed from any dependent type or whose
16108         size is specified by a constant expression that is
16109         value-dependent.  */
16110   if (TREE_CODE (type) == ARRAY_TYPE)
16111     {
16112       if (TYPE_DOMAIN (type)
16113           && dependent_type_p (TYPE_DOMAIN (type)))
16114         return true;
16115       return dependent_type_p (TREE_TYPE (type));
16116     }
16117   else if (TREE_CODE (type) == INTEGER_TYPE
16118            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16119     {
16120       /* If this is the TYPE_DOMAIN of an array type, consider it
16121          dependent.  We already checked for value-dependence in
16122          compute_array_index_type.  */
16123       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16124     }
16125
16126   /* -- a template-id in which either the template name is a template
16127      parameter ...  */
16128   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16129     return true;
16130   /* ... or any of the template arguments is a dependent type or
16131         an expression that is type-dependent or value-dependent.  */
16132   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16133            && (any_dependent_template_arguments_p
16134                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16135     return true;
16136
16137   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16138      argument of the `typeof' expression is not type-dependent, then
16139      it should already been have resolved.  */
16140   if (TREE_CODE (type) == TYPEOF_TYPE
16141       || TREE_CODE (type) == DECLTYPE_TYPE)
16142     return true;
16143
16144   /* A template argument pack is dependent if any of its packed
16145      arguments are.  */
16146   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16147     {
16148       tree args = ARGUMENT_PACK_ARGS (type);
16149       int i, len = TREE_VEC_LENGTH (args);
16150       for (i = 0; i < len; ++i)
16151         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16152           return true;
16153     }
16154
16155   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16156      be template parameters.  */
16157   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16158     return true;
16159
16160   /* The standard does not specifically mention types that are local
16161      to template functions or local classes, but they should be
16162      considered dependent too.  For example:
16163
16164        template <int I> void f() {
16165          enum E { a = I };
16166          S<sizeof (E)> s;
16167        }
16168
16169      The size of `E' cannot be known until the value of `I' has been
16170      determined.  Therefore, `E' must be considered dependent.  */
16171   scope = TYPE_CONTEXT (type);
16172   if (scope && TYPE_P (scope))
16173     return dependent_type_p (scope);
16174   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16175     return type_dependent_expression_p (scope);
16176
16177   /* Other types are non-dependent.  */
16178   return false;
16179 }
16180
16181 /* Returns TRUE if TYPE is dependent, in the sense of
16182    [temp.dep.type].  */
16183
16184 bool
16185 dependent_type_p (tree type)
16186 {
16187   /* If there are no template parameters in scope, then there can't be
16188      any dependent types.  */
16189   if (!processing_template_decl)
16190     {
16191       /* If we are not processing a template, then nobody should be
16192          providing us with a dependent type.  */
16193       gcc_assert (type);
16194       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16195       return false;
16196     }
16197
16198   /* If the type is NULL, we have not computed a type for the entity
16199      in question; in that case, the type is dependent.  */
16200   if (!type)
16201     return true;
16202
16203   /* Erroneous types can be considered non-dependent.  */
16204   if (type == error_mark_node)
16205     return false;
16206
16207   /* If we have not already computed the appropriate value for TYPE,
16208      do so now.  */
16209   if (!TYPE_DEPENDENT_P_VALID (type))
16210     {
16211       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16212       TYPE_DEPENDENT_P_VALID (type) = 1;
16213     }
16214
16215   return TYPE_DEPENDENT_P (type);
16216 }
16217
16218 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16219    lookup.  In other words, a dependent type that is not the current
16220    instantiation.  */
16221
16222 bool
16223 dependent_scope_p (tree scope)
16224 {
16225   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16226           && !currently_open_class (scope));
16227 }
16228
16229 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16230
16231 static bool
16232 dependent_scope_ref_p (tree expression, bool criterion (tree))
16233 {
16234   tree scope;
16235   tree name;
16236
16237   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16238
16239   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16240     return true;
16241
16242   scope = TREE_OPERAND (expression, 0);
16243   name = TREE_OPERAND (expression, 1);
16244
16245   /* [temp.dep.expr]
16246
16247      An id-expression is type-dependent if it contains a
16248      nested-name-specifier that contains a class-name that names a
16249      dependent type.  */
16250   /* The suggested resolution to Core Issue 224 implies that if the
16251      qualifying type is the current class, then we must peek
16252      inside it.  */
16253   if (DECL_P (name)
16254       && currently_open_class (scope)
16255       && !criterion (name))
16256     return false;
16257   if (dependent_type_p (scope))
16258     return true;
16259
16260   return false;
16261 }
16262
16263 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16264    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16265    expression.  */
16266
16267 bool
16268 value_dependent_expression_p (tree expression)
16269 {
16270   if (!processing_template_decl)
16271     return false;
16272
16273   /* A name declared with a dependent type.  */
16274   if (DECL_P (expression) && type_dependent_expression_p (expression))
16275     return true;
16276
16277   switch (TREE_CODE (expression))
16278     {
16279     case IDENTIFIER_NODE:
16280       /* A name that has not been looked up -- must be dependent.  */
16281       return true;
16282
16283     case TEMPLATE_PARM_INDEX:
16284       /* A non-type template parm.  */
16285       return true;
16286
16287     case CONST_DECL:
16288       /* A non-type template parm.  */
16289       if (DECL_TEMPLATE_PARM_P (expression))
16290         return true;
16291       return value_dependent_expression_p (DECL_INITIAL (expression));
16292
16293     case VAR_DECL:
16294        /* A constant with integral or enumeration type and is initialized
16295           with an expression that is value-dependent.  */
16296       if (DECL_INITIAL (expression)
16297           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16298           && value_dependent_expression_p (DECL_INITIAL (expression)))
16299         return true;
16300       return false;
16301
16302     case DYNAMIC_CAST_EXPR:
16303     case STATIC_CAST_EXPR:
16304     case CONST_CAST_EXPR:
16305     case REINTERPRET_CAST_EXPR:
16306     case CAST_EXPR:
16307       /* These expressions are value-dependent if the type to which
16308          the cast occurs is dependent or the expression being casted
16309          is value-dependent.  */
16310       {
16311         tree type = TREE_TYPE (expression);
16312
16313         if (dependent_type_p (type))
16314           return true;
16315
16316         /* A functional cast has a list of operands.  */
16317         expression = TREE_OPERAND (expression, 0);
16318         if (!expression)
16319           {
16320             /* If there are no operands, it must be an expression such
16321                as "int()". This should not happen for aggregate types
16322                because it would form non-constant expressions.  */
16323             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16324
16325             return false;
16326           }
16327
16328         if (TREE_CODE (expression) == TREE_LIST)
16329           return any_value_dependent_elements_p (expression);
16330
16331         return value_dependent_expression_p (expression);
16332       }
16333
16334     case SIZEOF_EXPR:
16335     case ALIGNOF_EXPR:
16336       /* A `sizeof' expression is value-dependent if the operand is
16337          type-dependent or is a pack expansion.  */
16338       expression = TREE_OPERAND (expression, 0);
16339       if (PACK_EXPANSION_P (expression))
16340         return true;
16341       else if (TYPE_P (expression))
16342         return dependent_type_p (expression);
16343       return type_dependent_expression_p (expression);
16344
16345     case SCOPE_REF:
16346       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16347
16348     case COMPONENT_REF:
16349       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16350               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16351
16352     case CALL_EXPR:
16353       /* A CALL_EXPR may appear in a constant expression if it is a
16354          call to a builtin function, e.g., __builtin_constant_p.  All
16355          such calls are value-dependent.  */
16356       return true;
16357
16358     case NONTYPE_ARGUMENT_PACK:
16359       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16360          is value-dependent.  */
16361       {
16362         tree values = ARGUMENT_PACK_ARGS (expression);
16363         int i, len = TREE_VEC_LENGTH (values);
16364         
16365         for (i = 0; i < len; ++i)
16366           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16367             return true;
16368         
16369         return false;
16370       }
16371
16372     case TRAIT_EXPR:
16373       {
16374         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16375         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16376                 || (type2 ? dependent_type_p (type2) : false));
16377       }
16378
16379     case MODOP_EXPR:
16380       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16381               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16382
16383     default:
16384       /* A constant expression is value-dependent if any subexpression is
16385          value-dependent.  */
16386       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16387         {
16388         case tcc_reference:
16389         case tcc_unary:
16390           return (value_dependent_expression_p
16391                   (TREE_OPERAND (expression, 0)));
16392
16393         case tcc_comparison:
16394         case tcc_binary:
16395           return ((value_dependent_expression_p
16396                    (TREE_OPERAND (expression, 0)))
16397                   || (value_dependent_expression_p
16398                       (TREE_OPERAND (expression, 1))));
16399
16400         case tcc_expression:
16401         case tcc_vl_exp:
16402           {
16403             int i;
16404             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16405               /* In some cases, some of the operands may be missing.
16406                  (For example, in the case of PREDECREMENT_EXPR, the
16407                  amount to increment by may be missing.)  That doesn't
16408                  make the expression dependent.  */
16409               if (TREE_OPERAND (expression, i)
16410                   && (value_dependent_expression_p
16411                       (TREE_OPERAND (expression, i))))
16412                 return true;
16413             return false;
16414           }
16415
16416         default:
16417           break;
16418         }
16419     }
16420
16421   /* The expression is not value-dependent.  */
16422   return false;
16423 }
16424
16425 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16426    [temp.dep.expr].  */
16427
16428 bool
16429 type_dependent_expression_p (tree expression)
16430 {
16431   if (!processing_template_decl)
16432     return false;
16433
16434   if (expression == error_mark_node)
16435     return false;
16436
16437   /* An unresolved name is always dependent.  */
16438   if (TREE_CODE (expression) == IDENTIFIER_NODE
16439       || TREE_CODE (expression) == USING_DECL)
16440     return true;
16441
16442   /* Some expression forms are never type-dependent.  */
16443   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16444       || TREE_CODE (expression) == SIZEOF_EXPR
16445       || TREE_CODE (expression) == ALIGNOF_EXPR
16446       || TREE_CODE (expression) == TRAIT_EXPR
16447       || TREE_CODE (expression) == TYPEID_EXPR
16448       || TREE_CODE (expression) == DELETE_EXPR
16449       || TREE_CODE (expression) == VEC_DELETE_EXPR
16450       || TREE_CODE (expression) == THROW_EXPR)
16451     return false;
16452
16453   /* The types of these expressions depends only on the type to which
16454      the cast occurs.  */
16455   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16456       || TREE_CODE (expression) == STATIC_CAST_EXPR
16457       || TREE_CODE (expression) == CONST_CAST_EXPR
16458       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16459       || TREE_CODE (expression) == CAST_EXPR)
16460     return dependent_type_p (TREE_TYPE (expression));
16461
16462   /* The types of these expressions depends only on the type created
16463      by the expression.  */
16464   if (TREE_CODE (expression) == NEW_EXPR
16465       || TREE_CODE (expression) == VEC_NEW_EXPR)
16466     {
16467       /* For NEW_EXPR tree nodes created inside a template, either
16468          the object type itself or a TREE_LIST may appear as the
16469          operand 1.  */
16470       tree type = TREE_OPERAND (expression, 1);
16471       if (TREE_CODE (type) == TREE_LIST)
16472         /* This is an array type.  We need to check array dimensions
16473            as well.  */
16474         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16475                || value_dependent_expression_p
16476                     (TREE_OPERAND (TREE_VALUE (type), 1));
16477       else
16478         return dependent_type_p (type);
16479     }
16480
16481   if (TREE_CODE (expression) == SCOPE_REF
16482       && dependent_scope_ref_p (expression,
16483                                 type_dependent_expression_p))
16484     return true;
16485
16486   if (TREE_CODE (expression) == FUNCTION_DECL
16487       && DECL_LANG_SPECIFIC (expression)
16488       && DECL_TEMPLATE_INFO (expression)
16489       && (any_dependent_template_arguments_p
16490           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16491     return true;
16492
16493   if (TREE_CODE (expression) == TEMPLATE_DECL
16494       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16495     return false;
16496
16497   if (TREE_CODE (expression) == STMT_EXPR)
16498     expression = stmt_expr_value_expr (expression);
16499
16500   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16501     {
16502       tree elt;
16503       unsigned i;
16504
16505       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16506         {
16507           if (type_dependent_expression_p (elt))
16508             return true;
16509         }
16510       return false;
16511     }
16512
16513   if (TREE_TYPE (expression) == unknown_type_node)
16514     {
16515       if (TREE_CODE (expression) == ADDR_EXPR)
16516         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16517       if (TREE_CODE (expression) == COMPONENT_REF
16518           || TREE_CODE (expression) == OFFSET_REF)
16519         {
16520           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16521             return true;
16522           expression = TREE_OPERAND (expression, 1);
16523           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16524             return false;
16525         }
16526       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16527       if (TREE_CODE (expression) == SCOPE_REF)
16528         return false;
16529
16530       if (TREE_CODE (expression) == BASELINK)
16531         expression = BASELINK_FUNCTIONS (expression);
16532
16533       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16534         {
16535           if (any_dependent_template_arguments_p
16536               (TREE_OPERAND (expression, 1)))
16537             return true;
16538           expression = TREE_OPERAND (expression, 0);
16539         }
16540       gcc_assert (TREE_CODE (expression) == OVERLOAD
16541                   || TREE_CODE (expression) == FUNCTION_DECL);
16542
16543       while (expression)
16544         {
16545           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16546             return true;
16547           expression = OVL_NEXT (expression);
16548         }
16549       return false;
16550     }
16551
16552   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16553
16554   return (dependent_type_p (TREE_TYPE (expression)));
16555 }
16556
16557 /* Like type_dependent_expression_p, but it also works while not processing
16558    a template definition, i.e. during substitution or mangling.  */
16559
16560 bool
16561 type_dependent_expression_p_push (tree expr)
16562 {
16563   bool b;
16564   ++processing_template_decl;
16565   b = type_dependent_expression_p (expr);
16566   --processing_template_decl;
16567   return b;
16568 }
16569
16570 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16571    contains a type-dependent expression.  */
16572
16573 bool
16574 any_type_dependent_arguments_p (const_tree args)
16575 {
16576   while (args)
16577     {
16578       tree arg = TREE_VALUE (args);
16579
16580       if (type_dependent_expression_p (arg))
16581         return true;
16582       args = TREE_CHAIN (args);
16583     }
16584   return false;
16585 }
16586
16587 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16588    expressions) contains any value-dependent expressions.  */
16589
16590 bool
16591 any_value_dependent_elements_p (const_tree list)
16592 {
16593   for (; list; list = TREE_CHAIN (list))
16594     if (value_dependent_expression_p (TREE_VALUE (list)))
16595       return true;
16596
16597   return false;
16598 }
16599
16600 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16601
16602 bool
16603 dependent_template_arg_p (tree arg)
16604 {
16605   if (!processing_template_decl)
16606     return false;
16607
16608   if (TREE_CODE (arg) == TEMPLATE_DECL
16609       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16610     return dependent_template_p (arg);
16611   else if (ARGUMENT_PACK_P (arg))
16612     {
16613       tree args = ARGUMENT_PACK_ARGS (arg);
16614       int i, len = TREE_VEC_LENGTH (args);
16615       for (i = 0; i < len; ++i)
16616         {
16617           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16618             return true;
16619         }
16620
16621       return false;
16622     }
16623   else if (TYPE_P (arg))
16624     return dependent_type_p (arg);
16625   else
16626     return (type_dependent_expression_p (arg)
16627             || value_dependent_expression_p (arg));
16628 }
16629
16630 /* Returns true if ARGS (a collection of template arguments) contains
16631    any types that require structural equality testing.  */
16632
16633 bool
16634 any_template_arguments_need_structural_equality_p (tree args)
16635 {
16636   int i;
16637   int j;
16638
16639   if (!args)
16640     return false;
16641   if (args == error_mark_node)
16642     return true;
16643
16644   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16645     {
16646       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16647       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16648         {
16649           tree arg = TREE_VEC_ELT (level, j);
16650           tree packed_args = NULL_TREE;
16651           int k, len = 1;
16652
16653           if (ARGUMENT_PACK_P (arg))
16654             {
16655               /* Look inside the argument pack.  */
16656               packed_args = ARGUMENT_PACK_ARGS (arg);
16657               len = TREE_VEC_LENGTH (packed_args);
16658             }
16659
16660           for (k = 0; k < len; ++k)
16661             {
16662               if (packed_args)
16663                 arg = TREE_VEC_ELT (packed_args, k);
16664
16665               if (error_operand_p (arg))
16666                 return true;
16667               else if (TREE_CODE (arg) == TEMPLATE_DECL
16668                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16669                 continue;
16670               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16671                 return true;
16672               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16673                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16674                 return true;
16675             }
16676         }
16677     }
16678
16679   return false;
16680 }
16681
16682 /* Returns true if ARGS (a collection of template arguments) contains
16683    any dependent arguments.  */
16684
16685 bool
16686 any_dependent_template_arguments_p (const_tree args)
16687 {
16688   int i;
16689   int j;
16690
16691   if (!args)
16692     return false;
16693   if (args == error_mark_node)
16694     return true;
16695
16696   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16697     {
16698       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16699       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16700         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16701           return true;
16702     }
16703
16704   return false;
16705 }
16706
16707 /* Returns TRUE if the template TMPL is dependent.  */
16708
16709 bool
16710 dependent_template_p (tree tmpl)
16711 {
16712   if (TREE_CODE (tmpl) == OVERLOAD)
16713     {
16714       while (tmpl)
16715         {
16716           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16717             return true;
16718           tmpl = OVL_CHAIN (tmpl);
16719         }
16720       return false;
16721     }
16722
16723   /* Template template parameters are dependent.  */
16724   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16725       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16726     return true;
16727   /* So are names that have not been looked up.  */
16728   if (TREE_CODE (tmpl) == SCOPE_REF
16729       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16730     return true;
16731   /* So are member templates of dependent classes.  */
16732   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16733     return dependent_type_p (DECL_CONTEXT (tmpl));
16734   return false;
16735 }
16736
16737 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16738
16739 bool
16740 dependent_template_id_p (tree tmpl, tree args)
16741 {
16742   return (dependent_template_p (tmpl)
16743           || any_dependent_template_arguments_p (args));
16744 }
16745
16746 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16747    is dependent.  */
16748
16749 bool
16750 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16751 {
16752   int i;
16753
16754   if (!processing_template_decl)
16755     return false;
16756
16757   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16758     {
16759       tree decl = TREE_VEC_ELT (declv, i);
16760       tree init = TREE_VEC_ELT (initv, i);
16761       tree cond = TREE_VEC_ELT (condv, i);
16762       tree incr = TREE_VEC_ELT (incrv, i);
16763
16764       if (type_dependent_expression_p (decl))
16765         return true;
16766
16767       if (init && type_dependent_expression_p (init))
16768         return true;
16769
16770       if (type_dependent_expression_p (cond))
16771         return true;
16772
16773       if (COMPARISON_CLASS_P (cond)
16774           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16775               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16776         return true;
16777
16778       if (TREE_CODE (incr) == MODOP_EXPR)
16779         {
16780           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16781               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16782             return true;
16783         }
16784       else if (type_dependent_expression_p (incr))
16785         return true;
16786       else if (TREE_CODE (incr) == MODIFY_EXPR)
16787         {
16788           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16789             return true;
16790           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16791             {
16792               tree t = TREE_OPERAND (incr, 1);
16793               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16794                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16795                 return true;
16796             }
16797         }
16798     }
16799
16800   return false;
16801 }
16802
16803 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16804    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16805    no such TYPE can be found.  Note that this function peers inside
16806    uninstantiated templates and therefore should be used only in
16807    extremely limited situations.  ONLY_CURRENT_P restricts this
16808    peering to the currently open classes hierarchy (which is required
16809    when comparing types).  */
16810
16811 tree
16812 resolve_typename_type (tree type, bool only_current_p)
16813 {
16814   tree scope;
16815   tree name;
16816   tree decl;
16817   int quals;
16818   tree pushed_scope;
16819   tree result;
16820
16821   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16822
16823   scope = TYPE_CONTEXT (type);
16824   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
16825      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
16826      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
16827      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
16828      identifier  of the TYPENAME_TYPE anymore.
16829      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
16830      TYPENAME_TYPE instead, we avoid messing up with a possible
16831      typedef variant case.  */
16832   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
16833
16834   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16835      it first before we can figure out what NAME refers to.  */
16836   if (TREE_CODE (scope) == TYPENAME_TYPE)
16837     scope = resolve_typename_type (scope, only_current_p);
16838   /* If we don't know what SCOPE refers to, then we cannot resolve the
16839      TYPENAME_TYPE.  */
16840   if (TREE_CODE (scope) == TYPENAME_TYPE)
16841     return type;
16842   /* If the SCOPE is a template type parameter, we have no way of
16843      resolving the name.  */
16844   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16845     return type;
16846   /* If the SCOPE is not the current instantiation, there's no reason
16847      to look inside it.  */
16848   if (only_current_p && !currently_open_class (scope))
16849     return type;
16850   /* If SCOPE isn't the template itself, it will not have a valid
16851      TYPE_FIELDS list.  */
16852   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16853     /* scope is either the template itself or a compatible instantiation
16854        like X<T>, so look up the name in the original template.  */
16855     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16856   else
16857     /* scope is a partial instantiation, so we can't do the lookup or we
16858        will lose the template arguments.  */
16859     return type;
16860   /* Enter the SCOPE so that name lookup will be resolved as if we
16861      were in the class definition.  In particular, SCOPE will no
16862      longer be considered a dependent type.  */
16863   pushed_scope = push_scope (scope);
16864   /* Look up the declaration.  */
16865   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16866
16867   result = NULL_TREE;
16868   
16869   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16870      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16871   if (!decl)
16872     /*nop*/;
16873   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16874            && TREE_CODE (decl) == TYPE_DECL)
16875     {
16876       result = TREE_TYPE (decl);
16877       if (result == error_mark_node)
16878         result = NULL_TREE;
16879     }
16880   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16881            && DECL_CLASS_TEMPLATE_P (decl))
16882     {
16883       tree tmpl;
16884       tree args;
16885       /* Obtain the template and the arguments.  */
16886       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16887       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16888       /* Instantiate the template.  */
16889       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16890                                       /*entering_scope=*/0,
16891                                       tf_error | tf_user);
16892       if (result == error_mark_node)
16893         result = NULL_TREE;
16894     }
16895   
16896   /* Leave the SCOPE.  */
16897   if (pushed_scope)
16898     pop_scope (pushed_scope);
16899
16900   /* If we failed to resolve it, return the original typename.  */
16901   if (!result)
16902     return type;
16903   
16904   /* If lookup found a typename type, resolve that too.  */
16905   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16906     {
16907       /* Ill-formed programs can cause infinite recursion here, so we
16908          must catch that.  */
16909       TYPENAME_IS_RESOLVING_P (type) = 1;
16910       result = resolve_typename_type (result, only_current_p);
16911       TYPENAME_IS_RESOLVING_P (type) = 0;
16912     }
16913   
16914   /* Qualify the resulting type.  */
16915   quals = cp_type_quals (type);
16916   if (quals)
16917     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16918
16919   return result;
16920 }
16921
16922 /* EXPR is an expression which is not type-dependent.  Return a proxy
16923    for EXPR that can be used to compute the types of larger
16924    expressions containing EXPR.  */
16925
16926 tree
16927 build_non_dependent_expr (tree expr)
16928 {
16929   tree inner_expr;
16930
16931   /* Preserve null pointer constants so that the type of things like
16932      "p == 0" where "p" is a pointer can be determined.  */
16933   if (null_ptr_cst_p (expr))
16934     return expr;
16935   /* Preserve OVERLOADs; the functions must be available to resolve
16936      types.  */
16937   inner_expr = expr;
16938   if (TREE_CODE (inner_expr) == STMT_EXPR)
16939     inner_expr = stmt_expr_value_expr (inner_expr);
16940   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16941     inner_expr = TREE_OPERAND (inner_expr, 0);
16942   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16943     inner_expr = TREE_OPERAND (inner_expr, 1);
16944   if (is_overloaded_fn (inner_expr)
16945       || TREE_CODE (inner_expr) == OFFSET_REF)
16946     return expr;
16947   /* There is no need to return a proxy for a variable.  */
16948   if (TREE_CODE (expr) == VAR_DECL)
16949     return expr;
16950   /* Preserve string constants; conversions from string constants to
16951      "char *" are allowed, even though normally a "const char *"
16952      cannot be used to initialize a "char *".  */
16953   if (TREE_CODE (expr) == STRING_CST)
16954     return expr;
16955   /* Preserve arithmetic constants, as an optimization -- there is no
16956      reason to create a new node.  */
16957   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16958     return expr;
16959   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16960      There is at least one place where we want to know that a
16961      particular expression is a throw-expression: when checking a ?:
16962      expression, there are special rules if the second or third
16963      argument is a throw-expression.  */
16964   if (TREE_CODE (expr) == THROW_EXPR)
16965     return expr;
16966
16967   if (TREE_CODE (expr) == COND_EXPR)
16968     return build3 (COND_EXPR,
16969                    TREE_TYPE (expr),
16970                    TREE_OPERAND (expr, 0),
16971                    (TREE_OPERAND (expr, 1)
16972                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16973                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16974                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16975   if (TREE_CODE (expr) == COMPOUND_EXPR
16976       && !COMPOUND_EXPR_OVERLOADED (expr))
16977     return build2 (COMPOUND_EXPR,
16978                    TREE_TYPE (expr),
16979                    TREE_OPERAND (expr, 0),
16980                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16981
16982   /* If the type is unknown, it can't really be non-dependent */
16983   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16984
16985   /* Otherwise, build a NON_DEPENDENT_EXPR.
16986
16987      REFERENCE_TYPEs are not stripped for expressions in templates
16988      because doing so would play havoc with mangling.  Consider, for
16989      example:
16990
16991        template <typename T> void f<T& g>() { g(); }
16992
16993      In the body of "f", the expression for "g" will have
16994      REFERENCE_TYPE, even though the standard says that it should
16995      not.  The reason is that we must preserve the syntactic form of
16996      the expression so that mangling (say) "f<g>" inside the body of
16997      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16998      stripped here.  */
16999   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17000 }
17001
17002 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
17003    Return a new TREE_LIST with the various arguments replaced with
17004    equivalent non-dependent expressions.  */
17005
17006 tree
17007 build_non_dependent_args (tree args)
17008 {
17009   tree a;
17010   tree new_args;
17011
17012   new_args = NULL_TREE;
17013   for (a = args; a; a = TREE_CHAIN (a))
17014     new_args = tree_cons (NULL_TREE,
17015                           build_non_dependent_expr (TREE_VALUE (a)),
17016                           new_args);
17017   return nreverse (new_args);
17018 }
17019
17020 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17021    with a level one deeper than the actual template parms.  */
17022
17023 tree
17024 make_auto (void)
17025 {
17026   tree au;
17027
17028   /* ??? Is it worth caching this for multiple autos at the same level?  */
17029   au = cxx_make_type (TEMPLATE_TYPE_PARM);
17030   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
17031   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17032   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17033     (0, processing_template_decl + 1, processing_template_decl + 1,
17034      TYPE_NAME (au), NULL_TREE);
17035   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17036   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17037   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17038
17039   return au;
17040 }
17041
17042 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17043
17044 static tree
17045 listify_autos (tree type, tree auto_node)
17046 {
17047   tree std_init_list = namespace_binding
17048     (get_identifier ("initializer_list"), std_node);
17049   tree argvec;
17050   tree init_auto;
17051   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17052     {    
17053       error ("deducing auto from brace-enclosed initializer list requires "
17054              "#include <initializer_list>");
17055       return error_mark_node;
17056     }
17057   argvec = make_tree_vec (1);
17058   TREE_VEC_ELT (argvec, 0) = auto_node;
17059   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
17060                                      NULL_TREE, 0, tf_warning_or_error);
17061
17062   TREE_VEC_ELT (argvec, 0) = init_auto;
17063   if (processing_template_decl)
17064     argvec = add_to_template_args (current_template_args (), argvec);
17065   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17066 }
17067
17068 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17069    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17070
17071 tree
17072 do_auto_deduction (tree type, tree init, tree auto_node)
17073 {
17074   tree parms, args, tparms, targs;
17075   int val;
17076
17077   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17078      with either a new invented type template parameter U or, if the
17079      initializer is a braced-init-list (8.5.4), with
17080      std::initializer_list<U>.  */
17081   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17082     type = listify_autos (type, auto_node);
17083
17084   parms = build_tree_list (NULL_TREE, type);
17085   args = build_tree_list (NULL_TREE, init);
17086   tparms = make_tree_vec (1);
17087   targs = make_tree_vec (1);
17088   TREE_VEC_ELT (tparms, 0)
17089     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17090   val = type_unification_real (tparms, targs, parms, args, 0,
17091                                DEDUCE_CALL, LOOKUP_NORMAL);
17092   if (val > 0)
17093     {
17094       error ("unable to deduce %qT from %qE", type, init);
17095       return error_mark_node;
17096     }
17097
17098   if (processing_template_decl)
17099     targs = add_to_template_args (current_template_args (), targs);
17100   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17101 }
17102
17103 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17104    result.  */
17105
17106 tree
17107 splice_late_return_type (tree type, tree late_return_type)
17108 {
17109   tree argvec;
17110
17111   if (late_return_type == NULL_TREE)
17112     return type;
17113   argvec = make_tree_vec (1);
17114   TREE_VEC_ELT (argvec, 0) = late_return_type;
17115   if (processing_template_decl)
17116     argvec = add_to_template_args (current_template_args (), argvec);
17117   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17118 }
17119
17120 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17121
17122 bool
17123 is_auto (const_tree type)
17124 {
17125   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17126       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17127     return true;
17128   else
17129     return false;
17130 }
17131
17132 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17133    appear as a type-specifier for the declaration in question, we don't
17134    have to look through the whole type.  */
17135
17136 tree
17137 type_uses_auto (tree type)
17138 {
17139   enum tree_code code;
17140   if (is_auto (type))
17141     return type;
17142
17143   code = TREE_CODE (type);
17144
17145   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17146       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17147       || code == METHOD_TYPE || code == ARRAY_TYPE)
17148     return type_uses_auto (TREE_TYPE (type));
17149
17150   if (TYPE_PTRMEMFUNC_P (type))
17151     return type_uses_auto (TREE_TYPE (TREE_TYPE
17152                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17153
17154   return NULL_TREE;
17155 }
17156
17157 /* Append TYPE_DECL to the template TEMPL.
17158    TEMPL is either a class type or a FUNCTION_DECL associated
17159    to a TEMPLATE_DECL.
17160    At TEMPL instanciation time, TYPE_DECL will be checked to see
17161    if it can be accessed through SCOPE.  */
17162
17163 void
17164 append_type_to_template_for_access_check (tree templ,
17165                                           tree type_decl,
17166                                           tree scope)
17167 {
17168   tree node, templ_decl;
17169
17170   gcc_assert (templ
17171               && get_template_info (templ)
17172               && TI_TEMPLATE (get_template_info (templ))
17173               && type_decl
17174               && (TREE_CODE (type_decl) == TYPE_DECL));
17175
17176   templ_decl = TI_TEMPLATE (get_template_info (templ));
17177   gcc_assert (templ_decl);
17178
17179   /* Make sure we don't append the type to the template twice.
17180      If this appears to be too slow, the
17181      MEMBER_TYPE_NEEDING_ACCESS_CHECK property
17182      of templ should be a hash table instead.  */
17183   for (node = MEMBER_TYPES_NEEDING_ACCESS_CHECK (templ_decl);
17184        node;
17185        node = TREE_CHAIN (node))
17186     {
17187       tree decl = TREE_PURPOSE (node);
17188       tree type_scope = TREE_VALUE (node);
17189
17190       if (decl == type_decl && type_scope == scope)
17191         return;
17192     }
17193
17194   MEMBER_TYPES_NEEDING_ACCESS_CHECK (templ_decl) =
17195     tree_cons (type_decl, scope,
17196                MEMBER_TYPES_NEEDING_ACCESS_CHECK (templ_decl));
17197 }
17198
17199 #include "gt-cp-pt.h"