OSDN Git Service

2009-04-16 Bob Duff <duff@adacore.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 pending_template GTY (()) {
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         max = fold_decl_constant_value (max);
9186
9187         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9188            with TREE_SIDE_EFFECTS that indicates this is not an integral
9189            constant expression.  */
9190         if (processing_template_decl
9191             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9192           {
9193             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9194             TREE_SIDE_EFFECTS (max) = 1;
9195           }
9196
9197         if (TREE_CODE (max) != INTEGER_CST
9198             && !at_function_scope_p ()
9199             && !TREE_SIDE_EFFECTS (max)
9200             && !value_dependent_expression_p (max))
9201           {
9202             if (complain & tf_error)
9203               error ("array bound is not an integer constant");
9204             return error_mark_node;
9205           }
9206
9207         /* [temp.deduct]
9208
9209            Type deduction may fail for any of the following
9210            reasons:
9211
9212              Attempting to create an array with a size that is
9213              zero or negative.  */
9214         if (integer_zerop (max) && !(complain & tf_error))
9215           /* We must fail if performing argument deduction (as
9216              indicated by the state of complain), so that
9217              another substitution can be found.  */
9218           return error_mark_node;
9219         else if (TREE_CODE (max) == INTEGER_CST
9220                  && INT_CST_LT (max, integer_zero_node))
9221           {
9222             if (complain & tf_error)
9223               error ("creating array with negative size (%qE)", max);
9224
9225             return error_mark_node;
9226           }
9227
9228         return compute_array_index_type (NULL_TREE, max);
9229       }
9230
9231     case TEMPLATE_TYPE_PARM:
9232     case TEMPLATE_TEMPLATE_PARM:
9233     case BOUND_TEMPLATE_TEMPLATE_PARM:
9234     case TEMPLATE_PARM_INDEX:
9235       {
9236         int idx;
9237         int level;
9238         int levels;
9239         tree arg = NULL_TREE;
9240
9241         r = NULL_TREE;
9242
9243         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9244         template_parm_level_and_index (t, &level, &idx); 
9245
9246         levels = TMPL_ARGS_DEPTH (args);
9247         if (level <= levels)
9248           {
9249             arg = TMPL_ARG (args, level, idx);
9250
9251             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9252               /* See through ARGUMENT_PACK_SELECT arguments. */
9253               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9254           }
9255
9256         if (arg == error_mark_node)
9257           return error_mark_node;
9258         else if (arg != NULL_TREE)
9259           {
9260             if (ARGUMENT_PACK_P (arg))
9261               /* If ARG is an argument pack, we don't actually want to
9262                  perform a substitution here, because substitutions
9263                  for argument packs are only done
9264                  element-by-element. We can get to this point when
9265                  substituting the type of a non-type template
9266                  parameter pack, when that type actually contains
9267                  template parameter packs from an outer template, e.g.,
9268
9269                  template<typename... Types> struct A {
9270                    template<Types... Values> struct B { };
9271                  };  */
9272               return t;
9273
9274             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9275               {
9276                 int quals;
9277                 gcc_assert (TYPE_P (arg));
9278
9279                 /* cv-quals from the template are discarded when
9280                    substituting in a function or reference type.  */
9281                 if (TREE_CODE (arg) == FUNCTION_TYPE
9282                     || TREE_CODE (arg) == METHOD_TYPE
9283                     || TREE_CODE (arg) == REFERENCE_TYPE)
9284                   quals = cp_type_quals (arg);
9285                 else
9286                   quals = cp_type_quals (arg) | cp_type_quals (t);
9287                   
9288                 return cp_build_qualified_type_real
9289                   (arg, quals, complain | tf_ignore_bad_quals);
9290               }
9291             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9292               {
9293                 /* We are processing a type constructed from a
9294                    template template parameter.  */
9295                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9296                                       args, complain, in_decl);
9297                 if (argvec == error_mark_node)
9298                   return error_mark_node;
9299
9300                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9301                    are resolving nested-types in the signature of a
9302                    member function templates.  Otherwise ARG is a
9303                    TEMPLATE_DECL and is the real template to be
9304                    instantiated.  */
9305                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9306                   arg = TYPE_NAME (arg);
9307
9308                 r = lookup_template_class (arg,
9309                                            argvec, in_decl,
9310                                            DECL_CONTEXT (arg),
9311                                             /*entering_scope=*/0,
9312                                            complain);
9313                 return cp_build_qualified_type_real
9314                   (r, TYPE_QUALS (t), complain);
9315               }
9316             else
9317               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9318               return arg;
9319           }
9320
9321         if (level == 1)
9322           /* This can happen during the attempted tsubst'ing in
9323              unify.  This means that we don't yet have any information
9324              about the template parameter in question.  */
9325           return t;
9326
9327         /* If we get here, we must have been looking at a parm for a
9328            more deeply nested template.  Make a new version of this
9329            template parameter, but with a lower level.  */
9330         switch (TREE_CODE (t))
9331           {
9332           case TEMPLATE_TYPE_PARM:
9333           case TEMPLATE_TEMPLATE_PARM:
9334           case BOUND_TEMPLATE_TEMPLATE_PARM:
9335             if (cp_type_quals (t))
9336               {
9337                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9338                 r = cp_build_qualified_type_real
9339                   (r, cp_type_quals (t),
9340                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9341                                ? tf_ignore_bad_quals : 0));
9342               }
9343             else
9344               {
9345                 r = copy_type (t);
9346                 TEMPLATE_TYPE_PARM_INDEX (r)
9347                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9348                                                 r, levels, args, complain);
9349                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9350                 TYPE_MAIN_VARIANT (r) = r;
9351                 TYPE_POINTER_TO (r) = NULL_TREE;
9352                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9353
9354                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9355                   /* We have reduced the level of the template
9356                      template parameter, but not the levels of its
9357                      template parameters, so canonical_type_parameter
9358                      will not be able to find the canonical template
9359                      template parameter for this level. Thus, we
9360                      require structural equality checking to compare
9361                      TEMPLATE_TEMPLATE_PARMs. */
9362                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9363                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9364                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9365                 else
9366                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9367
9368                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9369                   {
9370                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9371                                           complain, in_decl);
9372                     if (argvec == error_mark_node)
9373                       return error_mark_node;
9374
9375                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9376                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9377                   }
9378               }
9379             break;
9380
9381           case TEMPLATE_PARM_INDEX:
9382             r = reduce_template_parm_level (t, type, levels, args, complain);
9383             break;
9384
9385           default:
9386             gcc_unreachable ();
9387           }
9388
9389         return r;
9390       }
9391
9392     case TREE_LIST:
9393       {
9394         tree purpose, value, chain;
9395
9396         if (t == void_list_node)
9397           return t;
9398
9399         purpose = TREE_PURPOSE (t);
9400         if (purpose)
9401           {
9402             purpose = tsubst (purpose, args, complain, in_decl);
9403             if (purpose == error_mark_node)
9404               return error_mark_node;
9405           }
9406         value = TREE_VALUE (t);
9407         if (value)
9408           {
9409             value = tsubst (value, args, complain, in_decl);
9410             if (value == error_mark_node)
9411               return error_mark_node;
9412           }
9413         chain = TREE_CHAIN (t);
9414         if (chain && chain != void_type_node)
9415           {
9416             chain = tsubst (chain, args, complain, in_decl);
9417             if (chain == error_mark_node)
9418               return error_mark_node;
9419           }
9420         if (purpose == TREE_PURPOSE (t)
9421             && value == TREE_VALUE (t)
9422             && chain == TREE_CHAIN (t))
9423           return t;
9424         return hash_tree_cons (purpose, value, chain);
9425       }
9426
9427     case TREE_BINFO:
9428       /* We should never be tsubsting a binfo.  */
9429       gcc_unreachable ();
9430
9431     case TREE_VEC:
9432       /* A vector of template arguments.  */
9433       gcc_assert (!type);
9434       return tsubst_template_args (t, args, complain, in_decl);
9435
9436     case POINTER_TYPE:
9437     case REFERENCE_TYPE:
9438       {
9439         enum tree_code code;
9440
9441         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9442           return t;
9443
9444         code = TREE_CODE (t);
9445
9446
9447         /* [temp.deduct]
9448
9449            Type deduction may fail for any of the following
9450            reasons:
9451
9452            -- Attempting to create a pointer to reference type.
9453            -- Attempting to create a reference to a reference type or
9454               a reference to void.
9455
9456           Core issue 106 says that creating a reference to a reference
9457           during instantiation is no longer a cause for failure. We
9458           only enforce this check in strict C++98 mode.  */
9459         if ((TREE_CODE (type) == REFERENCE_TYPE
9460              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9461             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9462           {
9463             static location_t last_loc;
9464
9465             /* We keep track of the last time we issued this error
9466                message to avoid spewing a ton of messages during a
9467                single bad template instantiation.  */
9468             if (complain & tf_error
9469                 && last_loc != input_location)
9470               {
9471                 if (TREE_CODE (type) == VOID_TYPE)
9472                   error ("forming reference to void");
9473                 else
9474                   error ("forming %s to reference type %qT",
9475                          (code == POINTER_TYPE) ? "pointer" : "reference",
9476                          type);
9477                 last_loc = input_location;
9478               }
9479
9480             return error_mark_node;
9481           }
9482         else if (code == POINTER_TYPE)
9483           {
9484             r = build_pointer_type (type);
9485             if (TREE_CODE (type) == METHOD_TYPE)
9486               r = build_ptrmemfunc_type (r);
9487           }
9488         else if (TREE_CODE (type) == REFERENCE_TYPE)
9489           /* In C++0x, during template argument substitution, when there is an
9490              attempt to create a reference to a reference type, reference
9491              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9492
9493              "If a template-argument for a template-parameter T names a type
9494              that is a reference to a type A, an attempt to create the type
9495              'lvalue reference to cv T' creates the type 'lvalue reference to
9496              A,' while an attempt to create the type type rvalue reference to
9497              cv T' creates the type T"
9498           */
9499           r = cp_build_reference_type
9500               (TREE_TYPE (type),
9501                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9502         else
9503           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9504         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9505
9506         if (r != error_mark_node)
9507           /* Will this ever be needed for TYPE_..._TO values?  */
9508           layout_type (r);
9509
9510         return r;
9511       }
9512     case OFFSET_TYPE:
9513       {
9514         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9515         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9516           {
9517             /* [temp.deduct]
9518
9519                Type deduction may fail for any of the following
9520                reasons:
9521
9522                -- Attempting to create "pointer to member of T" when T
9523                   is not a class type.  */
9524             if (complain & tf_error)
9525               error ("creating pointer to member of non-class type %qT", r);
9526             return error_mark_node;
9527           }
9528         if (TREE_CODE (type) == REFERENCE_TYPE)
9529           {
9530             if (complain & tf_error)
9531               error ("creating pointer to member reference type %qT", type);
9532             return error_mark_node;
9533           }
9534         if (TREE_CODE (type) == VOID_TYPE)
9535           {
9536             if (complain & tf_error)
9537               error ("creating pointer to member of type void");
9538             return error_mark_node;
9539           }
9540         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9541         if (TREE_CODE (type) == FUNCTION_TYPE)
9542           {
9543             /* The type of the implicit object parameter gets its
9544                cv-qualifiers from the FUNCTION_TYPE. */
9545             tree method_type;
9546             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9547                                                       cp_type_quals (type));
9548             tree memptr;
9549             method_type = build_method_type_directly (this_type,
9550                                                       TREE_TYPE (type),
9551                                                       TYPE_ARG_TYPES (type));
9552             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9553             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9554                                                  complain);
9555           }
9556         else
9557           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9558                                                TYPE_QUALS (t),
9559                                                complain);
9560       }
9561     case FUNCTION_TYPE:
9562     case METHOD_TYPE:
9563       {
9564         tree fntype;
9565         tree specs;
9566         fntype = tsubst_function_type (t, args, complain, in_decl);
9567         if (fntype == error_mark_node)
9568           return error_mark_node;
9569
9570         /* Substitute the exception specification.  */
9571         specs = tsubst_exception_specification (t, args, complain,
9572                                                 in_decl);
9573         if (specs == error_mark_node)
9574           return error_mark_node;
9575         if (specs)
9576           fntype = build_exception_variant (fntype, specs);
9577         return fntype;
9578       }
9579     case ARRAY_TYPE:
9580       {
9581         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9582         if (domain == error_mark_node)
9583           return error_mark_node;
9584
9585         /* As an optimization, we avoid regenerating the array type if
9586            it will obviously be the same as T.  */
9587         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9588           return t;
9589
9590         /* These checks should match the ones in grokdeclarator.
9591
9592            [temp.deduct]
9593
9594            The deduction may fail for any of the following reasons:
9595
9596            -- Attempting to create an array with an element type that
9597               is void, a function type, or a reference type, or [DR337]
9598               an abstract class type.  */
9599         if (TREE_CODE (type) == VOID_TYPE
9600             || TREE_CODE (type) == FUNCTION_TYPE
9601             || TREE_CODE (type) == REFERENCE_TYPE)
9602           {
9603             if (complain & tf_error)
9604               error ("creating array of %qT", type);
9605             return error_mark_node;
9606           }
9607         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9608           {
9609             if (complain & tf_error)
9610               error ("creating array of %qT, which is an abstract class type",
9611                      type);
9612             return error_mark_node;
9613           }
9614
9615         r = build_cplus_array_type (type, domain);
9616
9617         if (TYPE_USER_ALIGN (t))
9618           {
9619             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9620             TYPE_USER_ALIGN (r) = 1;
9621           }
9622
9623         return r;
9624       }
9625
9626     case PLUS_EXPR:
9627     case MINUS_EXPR:
9628       {
9629         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9630         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9631
9632         if (e1 == error_mark_node || e2 == error_mark_node)
9633           return error_mark_node;
9634
9635         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9636       }
9637
9638     case NEGATE_EXPR:
9639     case NOP_EXPR:
9640       {
9641         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9642         if (e == error_mark_node)
9643           return error_mark_node;
9644
9645         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9646       }
9647
9648     case TYPENAME_TYPE:
9649       {
9650         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9651                                      in_decl, /*entering_scope=*/1);
9652         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9653                               complain, in_decl);
9654
9655         if (ctx == error_mark_node || f == error_mark_node)
9656           return error_mark_node;
9657
9658         if (!MAYBE_CLASS_TYPE_P (ctx))
9659           {
9660             if (complain & tf_error)
9661               error ("%qT is not a class, struct, or union type", ctx);
9662             return error_mark_node;
9663           }
9664         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9665           {
9666             /* Normally, make_typename_type does not require that the CTX
9667                have complete type in order to allow things like:
9668
9669                  template <class T> struct S { typename S<T>::X Y; };
9670
9671                But, such constructs have already been resolved by this
9672                point, so here CTX really should have complete type, unless
9673                it's a partial instantiation.  */
9674             ctx = complete_type (ctx);
9675             if (!COMPLETE_TYPE_P (ctx))
9676               {
9677                 if (complain & tf_error)
9678                   cxx_incomplete_type_error (NULL_TREE, ctx);
9679                 return error_mark_node;
9680               }
9681           }
9682
9683         f = make_typename_type (ctx, f, typename_type,
9684                                 (complain & tf_error) | tf_keep_type_decl);
9685         if (f == error_mark_node)
9686           return f;
9687         if (TREE_CODE (f) == TYPE_DECL)
9688           {
9689             complain |= tf_ignore_bad_quals;
9690             f = TREE_TYPE (f);
9691           }
9692
9693         if (TREE_CODE (f) != TYPENAME_TYPE)
9694           {
9695             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9696               error ("%qT resolves to %qT, which is not an enumeration type",
9697                      t, f);
9698             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9699               error ("%qT resolves to %qT, which is is not a class type",
9700                      t, f);
9701           }
9702
9703         return cp_build_qualified_type_real
9704           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9705       }
9706
9707     case UNBOUND_CLASS_TEMPLATE:
9708       {
9709         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9710                                      in_decl, /*entering_scope=*/1);
9711         tree name = TYPE_IDENTIFIER (t);
9712         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9713
9714         if (ctx == error_mark_node || name == error_mark_node)
9715           return error_mark_node;
9716
9717         if (parm_list)
9718           parm_list = tsubst_template_parms (parm_list, args, complain);
9719         return make_unbound_class_template (ctx, name, parm_list, complain);
9720       }
9721
9722     case INDIRECT_REF:
9723     case ADDR_EXPR:
9724     case CALL_EXPR:
9725       gcc_unreachable ();
9726
9727     case ARRAY_REF:
9728       {
9729         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9730         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9731                                /*integral_constant_expression_p=*/false);
9732         if (e1 == error_mark_node || e2 == error_mark_node)
9733           return error_mark_node;
9734
9735         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9736       }
9737
9738     case SCOPE_REF:
9739       {
9740         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9741         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9742         if (e1 == error_mark_node || e2 == error_mark_node)
9743           return error_mark_node;
9744
9745         return build_qualified_name (/*type=*/NULL_TREE,
9746                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9747       }
9748
9749     case TYPEOF_TYPE:
9750       {
9751         tree type;
9752
9753         type = finish_typeof (tsubst_expr 
9754                               (TYPEOF_TYPE_EXPR (t), args,
9755                                complain, in_decl,
9756                                /*integral_constant_expression_p=*/false));
9757         return cp_build_qualified_type_real (type,
9758                                              cp_type_quals (t)
9759                                              | cp_type_quals (type),
9760                                              complain);
9761       }
9762
9763     case DECLTYPE_TYPE:
9764       {
9765         tree type;
9766
9767         ++skip_evaluation;
9768
9769         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9770                             complain, in_decl,
9771                             /*integral_constant_expression_p=*/false);
9772
9773         --skip_evaluation;
9774
9775         type =
9776           finish_decltype_type (type,
9777                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9778         return cp_build_qualified_type_real (type,
9779                                              cp_type_quals (t)
9780                                              | cp_type_quals (type),
9781                                              complain);
9782       }
9783
9784     case TYPE_ARGUMENT_PACK:
9785     case NONTYPE_ARGUMENT_PACK:
9786       {
9787         tree r = make_node (TREE_CODE (t));
9788         tree packed_out = 
9789           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9790                                 args,
9791                                 complain,
9792                                 in_decl);
9793         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9794
9795         /* For template nontype argument packs, also substitute into
9796            the type.  */
9797         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9798           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9799
9800         return r;
9801       }
9802       break;
9803
9804     default:
9805       sorry ("use of %qs in template",
9806              tree_code_name [(int) TREE_CODE (t)]);
9807       return error_mark_node;
9808     }
9809 }
9810
9811 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9812    type of the expression on the left-hand side of the "." or "->"
9813    operator.  */
9814
9815 static tree
9816 tsubst_baselink (tree baselink, tree object_type,
9817                  tree args, tsubst_flags_t complain, tree in_decl)
9818 {
9819     tree name;
9820     tree qualifying_scope;
9821     tree fns;
9822     tree optype;
9823     tree template_args = 0;
9824     bool template_id_p = false;
9825
9826     /* A baselink indicates a function from a base class.  Both the
9827        BASELINK_ACCESS_BINFO and the base class referenced may
9828        indicate bases of the template class, rather than the
9829        instantiated class.  In addition, lookups that were not
9830        ambiguous before may be ambiguous now.  Therefore, we perform
9831        the lookup again.  */
9832     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9833     qualifying_scope = tsubst (qualifying_scope, args,
9834                                complain, in_decl);
9835     fns = BASELINK_FUNCTIONS (baselink);
9836     optype = BASELINK_OPTYPE (baselink);
9837     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9838       {
9839         template_id_p = true;
9840         template_args = TREE_OPERAND (fns, 1);
9841         fns = TREE_OPERAND (fns, 0);
9842         if (template_args)
9843           template_args = tsubst_template_args (template_args, args,
9844                                                 complain, in_decl);
9845       }
9846     name = DECL_NAME (get_first_fn (fns));
9847     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9848
9849     /* If lookup found a single function, mark it as used at this
9850        point.  (If it lookup found multiple functions the one selected
9851        later by overload resolution will be marked as used at that
9852        point.)  */
9853     if (BASELINK_P (baselink))
9854       fns = BASELINK_FUNCTIONS (baselink);
9855     if (!template_id_p && !really_overloaded_fn (fns))
9856       mark_used (OVL_CURRENT (fns));
9857
9858     /* Add back the template arguments, if present.  */
9859     if (BASELINK_P (baselink) && template_id_p)
9860       BASELINK_FUNCTIONS (baselink)
9861         = build_nt (TEMPLATE_ID_EXPR,
9862                     BASELINK_FUNCTIONS (baselink),
9863                     template_args);
9864     /* Update the conversion operator type.  */
9865     BASELINK_OPTYPE (baselink) 
9866       = tsubst (optype, args, complain, in_decl);
9867
9868     if (!object_type)
9869       object_type = current_class_type;
9870     return adjust_result_of_qualified_name_lookup (baselink,
9871                                                    qualifying_scope,
9872                                                    object_type);
9873 }
9874
9875 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9876    true if the qualified-id will be a postfix-expression in-and-of
9877    itself; false if more of the postfix-expression follows the
9878    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9879    of "&".  */
9880
9881 static tree
9882 tsubst_qualified_id (tree qualified_id, tree args,
9883                      tsubst_flags_t complain, tree in_decl,
9884                      bool done, bool address_p)
9885 {
9886   tree expr;
9887   tree scope;
9888   tree name;
9889   bool is_template;
9890   tree template_args;
9891
9892   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9893
9894   /* Figure out what name to look up.  */
9895   name = TREE_OPERAND (qualified_id, 1);
9896   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9897     {
9898       is_template = true;
9899       template_args = TREE_OPERAND (name, 1);
9900       if (template_args)
9901         template_args = tsubst_template_args (template_args, args,
9902                                               complain, in_decl);
9903       name = TREE_OPERAND (name, 0);
9904     }
9905   else
9906     {
9907       is_template = false;
9908       template_args = NULL_TREE;
9909     }
9910
9911   /* Substitute into the qualifying scope.  When there are no ARGS, we
9912      are just trying to simplify a non-dependent expression.  In that
9913      case the qualifying scope may be dependent, and, in any case,
9914      substituting will not help.  */
9915   scope = TREE_OPERAND (qualified_id, 0);
9916   if (args)
9917     {
9918       scope = tsubst (scope, args, complain, in_decl);
9919       expr = tsubst_copy (name, args, complain, in_decl);
9920     }
9921   else
9922     expr = name;
9923
9924   if (dependent_type_p (scope))
9925     return build_qualified_name (/*type=*/NULL_TREE,
9926                                  scope, expr,
9927                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9928
9929   if (!BASELINK_P (name) && !DECL_P (expr))
9930     {
9931       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9932         /* If this were actually a destructor call, it would have been
9933            parsed as such by the parser.  */
9934         expr = error_mark_node;
9935       else
9936         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9937       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9938                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9939         {
9940           if (complain & tf_error)
9941             {
9942               error ("dependent-name %qE is parsed as a non-type, but "
9943                      "instantiation yields a type", qualified_id);
9944               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
9945             }
9946           return error_mark_node;
9947         }
9948     }
9949
9950   if (DECL_P (expr))
9951     {
9952       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9953                                            scope);
9954       /* Remember that there was a reference to this entity.  */
9955       mark_used (expr);
9956     }
9957
9958   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9959     {
9960       if (complain & tf_error)
9961         qualified_name_lookup_error (scope,
9962                                      TREE_OPERAND (qualified_id, 1),
9963                                      expr, input_location);
9964       return error_mark_node;
9965     }
9966
9967   if (is_template)
9968     expr = lookup_template_function (expr, template_args);
9969
9970   if (expr == error_mark_node && complain & tf_error)
9971     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9972                                  expr, input_location);
9973   else if (TYPE_P (scope))
9974     {
9975       expr = (adjust_result_of_qualified_name_lookup
9976               (expr, scope, current_class_type));
9977       expr = (finish_qualified_id_expr
9978               (scope, expr, done, address_p,
9979                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9980                /*template_arg_p=*/false));
9981     }
9982
9983   /* Expressions do not generally have reference type.  */
9984   if (TREE_CODE (expr) != SCOPE_REF
9985       /* However, if we're about to form a pointer-to-member, we just
9986          want the referenced member referenced.  */
9987       && TREE_CODE (expr) != OFFSET_REF)
9988     expr = convert_from_reference (expr);
9989
9990   return expr;
9991 }
9992
9993 /* Like tsubst, but deals with expressions.  This function just replaces
9994    template parms; to finish processing the resultant expression, use
9995    tsubst_expr.  */
9996
9997 static tree
9998 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9999 {
10000   enum tree_code code;
10001   tree r;
10002
10003   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10004     return t;
10005
10006   code = TREE_CODE (t);
10007
10008   switch (code)
10009     {
10010     case PARM_DECL:
10011       r = retrieve_local_specialization (t);
10012
10013       if (r == NULL)
10014         {
10015           /* This can happen for a parameter name used later in a function
10016              declaration (such as in a late-specified return type).  Just
10017              make a dummy decl, since it's only used for its type.  */
10018           gcc_assert (skip_evaluation);   
10019           r = tsubst_decl (t, args, complain);
10020           /* Give it the template pattern as its context; its true context
10021              hasn't been instantiated yet and this is good enough for
10022              mangling.  */
10023           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10024         }
10025       
10026       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10027         r = ARGUMENT_PACK_SELECT_ARG (r);
10028       mark_used (r);
10029       return r;
10030
10031     case CONST_DECL:
10032       {
10033         tree enum_type;
10034         tree v;
10035
10036         if (DECL_TEMPLATE_PARM_P (t))
10037           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10038         /* There is no need to substitute into namespace-scope
10039            enumerators.  */
10040         if (DECL_NAMESPACE_SCOPE_P (t))
10041           return t;
10042         /* If ARGS is NULL, then T is known to be non-dependent.  */
10043         if (args == NULL_TREE)
10044           return integral_constant_value (t);
10045
10046         /* Unfortunately, we cannot just call lookup_name here.
10047            Consider:
10048
10049              template <int I> int f() {
10050              enum E { a = I };
10051              struct S { void g() { E e = a; } };
10052              };
10053
10054            When we instantiate f<7>::S::g(), say, lookup_name is not
10055            clever enough to find f<7>::a.  */
10056         enum_type
10057           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10058                               /*entering_scope=*/0);
10059
10060         for (v = TYPE_VALUES (enum_type);
10061              v != NULL_TREE;
10062              v = TREE_CHAIN (v))
10063           if (TREE_PURPOSE (v) == DECL_NAME (t))
10064             return TREE_VALUE (v);
10065
10066           /* We didn't find the name.  That should never happen; if
10067              name-lookup found it during preliminary parsing, we
10068              should find it again here during instantiation.  */
10069         gcc_unreachable ();
10070       }
10071       return t;
10072
10073     case FIELD_DECL:
10074       if (DECL_CONTEXT (t))
10075         {
10076           tree ctx;
10077
10078           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10079                                   /*entering_scope=*/1);
10080           if (ctx != DECL_CONTEXT (t))
10081             {
10082               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10083               if (!r)
10084                 {
10085                   if (complain & tf_error)
10086                     error ("using invalid field %qD", t);
10087                   return error_mark_node;
10088                 }
10089               return r;
10090             }
10091         }
10092
10093       return t;
10094
10095     case VAR_DECL:
10096     case FUNCTION_DECL:
10097       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10098           || local_variable_p (t))
10099         t = tsubst (t, args, complain, in_decl);
10100       mark_used (t);
10101       return t;
10102
10103     case BASELINK:
10104       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10105
10106     case TEMPLATE_DECL:
10107       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10108         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10109                        args, complain, in_decl);
10110       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10111         return tsubst (t, args, complain, in_decl);
10112       else if (DECL_CLASS_SCOPE_P (t)
10113                && uses_template_parms (DECL_CONTEXT (t)))
10114         {
10115           /* Template template argument like the following example need
10116              special treatment:
10117
10118                template <template <class> class TT> struct C {};
10119                template <class T> struct D {
10120                  template <class U> struct E {};
10121                  C<E> c;                                // #1
10122                };
10123                D<int> d;                                // #2
10124
10125              We are processing the template argument `E' in #1 for
10126              the template instantiation #2.  Originally, `E' is a
10127              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10128              have to substitute this with one having context `D<int>'.  */
10129
10130           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10131           return lookup_field (context, DECL_NAME(t), 0, false);
10132         }
10133       else
10134         /* Ordinary template template argument.  */
10135         return t;
10136
10137     case CAST_EXPR:
10138     case REINTERPRET_CAST_EXPR:
10139     case CONST_CAST_EXPR:
10140     case STATIC_CAST_EXPR:
10141     case DYNAMIC_CAST_EXPR:
10142     case NOP_EXPR:
10143       return build1
10144         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10145          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10146
10147     case SIZEOF_EXPR:
10148       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10149         {
10150           /* We only want to compute the number of arguments.  */
10151           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10152                                                 complain, in_decl);
10153           int len = 0;
10154
10155           if (TREE_CODE (expanded) == TREE_VEC)
10156             len = TREE_VEC_LENGTH (expanded);
10157
10158           if (expanded == error_mark_node)
10159             return error_mark_node;
10160           else if (PACK_EXPANSION_P (expanded)
10161                    || (TREE_CODE (expanded) == TREE_VEC
10162                        && len > 0
10163                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10164             {
10165               if (TREE_CODE (expanded) == TREE_VEC)
10166                 expanded = TREE_VEC_ELT (expanded, len - 1);
10167
10168               if (TYPE_P (expanded))
10169                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10170                                                    complain & tf_error);
10171               else
10172                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10173                                                    complain & tf_error);
10174             }
10175           else
10176             return build_int_cst (size_type_node, len);
10177         }
10178       /* Fall through */
10179
10180     case INDIRECT_REF:
10181     case NEGATE_EXPR:
10182     case TRUTH_NOT_EXPR:
10183     case BIT_NOT_EXPR:
10184     case ADDR_EXPR:
10185     case UNARY_PLUS_EXPR:      /* Unary + */
10186     case ALIGNOF_EXPR:
10187     case ARROW_EXPR:
10188     case THROW_EXPR:
10189     case TYPEID_EXPR:
10190     case REALPART_EXPR:
10191     case IMAGPART_EXPR:
10192       return build1
10193         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10194          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10195
10196     case COMPONENT_REF:
10197       {
10198         tree object;
10199         tree name;
10200
10201         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10202         name = TREE_OPERAND (t, 1);
10203         if (TREE_CODE (name) == BIT_NOT_EXPR)
10204           {
10205             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10206                                 complain, in_decl);
10207             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10208           }
10209         else if (TREE_CODE (name) == SCOPE_REF
10210                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10211           {
10212             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10213                                      complain, in_decl);
10214             name = TREE_OPERAND (name, 1);
10215             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10216                                 complain, in_decl);
10217             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10218             name = build_qualified_name (/*type=*/NULL_TREE,
10219                                          base, name,
10220                                          /*template_p=*/false);
10221           }
10222         else if (TREE_CODE (name) == BASELINK)
10223           name = tsubst_baselink (name,
10224                                   non_reference (TREE_TYPE (object)),
10225                                   args, complain,
10226                                   in_decl);
10227         else
10228           name = tsubst_copy (name, args, complain, in_decl);
10229         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10230       }
10231
10232     case PLUS_EXPR:
10233     case MINUS_EXPR:
10234     case MULT_EXPR:
10235     case TRUNC_DIV_EXPR:
10236     case CEIL_DIV_EXPR:
10237     case FLOOR_DIV_EXPR:
10238     case ROUND_DIV_EXPR:
10239     case EXACT_DIV_EXPR:
10240     case BIT_AND_EXPR:
10241     case BIT_IOR_EXPR:
10242     case BIT_XOR_EXPR:
10243     case TRUNC_MOD_EXPR:
10244     case FLOOR_MOD_EXPR:
10245     case TRUTH_ANDIF_EXPR:
10246     case TRUTH_ORIF_EXPR:
10247     case TRUTH_AND_EXPR:
10248     case TRUTH_OR_EXPR:
10249     case RSHIFT_EXPR:
10250     case LSHIFT_EXPR:
10251     case RROTATE_EXPR:
10252     case LROTATE_EXPR:
10253     case EQ_EXPR:
10254     case NE_EXPR:
10255     case MAX_EXPR:
10256     case MIN_EXPR:
10257     case LE_EXPR:
10258     case GE_EXPR:
10259     case LT_EXPR:
10260     case GT_EXPR:
10261     case COMPOUND_EXPR:
10262     case DOTSTAR_EXPR:
10263     case MEMBER_REF:
10264     case PREDECREMENT_EXPR:
10265     case PREINCREMENT_EXPR:
10266     case POSTDECREMENT_EXPR:
10267     case POSTINCREMENT_EXPR:
10268       return build_nt
10269         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10270          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10271
10272     case SCOPE_REF:
10273       return build_qualified_name (/*type=*/NULL_TREE,
10274                                    tsubst_copy (TREE_OPERAND (t, 0),
10275                                                 args, complain, in_decl),
10276                                    tsubst_copy (TREE_OPERAND (t, 1),
10277                                                 args, complain, in_decl),
10278                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10279
10280     case ARRAY_REF:
10281       return build_nt
10282         (ARRAY_REF,
10283          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10284          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10285          NULL_TREE, NULL_TREE);
10286
10287     case CALL_EXPR:
10288       {
10289         int n = VL_EXP_OPERAND_LENGTH (t);
10290         tree result = build_vl_exp (CALL_EXPR, n);
10291         int i;
10292         for (i = 0; i < n; i++)
10293           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10294                                              complain, in_decl);
10295         return result;
10296       }
10297
10298     case COND_EXPR:
10299     case MODOP_EXPR:
10300     case PSEUDO_DTOR_EXPR:
10301       {
10302         r = build_nt
10303           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10304            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10305            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10306         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10307         return r;
10308       }
10309
10310     case NEW_EXPR:
10311       {
10312         r = build_nt
10313         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10314          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10315          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10316         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10317         return r;
10318       }
10319
10320     case DELETE_EXPR:
10321       {
10322         r = build_nt
10323         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10324          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10325         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10326         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10327         return r;
10328       }
10329
10330     case TEMPLATE_ID_EXPR:
10331       {
10332         /* Substituted template arguments */
10333         tree fn = TREE_OPERAND (t, 0);
10334         tree targs = TREE_OPERAND (t, 1);
10335
10336         fn = tsubst_copy (fn, args, complain, in_decl);
10337         if (targs)
10338           targs = tsubst_template_args (targs, args, complain, in_decl);
10339
10340         return lookup_template_function (fn, targs);
10341       }
10342
10343     case TREE_LIST:
10344       {
10345         tree purpose, value, chain;
10346
10347         if (t == void_list_node)
10348           return t;
10349
10350         purpose = TREE_PURPOSE (t);
10351         if (purpose)
10352           purpose = tsubst_copy (purpose, args, complain, in_decl);
10353         value = TREE_VALUE (t);
10354         if (value)
10355           value = tsubst_copy (value, args, complain, in_decl);
10356         chain = TREE_CHAIN (t);
10357         if (chain && chain != void_type_node)
10358           chain = tsubst_copy (chain, args, complain, in_decl);
10359         if (purpose == TREE_PURPOSE (t)
10360             && value == TREE_VALUE (t)
10361             && chain == TREE_CHAIN (t))
10362           return t;
10363         return tree_cons (purpose, value, chain);
10364       }
10365
10366     case RECORD_TYPE:
10367     case UNION_TYPE:
10368     case ENUMERAL_TYPE:
10369     case INTEGER_TYPE:
10370     case TEMPLATE_TYPE_PARM:
10371     case TEMPLATE_TEMPLATE_PARM:
10372     case BOUND_TEMPLATE_TEMPLATE_PARM:
10373     case TEMPLATE_PARM_INDEX:
10374     case POINTER_TYPE:
10375     case REFERENCE_TYPE:
10376     case OFFSET_TYPE:
10377     case FUNCTION_TYPE:
10378     case METHOD_TYPE:
10379     case ARRAY_TYPE:
10380     case TYPENAME_TYPE:
10381     case UNBOUND_CLASS_TEMPLATE:
10382     case TYPEOF_TYPE:
10383     case DECLTYPE_TYPE:
10384     case TYPE_DECL:
10385       return tsubst (t, args, complain, in_decl);
10386
10387     case IDENTIFIER_NODE:
10388       if (IDENTIFIER_TYPENAME_P (t))
10389         {
10390           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10391           return mangle_conv_op_name_for_type (new_type);
10392         }
10393       else
10394         return t;
10395
10396     case CONSTRUCTOR:
10397       /* This is handled by tsubst_copy_and_build.  */
10398       gcc_unreachable ();
10399
10400     case VA_ARG_EXPR:
10401       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10402                                           in_decl),
10403                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10404
10405     case CLEANUP_POINT_EXPR:
10406       /* We shouldn't have built any of these during initial template
10407          generation.  Instead, they should be built during instantiation
10408          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10409       gcc_unreachable ();
10410
10411     case OFFSET_REF:
10412       mark_used (TREE_OPERAND (t, 1));
10413       return t;
10414
10415     case EXPR_PACK_EXPANSION:
10416       error ("invalid use of pack expansion expression");
10417       return error_mark_node;
10418
10419     case NONTYPE_ARGUMENT_PACK:
10420       error ("use %<...%> to expand argument pack");
10421       return error_mark_node;
10422
10423     default:
10424       return t;
10425     }
10426 }
10427
10428 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10429
10430 static tree
10431 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10432                     tree in_decl)
10433 {
10434   tree new_clauses = NULL, nc, oc;
10435
10436   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10437     {
10438       nc = copy_node (oc);
10439       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10440       new_clauses = nc;
10441
10442       switch (OMP_CLAUSE_CODE (nc))
10443         {
10444         case OMP_CLAUSE_LASTPRIVATE:
10445           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10446             {
10447               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10448               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10449                            in_decl, /*integral_constant_expression_p=*/false);
10450               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10451                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10452             }
10453           /* FALLTHRU */
10454         case OMP_CLAUSE_PRIVATE:
10455         case OMP_CLAUSE_SHARED:
10456         case OMP_CLAUSE_FIRSTPRIVATE:
10457         case OMP_CLAUSE_REDUCTION:
10458         case OMP_CLAUSE_COPYIN:
10459         case OMP_CLAUSE_COPYPRIVATE:
10460         case OMP_CLAUSE_IF:
10461         case OMP_CLAUSE_NUM_THREADS:
10462         case OMP_CLAUSE_SCHEDULE:
10463         case OMP_CLAUSE_COLLAPSE:
10464           OMP_CLAUSE_OPERAND (nc, 0)
10465             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10466                            in_decl, /*integral_constant_expression_p=*/false);
10467           break;
10468         case OMP_CLAUSE_NOWAIT:
10469         case OMP_CLAUSE_ORDERED:
10470         case OMP_CLAUSE_DEFAULT:
10471         case OMP_CLAUSE_UNTIED:
10472           break;
10473         default:
10474           gcc_unreachable ();
10475         }
10476     }
10477
10478   return finish_omp_clauses (nreverse (new_clauses));
10479 }
10480
10481 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10482
10483 static tree
10484 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10485                           tree in_decl)
10486 {
10487 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10488
10489   tree purpose, value, chain;
10490
10491   if (t == NULL)
10492     return t;
10493
10494   if (TREE_CODE (t) != TREE_LIST)
10495     return tsubst_copy_and_build (t, args, complain, in_decl,
10496                                   /*function_p=*/false,
10497                                   /*integral_constant_expression_p=*/false);
10498
10499   if (t == void_list_node)
10500     return t;
10501
10502   purpose = TREE_PURPOSE (t);
10503   if (purpose)
10504     purpose = RECUR (purpose);
10505   value = TREE_VALUE (t);
10506   if (value)
10507     value = RECUR (value);
10508   chain = TREE_CHAIN (t);
10509   if (chain && chain != void_type_node)
10510     chain = RECUR (chain);
10511   return tree_cons (purpose, value, chain);
10512 #undef RECUR
10513 }
10514
10515 /* Substitute one OMP_FOR iterator.  */
10516
10517 static void
10518 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10519                          tree condv, tree incrv, tree *clauses,
10520                          tree args, tsubst_flags_t complain, tree in_decl,
10521                          bool integral_constant_expression_p)
10522 {
10523 #define RECUR(NODE)                             \
10524   tsubst_expr ((NODE), args, complain, in_decl, \
10525                integral_constant_expression_p)
10526   tree decl, init, cond, incr, auto_node;
10527
10528   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10529   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10530   decl = RECUR (TREE_OPERAND (init, 0));
10531   init = TREE_OPERAND (init, 1);
10532   auto_node = type_uses_auto (TREE_TYPE (decl));
10533   if (auto_node && init)
10534     {
10535       tree init_expr = init;
10536       if (TREE_CODE (init_expr) == DECL_EXPR)
10537         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10538       init_expr = RECUR (init_expr);
10539       TREE_TYPE (decl)
10540         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10541     }
10542   gcc_assert (!type_dependent_expression_p (decl));
10543
10544   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10545     {
10546       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10547       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10548       if (TREE_CODE (incr) == MODIFY_EXPR)
10549         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10550                                     RECUR (TREE_OPERAND (incr, 1)),
10551                                     complain);
10552       else
10553         incr = RECUR (incr);
10554       TREE_VEC_ELT (declv, i) = decl;
10555       TREE_VEC_ELT (initv, i) = init;
10556       TREE_VEC_ELT (condv, i) = cond;
10557       TREE_VEC_ELT (incrv, i) = incr;
10558       return;
10559     }
10560
10561   if (init && TREE_CODE (init) != DECL_EXPR)
10562     {
10563       tree c;
10564       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10565         {
10566           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10567                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10568               && OMP_CLAUSE_DECL (c) == decl)
10569             break;
10570           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10571                    && OMP_CLAUSE_DECL (c) == decl)
10572             error ("iteration variable %qD should not be firstprivate", decl);
10573           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10574                    && OMP_CLAUSE_DECL (c) == decl)
10575             error ("iteration variable %qD should not be reduction", decl);
10576         }
10577       if (c == NULL)
10578         {
10579           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10580           OMP_CLAUSE_DECL (c) = decl;
10581           c = finish_omp_clauses (c);
10582           if (c)
10583             {
10584               OMP_CLAUSE_CHAIN (c) = *clauses;
10585               *clauses = c;
10586             }
10587         }
10588     }
10589   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10590   if (COMPARISON_CLASS_P (cond))
10591     cond = build2 (TREE_CODE (cond), boolean_type_node,
10592                    RECUR (TREE_OPERAND (cond, 0)),
10593                    RECUR (TREE_OPERAND (cond, 1)));
10594   else
10595     cond = RECUR (cond);
10596   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10597   switch (TREE_CODE (incr))
10598     {
10599     case PREINCREMENT_EXPR:
10600     case PREDECREMENT_EXPR:
10601     case POSTINCREMENT_EXPR:
10602     case POSTDECREMENT_EXPR:
10603       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10604                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10605       break;
10606     case MODIFY_EXPR:
10607       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10608           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10609         {
10610           tree rhs = TREE_OPERAND (incr, 1);
10611           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10612                          RECUR (TREE_OPERAND (incr, 0)),
10613                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10614                                  RECUR (TREE_OPERAND (rhs, 0)),
10615                                  RECUR (TREE_OPERAND (rhs, 1))));
10616         }
10617       else
10618         incr = RECUR (incr);
10619       break;
10620     case MODOP_EXPR:
10621       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10622           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10623         {
10624           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10625           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10626                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10627                                  TREE_TYPE (decl), lhs,
10628                                  RECUR (TREE_OPERAND (incr, 2))));
10629         }
10630       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10631                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10632                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10633         {
10634           tree rhs = TREE_OPERAND (incr, 2);
10635           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10636                          RECUR (TREE_OPERAND (incr, 0)),
10637                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10638                                  RECUR (TREE_OPERAND (rhs, 0)),
10639                                  RECUR (TREE_OPERAND (rhs, 1))));
10640         }
10641       else
10642         incr = RECUR (incr);
10643       break;
10644     default:
10645       incr = RECUR (incr);
10646       break;
10647     }
10648
10649   TREE_VEC_ELT (declv, i) = decl;
10650   TREE_VEC_ELT (initv, i) = init;
10651   TREE_VEC_ELT (condv, i) = cond;
10652   TREE_VEC_ELT (incrv, i) = incr;
10653 #undef RECUR
10654 }
10655
10656 /* Like tsubst_copy for expressions, etc. but also does semantic
10657    processing.  */
10658
10659 static tree
10660 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10661              bool integral_constant_expression_p)
10662 {
10663 #define RECUR(NODE)                             \
10664   tsubst_expr ((NODE), args, complain, in_decl, \
10665                integral_constant_expression_p)
10666
10667   tree stmt, tmp;
10668
10669   if (t == NULL_TREE || t == error_mark_node)
10670     return t;
10671
10672   if (EXPR_HAS_LOCATION (t))
10673     input_location = EXPR_LOCATION (t);
10674   if (STATEMENT_CODE_P (TREE_CODE (t)))
10675     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10676
10677   switch (TREE_CODE (t))
10678     {
10679     case STATEMENT_LIST:
10680       {
10681         tree_stmt_iterator i;
10682         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10683           RECUR (tsi_stmt (i));
10684         break;
10685       }
10686
10687     case CTOR_INITIALIZER:
10688       finish_mem_initializers (tsubst_initializer_list
10689                                (TREE_OPERAND (t, 0), args));
10690       break;
10691
10692     case RETURN_EXPR:
10693       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10694       break;
10695
10696     case EXPR_STMT:
10697       tmp = RECUR (EXPR_STMT_EXPR (t));
10698       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10699         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10700       else
10701         finish_expr_stmt (tmp);
10702       break;
10703
10704     case USING_STMT:
10705       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10706       break;
10707
10708     case DECL_EXPR:
10709       {
10710         tree decl;
10711         tree init;
10712
10713         decl = DECL_EXPR_DECL (t);
10714         if (TREE_CODE (decl) == LABEL_DECL)
10715           finish_label_decl (DECL_NAME (decl));
10716         else if (TREE_CODE (decl) == USING_DECL)
10717           {
10718             tree scope = USING_DECL_SCOPE (decl);
10719             tree name = DECL_NAME (decl);
10720             tree decl;
10721
10722             scope = RECUR (scope);
10723             decl = lookup_qualified_name (scope, name,
10724                                           /*is_type_p=*/false,
10725                                           /*complain=*/false);
10726             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10727               qualified_name_lookup_error (scope, name, decl, input_location);
10728             else
10729               do_local_using_decl (decl, scope, name);
10730           }
10731         else
10732           {
10733             init = DECL_INITIAL (decl);
10734             decl = tsubst (decl, args, complain, in_decl);
10735             if (decl != error_mark_node)
10736               {
10737                 /* By marking the declaration as instantiated, we avoid
10738                    trying to instantiate it.  Since instantiate_decl can't
10739                    handle local variables, and since we've already done
10740                    all that needs to be done, that's the right thing to
10741                    do.  */
10742                 if (TREE_CODE (decl) == VAR_DECL)
10743                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10744                 if (TREE_CODE (decl) == VAR_DECL
10745                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10746                   /* Anonymous aggregates are a special case.  */
10747                   finish_anon_union (decl);
10748                 else
10749                   {
10750                     maybe_push_decl (decl);
10751                     if (TREE_CODE (decl) == VAR_DECL
10752                         && DECL_PRETTY_FUNCTION_P (decl))
10753                       {
10754                         /* For __PRETTY_FUNCTION__ we have to adjust the
10755                            initializer.  */
10756                         const char *const name
10757                           = cxx_printable_name (current_function_decl, 2);
10758                         init = cp_fname_init (name, &TREE_TYPE (decl));
10759                       }
10760                     else
10761                       {
10762                         tree t = RECUR (init);
10763
10764                         if (init && !t)
10765                           /* If we had an initializer but it
10766                              instantiated to nothing,
10767                              value-initialize the object.  This will
10768                              only occur when the initializer was a
10769                              pack expansion where the parameter packs
10770                              used in that expansion were of length
10771                              zero.  */
10772                           init = build_value_init (TREE_TYPE (decl));
10773                         else
10774                           init = t;
10775                       }
10776
10777                     finish_decl (decl, init, NULL_TREE);
10778                   }
10779               }
10780           }
10781
10782         /* A DECL_EXPR can also be used as an expression, in the condition
10783            clause of an if/for/while construct.  */
10784         return decl;
10785       }
10786
10787     case FOR_STMT:
10788       stmt = begin_for_stmt ();
10789                           RECUR (FOR_INIT_STMT (t));
10790       finish_for_init_stmt (stmt);
10791       tmp = RECUR (FOR_COND (t));
10792       finish_for_cond (tmp, stmt);
10793       tmp = RECUR (FOR_EXPR (t));
10794       finish_for_expr (tmp, stmt);
10795       RECUR (FOR_BODY (t));
10796       finish_for_stmt (stmt);
10797       break;
10798
10799     case WHILE_STMT:
10800       stmt = begin_while_stmt ();
10801       tmp = RECUR (WHILE_COND (t));
10802       finish_while_stmt_cond (tmp, stmt);
10803       RECUR (WHILE_BODY (t));
10804       finish_while_stmt (stmt);
10805       break;
10806
10807     case DO_STMT:
10808       stmt = begin_do_stmt ();
10809       RECUR (DO_BODY (t));
10810       finish_do_body (stmt);
10811       tmp = RECUR (DO_COND (t));
10812       finish_do_stmt (tmp, stmt);
10813       break;
10814
10815     case IF_STMT:
10816       stmt = begin_if_stmt ();
10817       tmp = RECUR (IF_COND (t));
10818       finish_if_stmt_cond (tmp, stmt);
10819       RECUR (THEN_CLAUSE (t));
10820       finish_then_clause (stmt);
10821
10822       if (ELSE_CLAUSE (t))
10823         {
10824           begin_else_clause (stmt);
10825           RECUR (ELSE_CLAUSE (t));
10826           finish_else_clause (stmt);
10827         }
10828
10829       finish_if_stmt (stmt);
10830       break;
10831
10832     case BIND_EXPR:
10833       if (BIND_EXPR_BODY_BLOCK (t))
10834         stmt = begin_function_body ();
10835       else
10836         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10837                                     ? BCS_TRY_BLOCK : 0);
10838
10839       RECUR (BIND_EXPR_BODY (t));
10840
10841       if (BIND_EXPR_BODY_BLOCK (t))
10842         finish_function_body (stmt);
10843       else
10844         finish_compound_stmt (stmt);
10845       break;
10846
10847     case BREAK_STMT:
10848       finish_break_stmt ();
10849       break;
10850
10851     case CONTINUE_STMT:
10852       finish_continue_stmt ();
10853       break;
10854
10855     case SWITCH_STMT:
10856       stmt = begin_switch_stmt ();
10857       tmp = RECUR (SWITCH_STMT_COND (t));
10858       finish_switch_cond (tmp, stmt);
10859       RECUR (SWITCH_STMT_BODY (t));
10860       finish_switch_stmt (stmt);
10861       break;
10862
10863     case CASE_LABEL_EXPR:
10864       finish_case_label (RECUR (CASE_LOW (t)),
10865                          RECUR (CASE_HIGH (t)));
10866       break;
10867
10868     case LABEL_EXPR:
10869       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10870       break;
10871
10872     case GOTO_EXPR:
10873       tmp = GOTO_DESTINATION (t);
10874       if (TREE_CODE (tmp) != LABEL_DECL)
10875         /* Computed goto's must be tsubst'd into.  On the other hand,
10876            non-computed gotos must not be; the identifier in question
10877            will have no binding.  */
10878         tmp = RECUR (tmp);
10879       else
10880         tmp = DECL_NAME (tmp);
10881       finish_goto_stmt (tmp);
10882       break;
10883
10884     case ASM_EXPR:
10885       tmp = finish_asm_stmt
10886         (ASM_VOLATILE_P (t),
10887          RECUR (ASM_STRING (t)),
10888          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10889          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10890          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10891       {
10892         tree asm_expr = tmp;
10893         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10894           asm_expr = TREE_OPERAND (asm_expr, 0);
10895         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10896       }
10897       break;
10898
10899     case TRY_BLOCK:
10900       if (CLEANUP_P (t))
10901         {
10902           stmt = begin_try_block ();
10903           RECUR (TRY_STMTS (t));
10904           finish_cleanup_try_block (stmt);
10905           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10906         }
10907       else
10908         {
10909           tree compound_stmt = NULL_TREE;
10910
10911           if (FN_TRY_BLOCK_P (t))
10912             stmt = begin_function_try_block (&compound_stmt);
10913           else
10914             stmt = begin_try_block ();
10915
10916           RECUR (TRY_STMTS (t));
10917
10918           if (FN_TRY_BLOCK_P (t))
10919             finish_function_try_block (stmt);
10920           else
10921             finish_try_block (stmt);
10922
10923           RECUR (TRY_HANDLERS (t));
10924           if (FN_TRY_BLOCK_P (t))
10925             finish_function_handler_sequence (stmt, compound_stmt);
10926           else
10927             finish_handler_sequence (stmt);
10928         }
10929       break;
10930
10931     case HANDLER:
10932       {
10933         tree decl = HANDLER_PARMS (t);
10934
10935         if (decl)
10936           {
10937             decl = tsubst (decl, args, complain, in_decl);
10938             /* Prevent instantiate_decl from trying to instantiate
10939                this variable.  We've already done all that needs to be
10940                done.  */
10941             if (decl != error_mark_node)
10942               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10943           }
10944         stmt = begin_handler ();
10945         finish_handler_parms (decl, stmt);
10946         RECUR (HANDLER_BODY (t));
10947         finish_handler (stmt);
10948       }
10949       break;
10950
10951     case TAG_DEFN:
10952       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10953       break;
10954
10955     case STATIC_ASSERT:
10956       {
10957         tree condition = 
10958           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10959                        args,
10960                        complain, in_decl,
10961                        /*integral_constant_expression_p=*/true);
10962         finish_static_assert (condition,
10963                               STATIC_ASSERT_MESSAGE (t),
10964                               STATIC_ASSERT_SOURCE_LOCATION (t),
10965                               /*member_p=*/false);
10966       }
10967       break;
10968
10969     case OMP_PARALLEL:
10970       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10971                                 args, complain, in_decl);
10972       stmt = begin_omp_parallel ();
10973       RECUR (OMP_PARALLEL_BODY (t));
10974       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10975         = OMP_PARALLEL_COMBINED (t);
10976       break;
10977
10978     case OMP_TASK:
10979       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
10980                                 args, complain, in_decl);
10981       stmt = begin_omp_task ();
10982       RECUR (OMP_TASK_BODY (t));
10983       finish_omp_task (tmp, stmt);
10984       break;
10985
10986     case OMP_FOR:
10987       {
10988         tree clauses, body, pre_body;
10989         tree declv, initv, condv, incrv;
10990         int i;
10991
10992         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10993                                       args, complain, in_decl);
10994         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10995         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10996         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10997         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10998
10999         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11000           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11001                                    &clauses, args, complain, in_decl,
11002                                    integral_constant_expression_p);
11003
11004         stmt = begin_omp_structured_block ();
11005
11006         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11007           if (TREE_VEC_ELT (initv, i) == NULL
11008               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11009             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11010           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11011             {
11012               tree init = RECUR (TREE_VEC_ELT (initv, i));
11013               gcc_assert (init == TREE_VEC_ELT (declv, i));
11014               TREE_VEC_ELT (initv, i) = NULL_TREE;
11015             }
11016           else
11017             {
11018               tree decl_expr = TREE_VEC_ELT (initv, i);
11019               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11020               gcc_assert (init != NULL);
11021               TREE_VEC_ELT (initv, i) = RECUR (init);
11022               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11023               RECUR (decl_expr);
11024               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11025             }
11026
11027         pre_body = push_stmt_list ();
11028         RECUR (OMP_FOR_PRE_BODY (t));
11029         pre_body = pop_stmt_list (pre_body);
11030
11031         body = push_stmt_list ();
11032         RECUR (OMP_FOR_BODY (t));
11033         body = pop_stmt_list (body);
11034
11035         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11036                             body, pre_body, clauses);
11037
11038         add_stmt (finish_omp_structured_block (stmt));
11039       }
11040       break;
11041
11042     case OMP_SECTIONS:
11043     case OMP_SINGLE:
11044       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11045       stmt = push_stmt_list ();
11046       RECUR (OMP_BODY (t));
11047       stmt = pop_stmt_list (stmt);
11048
11049       t = copy_node (t);
11050       OMP_BODY (t) = stmt;
11051       OMP_CLAUSES (t) = tmp;
11052       add_stmt (t);
11053       break;
11054
11055     case OMP_SECTION:
11056     case OMP_CRITICAL:
11057     case OMP_MASTER:
11058     case OMP_ORDERED:
11059       stmt = push_stmt_list ();
11060       RECUR (OMP_BODY (t));
11061       stmt = pop_stmt_list (stmt);
11062
11063       t = copy_node (t);
11064       OMP_BODY (t) = stmt;
11065       add_stmt (t);
11066       break;
11067
11068     case OMP_ATOMIC:
11069       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11070       {
11071         tree op1 = TREE_OPERAND (t, 1);
11072         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11073         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11074         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11075       }
11076       break;
11077
11078     case EXPR_PACK_EXPANSION:
11079       error ("invalid use of pack expansion expression");
11080       return error_mark_node;
11081
11082     case NONTYPE_ARGUMENT_PACK:
11083       error ("use %<...%> to expand argument pack");
11084       return error_mark_node;
11085
11086     default:
11087       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11088
11089       return tsubst_copy_and_build (t, args, complain, in_decl,
11090                                     /*function_p=*/false,
11091                                     integral_constant_expression_p);
11092     }
11093
11094   return NULL_TREE;
11095 #undef RECUR
11096 }
11097
11098 /* T is a postfix-expression that is not being used in a function
11099    call.  Return the substituted version of T.  */
11100
11101 static tree
11102 tsubst_non_call_postfix_expression (tree t, tree args,
11103                                     tsubst_flags_t complain,
11104                                     tree in_decl)
11105 {
11106   if (TREE_CODE (t) == SCOPE_REF)
11107     t = tsubst_qualified_id (t, args, complain, in_decl,
11108                              /*done=*/false, /*address_p=*/false);
11109   else
11110     t = tsubst_copy_and_build (t, args, complain, in_decl,
11111                                /*function_p=*/false,
11112                                /*integral_constant_expression_p=*/false);
11113
11114   return t;
11115 }
11116
11117 /* Like tsubst but deals with expressions and performs semantic
11118    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11119
11120 tree
11121 tsubst_copy_and_build (tree t,
11122                        tree args,
11123                        tsubst_flags_t complain,
11124                        tree in_decl,
11125                        bool function_p,
11126                        bool integral_constant_expression_p)
11127 {
11128 #define RECUR(NODE)                                             \
11129   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11130                          /*function_p=*/false,                  \
11131                          integral_constant_expression_p)
11132
11133   tree op1;
11134
11135   if (t == NULL_TREE || t == error_mark_node)
11136     return t;
11137
11138   switch (TREE_CODE (t))
11139     {
11140     case USING_DECL:
11141       t = DECL_NAME (t);
11142       /* Fall through.  */
11143     case IDENTIFIER_NODE:
11144       {
11145         tree decl;
11146         cp_id_kind idk;
11147         bool non_integral_constant_expression_p;
11148         const char *error_msg;
11149
11150         if (IDENTIFIER_TYPENAME_P (t))
11151           {
11152             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11153             t = mangle_conv_op_name_for_type (new_type);
11154           }
11155
11156         /* Look up the name.  */
11157         decl = lookup_name (t);
11158
11159         /* By convention, expressions use ERROR_MARK_NODE to indicate
11160            failure, not NULL_TREE.  */
11161         if (decl == NULL_TREE)
11162           decl = error_mark_node;
11163
11164         decl = finish_id_expression (t, decl, NULL_TREE,
11165                                      &idk,
11166                                      integral_constant_expression_p,
11167                                      /*allow_non_integral_constant_expression_p=*/false,
11168                                      &non_integral_constant_expression_p,
11169                                      /*template_p=*/false,
11170                                      /*done=*/true,
11171                                      /*address_p=*/false,
11172                                      /*template_arg_p=*/false,
11173                                      &error_msg,
11174                                      input_location);
11175         if (error_msg)
11176           error (error_msg);
11177         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11178           decl = unqualified_name_lookup_error (decl);
11179         return decl;
11180       }
11181
11182     case TEMPLATE_ID_EXPR:
11183       {
11184         tree object;
11185         tree templ = RECUR (TREE_OPERAND (t, 0));
11186         tree targs = TREE_OPERAND (t, 1);
11187
11188         if (targs)
11189           targs = tsubst_template_args (targs, args, complain, in_decl);
11190
11191         if (TREE_CODE (templ) == COMPONENT_REF)
11192           {
11193             object = TREE_OPERAND (templ, 0);
11194             templ = TREE_OPERAND (templ, 1);
11195           }
11196         else
11197           object = NULL_TREE;
11198         templ = lookup_template_function (templ, targs);
11199
11200         if (object)
11201           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11202                          object, templ, NULL_TREE);
11203         else
11204           return baselink_for_fns (templ);
11205       }
11206
11207     case INDIRECT_REF:
11208       {
11209         tree r = RECUR (TREE_OPERAND (t, 0));
11210
11211         if (REFERENCE_REF_P (t))
11212           {
11213             /* A type conversion to reference type will be enclosed in
11214                such an indirect ref, but the substitution of the cast
11215                will have also added such an indirect ref.  */
11216             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11217               r = convert_from_reference (r);
11218           }
11219         else
11220           r = build_x_indirect_ref (r, "unary *", complain);
11221         return r;
11222       }
11223
11224     case NOP_EXPR:
11225       return build_nop
11226         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11227          RECUR (TREE_OPERAND (t, 0)));
11228
11229     case CAST_EXPR:
11230     case REINTERPRET_CAST_EXPR:
11231     case CONST_CAST_EXPR:
11232     case DYNAMIC_CAST_EXPR:
11233     case STATIC_CAST_EXPR:
11234       {
11235         tree type;
11236         tree op;
11237
11238         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11239         if (integral_constant_expression_p
11240             && !cast_valid_in_integral_constant_expression_p (type))
11241           {
11242             if (complain & tf_error)
11243               error ("a cast to a type other than an integral or "
11244                      "enumeration type cannot appear in a constant-expression");
11245             return error_mark_node; 
11246           }
11247
11248         op = RECUR (TREE_OPERAND (t, 0));
11249
11250         switch (TREE_CODE (t))
11251           {
11252           case CAST_EXPR:
11253             return build_functional_cast (type, op, complain);
11254           case REINTERPRET_CAST_EXPR:
11255             return build_reinterpret_cast (type, op, complain);
11256           case CONST_CAST_EXPR:
11257             return build_const_cast (type, op, complain);
11258           case DYNAMIC_CAST_EXPR:
11259             return build_dynamic_cast (type, op, complain);
11260           case STATIC_CAST_EXPR:
11261             return build_static_cast (type, op, complain);
11262           default:
11263             gcc_unreachable ();
11264           }
11265       }
11266
11267     case POSTDECREMENT_EXPR:
11268     case POSTINCREMENT_EXPR:
11269       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11270                                                 args, complain, in_decl);
11271       return build_x_unary_op (TREE_CODE (t), op1, complain);
11272
11273     case PREDECREMENT_EXPR:
11274     case PREINCREMENT_EXPR:
11275     case NEGATE_EXPR:
11276     case BIT_NOT_EXPR:
11277     case ABS_EXPR:
11278     case TRUTH_NOT_EXPR:
11279     case UNARY_PLUS_EXPR:  /* Unary + */
11280     case REALPART_EXPR:
11281     case IMAGPART_EXPR:
11282       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11283                                complain);
11284
11285     case ADDR_EXPR:
11286       op1 = TREE_OPERAND (t, 0);
11287       if (TREE_CODE (op1) == SCOPE_REF)
11288         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11289                                    /*done=*/true, /*address_p=*/true);
11290       else
11291         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11292                                                   in_decl);
11293       if (TREE_CODE (op1) == LABEL_DECL)
11294         return finish_label_address_expr (DECL_NAME (op1),
11295                                           EXPR_LOCATION (op1));
11296       return build_x_unary_op (ADDR_EXPR, op1, complain);
11297
11298     case PLUS_EXPR:
11299     case MINUS_EXPR:
11300     case MULT_EXPR:
11301     case TRUNC_DIV_EXPR:
11302     case CEIL_DIV_EXPR:
11303     case FLOOR_DIV_EXPR:
11304     case ROUND_DIV_EXPR:
11305     case EXACT_DIV_EXPR:
11306     case BIT_AND_EXPR:
11307     case BIT_IOR_EXPR:
11308     case BIT_XOR_EXPR:
11309     case TRUNC_MOD_EXPR:
11310     case FLOOR_MOD_EXPR:
11311     case TRUTH_ANDIF_EXPR:
11312     case TRUTH_ORIF_EXPR:
11313     case TRUTH_AND_EXPR:
11314     case TRUTH_OR_EXPR:
11315     case RSHIFT_EXPR:
11316     case LSHIFT_EXPR:
11317     case RROTATE_EXPR:
11318     case LROTATE_EXPR:
11319     case EQ_EXPR:
11320     case NE_EXPR:
11321     case MAX_EXPR:
11322     case MIN_EXPR:
11323     case LE_EXPR:
11324     case GE_EXPR:
11325     case LT_EXPR:
11326     case GT_EXPR:
11327     case MEMBER_REF:
11328     case DOTSTAR_EXPR:
11329       return build_x_binary_op
11330         (TREE_CODE (t),
11331          RECUR (TREE_OPERAND (t, 0)),
11332          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11333           ? ERROR_MARK
11334           : TREE_CODE (TREE_OPERAND (t, 0))),
11335          RECUR (TREE_OPERAND (t, 1)),
11336          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11337           ? ERROR_MARK
11338           : TREE_CODE (TREE_OPERAND (t, 1))),
11339          /*overloaded_p=*/NULL,
11340          complain);
11341
11342     case SCOPE_REF:
11343       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11344                                   /*address_p=*/false);
11345     case ARRAY_REF:
11346       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11347                                                 args, complain, in_decl);
11348       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11349
11350     case SIZEOF_EXPR:
11351       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11352         return tsubst_copy (t, args, complain, in_decl);
11353       /* Fall through */
11354       
11355     case ALIGNOF_EXPR:
11356       op1 = TREE_OPERAND (t, 0);
11357       if (!args)
11358         {
11359           /* When there are no ARGS, we are trying to evaluate a
11360              non-dependent expression from the parser.  Trying to do
11361              the substitutions may not work.  */
11362           if (!TYPE_P (op1))
11363             op1 = TREE_TYPE (op1);
11364         }
11365       else
11366         {
11367           ++skip_evaluation;
11368           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11369                                        /*function_p=*/false,
11370                                        /*integral_constant_expression_p=*/false);
11371           --skip_evaluation;
11372         }
11373       if (TYPE_P (op1))
11374         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11375                                            complain & tf_error);
11376       else
11377         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11378                                            complain & tf_error);
11379
11380     case MODOP_EXPR:
11381       {
11382         tree r = build_x_modify_expr
11383           (RECUR (TREE_OPERAND (t, 0)),
11384            TREE_CODE (TREE_OPERAND (t, 1)),
11385            RECUR (TREE_OPERAND (t, 2)),
11386            complain);
11387         /* TREE_NO_WARNING must be set if either the expression was
11388            parenthesized or it uses an operator such as >>= rather
11389            than plain assignment.  In the former case, it was already
11390            set and must be copied.  In the latter case,
11391            build_x_modify_expr sets it and it must not be reset
11392            here.  */
11393         if (TREE_NO_WARNING (t))
11394           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11395         return r;
11396       }
11397
11398     case ARROW_EXPR:
11399       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11400                                                 args, complain, in_decl);
11401       /* Remember that there was a reference to this entity.  */
11402       if (DECL_P (op1))
11403         mark_used (op1);
11404       return build_x_arrow (op1);
11405
11406     case NEW_EXPR:
11407       {
11408         tree init = RECUR (TREE_OPERAND (t, 3));
11409
11410         if (TREE_OPERAND (t, 3) && !init)
11411           /* If there was an initializer in the original tree, but
11412              it instantiated to an empty list, then we should pass on
11413              VOID_ZERO_NODE to tell build_new that it was an empty
11414              initializer () rather than no initializer.  This can only
11415              happen when the initializer is a pack expansion whose
11416              parameter packs are of length zero.  */
11417           init = void_zero_node;
11418
11419         return build_new
11420           (RECUR (TREE_OPERAND (t, 0)),
11421            RECUR (TREE_OPERAND (t, 1)),
11422            RECUR (TREE_OPERAND (t, 2)),
11423            init,
11424            NEW_EXPR_USE_GLOBAL (t),
11425            complain);
11426       }
11427
11428     case DELETE_EXPR:
11429      return delete_sanity
11430        (RECUR (TREE_OPERAND (t, 0)),
11431         RECUR (TREE_OPERAND (t, 1)),
11432         DELETE_EXPR_USE_VEC (t),
11433         DELETE_EXPR_USE_GLOBAL (t));
11434
11435     case COMPOUND_EXPR:
11436       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11437                                     RECUR (TREE_OPERAND (t, 1)),
11438                                     complain);
11439
11440     case CALL_EXPR:
11441       {
11442         tree function;
11443         tree call_args;
11444         bool qualified_p;
11445         bool koenig_p;
11446
11447         function = CALL_EXPR_FN (t);
11448         /* When we parsed the expression,  we determined whether or
11449            not Koenig lookup should be performed.  */
11450         koenig_p = KOENIG_LOOKUP_P (t);
11451         if (TREE_CODE (function) == SCOPE_REF)
11452           {
11453             qualified_p = true;
11454             function = tsubst_qualified_id (function, args, complain, in_decl,
11455                                             /*done=*/false,
11456                                             /*address_p=*/false);
11457           }
11458         else
11459           {
11460             if (TREE_CODE (function) == COMPONENT_REF)
11461               {
11462                 tree op = TREE_OPERAND (function, 1);
11463
11464                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11465                                || (BASELINK_P (op)
11466                                    && BASELINK_QUALIFIED_P (op)));
11467               }
11468             else
11469               qualified_p = false;
11470
11471             function = tsubst_copy_and_build (function, args, complain,
11472                                               in_decl,
11473                                               !qualified_p,
11474                                               integral_constant_expression_p);
11475
11476             if (BASELINK_P (function))
11477               qualified_p = true;
11478           }
11479
11480         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11481         call_args = RECUR (CALL_EXPR_ARGS (t));
11482
11483         /* We do not perform argument-dependent lookup if normal
11484            lookup finds a non-function, in accordance with the
11485            expected resolution of DR 218.  */
11486         if (koenig_p
11487             && ((is_overloaded_fn (function)
11488                  /* If lookup found a member function, the Koenig lookup is
11489                     not appropriate, even if an unqualified-name was used
11490                     to denote the function.  */
11491                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11492                 || TREE_CODE (function) == IDENTIFIER_NODE)
11493             /* Only do this when substitution turns a dependent call
11494                into a non-dependent call.  */
11495             && type_dependent_expression_p_push (t)
11496             && !any_type_dependent_arguments_p (call_args))
11497           function = perform_koenig_lookup (function, call_args);
11498
11499         if (TREE_CODE (function) == IDENTIFIER_NODE)
11500           {
11501             unqualified_name_lookup_error (function);
11502             return error_mark_node;
11503           }
11504
11505         /* Remember that there was a reference to this entity.  */
11506         if (DECL_P (function))
11507           mark_used (function);
11508
11509         if (TREE_CODE (function) == OFFSET_REF)
11510           return build_offset_ref_call_from_tree (function, call_args);
11511         if (TREE_CODE (function) == COMPONENT_REF)
11512           {
11513             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11514               return finish_call_expr (function, call_args,
11515                                        /*disallow_virtual=*/false,
11516                                        /*koenig_p=*/false,
11517                                        complain);
11518             else
11519               return (build_new_method_call
11520                       (TREE_OPERAND (function, 0),
11521                        TREE_OPERAND (function, 1),
11522                        call_args, NULL_TREE,
11523                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11524                        /*fn_p=*/NULL,
11525                        complain));
11526           }
11527         return finish_call_expr (function, call_args,
11528                                  /*disallow_virtual=*/qualified_p,
11529                                  koenig_p,
11530                                  complain);
11531       }
11532
11533     case COND_EXPR:
11534       return build_x_conditional_expr
11535         (RECUR (TREE_OPERAND (t, 0)),
11536          RECUR (TREE_OPERAND (t, 1)),
11537          RECUR (TREE_OPERAND (t, 2)),
11538          complain);
11539
11540     case PSEUDO_DTOR_EXPR:
11541       return finish_pseudo_destructor_expr
11542         (RECUR (TREE_OPERAND (t, 0)),
11543          RECUR (TREE_OPERAND (t, 1)),
11544          RECUR (TREE_OPERAND (t, 2)));
11545
11546     case TREE_LIST:
11547       {
11548         tree purpose, value, chain;
11549
11550         if (t == void_list_node)
11551           return t;
11552
11553         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11554             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11555           {
11556             /* We have pack expansions, so expand those and
11557                create a new list out of it.  */
11558             tree purposevec = NULL_TREE;
11559             tree valuevec = NULL_TREE;
11560             tree chain;
11561             int i, len = -1;
11562
11563             /* Expand the argument expressions.  */
11564             if (TREE_PURPOSE (t))
11565               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11566                                                  complain, in_decl);
11567             if (TREE_VALUE (t))
11568               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11569                                                complain, in_decl);
11570
11571             /* Build the rest of the list.  */
11572             chain = TREE_CHAIN (t);
11573             if (chain && chain != void_type_node)
11574               chain = RECUR (chain);
11575
11576             /* Determine the number of arguments.  */
11577             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11578               {
11579                 len = TREE_VEC_LENGTH (purposevec);
11580                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11581               }
11582             else if (TREE_CODE (valuevec) == TREE_VEC)
11583               len = TREE_VEC_LENGTH (valuevec);
11584             else
11585               {
11586                 /* Since we only performed a partial substitution into
11587                    the argument pack, we only return a single list
11588                    node.  */
11589                 if (purposevec == TREE_PURPOSE (t)
11590                     && valuevec == TREE_VALUE (t)
11591                     && chain == TREE_CHAIN (t))
11592                   return t;
11593
11594                 return tree_cons (purposevec, valuevec, chain);
11595               }
11596             
11597             /* Convert the argument vectors into a TREE_LIST */
11598             i = len;
11599             while (i > 0)
11600               {
11601                 /* Grab the Ith values.  */
11602                 i--;
11603                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11604                                      : NULL_TREE;
11605                 value 
11606                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11607                              : NULL_TREE;
11608
11609                 /* Build the list (backwards).  */
11610                 chain = tree_cons (purpose, value, chain);
11611               }
11612
11613             return chain;
11614           }
11615
11616         purpose = TREE_PURPOSE (t);
11617         if (purpose)
11618           purpose = RECUR (purpose);
11619         value = TREE_VALUE (t);
11620         if (value)
11621           value = RECUR (value);
11622         chain = TREE_CHAIN (t);
11623         if (chain && chain != void_type_node)
11624           chain = RECUR (chain);
11625         if (purpose == TREE_PURPOSE (t)
11626             && value == TREE_VALUE (t)
11627             && chain == TREE_CHAIN (t))
11628           return t;
11629         return tree_cons (purpose, value, chain);
11630       }
11631
11632     case COMPONENT_REF:
11633       {
11634         tree object;
11635         tree object_type;
11636         tree member;
11637
11638         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11639                                                      args, complain, in_decl);
11640         /* Remember that there was a reference to this entity.  */
11641         if (DECL_P (object))
11642           mark_used (object);
11643         object_type = TREE_TYPE (object);
11644
11645         member = TREE_OPERAND (t, 1);
11646         if (BASELINK_P (member))
11647           member = tsubst_baselink (member,
11648                                     non_reference (TREE_TYPE (object)),
11649                                     args, complain, in_decl);
11650         else
11651           member = tsubst_copy (member, args, complain, in_decl);
11652         if (member == error_mark_node)
11653           return error_mark_node;
11654
11655         if (object_type && !CLASS_TYPE_P (object_type))
11656           {
11657             if (SCALAR_TYPE_P (object_type))
11658               {
11659                 tree s = NULL_TREE;
11660                 tree dtor = member;
11661
11662                 if (TREE_CODE (dtor) == SCOPE_REF)
11663                   {
11664                     s = TREE_OPERAND (dtor, 0);
11665                     dtor = TREE_OPERAND (dtor, 1);
11666                   }
11667                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11668                   {
11669                     dtor = TREE_OPERAND (dtor, 0);
11670                     if (TYPE_P (dtor))
11671                       return finish_pseudo_destructor_expr (object, s, dtor);
11672                   }
11673               }
11674           }
11675         else if (TREE_CODE (member) == SCOPE_REF
11676                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11677           {
11678             tree tmpl;
11679             tree args;
11680
11681             /* Lookup the template functions now that we know what the
11682                scope is.  */
11683             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11684             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11685             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11686                                             /*is_type_p=*/false,
11687                                             /*complain=*/false);
11688             if (BASELINK_P (member))
11689               {
11690                 BASELINK_FUNCTIONS (member)
11691                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11692                               args);
11693                 member = (adjust_result_of_qualified_name_lookup
11694                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11695                            object_type));
11696               }
11697             else
11698               {
11699                 qualified_name_lookup_error (object_type, tmpl, member,
11700                                              input_location);
11701                 return error_mark_node;
11702               }
11703           }
11704         else if (TREE_CODE (member) == SCOPE_REF
11705                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11706                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11707           {
11708             if (complain & tf_error)
11709               {
11710                 if (TYPE_P (TREE_OPERAND (member, 0)))
11711                   error ("%qT is not a class or namespace",
11712                          TREE_OPERAND (member, 0));
11713                 else
11714                   error ("%qD is not a class or namespace",
11715                          TREE_OPERAND (member, 0));
11716               }
11717             return error_mark_node;
11718           }
11719         else if (TREE_CODE (member) == FIELD_DECL)
11720           return finish_non_static_data_member (member, object, NULL_TREE);
11721
11722         return finish_class_member_access_expr (object, member,
11723                                                 /*template_p=*/false,
11724                                                 complain);
11725       }
11726
11727     case THROW_EXPR:
11728       return build_throw
11729         (RECUR (TREE_OPERAND (t, 0)));
11730
11731     case CONSTRUCTOR:
11732       {
11733         VEC(constructor_elt,gc) *n;
11734         constructor_elt *ce;
11735         unsigned HOST_WIDE_INT idx;
11736         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11737         bool process_index_p;
11738         int newlen;
11739         bool need_copy_p = false;
11740         tree r;
11741
11742         if (type == error_mark_node)
11743           return error_mark_node;
11744
11745         /* digest_init will do the wrong thing if we let it.  */
11746         if (type && TYPE_PTRMEMFUNC_P (type))
11747           return t;
11748
11749         /* We do not want to process the index of aggregate
11750            initializers as they are identifier nodes which will be
11751            looked up by digest_init.  */
11752         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11753
11754         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11755         newlen = VEC_length (constructor_elt, n);
11756         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11757           {
11758             if (ce->index && process_index_p)
11759               ce->index = RECUR (ce->index);
11760
11761             if (PACK_EXPANSION_P (ce->value))
11762               {
11763                 /* Substitute into the pack expansion.  */
11764                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11765                                                   in_decl);
11766
11767                 if (ce->value == error_mark_node)
11768                   ;
11769                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11770                   /* Just move the argument into place.  */
11771                   ce->value = TREE_VEC_ELT (ce->value, 0);
11772                 else
11773                   {
11774                     /* Update the length of the final CONSTRUCTOR
11775                        arguments vector, and note that we will need to
11776                        copy.*/
11777                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11778                     need_copy_p = true;
11779                   }
11780               }
11781             else
11782               ce->value = RECUR (ce->value);
11783           }
11784
11785         if (need_copy_p)
11786           {
11787             VEC(constructor_elt,gc) *old_n = n;
11788
11789             n = VEC_alloc (constructor_elt, gc, newlen);
11790             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11791                  idx++)
11792               {
11793                 if (TREE_CODE (ce->value) == TREE_VEC)
11794                   {
11795                     int i, len = TREE_VEC_LENGTH (ce->value);
11796                     for (i = 0; i < len; ++i)
11797                       CONSTRUCTOR_APPEND_ELT (n, 0,
11798                                               TREE_VEC_ELT (ce->value, i));
11799                   }
11800                 else
11801                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11802               }
11803           }
11804
11805         r = build_constructor (init_list_type_node, n);
11806         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11807
11808         if (TREE_HAS_CONSTRUCTOR (t))
11809           return finish_compound_literal (type, r);
11810
11811         return r;
11812       }
11813
11814     case TYPEID_EXPR:
11815       {
11816         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11817         if (TYPE_P (operand_0))
11818           return get_typeid (operand_0);
11819         return build_typeid (operand_0);
11820       }
11821
11822     case VAR_DECL:
11823       if (!args)
11824         return t;
11825       /* Fall through */
11826
11827     case PARM_DECL:
11828       {
11829         tree r = tsubst_copy (t, args, complain, in_decl);
11830
11831         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11832           /* If the original type was a reference, we'll be wrapped in
11833              the appropriate INDIRECT_REF.  */
11834           r = convert_from_reference (r);
11835         return r;
11836       }
11837
11838     case VA_ARG_EXPR:
11839       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11840                              tsubst_copy (TREE_TYPE (t), args, complain,
11841                                           in_decl));
11842
11843     case OFFSETOF_EXPR:
11844       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11845
11846     case TRAIT_EXPR:
11847       {
11848         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11849                                   complain, in_decl);
11850
11851         tree type2 = TRAIT_EXPR_TYPE2 (t);
11852         if (type2)
11853           type2 = tsubst_copy (type2, args, complain, in_decl);
11854         
11855         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11856       }
11857
11858     case STMT_EXPR:
11859       {
11860         tree old_stmt_expr = cur_stmt_expr;
11861         tree stmt_expr = begin_stmt_expr ();
11862
11863         cur_stmt_expr = stmt_expr;
11864         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11865                      integral_constant_expression_p);
11866         stmt_expr = finish_stmt_expr (stmt_expr, false);
11867         cur_stmt_expr = old_stmt_expr;
11868
11869         return stmt_expr;
11870       }
11871
11872     case CONST_DECL:
11873       t = tsubst_copy (t, args, complain, in_decl);
11874       /* As in finish_id_expression, we resolve enumeration constants
11875          to their underlying values.  */
11876       if (TREE_CODE (t) == CONST_DECL)
11877         {
11878           used_types_insert (TREE_TYPE (t));
11879           return DECL_INITIAL (t);
11880         }
11881       return t;
11882
11883     default:
11884       /* Handle Objective-C++ constructs, if appropriate.  */
11885       {
11886         tree subst
11887           = objcp_tsubst_copy_and_build (t, args, complain,
11888                                          in_decl, /*function_p=*/false);
11889         if (subst)
11890           return subst;
11891       }
11892       return tsubst_copy (t, args, complain, in_decl);
11893     }
11894
11895 #undef RECUR
11896 }
11897
11898 /* Verify that the instantiated ARGS are valid. For type arguments,
11899    make sure that the type's linkage is ok. For non-type arguments,
11900    make sure they are constants if they are integral or enumerations.
11901    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11902
11903 static bool
11904 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
11905 {
11906   if (ARGUMENT_PACK_P (t))
11907     {
11908       tree vec = ARGUMENT_PACK_ARGS (t);
11909       int len = TREE_VEC_LENGTH (vec);
11910       bool result = false;
11911       int i;
11912
11913       for (i = 0; i < len; ++i)
11914         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
11915           result = true;
11916       return result;
11917     }
11918   else if (TYPE_P (t))
11919     {
11920       /* [basic.link]: A name with no linkage (notably, the name
11921          of a class or enumeration declared in a local scope)
11922          shall not be used to declare an entity with linkage.
11923          This implies that names with no linkage cannot be used as
11924          template arguments.  */
11925       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11926
11927       if (nt)
11928         {
11929           /* DR 488 makes use of a type with no linkage cause
11930              type deduction to fail.  */
11931           if (complain & tf_error)
11932             {
11933               if (TYPE_ANONYMOUS_P (nt))
11934                 error ("%qT is/uses anonymous type", t);
11935               else
11936                 error ("template argument for %qD uses local type %qT",
11937                        tmpl, t);
11938             }
11939           return true;
11940         }
11941       /* In order to avoid all sorts of complications, we do not
11942          allow variably-modified types as template arguments.  */
11943       else if (variably_modified_type_p (t, NULL_TREE))
11944         {
11945           if (complain & tf_error)
11946             error ("%qT is a variably modified type", t);
11947           return true;
11948         }
11949     }
11950   /* A non-type argument of integral or enumerated type must be a
11951      constant.  */
11952   else if (TREE_TYPE (t)
11953            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11954            && !TREE_CONSTANT (t))
11955     {
11956       if (complain & tf_error)
11957         error ("integral expression %qE is not constant", t);
11958       return true;
11959     }
11960   return false;
11961 }
11962
11963 static bool
11964 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11965 {
11966   int ix, len = DECL_NTPARMS (tmpl);
11967   bool result = false;
11968
11969   for (ix = 0; ix != len; ix++)
11970     {
11971       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
11972         result = true;
11973     }
11974   if (result && (complain & tf_error))
11975     error ("  trying to instantiate %qD", tmpl);
11976   return result;
11977 }
11978
11979 /* Instantiate the indicated variable or function template TMPL with
11980    the template arguments in TARG_PTR.  */
11981
11982 tree
11983 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11984 {
11985   tree fndecl;
11986   tree gen_tmpl;
11987   tree spec;
11988   HOST_WIDE_INT saved_processing_template_decl;
11989
11990   if (tmpl == error_mark_node)
11991     return error_mark_node;
11992
11993   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11994
11995   /* If this function is a clone, handle it specially.  */
11996   if (DECL_CLONED_FUNCTION_P (tmpl))
11997     {
11998       tree spec;
11999       tree clone;
12000
12001       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
12002                                    complain);
12003       if (spec == error_mark_node)
12004         return error_mark_node;
12005
12006       /* Look for the clone.  */
12007       FOR_EACH_CLONE (clone, spec)
12008         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12009           return clone;
12010       /* We should always have found the clone by now.  */
12011       gcc_unreachable ();
12012       return NULL_TREE;
12013     }
12014
12015   /* Check to see if we already have this specialization.  */
12016   spec = retrieve_specialization (tmpl, targ_ptr,
12017                                   /*class_specializations_p=*/false);
12018   if (spec != NULL_TREE)
12019     return spec;
12020
12021   gen_tmpl = most_general_template (tmpl);
12022   if (tmpl != gen_tmpl)
12023     {
12024       /* The TMPL is a partial instantiation.  To get a full set of
12025          arguments we must add the arguments used to perform the
12026          partial instantiation.  */
12027       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12028                                               targ_ptr);
12029
12030       /* Check to see if we already have this specialization.  */
12031       spec = retrieve_specialization (gen_tmpl, targ_ptr,
12032                                       /*class_specializations_p=*/false);
12033       if (spec != NULL_TREE)
12034         return spec;
12035     }
12036
12037   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12038                                complain))
12039     return error_mark_node;
12040
12041   /* We are building a FUNCTION_DECL, during which the access of its
12042      parameters and return types have to be checked.  However this
12043      FUNCTION_DECL which is the desired context for access checking
12044      is not built yet.  We solve this chicken-and-egg problem by
12045      deferring all checks until we have the FUNCTION_DECL.  */
12046   push_deferring_access_checks (dk_deferred);
12047
12048   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12049      (because, for example, we have encountered a non-dependent
12050      function call in the body of a template function and must now
12051      determine which of several overloaded functions will be called),
12052      within the instantiation itself we are not processing a
12053      template.  */  
12054   saved_processing_template_decl = processing_template_decl;
12055   processing_template_decl = 0;
12056   /* Substitute template parameters to obtain the specialization.  */
12057   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12058                    targ_ptr, complain, gen_tmpl);
12059   processing_template_decl = saved_processing_template_decl;
12060   if (fndecl == error_mark_node)
12061     return error_mark_node;
12062
12063   /* Now we know the specialization, compute access previously
12064      deferred.  */
12065   push_access_scope (fndecl);
12066
12067   /* Some typedefs referenced from within the template code need to be access
12068      checked at template instantiation time, i.e now. These types were
12069      added to the template at parsing time. Let's get those and perfom
12070      the acces checks then.  */
12071   perform_typedefs_access_check (tmpl, targ_ptr);
12072   perform_deferred_access_checks ();
12073   pop_access_scope (fndecl);
12074   pop_deferring_access_checks ();
12075
12076   /* The DECL_TI_TEMPLATE should always be the immediate parent
12077      template, not the most general template.  */
12078   DECL_TI_TEMPLATE (fndecl) = tmpl;
12079
12080   /* If we've just instantiated the main entry point for a function,
12081      instantiate all the alternate entry points as well.  We do this
12082      by cloning the instantiation of the main entry point, not by
12083      instantiating the template clones.  */
12084   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12085     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12086
12087   return fndecl;
12088 }
12089
12090 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
12091    arguments that are being used when calling it.  TARGS is a vector
12092    into which the deduced template arguments are placed.
12093
12094    Return zero for success, 2 for an incomplete match that doesn't resolve
12095    all the types, and 1 for complete failure.  An error message will be
12096    printed only for an incomplete match.
12097
12098    If FN is a conversion operator, or we are trying to produce a specific
12099    specialization, RETURN_TYPE is the return type desired.
12100
12101    The EXPLICIT_TARGS are explicit template arguments provided via a
12102    template-id.
12103
12104    The parameter STRICT is one of:
12105
12106    DEDUCE_CALL:
12107      We are deducing arguments for a function call, as in
12108      [temp.deduct.call].
12109
12110    DEDUCE_CONV:
12111      We are deducing arguments for a conversion function, as in
12112      [temp.deduct.conv].
12113
12114    DEDUCE_EXACT:
12115      We are deducing arguments when doing an explicit instantiation
12116      as in [temp.explicit], when determining an explicit specialization
12117      as in [temp.expl.spec], or when taking the address of a function
12118      template, as in [temp.deduct.funcaddr].  */
12119
12120 int
12121 fn_type_unification (tree fn,
12122                      tree explicit_targs,
12123                      tree targs,
12124                      tree args,
12125                      tree return_type,
12126                      unification_kind_t strict,
12127                      int flags)
12128 {
12129   tree parms;
12130   tree fntype;
12131   int result;
12132   bool incomplete_argument_packs_p = false;
12133
12134   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12135
12136   fntype = TREE_TYPE (fn);
12137   if (explicit_targs)
12138     {
12139       /* [temp.deduct]
12140
12141          The specified template arguments must match the template
12142          parameters in kind (i.e., type, nontype, template), and there
12143          must not be more arguments than there are parameters;
12144          otherwise type deduction fails.
12145
12146          Nontype arguments must match the types of the corresponding
12147          nontype template parameters, or must be convertible to the
12148          types of the corresponding nontype parameters as specified in
12149          _temp.arg.nontype_, otherwise type deduction fails.
12150
12151          All references in the function type of the function template
12152          to the corresponding template parameters are replaced by the
12153          specified template argument values.  If a substitution in a
12154          template parameter or in the function type of the function
12155          template results in an invalid type, type deduction fails.  */
12156       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12157       int i, len = TREE_VEC_LENGTH (tparms);
12158       tree converted_args;
12159       bool incomplete = false;
12160
12161       if (explicit_targs == error_mark_node)
12162         return 1;
12163
12164       converted_args
12165         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12166                                   /*require_all_args=*/false,
12167                                   /*use_default_args=*/false));
12168       if (converted_args == error_mark_node)
12169         return 1;
12170
12171       /* Substitute the explicit args into the function type.  This is
12172          necessary so that, for instance, explicitly declared function
12173          arguments can match null pointed constants.  If we were given
12174          an incomplete set of explicit args, we must not do semantic
12175          processing during substitution as we could create partial
12176          instantiations.  */
12177       for (i = 0; i < len; i++)
12178         {
12179           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12180           bool parameter_pack = false;
12181
12182           /* Dig out the actual parm.  */
12183           if (TREE_CODE (parm) == TYPE_DECL
12184               || TREE_CODE (parm) == TEMPLATE_DECL)
12185             {
12186               parm = TREE_TYPE (parm);
12187               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12188             }
12189           else if (TREE_CODE (parm) == PARM_DECL)
12190             {
12191               parm = DECL_INITIAL (parm);
12192               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12193             }
12194
12195           if (parameter_pack)
12196             {
12197               int level, idx;
12198               tree targ;
12199               template_parm_level_and_index (parm, &level, &idx);
12200
12201               /* Mark the argument pack as "incomplete". We could
12202                  still deduce more arguments during unification.  */
12203               targ = TMPL_ARG (converted_args, level, idx);
12204               if (targ)
12205                 {
12206                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12207                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12208                     = ARGUMENT_PACK_ARGS (targ);
12209                 }
12210
12211               /* We have some incomplete argument packs.  */
12212               incomplete_argument_packs_p = true;
12213             }
12214         }
12215
12216       if (incomplete_argument_packs_p)
12217         /* Any substitution is guaranteed to be incomplete if there
12218            are incomplete argument packs, because we can still deduce
12219            more arguments.  */
12220         incomplete = 1;
12221       else
12222         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12223
12224       processing_template_decl += incomplete;
12225       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12226       processing_template_decl -= incomplete;
12227
12228       if (fntype == error_mark_node)
12229         return 1;
12230
12231       /* Place the explicitly specified arguments in TARGS.  */
12232       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12233         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12234     }
12235
12236   /* Never do unification on the 'this' parameter.  */
12237   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12238
12239   if (return_type)
12240     {
12241       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12242       args = tree_cons (NULL_TREE, return_type, args);
12243     }
12244
12245   /* We allow incomplete unification without an error message here
12246      because the standard doesn't seem to explicitly prohibit it.  Our
12247      callers must be ready to deal with unification failures in any
12248      event.  */
12249   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12250                                   targs, parms, args, /*subr=*/0,
12251                                   strict, flags);
12252
12253   if (result == 0 && incomplete_argument_packs_p)
12254     {
12255       int i, len = NUM_TMPL_ARGS (targs);
12256
12257       /* Clear the "incomplete" flags on all argument packs.  */
12258       for (i = 0; i < len; i++)
12259         {
12260           tree arg = TREE_VEC_ELT (targs, i);
12261           if (ARGUMENT_PACK_P (arg))
12262             {
12263               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12264               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12265             }
12266         }
12267     }
12268
12269   /* Now that we have bindings for all of the template arguments,
12270      ensure that the arguments deduced for the template template
12271      parameters have compatible template parameter lists.  We cannot
12272      check this property before we have deduced all template
12273      arguments, because the template parameter types of a template
12274      template parameter might depend on prior template parameters
12275      deduced after the template template parameter.  The following
12276      ill-formed example illustrates this issue:
12277
12278        template<typename T, template<T> class C> void f(C<5>, T);
12279
12280        template<int N> struct X {};
12281
12282        void g() {
12283          f(X<5>(), 5l); // error: template argument deduction fails
12284        }
12285
12286      The template parameter list of 'C' depends on the template type
12287      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12288      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12289      time that we deduce 'C'.  */
12290   if (result == 0
12291       && !template_template_parm_bindings_ok_p 
12292            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12293     return 1;
12294
12295   if (result == 0)
12296     /* All is well so far.  Now, check:
12297
12298        [temp.deduct]
12299
12300        When all template arguments have been deduced, all uses of
12301        template parameters in nondeduced contexts are replaced with
12302        the corresponding deduced argument values.  If the
12303        substitution results in an invalid type, as described above,
12304        type deduction fails.  */
12305     {
12306       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
12307       if (substed == error_mark_node)
12308         return 1;
12309
12310       /* If we're looking for an exact match, check that what we got
12311          is indeed an exact match.  It might not be if some template
12312          parameters are used in non-deduced contexts.  */
12313       if (strict == DEDUCE_EXACT)
12314         {
12315           tree sarg
12316             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
12317           tree arg = args;
12318           if (return_type)
12319             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
12320           for (; arg && sarg;
12321                arg = TREE_CHAIN (arg), sarg = TREE_CHAIN (sarg))
12322             if (!same_type_p (TREE_VALUE (arg), TREE_VALUE (sarg)))
12323               return 1;
12324         }
12325     }
12326
12327   return result;
12328 }
12329
12330 /* Adjust types before performing type deduction, as described in
12331    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12332    sections are symmetric.  PARM is the type of a function parameter
12333    or the return type of the conversion function.  ARG is the type of
12334    the argument passed to the call, or the type of the value
12335    initialized with the result of the conversion function.
12336    ARG_EXPR is the original argument expression, which may be null.  */
12337
12338 static int
12339 maybe_adjust_types_for_deduction (unification_kind_t strict,
12340                                   tree* parm,
12341                                   tree* arg,
12342                                   tree arg_expr)
12343 {
12344   int result = 0;
12345
12346   switch (strict)
12347     {
12348     case DEDUCE_CALL:
12349       break;
12350
12351     case DEDUCE_CONV:
12352       {
12353         /* Swap PARM and ARG throughout the remainder of this
12354            function; the handling is precisely symmetric since PARM
12355            will initialize ARG rather than vice versa.  */
12356         tree* temp = parm;
12357         parm = arg;
12358         arg = temp;
12359         break;
12360       }
12361
12362     case DEDUCE_EXACT:
12363       /* There is nothing to do in this case.  */
12364       return 0;
12365
12366     default:
12367       gcc_unreachable ();
12368     }
12369
12370   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12371     {
12372       /* [temp.deduct.call]
12373
12374          If P is not a reference type:
12375
12376          --If A is an array type, the pointer type produced by the
12377          array-to-pointer standard conversion (_conv.array_) is
12378          used in place of A for type deduction; otherwise,
12379
12380          --If A is a function type, the pointer type produced by
12381          the function-to-pointer standard conversion
12382          (_conv.func_) is used in place of A for type deduction;
12383          otherwise,
12384
12385          --If A is a cv-qualified type, the top level
12386          cv-qualifiers of A's type are ignored for type
12387          deduction.  */
12388       if (TREE_CODE (*arg) == ARRAY_TYPE)
12389         *arg = build_pointer_type (TREE_TYPE (*arg));
12390       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12391         *arg = build_pointer_type (*arg);
12392       else
12393         *arg = TYPE_MAIN_VARIANT (*arg);
12394     }
12395
12396   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12397      of the form T&&, where T is a template parameter, and the argument
12398      is an lvalue, T is deduced as A& */
12399   if (TREE_CODE (*parm) == REFERENCE_TYPE
12400       && TYPE_REF_IS_RVALUE (*parm)
12401       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12402       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12403       && arg_expr && real_lvalue_p (arg_expr))
12404     *arg = build_reference_type (*arg);
12405
12406   /* [temp.deduct.call]
12407
12408      If P is a cv-qualified type, the top level cv-qualifiers
12409      of P's type are ignored for type deduction.  If P is a
12410      reference type, the type referred to by P is used for
12411      type deduction.  */
12412   *parm = TYPE_MAIN_VARIANT (*parm);
12413   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12414     {
12415       *parm = TREE_TYPE (*parm);
12416       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12417     }
12418
12419   /* DR 322. For conversion deduction, remove a reference type on parm
12420      too (which has been swapped into ARG).  */
12421   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12422     *arg = TREE_TYPE (*arg);
12423
12424   return result;
12425 }
12426
12427 /* Most parms like fn_type_unification.
12428
12429    If SUBR is 1, we're being called recursively (to unify the
12430    arguments of a function or method parameter of a function
12431    template). */
12432
12433 static int
12434 type_unification_real (tree tparms,
12435                        tree targs,
12436                        tree xparms,
12437                        tree xargs,
12438                        int subr,
12439                        unification_kind_t strict,
12440                        int flags)
12441 {
12442   tree parm, arg, arg_expr;
12443   int i;
12444   int ntparms = TREE_VEC_LENGTH (tparms);
12445   int sub_strict;
12446   int saw_undeduced = 0;
12447   tree parms, args;
12448
12449   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12450   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12451   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
12452   gcc_assert (ntparms > 0);
12453
12454   switch (strict)
12455     {
12456     case DEDUCE_CALL:
12457       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12458                     | UNIFY_ALLOW_DERIVED);
12459       break;
12460
12461     case DEDUCE_CONV:
12462       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12463       break;
12464
12465     case DEDUCE_EXACT:
12466       sub_strict = UNIFY_ALLOW_NONE;
12467       break;
12468
12469     default:
12470       gcc_unreachable ();
12471     }
12472
12473  again:
12474   parms = xparms;
12475   args = xargs;
12476
12477   while (parms && parms != void_list_node
12478          && args && args != void_list_node)
12479     {
12480       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12481         break;
12482
12483       parm = TREE_VALUE (parms);
12484       parms = TREE_CHAIN (parms);
12485       arg = TREE_VALUE (args);
12486       args = TREE_CHAIN (args);
12487       arg_expr = NULL;
12488
12489       if (arg == error_mark_node)
12490         return 1;
12491       if (arg == unknown_type_node)
12492         /* We can't deduce anything from this, but we might get all the
12493            template args from other function args.  */
12494         continue;
12495
12496       /* Conversions will be performed on a function argument that
12497          corresponds with a function parameter that contains only
12498          non-deducible template parameters and explicitly specified
12499          template parameters.  */
12500       if (!uses_template_parms (parm))
12501         {
12502           tree type;
12503
12504           if (!TYPE_P (arg))
12505             type = TREE_TYPE (arg);
12506           else
12507             type = arg;
12508
12509           if (same_type_p (parm, type))
12510             continue;
12511           if (strict != DEDUCE_EXACT
12512               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12513                                   flags))
12514             continue;
12515
12516           return 1;
12517         }
12518
12519       if (!TYPE_P (arg))
12520         {
12521           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12522           if (type_unknown_p (arg))
12523             {
12524               /* [temp.deduct.type] 
12525
12526                  A template-argument can be deduced from a pointer to
12527                  function or pointer to member function argument if
12528                  the set of overloaded functions does not contain
12529                  function templates and at most one of a set of
12530                  overloaded functions provides a unique match.  */
12531               if (resolve_overloaded_unification
12532                   (tparms, targs, parm, arg, strict, sub_strict))
12533                 continue;
12534
12535               return 1;
12536             }
12537           arg_expr = arg;
12538           arg = unlowered_expr_type (arg);
12539           if (arg == error_mark_node)
12540             return 1;
12541         }
12542
12543       {
12544         int arg_strict = sub_strict;
12545
12546         if (!subr)
12547           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12548                                                           arg_expr);
12549
12550         if (arg == init_list_type_node && arg_expr)
12551           arg = arg_expr;
12552         if (unify (tparms, targs, parm, arg, arg_strict))
12553           return 1;
12554       }
12555     }
12556
12557
12558   if (parms 
12559       && parms != void_list_node
12560       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12561     {
12562       /* Unify the remaining arguments with the pack expansion type.  */
12563       tree argvec;
12564       tree parmvec = make_tree_vec (1);
12565       int len = 0;
12566       tree t;
12567
12568       /* Count the number of arguments that remain.  */
12569       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12570         len++;
12571         
12572       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12573       argvec = make_tree_vec (len);
12574       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12575         {
12576           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12577           ++i;
12578         }
12579
12580       /* Copy the parameter into parmvec.  */
12581       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12582       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12583                                 /*call_args_p=*/true, /*subr=*/subr))
12584         return 1;
12585
12586       /* Advance to the end of the list of parameters.  */
12587       parms = TREE_CHAIN (parms);
12588     }
12589
12590   /* Fail if we've reached the end of the parm list, and more args
12591      are present, and the parm list isn't variadic.  */
12592   if (args && args != void_list_node && parms == void_list_node)
12593     return 1;
12594   /* Fail if parms are left and they don't have default values.  */
12595   if (parms && parms != void_list_node
12596       && TREE_PURPOSE (parms) == NULL_TREE)
12597     return 1;
12598
12599   if (!subr)
12600     for (i = 0; i < ntparms; i++)
12601       if (!TREE_VEC_ELT (targs, i))
12602         {
12603           tree tparm;
12604
12605           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12606             continue;
12607
12608           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12609
12610           /* If this is an undeduced nontype parameter that depends on
12611              a type parameter, try another pass; its type may have been
12612              deduced from a later argument than the one from which
12613              this parameter can be deduced.  */
12614           if (TREE_CODE (tparm) == PARM_DECL
12615               && uses_template_parms (TREE_TYPE (tparm))
12616               && !saw_undeduced++)
12617             goto again;
12618
12619           /* Core issue #226 (C++0x) [temp.deduct]:
12620
12621                If a template argument has not been deduced, its
12622                default template argument, if any, is used. 
12623
12624              When we are in C++98 mode, TREE_PURPOSE will either
12625              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12626              to explicitly check cxx_dialect here.  */
12627           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12628             {
12629               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12630                                  targs, tf_none, NULL_TREE);
12631               if (arg == error_mark_node)
12632                 return 1;
12633               else
12634                 {
12635                   TREE_VEC_ELT (targs, i) = arg;
12636                   continue;
12637                 }
12638             }
12639
12640           /* If the type parameter is a parameter pack, then it will
12641              be deduced to an empty parameter pack.  */
12642           if (template_parameter_pack_p (tparm))
12643             {
12644               tree arg;
12645
12646               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12647                 {
12648                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12649                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12650                   TREE_CONSTANT (arg) = 1;
12651                 }
12652               else
12653                 arg = make_node (TYPE_ARGUMENT_PACK);
12654
12655               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12656
12657               TREE_VEC_ELT (targs, i) = arg;
12658               continue;
12659             }
12660
12661           return 2;
12662         }
12663
12664   return 0;
12665 }
12666
12667 /* Subroutine of type_unification_real.  Args are like the variables
12668    at the call site.  ARG is an overloaded function (or template-id);
12669    we try deducing template args from each of the overloads, and if
12670    only one succeeds, we go with that.  Modifies TARGS and returns
12671    true on success.  */
12672
12673 static bool
12674 resolve_overloaded_unification (tree tparms,
12675                                 tree targs,
12676                                 tree parm,
12677                                 tree arg,
12678                                 unification_kind_t strict,
12679                                 int sub_strict)
12680 {
12681   tree tempargs = copy_node (targs);
12682   int good = 0;
12683   tree goodfn = NULL_TREE;
12684   bool addr_p;
12685
12686   if (TREE_CODE (arg) == ADDR_EXPR)
12687     {
12688       arg = TREE_OPERAND (arg, 0);
12689       addr_p = true;
12690     }
12691   else
12692     addr_p = false;
12693
12694   if (TREE_CODE (arg) == COMPONENT_REF)
12695     /* Handle `&x' where `x' is some static or non-static member
12696        function name.  */
12697     arg = TREE_OPERAND (arg, 1);
12698
12699   if (TREE_CODE (arg) == OFFSET_REF)
12700     arg = TREE_OPERAND (arg, 1);
12701
12702   /* Strip baselink information.  */
12703   if (BASELINK_P (arg))
12704     arg = BASELINK_FUNCTIONS (arg);
12705
12706   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12707     {
12708       /* If we got some explicit template args, we need to plug them into
12709          the affected templates before we try to unify, in case the
12710          explicit args will completely resolve the templates in question.  */
12711
12712       tree expl_subargs = TREE_OPERAND (arg, 1);
12713       arg = TREE_OPERAND (arg, 0);
12714
12715       for (; arg; arg = OVL_NEXT (arg))
12716         {
12717           tree fn = OVL_CURRENT (arg);
12718           tree subargs, elem;
12719
12720           if (TREE_CODE (fn) != TEMPLATE_DECL)
12721             continue;
12722
12723           ++processing_template_decl;
12724           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12725                                   expl_subargs, /*check_ret=*/false);
12726           if (subargs)
12727             {
12728               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12729               if (try_one_overload (tparms, targs, tempargs, parm,
12730                                     elem, strict, sub_strict, addr_p)
12731                   && (!goodfn || !decls_match (goodfn, elem)))
12732                 {
12733                   goodfn = elem;
12734                   ++good;
12735                 }
12736             }
12737           --processing_template_decl;
12738         }
12739     }
12740   else if (TREE_CODE (arg) != OVERLOAD
12741            && TREE_CODE (arg) != FUNCTION_DECL)
12742     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12743        -- but the deduction does not succeed because the expression is
12744        not just the function on its own.  */
12745     return false;
12746   else
12747     for (; arg; arg = OVL_NEXT (arg))
12748       if (try_one_overload (tparms, targs, tempargs, parm,
12749                             TREE_TYPE (OVL_CURRENT (arg)),
12750                             strict, sub_strict, addr_p)
12751           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
12752         {
12753           goodfn = OVL_CURRENT (arg);
12754           ++good;
12755         }
12756
12757   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12758      to function or pointer to member function argument if the set of
12759      overloaded functions does not contain function templates and at most
12760      one of a set of overloaded functions provides a unique match.
12761
12762      So if we found multiple possibilities, we return success but don't
12763      deduce anything.  */
12764
12765   if (good == 1)
12766     {
12767       int i = TREE_VEC_LENGTH (targs);
12768       for (; i--; )
12769         if (TREE_VEC_ELT (tempargs, i))
12770           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12771     }
12772   if (good)
12773     return true;
12774
12775   return false;
12776 }
12777
12778 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12779    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12780    different overloads deduce different arguments for a given parm.
12781    ADDR_P is true if the expression for which deduction is being
12782    performed was of the form "& fn" rather than simply "fn".
12783
12784    Returns 1 on success.  */
12785
12786 static int
12787 try_one_overload (tree tparms,
12788                   tree orig_targs,
12789                   tree targs,
12790                   tree parm,
12791                   tree arg,
12792                   unification_kind_t strict,
12793                   int sub_strict,
12794                   bool addr_p)
12795 {
12796   int nargs;
12797   tree tempargs;
12798   int i;
12799
12800   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12801      to function or pointer to member function argument if the set of
12802      overloaded functions does not contain function templates and at most
12803      one of a set of overloaded functions provides a unique match.
12804
12805      So if this is a template, just return success.  */
12806
12807   if (uses_template_parms (arg))
12808     return 1;
12809
12810   if (TREE_CODE (arg) == METHOD_TYPE)
12811     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12812   else if (addr_p)
12813     arg = build_pointer_type (arg);
12814
12815   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12816
12817   /* We don't copy orig_targs for this because if we have already deduced
12818      some template args from previous args, unify would complain when we
12819      try to deduce a template parameter for the same argument, even though
12820      there isn't really a conflict.  */
12821   nargs = TREE_VEC_LENGTH (targs);
12822   tempargs = make_tree_vec (nargs);
12823
12824   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12825     return 0;
12826
12827   /* First make sure we didn't deduce anything that conflicts with
12828      explicitly specified args.  */
12829   for (i = nargs; i--; )
12830     {
12831       tree elt = TREE_VEC_ELT (tempargs, i);
12832       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12833
12834       if (!elt)
12835         /*NOP*/;
12836       else if (uses_template_parms (elt))
12837         /* Since we're unifying against ourselves, we will fill in
12838            template args used in the function parm list with our own
12839            template parms.  Discard them.  */
12840         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12841       else if (oldelt && !template_args_equal (oldelt, elt))
12842         return 0;
12843     }
12844
12845   for (i = nargs; i--; )
12846     {
12847       tree elt = TREE_VEC_ELT (tempargs, i);
12848
12849       if (elt)
12850         TREE_VEC_ELT (targs, i) = elt;
12851     }
12852
12853   return 1;
12854 }
12855
12856 /* PARM is a template class (perhaps with unbound template
12857    parameters).  ARG is a fully instantiated type.  If ARG can be
12858    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12859    TARGS are as for unify.  */
12860
12861 static tree
12862 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12863 {
12864   tree copy_of_targs;
12865
12866   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12867       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12868           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12869     return NULL_TREE;
12870
12871   /* We need to make a new template argument vector for the call to
12872      unify.  If we used TARGS, we'd clutter it up with the result of
12873      the attempted unification, even if this class didn't work out.
12874      We also don't want to commit ourselves to all the unifications
12875      we've already done, since unification is supposed to be done on
12876      an argument-by-argument basis.  In other words, consider the
12877      following pathological case:
12878
12879        template <int I, int J, int K>
12880        struct S {};
12881
12882        template <int I, int J>
12883        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12884
12885        template <int I, int J, int K>
12886        void f(S<I, J, K>, S<I, I, I>);
12887
12888        void g() {
12889          S<0, 0, 0> s0;
12890          S<0, 1, 2> s2;
12891
12892          f(s0, s2);
12893        }
12894
12895      Now, by the time we consider the unification involving `s2', we
12896      already know that we must have `f<0, 0, 0>'.  But, even though
12897      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12898      because there are two ways to unify base classes of S<0, 1, 2>
12899      with S<I, I, I>.  If we kept the already deduced knowledge, we
12900      would reject the possibility I=1.  */
12901   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12902
12903   /* If unification failed, we're done.  */
12904   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12905              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12906     return NULL_TREE;
12907
12908   return arg;
12909 }
12910
12911 /* Given a template type PARM and a class type ARG, find the unique
12912    base type in ARG that is an instance of PARM.  We do not examine
12913    ARG itself; only its base-classes.  If there is not exactly one
12914    appropriate base class, return NULL_TREE.  PARM may be the type of
12915    a partial specialization, as well as a plain template type.  Used
12916    by unify.  */
12917
12918 static tree
12919 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12920 {
12921   tree rval = NULL_TREE;
12922   tree binfo;
12923
12924   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
12925
12926   binfo = TYPE_BINFO (complete_type (arg));
12927   if (!binfo)
12928     /* The type could not be completed.  */
12929     return NULL_TREE;
12930
12931   /* Walk in inheritance graph order.  The search order is not
12932      important, and this avoids multiple walks of virtual bases.  */
12933   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12934     {
12935       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12936
12937       if (r)
12938         {
12939           /* If there is more than one satisfactory baseclass, then:
12940
12941                [temp.deduct.call]
12942
12943               If they yield more than one possible deduced A, the type
12944               deduction fails.
12945
12946              applies.  */
12947           if (rval && !same_type_p (r, rval))
12948             return NULL_TREE;
12949
12950           rval = r;
12951         }
12952     }
12953
12954   return rval;
12955 }
12956
12957 /* Returns the level of DECL, which declares a template parameter.  */
12958
12959 static int
12960 template_decl_level (tree decl)
12961 {
12962   switch (TREE_CODE (decl))
12963     {
12964     case TYPE_DECL:
12965     case TEMPLATE_DECL:
12966       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12967
12968     case PARM_DECL:
12969       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12970
12971     default:
12972       gcc_unreachable ();
12973     }
12974   return 0;
12975 }
12976
12977 /* Decide whether ARG can be unified with PARM, considering only the
12978    cv-qualifiers of each type, given STRICT as documented for unify.
12979    Returns nonzero iff the unification is OK on that basis.  */
12980
12981 static int
12982 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12983 {
12984   int arg_quals = cp_type_quals (arg);
12985   int parm_quals = cp_type_quals (parm);
12986
12987   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12988       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12989     {
12990       /*  Although a CVR qualifier is ignored when being applied to a
12991           substituted template parameter ([8.3.2]/1 for example), that
12992           does not apply during deduction [14.8.2.4]/1, (even though
12993           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12994           this).  Except when we're allowing additional CV qualifiers
12995           at the outer level [14.8.2.1]/3,1st bullet.  */
12996       if ((TREE_CODE (arg) == REFERENCE_TYPE
12997            || TREE_CODE (arg) == FUNCTION_TYPE
12998            || TREE_CODE (arg) == METHOD_TYPE)
12999           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13000         return 0;
13001
13002       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13003           && (parm_quals & TYPE_QUAL_RESTRICT))
13004         return 0;
13005     }
13006
13007   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13008       && (arg_quals & parm_quals) != parm_quals)
13009     return 0;
13010
13011   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13012       && (parm_quals & arg_quals) != arg_quals)
13013     return 0;
13014
13015   return 1;
13016 }
13017
13018 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13019 void 
13020 template_parm_level_and_index (tree parm, int* level, int* index)
13021 {
13022   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13023       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13024       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13025     {
13026       *index = TEMPLATE_TYPE_IDX (parm);
13027       *level = TEMPLATE_TYPE_LEVEL (parm);
13028     }
13029   else
13030     {
13031       *index = TEMPLATE_PARM_IDX (parm);
13032       *level = TEMPLATE_PARM_LEVEL (parm);
13033     }
13034 }
13035
13036 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13037    expansion at the end of PACKED_PARMS. Returns 0 if the type
13038    deduction succeeds, 1 otherwise. STRICT is the same as in
13039    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13040    call argument list. We'll need to adjust the arguments to make them
13041    types. SUBR tells us if this is from a recursive call to
13042    type_unification_real.  */
13043 int
13044 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13045                       tree packed_args, int strict, bool call_args_p,
13046                       bool subr)
13047 {
13048   tree parm 
13049     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13050   tree pattern = PACK_EXPANSION_PATTERN (parm);
13051   tree pack, packs = NULL_TREE;
13052   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13053   int len = TREE_VEC_LENGTH (packed_args);
13054
13055   /* Determine the parameter packs we will be deducing from the
13056      pattern, and record their current deductions.  */
13057   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13058        pack; pack = TREE_CHAIN (pack))
13059     {
13060       tree parm_pack = TREE_VALUE (pack);
13061       int idx, level;
13062
13063       /* Determine the index and level of this parameter pack.  */
13064       template_parm_level_and_index (parm_pack, &level, &idx);
13065
13066       /* Keep track of the parameter packs and their corresponding
13067          argument packs.  */
13068       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13069       TREE_TYPE (packs) = make_tree_vec (len - start);
13070     }
13071   
13072   /* Loop through all of the arguments that have not yet been
13073      unified and unify each with the pattern.  */
13074   for (i = start; i < len; i++)
13075     {
13076       tree parm = pattern;
13077
13078       /* For each parameter pack, clear out the deduced value so that
13079          we can deduce it again.  */
13080       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13081         {
13082           int idx, level;
13083           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13084
13085           TMPL_ARG (targs, level, idx) = NULL_TREE;
13086         }
13087
13088       /* Unify the pattern with the current argument.  */
13089       {
13090         tree arg = TREE_VEC_ELT (packed_args, i);
13091         tree arg_expr = NULL_TREE;
13092         int arg_strict = strict;
13093         bool skip_arg_p = false;
13094
13095         if (call_args_p)
13096           {
13097             int sub_strict;
13098
13099             /* This mirrors what we do in type_unification_real.  */
13100             switch (strict)
13101               {
13102               case DEDUCE_CALL:
13103                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13104                               | UNIFY_ALLOW_MORE_CV_QUAL
13105                               | UNIFY_ALLOW_DERIVED);
13106                 break;
13107                 
13108               case DEDUCE_CONV:
13109                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13110                 break;
13111                 
13112               case DEDUCE_EXACT:
13113                 sub_strict = UNIFY_ALLOW_NONE;
13114                 break;
13115                 
13116               default:
13117                 gcc_unreachable ();
13118               }
13119
13120             if (!TYPE_P (arg))
13121               {
13122                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13123                 if (type_unknown_p (arg))
13124                   {
13125                     /* [temp.deduct.type] A template-argument can be
13126                        deduced from a pointer to function or pointer
13127                        to member function argument if the set of
13128                        overloaded functions does not contain function
13129                        templates and at most one of a set of
13130                        overloaded functions provides a unique
13131                        match.  */
13132
13133                     if (resolve_overloaded_unification
13134                         (tparms, targs, parm, arg, strict, sub_strict)
13135                         != 0)
13136                       return 1;
13137                     skip_arg_p = true;
13138                   }
13139
13140                 if (!skip_arg_p)
13141                   {
13142                     arg_expr = arg;
13143                     arg = unlowered_expr_type (arg);
13144                     if (arg == error_mark_node)
13145                       return 1;
13146                   }
13147               }
13148       
13149             arg_strict = sub_strict;
13150
13151             if (!subr)
13152               arg_strict |= 
13153                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
13154                                                   arg_expr);
13155           }
13156
13157         if (!skip_arg_p)
13158           {
13159             if (unify (tparms, targs, parm, arg, arg_strict))
13160               return 1;
13161           }
13162       }
13163
13164       /* For each parameter pack, collect the deduced value.  */
13165       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13166         {
13167           int idx, level;
13168           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13169
13170           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13171             TMPL_ARG (targs, level, idx);
13172         }
13173     }
13174
13175   /* Verify that the results of unification with the parameter packs
13176      produce results consistent with what we've seen before, and make
13177      the deduced argument packs available.  */
13178   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13179     {
13180       tree old_pack = TREE_VALUE (pack);
13181       tree new_args = TREE_TYPE (pack);
13182       int i, len = TREE_VEC_LENGTH (new_args);
13183       bool nondeduced_p = false;
13184
13185       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13186          actually deduce anything.  */
13187       for (i = 0; i < len && !nondeduced_p; ++i)
13188         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13189           nondeduced_p = true;
13190       if (nondeduced_p)
13191         continue;
13192
13193       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13194         {
13195           /* Prepend the explicit arguments onto NEW_ARGS.  */
13196           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13197           tree old_args = new_args;
13198           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13199           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13200
13201           /* Copy the explicit arguments.  */
13202           new_args = make_tree_vec (len);
13203           for (i = 0; i < explicit_len; i++)
13204             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13205
13206           /* Copy the deduced arguments.  */
13207           for (; i < len; i++)
13208             TREE_VEC_ELT (new_args, i) =
13209               TREE_VEC_ELT (old_args, i - explicit_len);
13210         }
13211
13212       if (!old_pack)
13213         {
13214           tree result;
13215           int idx, level;
13216           
13217           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13218
13219           /* Build the deduced *_ARGUMENT_PACK.  */
13220           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13221             {
13222               result = make_node (NONTYPE_ARGUMENT_PACK);
13223               TREE_TYPE (result) = 
13224                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13225               TREE_CONSTANT (result) = 1;
13226             }
13227           else
13228             result = make_node (TYPE_ARGUMENT_PACK);
13229
13230           SET_ARGUMENT_PACK_ARGS (result, new_args);
13231
13232           /* Note the deduced argument packs for this parameter
13233              pack.  */
13234           TMPL_ARG (targs, level, idx) = result;
13235         }
13236       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13237                && (ARGUMENT_PACK_ARGS (old_pack) 
13238                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13239         {
13240           /* We only had the explicitly-provided arguments before, but
13241              now we have a complete set of arguments.  */
13242           int idx, level;
13243           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13244           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13245
13246           /* Keep the original deduced argument pack.  */
13247           TMPL_ARG (targs, level, idx) = old_pack;
13248
13249           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13250           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13251           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13252         }
13253       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13254                                     new_args))
13255         /* Inconsistent unification of this parameter pack.  */
13256         return 1;
13257       else
13258         {
13259           int idx, level;
13260           
13261           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13262
13263           /* Keep the original deduced argument pack.  */
13264           TMPL_ARG (targs, level, idx) = old_pack;
13265         }
13266     }
13267
13268   return 0;
13269 }
13270
13271 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13272    set of template parameters to a template.  TARGS is the bindings
13273    for those template parameters, as determined thus far; TARGS may
13274    include template arguments for outer levels of template parameters
13275    as well.  PARM is a parameter to a template function, or a
13276    subcomponent of that parameter; ARG is the corresponding argument.
13277    This function attempts to match PARM with ARG in a manner
13278    consistent with the existing assignments in TARGS.  If more values
13279    are deduced, then TARGS is updated.
13280
13281    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13282    parameter STRICT is a bitwise or of the following flags:
13283
13284      UNIFY_ALLOW_NONE:
13285        Require an exact match between PARM and ARG.
13286      UNIFY_ALLOW_MORE_CV_QUAL:
13287        Allow the deduced ARG to be more cv-qualified (by qualification
13288        conversion) than ARG.
13289      UNIFY_ALLOW_LESS_CV_QUAL:
13290        Allow the deduced ARG to be less cv-qualified than ARG.
13291      UNIFY_ALLOW_DERIVED:
13292        Allow the deduced ARG to be a template base class of ARG,
13293        or a pointer to a template base class of the type pointed to by
13294        ARG.
13295      UNIFY_ALLOW_INTEGER:
13296        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13297        case for more information.
13298      UNIFY_ALLOW_OUTER_LEVEL:
13299        This is the outermost level of a deduction. Used to determine validity
13300        of qualification conversions. A valid qualification conversion must
13301        have const qualified pointers leading up to the inner type which
13302        requires additional CV quals, except at the outer level, where const
13303        is not required [conv.qual]. It would be normal to set this flag in
13304        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13305      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13306        This is the outermost level of a deduction, and PARM can be more CV
13307        qualified at this point.
13308      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13309        This is the outermost level of a deduction, and PARM can be less CV
13310        qualified at this point.  */
13311
13312 static int
13313 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13314 {
13315   int idx;
13316   tree targ;
13317   tree tparm;
13318   int strict_in = strict;
13319
13320   /* I don't think this will do the right thing with respect to types.
13321      But the only case I've seen it in so far has been array bounds, where
13322      signedness is the only information lost, and I think that will be
13323      okay.  */
13324   while (TREE_CODE (parm) == NOP_EXPR)
13325     parm = TREE_OPERAND (parm, 0);
13326
13327   if (arg == error_mark_node)
13328     return 1;
13329   if (arg == unknown_type_node
13330       || arg == init_list_type_node)
13331     /* We can't deduce anything from this, but we might get all the
13332        template args from other function args.  */
13333     return 0;
13334
13335   /* If PARM uses template parameters, then we can't bail out here,
13336      even if ARG == PARM, since we won't record unifications for the
13337      template parameters.  We might need them if we're trying to
13338      figure out which of two things is more specialized.  */
13339   if (arg == parm && !uses_template_parms (parm))
13340     return 0;
13341
13342   /* Handle init lists early, so the rest of the function can assume
13343      we're dealing with a type. */
13344   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13345     {
13346       tree elt, elttype;
13347       unsigned i;
13348
13349       if (!is_std_init_list (parm))
13350         /* We can only deduce from an initializer list argument if the
13351            parameter is std::initializer_list; otherwise this is a
13352            non-deduced context. */
13353         return 0;
13354
13355       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13356
13357       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13358         {
13359           int elt_strict = strict;
13360           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13361             {
13362               tree type = TREE_TYPE (elt);
13363               /* It should only be possible to get here for a call.  */
13364               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13365               elt_strict |= maybe_adjust_types_for_deduction
13366                 (DEDUCE_CALL, &elttype, &type, elt);
13367               elt = type;
13368             }
13369
13370           if (unify (tparms, targs, elttype, elt, elt_strict))
13371             return 1;
13372         }
13373       return 0;
13374     }
13375
13376   /* Immediately reject some pairs that won't unify because of
13377      cv-qualification mismatches.  */
13378   if (TREE_CODE (arg) == TREE_CODE (parm)
13379       && TYPE_P (arg)
13380       /* It is the elements of the array which hold the cv quals of an array
13381          type, and the elements might be template type parms. We'll check
13382          when we recurse.  */
13383       && TREE_CODE (arg) != ARRAY_TYPE
13384       /* We check the cv-qualifiers when unifying with template type
13385          parameters below.  We want to allow ARG `const T' to unify with
13386          PARM `T' for example, when computing which of two templates
13387          is more specialized, for example.  */
13388       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13389       && !check_cv_quals_for_unify (strict_in, arg, parm))
13390     return 1;
13391
13392   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13393       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13394     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13395   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13396   strict &= ~UNIFY_ALLOW_DERIVED;
13397   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13398   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13399
13400   switch (TREE_CODE (parm))
13401     {
13402     case TYPENAME_TYPE:
13403     case SCOPE_REF:
13404     case UNBOUND_CLASS_TEMPLATE:
13405       /* In a type which contains a nested-name-specifier, template
13406          argument values cannot be deduced for template parameters used
13407          within the nested-name-specifier.  */
13408       return 0;
13409
13410     case TEMPLATE_TYPE_PARM:
13411     case TEMPLATE_TEMPLATE_PARM:
13412     case BOUND_TEMPLATE_TEMPLATE_PARM:
13413       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13414       if (tparm == error_mark_node)
13415         return 1;
13416
13417       if (TEMPLATE_TYPE_LEVEL (parm)
13418           != template_decl_level (tparm))
13419         /* The PARM is not one we're trying to unify.  Just check
13420            to see if it matches ARG.  */
13421         return (TREE_CODE (arg) == TREE_CODE (parm)
13422                 && same_type_p (parm, arg)) ? 0 : 1;
13423       idx = TEMPLATE_TYPE_IDX (parm);
13424       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13425       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13426
13427       /* Check for mixed types and values.  */
13428       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13429            && TREE_CODE (tparm) != TYPE_DECL)
13430           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13431               && TREE_CODE (tparm) != TEMPLATE_DECL))
13432         return 1;
13433
13434       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13435         {
13436           /* ARG must be constructed from a template class or a template
13437              template parameter.  */
13438           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13439               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13440             return 1;
13441
13442           {
13443             tree parmvec = TYPE_TI_ARGS (parm);
13444             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13445             tree parm_parms 
13446               = DECL_INNERMOST_TEMPLATE_PARMS
13447                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13448             int i, len;
13449             int parm_variadic_p = 0;
13450
13451             /* The resolution to DR150 makes clear that default
13452                arguments for an N-argument may not be used to bind T
13453                to a template template parameter with fewer than N
13454                parameters.  It is not safe to permit the binding of
13455                default arguments as an extension, as that may change
13456                the meaning of a conforming program.  Consider:
13457
13458                   struct Dense { static const unsigned int dim = 1; };
13459
13460                   template <template <typename> class View,
13461                             typename Block>
13462                   void operator+(float, View<Block> const&);
13463
13464                   template <typename Block,
13465                             unsigned int Dim = Block::dim>
13466                   struct Lvalue_proxy { operator float() const; };
13467
13468                   void
13469                   test_1d (void) {
13470                     Lvalue_proxy<Dense> p;
13471                     float b;
13472                     b + p;
13473                   }
13474
13475               Here, if Lvalue_proxy is permitted to bind to View, then
13476               the global operator+ will be used; if they are not, the
13477               Lvalue_proxy will be converted to float.  */
13478             if (coerce_template_parms (parm_parms,
13479                                        argvec,
13480                                        TYPE_TI_TEMPLATE (parm),
13481                                        tf_none,
13482                                        /*require_all_args=*/true,
13483                                        /*use_default_args=*/false)
13484                 == error_mark_node)
13485               return 1;
13486
13487             /* Deduce arguments T, i from TT<T> or TT<i>.
13488                We check each element of PARMVEC and ARGVEC individually
13489                rather than the whole TREE_VEC since they can have
13490                different number of elements.  */
13491
13492             parmvec = expand_template_argument_pack (parmvec);
13493             argvec = expand_template_argument_pack (argvec);
13494
13495             len = TREE_VEC_LENGTH (parmvec);
13496
13497             /* Check if the parameters end in a pack, making them
13498                variadic.  */
13499             if (len > 0
13500                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13501               parm_variadic_p = 1;
13502             
13503             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13504               return 1;
13505
13506              for (i = 0; i < len - parm_variadic_p; ++i)
13507               {
13508                 if (unify (tparms, targs,
13509                            TREE_VEC_ELT (parmvec, i),
13510                            TREE_VEC_ELT (argvec, i),
13511                            UNIFY_ALLOW_NONE))
13512                   return 1;
13513               }
13514
13515             if (parm_variadic_p
13516                 && unify_pack_expansion (tparms, targs,
13517                                          parmvec, argvec,
13518                                          UNIFY_ALLOW_NONE,
13519                                          /*call_args_p=*/false,
13520                                          /*subr=*/false))
13521               return 1;
13522           }
13523           arg = TYPE_TI_TEMPLATE (arg);
13524
13525           /* Fall through to deduce template name.  */
13526         }
13527
13528       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13529           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13530         {
13531           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13532
13533           /* Simple cases: Value already set, does match or doesn't.  */
13534           if (targ != NULL_TREE && template_args_equal (targ, arg))
13535             return 0;
13536           else if (targ)
13537             return 1;
13538         }
13539       else
13540         {
13541           /* If PARM is `const T' and ARG is only `int', we don't have
13542              a match unless we are allowing additional qualification.
13543              If ARG is `const int' and PARM is just `T' that's OK;
13544              that binds `const int' to `T'.  */
13545           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13546                                          arg, parm))
13547             return 1;
13548
13549           /* Consider the case where ARG is `const volatile int' and
13550              PARM is `const T'.  Then, T should be `volatile int'.  */
13551           arg = cp_build_qualified_type_real
13552             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13553           if (arg == error_mark_node)
13554             return 1;
13555
13556           /* Simple cases: Value already set, does match or doesn't.  */
13557           if (targ != NULL_TREE && same_type_p (targ, arg))
13558             return 0;
13559           else if (targ)
13560             return 1;
13561
13562           /* Make sure that ARG is not a variable-sized array.  (Note
13563              that were talking about variable-sized arrays (like
13564              `int[n]'), rather than arrays of unknown size (like
13565              `int[]').)  We'll get very confused by such a type since
13566              the bound of the array will not be computable in an
13567              instantiation.  Besides, such types are not allowed in
13568              ISO C++, so we can do as we please here.  */
13569           if (variably_modified_type_p (arg, NULL_TREE))
13570             return 1;
13571
13572           /* Strip typedefs as in convert_template_argument.  */
13573           arg = canonical_type_variant (arg);
13574         }
13575
13576       /* If ARG is a parameter pack or an expansion, we cannot unify
13577          against it unless PARM is also a parameter pack.  */
13578       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13579           && !template_parameter_pack_p (parm))
13580         return 1;
13581
13582       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13583       return 0;
13584
13585     case TEMPLATE_PARM_INDEX:
13586       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13587       if (tparm == error_mark_node)
13588         return 1;
13589
13590       if (TEMPLATE_PARM_LEVEL (parm)
13591           != template_decl_level (tparm))
13592         /* The PARM is not one we're trying to unify.  Just check
13593            to see if it matches ARG.  */
13594         return !(TREE_CODE (arg) == TREE_CODE (parm)
13595                  && cp_tree_equal (parm, arg));
13596
13597       idx = TEMPLATE_PARM_IDX (parm);
13598       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13599
13600       if (targ)
13601         return !cp_tree_equal (targ, arg);
13602
13603       /* [temp.deduct.type] If, in the declaration of a function template
13604          with a non-type template-parameter, the non-type
13605          template-parameter is used in an expression in the function
13606          parameter-list and, if the corresponding template-argument is
13607          deduced, the template-argument type shall match the type of the
13608          template-parameter exactly, except that a template-argument
13609          deduced from an array bound may be of any integral type.
13610          The non-type parameter might use already deduced type parameters.  */
13611       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13612       if (!TREE_TYPE (arg))
13613         /* Template-parameter dependent expression.  Just accept it for now.
13614            It will later be processed in convert_template_argument.  */
13615         ;
13616       else if (same_type_p (TREE_TYPE (arg), tparm))
13617         /* OK */;
13618       else if ((strict & UNIFY_ALLOW_INTEGER)
13619                && (TREE_CODE (tparm) == INTEGER_TYPE
13620                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13621         /* Convert the ARG to the type of PARM; the deduced non-type
13622            template argument must exactly match the types of the
13623            corresponding parameter.  */
13624         arg = fold (build_nop (tparm, arg));
13625       else if (uses_template_parms (tparm))
13626         /* We haven't deduced the type of this parameter yet.  Try again
13627            later.  */
13628         return 0;
13629       else
13630         return 1;
13631
13632       /* If ARG is a parameter pack or an expansion, we cannot unify
13633          against it unless PARM is also a parameter pack.  */
13634       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13635           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13636         return 1;
13637
13638       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13639       return 0;
13640
13641     case PTRMEM_CST:
13642      {
13643         /* A pointer-to-member constant can be unified only with
13644          another constant.  */
13645       if (TREE_CODE (arg) != PTRMEM_CST)
13646         return 1;
13647
13648       /* Just unify the class member. It would be useless (and possibly
13649          wrong, depending on the strict flags) to unify also
13650          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13651          arg refer to the same variable, even if through different
13652          classes. For instance:
13653
13654          struct A { int x; };
13655          struct B : A { };
13656
13657          Unification of &A::x and &B::x must succeed.  */
13658       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13659                     PTRMEM_CST_MEMBER (arg), strict);
13660      }
13661
13662     case POINTER_TYPE:
13663       {
13664         if (TREE_CODE (arg) != POINTER_TYPE)
13665           return 1;
13666
13667         /* [temp.deduct.call]
13668
13669            A can be another pointer or pointer to member type that can
13670            be converted to the deduced A via a qualification
13671            conversion (_conv.qual_).
13672
13673            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13674            This will allow for additional cv-qualification of the
13675            pointed-to types if appropriate.  */
13676
13677         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13678           /* The derived-to-base conversion only persists through one
13679              level of pointers.  */
13680           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13681
13682         return unify (tparms, targs, TREE_TYPE (parm),
13683                       TREE_TYPE (arg), strict);
13684       }
13685
13686     case REFERENCE_TYPE:
13687       if (TREE_CODE (arg) != REFERENCE_TYPE)
13688         return 1;
13689       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13690                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13691
13692     case ARRAY_TYPE:
13693       if (TREE_CODE (arg) != ARRAY_TYPE)
13694         return 1;
13695       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13696           != (TYPE_DOMAIN (arg) == NULL_TREE))
13697         return 1;
13698       if (TYPE_DOMAIN (parm) != NULL_TREE)
13699         {
13700           tree parm_max;
13701           tree arg_max;
13702           bool parm_cst;
13703           bool arg_cst;
13704
13705           /* Our representation of array types uses "N - 1" as the
13706              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13707              not an integer constant.  We cannot unify arbitrarily
13708              complex expressions, so we eliminate the MINUS_EXPRs
13709              here.  */
13710           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13711           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13712           if (!parm_cst)
13713             {
13714               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13715               parm_max = TREE_OPERAND (parm_max, 0);
13716             }
13717           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13718           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13719           if (!arg_cst)
13720             {
13721               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13722                  trying to unify the type of a variable with the type
13723                  of a template parameter.  For example:
13724
13725                    template <unsigned int N>
13726                    void f (char (&) [N]);
13727                    int g(); 
13728                    void h(int i) {
13729                      char a[g(i)];
13730                      f(a); 
13731                    }
13732
13733                 Here, the type of the ARG will be "int [g(i)]", and
13734                 may be a SAVE_EXPR, etc.  */
13735               if (TREE_CODE (arg_max) != MINUS_EXPR)
13736                 return 1;
13737               arg_max = TREE_OPERAND (arg_max, 0);
13738             }
13739
13740           /* If only one of the bounds used a MINUS_EXPR, compensate
13741              by adding one to the other bound.  */
13742           if (parm_cst && !arg_cst)
13743             parm_max = fold_build2 (PLUS_EXPR,
13744                                     integer_type_node,
13745                                     parm_max,
13746                                     integer_one_node);
13747           else if (arg_cst && !parm_cst)
13748             arg_max = fold_build2 (PLUS_EXPR,
13749                                    integer_type_node,
13750                                    arg_max,
13751                                    integer_one_node);
13752
13753           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13754             return 1;
13755         }
13756       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13757                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13758
13759     case REAL_TYPE:
13760     case COMPLEX_TYPE:
13761     case VECTOR_TYPE:
13762     case INTEGER_TYPE:
13763     case BOOLEAN_TYPE:
13764     case ENUMERAL_TYPE:
13765     case VOID_TYPE:
13766       if (TREE_CODE (arg) != TREE_CODE (parm))
13767         return 1;
13768
13769       /* We have already checked cv-qualification at the top of the
13770          function.  */
13771       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13772         return 1;
13773
13774       /* As far as unification is concerned, this wins.  Later checks
13775          will invalidate it if necessary.  */
13776       return 0;
13777
13778       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13779       /* Type INTEGER_CST can come from ordinary constant template args.  */
13780     case INTEGER_CST:
13781       while (TREE_CODE (arg) == NOP_EXPR)
13782         arg = TREE_OPERAND (arg, 0);
13783
13784       if (TREE_CODE (arg) != INTEGER_CST)
13785         return 1;
13786       return !tree_int_cst_equal (parm, arg);
13787
13788     case TREE_VEC:
13789       {
13790         int i;
13791         if (TREE_CODE (arg) != TREE_VEC)
13792           return 1;
13793         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13794           return 1;
13795         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13796           if (unify (tparms, targs,
13797                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13798                      UNIFY_ALLOW_NONE))
13799             return 1;
13800         return 0;
13801       }
13802
13803     case RECORD_TYPE:
13804     case UNION_TYPE:
13805       if (TREE_CODE (arg) != TREE_CODE (parm))
13806         return 1;
13807
13808       if (TYPE_PTRMEMFUNC_P (parm))
13809         {
13810           if (!TYPE_PTRMEMFUNC_P (arg))
13811             return 1;
13812
13813           return unify (tparms, targs,
13814                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13815                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13816                         strict);
13817         }
13818
13819       if (CLASSTYPE_TEMPLATE_INFO (parm))
13820         {
13821           tree t = NULL_TREE;
13822
13823           if (strict_in & UNIFY_ALLOW_DERIVED)
13824             {
13825               /* First, we try to unify the PARM and ARG directly.  */
13826               t = try_class_unification (tparms, targs,
13827                                          parm, arg);
13828
13829               if (!t)
13830                 {
13831                   /* Fallback to the special case allowed in
13832                      [temp.deduct.call]:
13833
13834                        If P is a class, and P has the form
13835                        template-id, then A can be a derived class of
13836                        the deduced A.  Likewise, if P is a pointer to
13837                        a class of the form template-id, A can be a
13838                        pointer to a derived class pointed to by the
13839                        deduced A.  */
13840                   t = get_template_base (tparms, targs, parm, arg);
13841
13842                   if (!t)
13843                     return 1;
13844                 }
13845             }
13846           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13847                    && (CLASSTYPE_TI_TEMPLATE (parm)
13848                        == CLASSTYPE_TI_TEMPLATE (arg)))
13849             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13850                Then, we should unify `int' and `U'.  */
13851             t = arg;
13852           else
13853             /* There's no chance of unification succeeding.  */
13854             return 1;
13855
13856           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13857                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13858         }
13859       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13860         return 1;
13861       return 0;
13862
13863     case METHOD_TYPE:
13864     case FUNCTION_TYPE:
13865       if (TREE_CODE (arg) != TREE_CODE (parm))
13866         return 1;
13867
13868       /* CV qualifications for methods can never be deduced, they must
13869          match exactly.  We need to check them explicitly here,
13870          because type_unification_real treats them as any other
13871          cv-qualified parameter.  */
13872       if (TREE_CODE (parm) == METHOD_TYPE
13873           && (!check_cv_quals_for_unify
13874               (UNIFY_ALLOW_NONE,
13875                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13876                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13877         return 1;
13878
13879       if (unify (tparms, targs, TREE_TYPE (parm),
13880                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13881         return 1;
13882       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13883                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13884                                     LOOKUP_NORMAL);
13885
13886     case OFFSET_TYPE:
13887       /* Unify a pointer to member with a pointer to member function, which
13888          deduces the type of the member as a function type. */
13889       if (TYPE_PTRMEMFUNC_P (arg))
13890         {
13891           tree method_type;
13892           tree fntype;
13893           cp_cv_quals cv_quals;
13894
13895           /* Check top-level cv qualifiers */
13896           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13897             return 1;
13898
13899           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13900                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13901             return 1;
13902
13903           /* Determine the type of the function we are unifying against. */
13904           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13905           fntype =
13906             build_function_type (TREE_TYPE (method_type),
13907                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13908
13909           /* Extract the cv-qualifiers of the member function from the
13910              implicit object parameter and place them on the function
13911              type to be restored later. */
13912           cv_quals =
13913             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13914           fntype = build_qualified_type (fntype, cv_quals);
13915           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13916         }
13917
13918       if (TREE_CODE (arg) != OFFSET_TYPE)
13919         return 1;
13920       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13921                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13922         return 1;
13923       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13924                     strict);
13925
13926     case CONST_DECL:
13927       if (DECL_TEMPLATE_PARM_P (parm))
13928         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13929       if (arg != integral_constant_value (parm))
13930         return 1;
13931       return 0;
13932
13933     case FIELD_DECL:
13934     case TEMPLATE_DECL:
13935       /* Matched cases are handled by the ARG == PARM test above.  */
13936       return 1;
13937
13938     case TYPE_ARGUMENT_PACK:
13939     case NONTYPE_ARGUMENT_PACK:
13940       {
13941         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13942         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13943         int i, len = TREE_VEC_LENGTH (packed_parms);
13944         int argslen = TREE_VEC_LENGTH (packed_args);
13945         int parm_variadic_p = 0;
13946
13947         for (i = 0; i < len; ++i)
13948           {
13949             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13950               {
13951                 if (i == len - 1)
13952                   /* We can unify against something with a trailing
13953                      parameter pack.  */
13954                   parm_variadic_p = 1;
13955                 else
13956                   /* Since there is something following the pack
13957                      expansion, we cannot unify this template argument
13958                      list.  */
13959                   return 0;
13960               }
13961           }
13962           
13963
13964         /* If we don't have enough arguments to satisfy the parameters
13965            (not counting the pack expression at the end), or we have
13966            too many arguments for a parameter list that doesn't end in
13967            a pack expression, we can't unify.  */
13968         if (argslen < (len - parm_variadic_p)
13969             || (argslen > len && !parm_variadic_p))
13970           return 1;
13971
13972         /* Unify all of the parameters that precede the (optional)
13973            pack expression.  */
13974         for (i = 0; i < len - parm_variadic_p; ++i)
13975           {
13976             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13977                        TREE_VEC_ELT (packed_args, i), strict))
13978               return 1;
13979           }
13980
13981         if (parm_variadic_p)
13982           return unify_pack_expansion (tparms, targs, 
13983                                        packed_parms, packed_args,
13984                                        strict, /*call_args_p=*/false,
13985                                        /*subr=*/false);
13986         return 0;
13987       }
13988
13989       break;
13990
13991     case TYPEOF_TYPE:
13992     case DECLTYPE_TYPE:
13993       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13994          nodes.  */
13995       return 0;
13996
13997     case ERROR_MARK:
13998       /* Unification fails if we hit an error node.  */
13999       return 1;
14000
14001     default:
14002       gcc_assert (EXPR_P (parm));
14003
14004       /* We must be looking at an expression.  This can happen with
14005          something like:
14006
14007            template <int I>
14008            void foo(S<I>, S<I + 2>);
14009
14010          This is a "nondeduced context":
14011
14012            [deduct.type]
14013
14014            The nondeduced contexts are:
14015
14016            --A type that is a template-id in which one or more of
14017              the template-arguments is an expression that references
14018              a template-parameter.
14019
14020          In these cases, we assume deduction succeeded, but don't
14021          actually infer any unifications.  */
14022
14023       if (!uses_template_parms (parm)
14024           && !template_args_equal (parm, arg))
14025         return 1;
14026       else
14027         return 0;
14028     }
14029 }
14030 \f
14031 /* Note that DECL can be defined in this translation unit, if
14032    required.  */
14033
14034 static void
14035 mark_definable (tree decl)
14036 {
14037   tree clone;
14038   DECL_NOT_REALLY_EXTERN (decl) = 1;
14039   FOR_EACH_CLONE (clone, decl)
14040     DECL_NOT_REALLY_EXTERN (clone) = 1;
14041 }
14042
14043 /* Called if RESULT is explicitly instantiated, or is a member of an
14044    explicitly instantiated class.  */
14045
14046 void
14047 mark_decl_instantiated (tree result, int extern_p)
14048 {
14049   SET_DECL_EXPLICIT_INSTANTIATION (result);
14050
14051   /* If this entity has already been written out, it's too late to
14052      make any modifications.  */
14053   if (TREE_ASM_WRITTEN (result))
14054     return;
14055
14056   if (TREE_CODE (result) != FUNCTION_DECL)
14057     /* The TREE_PUBLIC flag for function declarations will have been
14058        set correctly by tsubst.  */
14059     TREE_PUBLIC (result) = 1;
14060
14061   /* This might have been set by an earlier implicit instantiation.  */
14062   DECL_COMDAT (result) = 0;
14063
14064   if (extern_p)
14065     DECL_NOT_REALLY_EXTERN (result) = 0;
14066   else
14067     {
14068       mark_definable (result);
14069       /* Always make artificials weak.  */
14070       if (DECL_ARTIFICIAL (result) && flag_weak)
14071         comdat_linkage (result);
14072       /* For WIN32 we also want to put explicit instantiations in
14073          linkonce sections.  */
14074       else if (TREE_PUBLIC (result))
14075         maybe_make_one_only (result);
14076     }
14077
14078   /* If EXTERN_P, then this function will not be emitted -- unless
14079      followed by an explicit instantiation, at which point its linkage
14080      will be adjusted.  If !EXTERN_P, then this function will be
14081      emitted here.  In neither circumstance do we want
14082      import_export_decl to adjust the linkage.  */
14083   DECL_INTERFACE_KNOWN (result) = 1;
14084 }
14085
14086 /* Given two function templates PAT1 and PAT2, return:
14087
14088    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14089    -1 if PAT2 is more specialized than PAT1.
14090    0 if neither is more specialized.
14091
14092    LEN indicates the number of parameters we should consider
14093    (defaulted parameters should not be considered).
14094
14095    The 1998 std underspecified function template partial ordering, and
14096    DR214 addresses the issue.  We take pairs of arguments, one from
14097    each of the templates, and deduce them against each other.  One of
14098    the templates will be more specialized if all the *other*
14099    template's arguments deduce against its arguments and at least one
14100    of its arguments *does* *not* deduce against the other template's
14101    corresponding argument.  Deduction is done as for class templates.
14102    The arguments used in deduction have reference and top level cv
14103    qualifiers removed.  Iff both arguments were originally reference
14104    types *and* deduction succeeds in both directions, the template
14105    with the more cv-qualified argument wins for that pairing (if
14106    neither is more cv-qualified, they both are equal).  Unlike regular
14107    deduction, after all the arguments have been deduced in this way,
14108    we do *not* verify the deduced template argument values can be
14109    substituted into non-deduced contexts, nor do we have to verify
14110    that all template arguments have been deduced.  */
14111
14112 int
14113 more_specialized_fn (tree pat1, tree pat2, int len)
14114 {
14115   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
14116   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
14117   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
14118   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
14119   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
14120   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
14121   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
14122   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
14123   int better1 = 0;
14124   int better2 = 0;
14125
14126   /* Remove the this parameter from non-static member functions.  If
14127      one is a non-static member function and the other is not a static
14128      member function, remove the first parameter from that function
14129      also.  This situation occurs for operator functions where we
14130      locate both a member function (with this pointer) and non-member
14131      operator (with explicit first operand).  */
14132   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
14133     {
14134       len--; /* LEN is the number of significant arguments for DECL1 */
14135       args1 = TREE_CHAIN (args1);
14136       if (!DECL_STATIC_FUNCTION_P (decl2))
14137         args2 = TREE_CHAIN (args2);
14138     }
14139   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
14140     {
14141       args2 = TREE_CHAIN (args2);
14142       if (!DECL_STATIC_FUNCTION_P (decl1))
14143         {
14144           len--;
14145           args1 = TREE_CHAIN (args1);
14146         }
14147     }
14148
14149   /* If only one is a conversion operator, they are unordered.  */
14150   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14151     return 0;
14152
14153   /* Consider the return type for a conversion function */
14154   if (DECL_CONV_FN_P (decl1))
14155     {
14156       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14157       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14158       len++;
14159     }
14160
14161   processing_template_decl++;
14162
14163   while (len--
14164          /* Stop when an ellipsis is seen.  */
14165          && args1 != NULL_TREE && args2 != NULL_TREE)
14166     {
14167       tree arg1 = TREE_VALUE (args1);
14168       tree arg2 = TREE_VALUE (args2);
14169       int deduce1, deduce2;
14170       int quals1 = -1;
14171       int quals2 = -1;
14172
14173       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14174           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14175         {
14176           /* When both arguments are pack expansions, we need only
14177              unify the patterns themselves.  */
14178           arg1 = PACK_EXPANSION_PATTERN (arg1);
14179           arg2 = PACK_EXPANSION_PATTERN (arg2);
14180
14181           /* This is the last comparison we need to do.  */
14182           len = 0;
14183         }
14184
14185       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14186         {
14187           arg1 = TREE_TYPE (arg1);
14188           quals1 = cp_type_quals (arg1);
14189         }
14190
14191       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14192         {
14193           arg2 = TREE_TYPE (arg2);
14194           quals2 = cp_type_quals (arg2);
14195         }
14196
14197       if ((quals1 < 0) != (quals2 < 0))
14198         {
14199           /* Only of the args is a reference, see if we should apply
14200              array/function pointer decay to it.  This is not part of
14201              DR214, but is, IMHO, consistent with the deduction rules
14202              for the function call itself, and with our earlier
14203              implementation of the underspecified partial ordering
14204              rules.  (nathan).  */
14205           if (quals1 >= 0)
14206             {
14207               switch (TREE_CODE (arg1))
14208                 {
14209                 case ARRAY_TYPE:
14210                   arg1 = TREE_TYPE (arg1);
14211                   /* FALLTHROUGH. */
14212                 case FUNCTION_TYPE:
14213                   arg1 = build_pointer_type (arg1);
14214                   break;
14215
14216                 default:
14217                   break;
14218                 }
14219             }
14220           else
14221             {
14222               switch (TREE_CODE (arg2))
14223                 {
14224                 case ARRAY_TYPE:
14225                   arg2 = TREE_TYPE (arg2);
14226                   /* FALLTHROUGH. */
14227                 case FUNCTION_TYPE:
14228                   arg2 = build_pointer_type (arg2);
14229                   break;
14230
14231                 default:
14232                   break;
14233                 }
14234             }
14235         }
14236
14237       arg1 = TYPE_MAIN_VARIANT (arg1);
14238       arg2 = TYPE_MAIN_VARIANT (arg2);
14239
14240       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14241         {
14242           int i, len2 = list_length (args2);
14243           tree parmvec = make_tree_vec (1);
14244           tree argvec = make_tree_vec (len2);
14245           tree ta = args2;
14246
14247           /* Setup the parameter vector, which contains only ARG1.  */
14248           TREE_VEC_ELT (parmvec, 0) = arg1;
14249
14250           /* Setup the argument vector, which contains the remaining
14251              arguments.  */
14252           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14253             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14254
14255           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14256                                            argvec, UNIFY_ALLOW_NONE, 
14257                                            /*call_args_p=*/false, 
14258                                            /*subr=*/0);
14259
14260           /* We cannot deduce in the other direction, because ARG1 is
14261              a pack expansion but ARG2 is not.  */
14262           deduce2 = 0;
14263         }
14264       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14265         {
14266           int i, len1 = list_length (args1);
14267           tree parmvec = make_tree_vec (1);
14268           tree argvec = make_tree_vec (len1);
14269           tree ta = args1;
14270
14271           /* Setup the parameter vector, which contains only ARG1.  */
14272           TREE_VEC_ELT (parmvec, 0) = arg2;
14273
14274           /* Setup the argument vector, which contains the remaining
14275              arguments.  */
14276           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14277             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14278
14279           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14280                                            argvec, UNIFY_ALLOW_NONE, 
14281                                            /*call_args_p=*/false, 
14282                                            /*subr=*/0);
14283
14284           /* We cannot deduce in the other direction, because ARG2 is
14285              a pack expansion but ARG1 is not.*/
14286           deduce1 = 0;
14287         }
14288
14289       else
14290         {
14291           /* The normal case, where neither argument is a pack
14292              expansion.  */
14293           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14294           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14295         }
14296
14297       if (!deduce1)
14298         better2 = -1;
14299       if (!deduce2)
14300         better1 = -1;
14301       if (better1 < 0 && better2 < 0)
14302         /* We've failed to deduce something in either direction.
14303            These must be unordered.  */
14304         break;
14305
14306       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14307         {
14308           /* Deduces in both directions, see if quals can
14309              disambiguate.  Pretend the worse one failed to deduce. */
14310           if ((quals1 & quals2) == quals2)
14311             deduce1 = 0;
14312           if ((quals1 & quals2) == quals1)
14313             deduce2 = 0;
14314         }
14315       if (deduce1 && !deduce2 && !better2)
14316         better2 = 1;
14317       if (deduce2 && !deduce1 && !better1)
14318         better1 = 1;
14319
14320       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14321           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14322         /* We have already processed all of the arguments in our
14323            handing of the pack expansion type.  */
14324         len = 0;
14325
14326       args1 = TREE_CHAIN (args1);
14327       args2 = TREE_CHAIN (args2);
14328     }
14329
14330   processing_template_decl--;
14331
14332   /* All things being equal, if the next argument is a pack expansion
14333      for one function but not for the other, prefer the
14334      non-variadic function.  */
14335   if ((better1 > 0) - (better2 > 0) == 0
14336       && args1 && TREE_VALUE (args1)
14337       && args2 && TREE_VALUE (args2))
14338     {
14339       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14340         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14341       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14342         return 1;
14343     }
14344
14345   return (better1 > 0) - (better2 > 0);
14346 }
14347
14348 /* Determine which of two partial specializations is more specialized.
14349
14350    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14351    to the first partial specialization.  The TREE_VALUE is the
14352    innermost set of template parameters for the partial
14353    specialization.  PAT2 is similar, but for the second template.
14354
14355    Return 1 if the first partial specialization is more specialized;
14356    -1 if the second is more specialized; 0 if neither is more
14357    specialized.
14358
14359    See [temp.class.order] for information about determining which of
14360    two templates is more specialized.  */
14361
14362 static int
14363 more_specialized_class (tree pat1, tree pat2)
14364 {
14365   tree targs;
14366   tree tmpl1, tmpl2;
14367   int winner = 0;
14368   bool any_deductions = false;
14369
14370   tmpl1 = TREE_TYPE (pat1);
14371   tmpl2 = TREE_TYPE (pat2);
14372
14373   /* Just like what happens for functions, if we are ordering between
14374      different class template specializations, we may encounter dependent
14375      types in the arguments, and we need our dependency check functions
14376      to behave correctly.  */
14377   ++processing_template_decl;
14378   targs = get_class_bindings (TREE_VALUE (pat1),
14379                               CLASSTYPE_TI_ARGS (tmpl1),
14380                               CLASSTYPE_TI_ARGS (tmpl2));
14381   if (targs)
14382     {
14383       --winner;
14384       any_deductions = true;
14385     }
14386
14387   targs = get_class_bindings (TREE_VALUE (pat2),
14388                               CLASSTYPE_TI_ARGS (tmpl2),
14389                               CLASSTYPE_TI_ARGS (tmpl1));
14390   if (targs)
14391     {
14392       ++winner;
14393       any_deductions = true;
14394     }
14395   --processing_template_decl;
14396
14397   /* In the case of a tie where at least one of the class templates
14398      has a parameter pack at the end, the template with the most
14399      non-packed parameters wins.  */
14400   if (winner == 0
14401       && any_deductions
14402       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14403           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14404     {
14405       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14406       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14407       int len1 = TREE_VEC_LENGTH (args1);
14408       int len2 = TREE_VEC_LENGTH (args2);
14409
14410       /* We don't count the pack expansion at the end.  */
14411       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14412         --len1;
14413       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14414         --len2;
14415
14416       if (len1 > len2)
14417         return 1;
14418       else if (len1 < len2)
14419         return -1;
14420     }
14421
14422   return winner;
14423 }
14424
14425 /* Return the template arguments that will produce the function signature
14426    DECL from the function template FN, with the explicit template
14427    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14428    also match.  Return NULL_TREE if no satisfactory arguments could be
14429    found.  */
14430
14431 static tree
14432 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14433 {
14434   int ntparms = DECL_NTPARMS (fn);
14435   tree targs = make_tree_vec (ntparms);
14436   tree decl_type;
14437   tree decl_arg_types;
14438
14439   /* Substitute the explicit template arguments into the type of DECL.
14440      The call to fn_type_unification will handle substitution into the
14441      FN.  */
14442   decl_type = TREE_TYPE (decl);
14443   if (explicit_args && uses_template_parms (decl_type))
14444     {
14445       tree tmpl;
14446       tree converted_args;
14447
14448       if (DECL_TEMPLATE_INFO (decl))
14449         tmpl = DECL_TI_TEMPLATE (decl);
14450       else
14451         /* We can get here for some invalid specializations.  */
14452         return NULL_TREE;
14453
14454       converted_args
14455         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14456                                  explicit_args, NULL_TREE,
14457                                  tf_none,
14458                                  /*require_all_args=*/false,
14459                                  /*use_default_args=*/false);
14460       if (converted_args == error_mark_node)
14461         return NULL_TREE;
14462
14463       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14464       if (decl_type == error_mark_node)
14465         return NULL_TREE;
14466     }
14467
14468   /* Never do unification on the 'this' parameter.  */
14469   decl_arg_types = skip_artificial_parms_for (decl, 
14470                                               TYPE_ARG_TYPES (decl_type));
14471
14472   if (fn_type_unification (fn, explicit_args, targs,
14473                            decl_arg_types,
14474                            (check_rettype || DECL_CONV_FN_P (fn)
14475                             ? TREE_TYPE (decl_type) : NULL_TREE),
14476                            DEDUCE_EXACT, LOOKUP_NORMAL))
14477     return NULL_TREE;
14478
14479   return targs;
14480 }
14481
14482 /* Return the innermost template arguments that, when applied to a
14483    template specialization whose innermost template parameters are
14484    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
14485    ARGS.
14486
14487    For example, suppose we have:
14488
14489      template <class T, class U> struct S {};
14490      template <class T> struct S<T*, int> {};
14491
14492    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14493    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14494    int}.  The resulting vector will be {double}, indicating that `T'
14495    is bound to `double'.  */
14496
14497 static tree
14498 get_class_bindings (tree tparms, tree spec_args, tree args)
14499 {
14500   int i, ntparms = TREE_VEC_LENGTH (tparms);
14501   tree deduced_args;
14502   tree innermost_deduced_args;
14503
14504   innermost_deduced_args = make_tree_vec (ntparms);
14505   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14506     {
14507       deduced_args = copy_node (args);
14508       SET_TMPL_ARGS_LEVEL (deduced_args,
14509                            TMPL_ARGS_DEPTH (deduced_args),
14510                            innermost_deduced_args);
14511     }
14512   else
14513     deduced_args = innermost_deduced_args;
14514
14515   if (unify (tparms, deduced_args,
14516              INNERMOST_TEMPLATE_ARGS (spec_args),
14517              INNERMOST_TEMPLATE_ARGS (args),
14518              UNIFY_ALLOW_NONE))
14519     return NULL_TREE;
14520
14521   for (i =  0; i < ntparms; ++i)
14522     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14523       return NULL_TREE;
14524
14525   /* Verify that nondeduced template arguments agree with the type
14526      obtained from argument deduction.
14527
14528      For example:
14529
14530        struct A { typedef int X; };
14531        template <class T, class U> struct C {};
14532        template <class T> struct C<T, typename T::X> {};
14533
14534      Then with the instantiation `C<A, int>', we can deduce that
14535      `T' is `A' but unify () does not check whether `typename T::X'
14536      is `int'.  */
14537   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14538   if (spec_args == error_mark_node
14539       /* We only need to check the innermost arguments; the other
14540          arguments will always agree.  */
14541       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14542                               INNERMOST_TEMPLATE_ARGS (args)))
14543     return NULL_TREE;
14544
14545   /* Now that we have bindings for all of the template arguments,
14546      ensure that the arguments deduced for the template template
14547      parameters have compatible template parameter lists.  See the use
14548      of template_template_parm_bindings_ok_p in fn_type_unification
14549      for more information.  */
14550   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14551     return NULL_TREE;
14552
14553   return deduced_args;
14554 }
14555
14556 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14557    Return the TREE_LIST node with the most specialized template, if
14558    any.  If there is no most specialized template, the error_mark_node
14559    is returned.
14560
14561    Note that this function does not look at, or modify, the
14562    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14563    returned is one of the elements of INSTANTIATIONS, callers may
14564    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14565    and retrieve it from the value returned.  */
14566
14567 tree
14568 most_specialized_instantiation (tree templates)
14569 {
14570   tree fn, champ;
14571
14572   ++processing_template_decl;
14573
14574   champ = templates;
14575   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14576     {
14577       int fate = 0;
14578
14579       if (get_bindings (TREE_VALUE (champ),
14580                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14581                         NULL_TREE, /*check_ret=*/false))
14582         fate--;
14583
14584       if (get_bindings (TREE_VALUE (fn),
14585                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14586                         NULL_TREE, /*check_ret=*/false))
14587         fate++;
14588
14589       if (fate == -1)
14590         champ = fn;
14591       else if (!fate)
14592         {
14593           /* Equally specialized, move to next function.  If there
14594              is no next function, nothing's most specialized.  */
14595           fn = TREE_CHAIN (fn);
14596           champ = fn;
14597           if (!fn)
14598             break;
14599         }
14600     }
14601
14602   if (champ)
14603     /* Now verify that champ is better than everything earlier in the
14604        instantiation list.  */
14605     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14606       if (get_bindings (TREE_VALUE (champ),
14607                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14608                         NULL_TREE, /*check_ret=*/false)
14609           || !get_bindings (TREE_VALUE (fn),
14610                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14611                             NULL_TREE, /*check_ret=*/false))
14612         {
14613           champ = NULL_TREE;
14614           break;
14615         }
14616
14617   processing_template_decl--;
14618
14619   if (!champ)
14620     return error_mark_node;
14621
14622   return champ;
14623 }
14624
14625 /* If DECL is a specialization of some template, return the most
14626    general such template.  Otherwise, returns NULL_TREE.
14627
14628    For example, given:
14629
14630      template <class T> struct S { template <class U> void f(U); };
14631
14632    if TMPL is `template <class U> void S<int>::f(U)' this will return
14633    the full template.  This function will not trace past partial
14634    specializations, however.  For example, given in addition:
14635
14636      template <class T> struct S<T*> { template <class U> void f(U); };
14637
14638    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14639    `template <class T> template <class U> S<T*>::f(U)'.  */
14640
14641 tree
14642 most_general_template (tree decl)
14643 {
14644   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14645      an immediate specialization.  */
14646   if (TREE_CODE (decl) == FUNCTION_DECL)
14647     {
14648       if (DECL_TEMPLATE_INFO (decl)) {
14649         decl = DECL_TI_TEMPLATE (decl);
14650
14651         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14652            template friend.  */
14653         if (TREE_CODE (decl) != TEMPLATE_DECL)
14654           return NULL_TREE;
14655       } else
14656         return NULL_TREE;
14657     }
14658
14659   /* Look for more and more general templates.  */
14660   while (DECL_TEMPLATE_INFO (decl))
14661     {
14662       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14663          (See cp-tree.h for details.)  */
14664       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14665         break;
14666
14667       if (CLASS_TYPE_P (TREE_TYPE (decl))
14668           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14669         break;
14670
14671       /* Stop if we run into an explicitly specialized class template.  */
14672       if (!DECL_NAMESPACE_SCOPE_P (decl)
14673           && DECL_CONTEXT (decl)
14674           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14675         break;
14676
14677       decl = DECL_TI_TEMPLATE (decl);
14678     }
14679
14680   return decl;
14681 }
14682
14683 /* Return the most specialized of the class template partial
14684    specializations of TMPL which can produce TYPE, a specialization of
14685    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14686    a _TYPE node corresponding to the partial specialization, while the
14687    TREE_PURPOSE is the set of template arguments that must be
14688    substituted into the TREE_TYPE in order to generate TYPE.
14689
14690    If the choice of partial specialization is ambiguous, a diagnostic
14691    is issued, and the error_mark_node is returned.  If there are no
14692    partial specializations of TMPL matching TYPE, then NULL_TREE is
14693    returned.  */
14694
14695 static tree
14696 most_specialized_class (tree type, tree tmpl)
14697 {
14698   tree list = NULL_TREE;
14699   tree t;
14700   tree champ;
14701   int fate;
14702   bool ambiguous_p;
14703   tree args;
14704   tree outer_args = NULL_TREE;
14705
14706   tmpl = most_general_template (tmpl);
14707   args = CLASSTYPE_TI_ARGS (type);
14708
14709   /* For determining which partial specialization to use, only the
14710      innermost args are interesting.  */
14711   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14712     {
14713       outer_args = strip_innermost_template_args (args, 1);
14714       args = INNERMOST_TEMPLATE_ARGS (args);
14715     }
14716
14717   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14718     {
14719       tree partial_spec_args;
14720       tree spec_args;
14721       tree parms = TREE_VALUE (t);
14722
14723       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14724       if (outer_args)
14725         {
14726           int i;
14727
14728           ++processing_template_decl;
14729
14730           /* Discard the outer levels of args, and then substitute in the
14731              template args from the enclosing class.  */
14732           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14733           partial_spec_args = tsubst_template_args
14734             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14735
14736           /* PARMS already refers to just the innermost parms, but the
14737              template parms in partial_spec_args had their levels lowered
14738              by tsubst, so we need to do the same for the parm list.  We
14739              can't just tsubst the TREE_VEC itself, as tsubst wants to
14740              treat a TREE_VEC as an argument vector.  */
14741           parms = copy_node (parms);
14742           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14743             TREE_VEC_ELT (parms, i) =
14744               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14745
14746           --processing_template_decl;
14747         }
14748       spec_args = get_class_bindings (parms,
14749                                       partial_spec_args,
14750                                       args);
14751       if (spec_args)
14752         {
14753           if (outer_args)
14754             spec_args = add_to_template_args (outer_args, spec_args);
14755           list = tree_cons (spec_args, TREE_VALUE (t), list);
14756           TREE_TYPE (list) = TREE_TYPE (t);
14757         }
14758     }
14759
14760   if (! list)
14761     return NULL_TREE;
14762
14763   ambiguous_p = false;
14764   t = list;
14765   champ = t;
14766   t = TREE_CHAIN (t);
14767   for (; t; t = TREE_CHAIN (t))
14768     {
14769       fate = more_specialized_class (champ, t);
14770       if (fate == 1)
14771         ;
14772       else
14773         {
14774           if (fate == 0)
14775             {
14776               t = TREE_CHAIN (t);
14777               if (! t)
14778                 {
14779                   ambiguous_p = true;
14780                   break;
14781                 }
14782             }
14783           champ = t;
14784         }
14785     }
14786
14787   if (!ambiguous_p)
14788     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14789       {
14790         fate = more_specialized_class (champ, t);
14791         if (fate != 1)
14792           {
14793             ambiguous_p = true;
14794             break;
14795           }
14796       }
14797
14798   if (ambiguous_p)
14799     {
14800       const char *str = "candidates are:";
14801       error ("ambiguous class template instantiation for %q#T", type);
14802       for (t = list; t; t = TREE_CHAIN (t))
14803         {
14804           error ("%s %+#T", str, TREE_TYPE (t));
14805           str = "               ";
14806         }
14807       return error_mark_node;
14808     }
14809
14810   return champ;
14811 }
14812
14813 /* Explicitly instantiate DECL.  */
14814
14815 void
14816 do_decl_instantiation (tree decl, tree storage)
14817 {
14818   tree result = NULL_TREE;
14819   int extern_p = 0;
14820
14821   if (!decl || decl == error_mark_node)
14822     /* An error occurred, for which grokdeclarator has already issued
14823        an appropriate message.  */
14824     return;
14825   else if (! DECL_LANG_SPECIFIC (decl))
14826     {
14827       error ("explicit instantiation of non-template %q#D", decl);
14828       return;
14829     }
14830   else if (TREE_CODE (decl) == VAR_DECL)
14831     {
14832       /* There is an asymmetry here in the way VAR_DECLs and
14833          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14834          the latter, the DECL we get back will be marked as a
14835          template instantiation, and the appropriate
14836          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14837          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14838          should handle VAR_DECLs as it currently handles
14839          FUNCTION_DECLs.  */
14840       if (!DECL_CLASS_SCOPE_P (decl))
14841         {
14842           error ("%qD is not a static data member of a class template", decl);
14843           return;
14844         }
14845       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14846       if (!result || TREE_CODE (result) != VAR_DECL)
14847         {
14848           error ("no matching template for %qD found", decl);
14849           return;
14850         }
14851       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14852         {
14853           error ("type %qT for explicit instantiation %qD does not match "
14854                  "declared type %qT", TREE_TYPE (result), decl,
14855                  TREE_TYPE (decl));
14856           return;
14857         }
14858     }
14859   else if (TREE_CODE (decl) != FUNCTION_DECL)
14860     {
14861       error ("explicit instantiation of %q#D", decl);
14862       return;
14863     }
14864   else
14865     result = decl;
14866
14867   /* Check for various error cases.  Note that if the explicit
14868      instantiation is valid the RESULT will currently be marked as an
14869      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14870      until we get here.  */
14871
14872   if (DECL_TEMPLATE_SPECIALIZATION (result))
14873     {
14874       /* DR 259 [temp.spec].
14875
14876          Both an explicit instantiation and a declaration of an explicit
14877          specialization shall not appear in a program unless the explicit
14878          instantiation follows a declaration of the explicit specialization.
14879
14880          For a given set of template parameters, if an explicit
14881          instantiation of a template appears after a declaration of an
14882          explicit specialization for that template, the explicit
14883          instantiation has no effect.  */
14884       return;
14885     }
14886   else if (DECL_EXPLICIT_INSTANTIATION (result))
14887     {
14888       /* [temp.spec]
14889
14890          No program shall explicitly instantiate any template more
14891          than once.
14892
14893          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14894          the first instantiation was `extern' and the second is not,
14895          and EXTERN_P for the opposite case.  */
14896       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14897         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
14898       /* If an "extern" explicit instantiation follows an ordinary
14899          explicit instantiation, the template is instantiated.  */
14900       if (extern_p)
14901         return;
14902     }
14903   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14904     {
14905       error ("no matching template for %qD found", result);
14906       return;
14907     }
14908   else if (!DECL_TEMPLATE_INFO (result))
14909     {
14910       permerror (input_location, "explicit instantiation of non-template %q#D", result);
14911       return;
14912     }
14913
14914   if (storage == NULL_TREE)
14915     ;
14916   else if (storage == ridpointers[(int) RID_EXTERN])
14917     {
14918       if (!in_system_header && (cxx_dialect == cxx98))
14919         pedwarn (input_location, OPT_pedantic, 
14920                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
14921                  "instantiations");
14922       extern_p = 1;
14923     }
14924   else
14925     error ("storage class %qD applied to template instantiation", storage);
14926
14927   check_explicit_instantiation_namespace (result);
14928   mark_decl_instantiated (result, extern_p);
14929   if (! extern_p)
14930     instantiate_decl (result, /*defer_ok=*/1,
14931                       /*expl_inst_class_mem_p=*/false);
14932 }
14933
14934 static void
14935 mark_class_instantiated (tree t, int extern_p)
14936 {
14937   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14938   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14939   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14940   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14941   if (! extern_p)
14942     {
14943       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14944       rest_of_type_compilation (t, 1);
14945     }
14946 }
14947
14948 /* Called from do_type_instantiation through binding_table_foreach to
14949    do recursive instantiation for the type bound in ENTRY.  */
14950 static void
14951 bt_instantiate_type_proc (binding_entry entry, void *data)
14952 {
14953   tree storage = *(tree *) data;
14954
14955   if (MAYBE_CLASS_TYPE_P (entry->type)
14956       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14957     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14958 }
14959
14960 /* Called from do_type_instantiation to instantiate a member
14961    (a member function or a static member variable) of an
14962    explicitly instantiated class template.  */
14963 static void
14964 instantiate_class_member (tree decl, int extern_p)
14965 {
14966   mark_decl_instantiated (decl, extern_p);
14967   if (! extern_p)
14968     instantiate_decl (decl, /*defer_ok=*/1,
14969                       /*expl_inst_class_mem_p=*/true);
14970 }
14971
14972 /* Perform an explicit instantiation of template class T.  STORAGE, if
14973    non-null, is the RID for extern, inline or static.  COMPLAIN is
14974    nonzero if this is called from the parser, zero if called recursively,
14975    since the standard is unclear (as detailed below).  */
14976
14977 void
14978 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14979 {
14980   int extern_p = 0;
14981   int nomem_p = 0;
14982   int static_p = 0;
14983   int previous_instantiation_extern_p = 0;
14984
14985   if (TREE_CODE (t) == TYPE_DECL)
14986     t = TREE_TYPE (t);
14987
14988   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14989     {
14990       error ("explicit instantiation of non-template type %qT", t);
14991       return;
14992     }
14993
14994   complete_type (t);
14995
14996   if (!COMPLETE_TYPE_P (t))
14997     {
14998       if (complain & tf_error)
14999         error ("explicit instantiation of %q#T before definition of template",
15000                t);
15001       return;
15002     }
15003
15004   if (storage != NULL_TREE)
15005     {
15006       if (!in_system_header)
15007         {
15008           if (storage == ridpointers[(int) RID_EXTERN])
15009             {
15010               if (cxx_dialect == cxx98)
15011                 pedwarn (input_location, OPT_pedantic, 
15012                          "ISO C++ 1998 forbids the use of %<extern%> on "
15013                          "explicit instantiations");
15014             }
15015           else
15016             pedwarn (input_location, OPT_pedantic, 
15017                      "ISO C++ forbids the use of %qE"
15018                      " on explicit instantiations", storage);
15019         }
15020
15021       if (storage == ridpointers[(int) RID_INLINE])
15022         nomem_p = 1;
15023       else if (storage == ridpointers[(int) RID_EXTERN])
15024         extern_p = 1;
15025       else if (storage == ridpointers[(int) RID_STATIC])
15026         static_p = 1;
15027       else
15028         {
15029           error ("storage class %qD applied to template instantiation",
15030                  storage);
15031           extern_p = 0;
15032         }
15033     }
15034
15035   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15036     {
15037       /* DR 259 [temp.spec].
15038
15039          Both an explicit instantiation and a declaration of an explicit
15040          specialization shall not appear in a program unless the explicit
15041          instantiation follows a declaration of the explicit specialization.
15042
15043          For a given set of template parameters, if an explicit
15044          instantiation of a template appears after a declaration of an
15045          explicit specialization for that template, the explicit
15046          instantiation has no effect.  */
15047       return;
15048     }
15049   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15050     {
15051       /* [temp.spec]
15052
15053          No program shall explicitly instantiate any template more
15054          than once.
15055
15056          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15057          instantiation was `extern'.  If EXTERN_P then the second is.
15058          These cases are OK.  */
15059       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15060
15061       if (!previous_instantiation_extern_p && !extern_p
15062           && (complain & tf_error))
15063         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
15064
15065       /* If we've already instantiated the template, just return now.  */
15066       if (!CLASSTYPE_INTERFACE_ONLY (t))
15067         return;
15068     }
15069
15070   check_explicit_instantiation_namespace (TYPE_NAME (t));
15071   mark_class_instantiated (t, extern_p);
15072
15073   if (nomem_p)
15074     return;
15075
15076   {
15077     tree tmp;
15078
15079     /* In contrast to implicit instantiation, where only the
15080        declarations, and not the definitions, of members are
15081        instantiated, we have here:
15082
15083          [temp.explicit]
15084
15085          The explicit instantiation of a class template specialization
15086          implies the instantiation of all of its members not
15087          previously explicitly specialized in the translation unit
15088          containing the explicit instantiation.
15089
15090        Of course, we can't instantiate member template classes, since
15091        we don't have any arguments for them.  Note that the standard
15092        is unclear on whether the instantiation of the members are
15093        *explicit* instantiations or not.  However, the most natural
15094        interpretation is that it should be an explicit instantiation.  */
15095
15096     if (! static_p)
15097       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
15098         if (TREE_CODE (tmp) == FUNCTION_DECL
15099             && DECL_TEMPLATE_INSTANTIATION (tmp))
15100           instantiate_class_member (tmp, extern_p);
15101
15102     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
15103       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
15104         instantiate_class_member (tmp, extern_p);
15105
15106     if (CLASSTYPE_NESTED_UTDS (t))
15107       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
15108                              bt_instantiate_type_proc, &storage);
15109   }
15110 }
15111
15112 /* Given a function DECL, which is a specialization of TMPL, modify
15113    DECL to be a re-instantiation of TMPL with the same template
15114    arguments.  TMPL should be the template into which tsubst'ing
15115    should occur for DECL, not the most general template.
15116
15117    One reason for doing this is a scenario like this:
15118
15119      template <class T>
15120      void f(const T&, int i);
15121
15122      void g() { f(3, 7); }
15123
15124      template <class T>
15125      void f(const T& t, const int i) { }
15126
15127    Note that when the template is first instantiated, with
15128    instantiate_template, the resulting DECL will have no name for the
15129    first parameter, and the wrong type for the second.  So, when we go
15130    to instantiate the DECL, we regenerate it.  */
15131
15132 static void
15133 regenerate_decl_from_template (tree decl, tree tmpl)
15134 {
15135   /* The arguments used to instantiate DECL, from the most general
15136      template.  */
15137   tree args;
15138   tree code_pattern;
15139
15140   args = DECL_TI_ARGS (decl);
15141   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
15142
15143   /* Make sure that we can see identifiers, and compute access
15144      correctly.  */
15145   push_access_scope (decl);
15146
15147   if (TREE_CODE (decl) == FUNCTION_DECL)
15148     {
15149       tree decl_parm;
15150       tree pattern_parm;
15151       tree specs;
15152       int args_depth;
15153       int parms_depth;
15154
15155       args_depth = TMPL_ARGS_DEPTH (args);
15156       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15157       if (args_depth > parms_depth)
15158         args = get_innermost_template_args (args, parms_depth);
15159
15160       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15161                                               args, tf_error, NULL_TREE);
15162       if (specs)
15163         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15164                                                     specs);
15165
15166       /* Merge parameter declarations.  */
15167       decl_parm = skip_artificial_parms_for (decl,
15168                                              DECL_ARGUMENTS (decl));
15169       pattern_parm
15170         = skip_artificial_parms_for (code_pattern,
15171                                      DECL_ARGUMENTS (code_pattern));
15172       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15173         {
15174           tree parm_type;
15175           tree attributes;
15176           
15177           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15178             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15179           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15180                               NULL_TREE);
15181           parm_type = type_decays_to (parm_type);
15182           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15183             TREE_TYPE (decl_parm) = parm_type;
15184           attributes = DECL_ATTRIBUTES (pattern_parm);
15185           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15186             {
15187               DECL_ATTRIBUTES (decl_parm) = attributes;
15188               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15189             }
15190           decl_parm = TREE_CHAIN (decl_parm);
15191           pattern_parm = TREE_CHAIN (pattern_parm);
15192         }
15193       /* Merge any parameters that match with the function parameter
15194          pack.  */
15195       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15196         {
15197           int i, len;
15198           tree expanded_types;
15199           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15200              the parameters in this function parameter pack.  */
15201           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15202                                                  args, tf_error, NULL_TREE);
15203           len = TREE_VEC_LENGTH (expanded_types);
15204           for (i = 0; i < len; i++)
15205             {
15206               tree parm_type;
15207               tree attributes;
15208           
15209               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15210                 /* Rename the parameter to include the index.  */
15211                 DECL_NAME (decl_parm) = 
15212                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15213               parm_type = TREE_VEC_ELT (expanded_types, i);
15214               parm_type = type_decays_to (parm_type);
15215               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15216                 TREE_TYPE (decl_parm) = parm_type;
15217               attributes = DECL_ATTRIBUTES (pattern_parm);
15218               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15219                 {
15220                   DECL_ATTRIBUTES (decl_parm) = attributes;
15221                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15222                 }
15223               decl_parm = TREE_CHAIN (decl_parm);
15224             }
15225         }
15226       /* Merge additional specifiers from the CODE_PATTERN.  */
15227       if (DECL_DECLARED_INLINE_P (code_pattern)
15228           && !DECL_DECLARED_INLINE_P (decl))
15229         DECL_DECLARED_INLINE_P (decl) = 1;
15230     }
15231   else if (TREE_CODE (decl) == VAR_DECL)
15232     DECL_INITIAL (decl) =
15233       tsubst_expr (DECL_INITIAL (code_pattern), args,
15234                    tf_error, DECL_TI_TEMPLATE (decl),
15235                    /*integral_constant_expression_p=*/false);
15236   else
15237     gcc_unreachable ();
15238
15239   pop_access_scope (decl);
15240 }
15241
15242 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15243    substituted to get DECL.  */
15244
15245 tree
15246 template_for_substitution (tree decl)
15247 {
15248   tree tmpl = DECL_TI_TEMPLATE (decl);
15249
15250   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15251      for the instantiation.  This is not always the most general
15252      template.  Consider, for example:
15253
15254         template <class T>
15255         struct S { template <class U> void f();
15256                    template <> void f<int>(); };
15257
15258      and an instantiation of S<double>::f<int>.  We want TD to be the
15259      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15260   while (/* An instantiation cannot have a definition, so we need a
15261             more general template.  */
15262          DECL_TEMPLATE_INSTANTIATION (tmpl)
15263            /* We must also deal with friend templates.  Given:
15264
15265                 template <class T> struct S {
15266                   template <class U> friend void f() {};
15267                 };
15268
15269               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15270               so far as the language is concerned, but that's still
15271               where we get the pattern for the instantiation from.  On
15272               other hand, if the definition comes outside the class, say:
15273
15274                 template <class T> struct S {
15275                   template <class U> friend void f();
15276                 };
15277                 template <class U> friend void f() {}
15278
15279               we don't need to look any further.  That's what the check for
15280               DECL_INITIAL is for.  */
15281           || (TREE_CODE (decl) == FUNCTION_DECL
15282               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15283               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15284     {
15285       /* The present template, TD, should not be a definition.  If it
15286          were a definition, we should be using it!  Note that we
15287          cannot restructure the loop to just keep going until we find
15288          a template with a definition, since that might go too far if
15289          a specialization was declared, but not defined.  */
15290       gcc_assert (TREE_CODE (decl) != VAR_DECL
15291                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15292
15293       /* Fetch the more general template.  */
15294       tmpl = DECL_TI_TEMPLATE (tmpl);
15295     }
15296
15297   return tmpl;
15298 }
15299
15300 /* Produce the definition of D, a _DECL generated from a template.  If
15301    DEFER_OK is nonzero, then we don't have to actually do the
15302    instantiation now; we just have to do it sometime.  Normally it is
15303    an error if this is an explicit instantiation but D is undefined.
15304    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15305    explicitly instantiated class template.  */
15306
15307 tree
15308 instantiate_decl (tree d, int defer_ok,
15309                   bool expl_inst_class_mem_p)
15310 {
15311   tree tmpl = DECL_TI_TEMPLATE (d);
15312   tree gen_args;
15313   tree args;
15314   tree td;
15315   tree code_pattern;
15316   tree spec;
15317   tree gen_tmpl;
15318   bool pattern_defined;
15319   int need_push;
15320   location_t saved_loc = input_location;
15321   bool external_p;
15322
15323   /* This function should only be used to instantiate templates for
15324      functions and static member variables.  */
15325   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15326               || TREE_CODE (d) == VAR_DECL);
15327
15328   /* Variables are never deferred; if instantiation is required, they
15329      are instantiated right away.  That allows for better code in the
15330      case that an expression refers to the value of the variable --
15331      if the variable has a constant value the referring expression can
15332      take advantage of that fact.  */
15333   if (TREE_CODE (d) == VAR_DECL)
15334     defer_ok = 0;
15335
15336   /* Don't instantiate cloned functions.  Instead, instantiate the
15337      functions they cloned.  */
15338   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15339     d = DECL_CLONED_FUNCTION (d);
15340
15341   if (DECL_TEMPLATE_INSTANTIATED (d))
15342     /* D has already been instantiated.  It might seem reasonable to
15343        check whether or not D is an explicit instantiation, and, if so,
15344        stop here.  But when an explicit instantiation is deferred
15345        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15346        is set, even though we still need to do the instantiation.  */
15347     return d;
15348
15349   /* If we already have a specialization of this declaration, then
15350      there's no reason to instantiate it.  Note that
15351      retrieve_specialization gives us both instantiations and
15352      specializations, so we must explicitly check
15353      DECL_TEMPLATE_SPECIALIZATION.  */
15354   gen_tmpl = most_general_template (tmpl);
15355   gen_args = DECL_TI_ARGS (d);
15356   spec = retrieve_specialization (gen_tmpl, gen_args,
15357                                   /*class_specializations_p=*/false);
15358   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15359     return spec;
15360
15361   /* This needs to happen before any tsubsting.  */
15362   if (! push_tinst_level (d))
15363     return d;
15364
15365   timevar_push (TV_PARSE);
15366
15367   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15368      for the instantiation.  */
15369   td = template_for_substitution (d);
15370   code_pattern = DECL_TEMPLATE_RESULT (td);
15371
15372   /* We should never be trying to instantiate a member of a class
15373      template or partial specialization.  */
15374   gcc_assert (d != code_pattern);
15375
15376   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15377       || DECL_TEMPLATE_SPECIALIZATION (td))
15378     /* In the case of a friend template whose definition is provided
15379        outside the class, we may have too many arguments.  Drop the
15380        ones we don't need.  The same is true for specializations.  */
15381     args = get_innermost_template_args
15382       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15383   else
15384     args = gen_args;
15385
15386   if (TREE_CODE (d) == FUNCTION_DECL)
15387     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15388   else
15389     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15390
15391   /* We may be in the middle of deferred access check.  Disable it now.  */
15392   push_deferring_access_checks (dk_no_deferred);
15393
15394   /* Unless an explicit instantiation directive has already determined
15395      the linkage of D, remember that a definition is available for
15396      this entity.  */
15397   if (pattern_defined
15398       && !DECL_INTERFACE_KNOWN (d)
15399       && !DECL_NOT_REALLY_EXTERN (d))
15400     mark_definable (d);
15401
15402   input_location = DECL_SOURCE_LOCATION (d);
15403
15404   /* If D is a member of an explicitly instantiated class template,
15405      and no definition is available, treat it like an implicit
15406      instantiation.  */
15407   if (!pattern_defined && expl_inst_class_mem_p
15408       && DECL_EXPLICIT_INSTANTIATION (d))
15409     {
15410       DECL_NOT_REALLY_EXTERN (d) = 0;
15411       DECL_INTERFACE_KNOWN (d) = 0;
15412       SET_DECL_IMPLICIT_INSTANTIATION (d);
15413     }
15414
15415   if (!defer_ok)
15416     {
15417       /* Recheck the substitutions to obtain any warning messages
15418          about ignoring cv qualifiers.  */
15419       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15420       tree type = TREE_TYPE (gen);
15421
15422       /* Make sure that we can see identifiers, and compute access
15423          correctly.  D is already the target FUNCTION_DECL with the
15424          right context.  */
15425       push_access_scope (d);
15426
15427       if (TREE_CODE (gen) == FUNCTION_DECL)
15428         {
15429           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15430           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15431                                           d);
15432           /* Don't simply tsubst the function type, as that will give
15433              duplicate warnings about poor parameter qualifications.
15434              The function arguments are the same as the decl_arguments
15435              without the top level cv qualifiers.  */
15436           type = TREE_TYPE (type);
15437         }
15438       tsubst (type, gen_args, tf_warning_or_error, d);
15439
15440       pop_access_scope (d);
15441     }
15442
15443   /* Check to see whether we know that this template will be
15444      instantiated in some other file, as with "extern template"
15445      extension.  */
15446   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15447   /* In general, we do not instantiate such templates...  */
15448   if (external_p
15449       /* ... but we instantiate inline functions so that we can inline
15450          them.  An explicit instantiation declaration prohibits implicit
15451          instantiation of non-inline functions.  With high levels of
15452          optimization, we would normally inline non-inline functions
15453          -- but we're not allowed to do that for "extern template" functions.
15454          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15455          possibly_inlined_p.  And ...  */
15456       && ! (TREE_CODE (d) == FUNCTION_DECL
15457             && DECL_DECLARED_INLINE_P (d))
15458       /* ... we instantiate static data members whose values are
15459          needed in integral constant expressions.  */
15460       && ! (TREE_CODE (d) == VAR_DECL
15461             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15462     goto out;
15463   /* Defer all other templates, unless we have been explicitly
15464      forbidden from doing so.  */
15465   if (/* If there is no definition, we cannot instantiate the
15466          template.  */
15467       ! pattern_defined
15468       /* If it's OK to postpone instantiation, do so.  */
15469       || defer_ok
15470       /* If this is a static data member that will be defined
15471          elsewhere, we don't want to instantiate the entire data
15472          member, but we do want to instantiate the initializer so that
15473          we can substitute that elsewhere.  */
15474       || (external_p && TREE_CODE (d) == VAR_DECL))
15475     {
15476       /* The definition of the static data member is now required so
15477          we must substitute the initializer.  */
15478       if (TREE_CODE (d) == VAR_DECL
15479           && !DECL_INITIAL (d)
15480           && DECL_INITIAL (code_pattern))
15481         {
15482           tree ns;
15483           tree init;
15484
15485           ns = decl_namespace_context (d);
15486           push_nested_namespace (ns);
15487           push_nested_class (DECL_CONTEXT (d));
15488           init = tsubst_expr (DECL_INITIAL (code_pattern),
15489                               args,
15490                               tf_warning_or_error, NULL_TREE,
15491                               /*integral_constant_expression_p=*/false);
15492           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15493                           /*asmspec_tree=*/NULL_TREE,
15494                           LOOKUP_ONLYCONVERTING);
15495           pop_nested_class ();
15496           pop_nested_namespace (ns);
15497         }
15498
15499       /* We restore the source position here because it's used by
15500          add_pending_template.  */
15501       input_location = saved_loc;
15502
15503       if (at_eof && !pattern_defined
15504           && DECL_EXPLICIT_INSTANTIATION (d)
15505           && DECL_NOT_REALLY_EXTERN (d))
15506         /* [temp.explicit]
15507
15508            The definition of a non-exported function template, a
15509            non-exported member function template, or a non-exported
15510            member function or static data member of a class template
15511            shall be present in every translation unit in which it is
15512            explicitly instantiated.  */
15513         permerror (input_location,  "explicit instantiation of %qD "
15514                    "but no definition available", d);
15515
15516       /* ??? Historically, we have instantiated inline functions, even
15517          when marked as "extern template".  */
15518       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15519         add_pending_template (d);
15520       goto out;
15521     }
15522   /* Tell the repository that D is available in this translation unit
15523      -- and see if it is supposed to be instantiated here.  */
15524   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15525     {
15526       /* In a PCH file, despite the fact that the repository hasn't
15527          requested instantiation in the PCH it is still possible that
15528          an instantiation will be required in a file that includes the
15529          PCH.  */
15530       if (pch_file)
15531         add_pending_template (d);
15532       /* Instantiate inline functions so that the inliner can do its
15533          job, even though we'll not be emitting a copy of this
15534          function.  */
15535       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15536         goto out;
15537     }
15538
15539   need_push = !cfun || !global_bindings_p ();
15540   if (need_push)
15541     push_to_top_level ();
15542
15543   /* Mark D as instantiated so that recursive calls to
15544      instantiate_decl do not try to instantiate it again.  */
15545   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15546
15547   /* Regenerate the declaration in case the template has been modified
15548      by a subsequent redeclaration.  */
15549   regenerate_decl_from_template (d, td);
15550
15551   /* We already set the file and line above.  Reset them now in case
15552      they changed as a result of calling regenerate_decl_from_template.  */
15553   input_location = DECL_SOURCE_LOCATION (d);
15554
15555   if (TREE_CODE (d) == VAR_DECL)
15556     {
15557       tree init;
15558
15559       /* Clear out DECL_RTL; whatever was there before may not be right
15560          since we've reset the type of the declaration.  */
15561       SET_DECL_RTL (d, NULL_RTX);
15562       DECL_IN_AGGR_P (d) = 0;
15563
15564       /* The initializer is placed in DECL_INITIAL by
15565          regenerate_decl_from_template.  Pull it out so that
15566          finish_decl can process it.  */
15567       init = DECL_INITIAL (d);
15568       DECL_INITIAL (d) = NULL_TREE;
15569       DECL_INITIALIZED_P (d) = 0;
15570
15571       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15572          initializer.  That function will defer actual emission until
15573          we have a chance to determine linkage.  */
15574       DECL_EXTERNAL (d) = 0;
15575
15576       /* Enter the scope of D so that access-checking works correctly.  */
15577       push_nested_class (DECL_CONTEXT (d));
15578       finish_decl (d, init, NULL_TREE);
15579       pop_nested_class ();
15580     }
15581   else if (TREE_CODE (d) == FUNCTION_DECL)
15582     {
15583       htab_t saved_local_specializations;
15584       tree subst_decl;
15585       tree tmpl_parm;
15586       tree spec_parm;
15587
15588       /* Save away the current list, in case we are instantiating one
15589          template from within the body of another.  */
15590       saved_local_specializations = local_specializations;
15591
15592       /* Set up the list of local specializations.  */
15593       local_specializations = htab_create (37,
15594                                            hash_local_specialization,
15595                                            eq_local_specializations,
15596                                            NULL);
15597
15598       /* Set up context.  */
15599       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15600
15601       /* Create substitution entries for the parameters.  */
15602       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15603       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15604       spec_parm = DECL_ARGUMENTS (d);
15605       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15606         {
15607           register_local_specialization (spec_parm, tmpl_parm);
15608           spec_parm = skip_artificial_parms_for (d, spec_parm);
15609           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15610         }
15611       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15612         {
15613           register_local_specialization (spec_parm, tmpl_parm);
15614           tmpl_parm = TREE_CHAIN (tmpl_parm);
15615           spec_parm = TREE_CHAIN (spec_parm);
15616         }
15617       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15618         {
15619           /* Register the (value) argument pack as a specialization of
15620              TMPL_PARM, then move on.  */
15621           tree argpack = make_fnparm_pack (spec_parm);
15622           register_local_specialization (argpack, tmpl_parm);
15623           tmpl_parm = TREE_CHAIN (tmpl_parm);
15624           spec_parm = NULL_TREE;
15625         }
15626       gcc_assert (!spec_parm);
15627
15628       /* Substitute into the body of the function.  */
15629       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15630                    tf_warning_or_error, tmpl,
15631                    /*integral_constant_expression_p=*/false);
15632
15633       /* Set the current input_location to the end of the function
15634          so that finish_function knows where we are.  */
15635       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15636
15637       /* We don't need the local specializations any more.  */
15638       htab_delete (local_specializations);
15639       local_specializations = saved_local_specializations;
15640
15641       /* Finish the function.  */
15642       d = finish_function (0);
15643       expand_or_defer_fn (d);
15644     }
15645
15646   /* We're not deferring instantiation any more.  */
15647   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15648
15649   if (need_push)
15650     pop_from_top_level ();
15651
15652 out:
15653   input_location = saved_loc;
15654   pop_deferring_access_checks ();
15655   pop_tinst_level ();
15656
15657   timevar_pop (TV_PARSE);
15658
15659   return d;
15660 }
15661
15662 /* Run through the list of templates that we wish we could
15663    instantiate, and instantiate any we can.  RETRIES is the
15664    number of times we retry pending template instantiation.  */
15665
15666 void
15667 instantiate_pending_templates (int retries)
15668 {
15669   int reconsider;
15670   location_t saved_loc = input_location;
15671
15672   /* Instantiating templates may trigger vtable generation.  This in turn
15673      may require further template instantiations.  We place a limit here
15674      to avoid infinite loop.  */
15675   if (pending_templates && retries >= max_tinst_depth)
15676     {
15677       tree decl = pending_templates->tinst->decl;
15678
15679       error ("template instantiation depth exceeds maximum of %d"
15680              " instantiating %q+D, possibly from virtual table generation"
15681              " (use -ftemplate-depth-NN to increase the maximum)",
15682              max_tinst_depth, decl);
15683       if (TREE_CODE (decl) == FUNCTION_DECL)
15684         /* Pretend that we defined it.  */
15685         DECL_INITIAL (decl) = error_mark_node;
15686       return;
15687     }
15688
15689   do
15690     {
15691       struct pending_template **t = &pending_templates;
15692       struct pending_template *last = NULL;
15693       reconsider = 0;
15694       while (*t)
15695         {
15696           tree instantiation = reopen_tinst_level ((*t)->tinst);
15697           bool complete = false;
15698
15699           if (TYPE_P (instantiation))
15700             {
15701               tree fn;
15702
15703               if (!COMPLETE_TYPE_P (instantiation))
15704                 {
15705                   instantiate_class_template (instantiation);
15706                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15707                     for (fn = TYPE_METHODS (instantiation);
15708                          fn;
15709                          fn = TREE_CHAIN (fn))
15710                       if (! DECL_ARTIFICIAL (fn))
15711                         instantiate_decl (fn,
15712                                           /*defer_ok=*/0,
15713                                           /*expl_inst_class_mem_p=*/false);
15714                   if (COMPLETE_TYPE_P (instantiation))
15715                     reconsider = 1;
15716                 }
15717
15718               complete = COMPLETE_TYPE_P (instantiation);
15719             }
15720           else
15721             {
15722               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15723                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15724                 {
15725                   instantiation
15726                     = instantiate_decl (instantiation,
15727                                         /*defer_ok=*/0,
15728                                         /*expl_inst_class_mem_p=*/false);
15729                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15730                     reconsider = 1;
15731                 }
15732
15733               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15734                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15735             }
15736
15737           if (complete)
15738             /* If INSTANTIATION has been instantiated, then we don't
15739                need to consider it again in the future.  */
15740             *t = (*t)->next;
15741           else
15742             {
15743               last = *t;
15744               t = &(*t)->next;
15745             }
15746           tinst_depth = 0;
15747           current_tinst_level = NULL;
15748         }
15749       last_pending_template = last;
15750     }
15751   while (reconsider);
15752
15753   input_location = saved_loc;
15754 }
15755
15756 /* Substitute ARGVEC into T, which is a list of initializers for
15757    either base class or a non-static data member.  The TREE_PURPOSEs
15758    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15759    instantiate_decl.  */
15760
15761 static tree
15762 tsubst_initializer_list (tree t, tree argvec)
15763 {
15764   tree inits = NULL_TREE;
15765
15766   for (; t; t = TREE_CHAIN (t))
15767     {
15768       tree decl;
15769       tree init;
15770       tree expanded_bases = NULL_TREE;
15771       tree expanded_arguments = NULL_TREE;
15772       int i, len = 1;
15773
15774       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15775         {
15776           tree expr;
15777           tree arg;
15778
15779           /* Expand the base class expansion type into separate base
15780              classes.  */
15781           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15782                                                  tf_warning_or_error,
15783                                                  NULL_TREE);
15784           if (expanded_bases == error_mark_node)
15785             continue;
15786           
15787           /* We'll be building separate TREE_LISTs of arguments for
15788              each base.  */
15789           len = TREE_VEC_LENGTH (expanded_bases);
15790           expanded_arguments = make_tree_vec (len);
15791           for (i = 0; i < len; i++)
15792             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15793
15794           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15795              expand each argument in the TREE_VALUE of t.  */
15796           expr = make_node (EXPR_PACK_EXPANSION);
15797           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15798             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15799
15800           if (TREE_VALUE (t) == void_type_node)
15801             /* VOID_TYPE_NODE is used to indicate
15802                value-initialization.  */
15803             {
15804               for (i = 0; i < len; i++)
15805                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15806             }
15807           else
15808             {
15809               /* Substitute parameter packs into each argument in the
15810                  TREE_LIST.  */
15811               in_base_initializer = 1;
15812               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15813                 {
15814                   tree expanded_exprs;
15815
15816                   /* Expand the argument.  */
15817                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15818                   expanded_exprs 
15819                     = tsubst_pack_expansion (expr, argvec,
15820                                              tf_warning_or_error,
15821                                              NULL_TREE);
15822                   if (expanded_exprs == error_mark_node)
15823                     continue;
15824
15825                   /* Prepend each of the expanded expressions to the
15826                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15827                   for (i = 0; i < len; i++)
15828                     {
15829                       TREE_VEC_ELT (expanded_arguments, i) = 
15830                         tree_cons (NULL_TREE, 
15831                                    TREE_VEC_ELT (expanded_exprs, i),
15832                                    TREE_VEC_ELT (expanded_arguments, i));
15833                     }
15834                 }
15835               in_base_initializer = 0;
15836
15837               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15838                  since we built them backwards.  */
15839               for (i = 0; i < len; i++)
15840                 {
15841                   TREE_VEC_ELT (expanded_arguments, i) = 
15842                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15843                 }
15844             }
15845         }
15846
15847       for (i = 0; i < len; ++i)
15848         {
15849           if (expanded_bases)
15850             {
15851               decl = TREE_VEC_ELT (expanded_bases, i);
15852               decl = expand_member_init (decl);
15853               init = TREE_VEC_ELT (expanded_arguments, i);
15854             }
15855           else
15856             {
15857               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15858                                   tf_warning_or_error, NULL_TREE);
15859
15860               decl = expand_member_init (decl);
15861               if (decl && !DECL_P (decl))
15862                 in_base_initializer = 1;
15863
15864               init = tsubst_expr (TREE_VALUE (t), argvec, 
15865                                   tf_warning_or_error, NULL_TREE,
15866                                   /*integral_constant_expression_p=*/false);
15867               in_base_initializer = 0;
15868             }
15869
15870           if (decl)
15871             {
15872               init = build_tree_list (decl, init);
15873               TREE_CHAIN (init) = inits;
15874               inits = init;
15875             }
15876         }
15877     }
15878   return inits;
15879 }
15880
15881 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15882
15883 static void
15884 set_current_access_from_decl (tree decl)
15885 {
15886   if (TREE_PRIVATE (decl))
15887     current_access_specifier = access_private_node;
15888   else if (TREE_PROTECTED (decl))
15889     current_access_specifier = access_protected_node;
15890   else
15891     current_access_specifier = access_public_node;
15892 }
15893
15894 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15895    is the instantiation (which should have been created with
15896    start_enum) and ARGS are the template arguments to use.  */
15897
15898 static void
15899 tsubst_enum (tree tag, tree newtag, tree args)
15900 {
15901   tree e;
15902
15903   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15904     {
15905       tree value;
15906       tree decl;
15907
15908       decl = TREE_VALUE (e);
15909       /* Note that in a template enum, the TREE_VALUE is the
15910          CONST_DECL, not the corresponding INTEGER_CST.  */
15911       value = tsubst_expr (DECL_INITIAL (decl),
15912                            args, tf_warning_or_error, NULL_TREE,
15913                            /*integral_constant_expression_p=*/true);
15914
15915       /* Give this enumeration constant the correct access.  */
15916       set_current_access_from_decl (decl);
15917
15918       /* Actually build the enumerator itself.  */
15919       build_enumerator (DECL_NAME (decl), value, newtag);
15920     }
15921
15922   finish_enum (newtag);
15923   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15924     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15925 }
15926
15927 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15928    its type -- but without substituting the innermost set of template
15929    arguments.  So, innermost set of template parameters will appear in
15930    the type.  */
15931
15932 tree
15933 get_mostly_instantiated_function_type (tree decl)
15934 {
15935   tree fn_type;
15936   tree tmpl;
15937   tree targs;
15938   tree tparms;
15939   int parm_depth;
15940
15941   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15942   targs = DECL_TI_ARGS (decl);
15943   tparms = DECL_TEMPLATE_PARMS (tmpl);
15944   parm_depth = TMPL_PARMS_DEPTH (tparms);
15945
15946   /* There should be as many levels of arguments as there are levels
15947      of parameters.  */
15948   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15949
15950   fn_type = TREE_TYPE (tmpl);
15951
15952   if (parm_depth == 1)
15953     /* No substitution is necessary.  */
15954     ;
15955   else
15956     {
15957       int i, save_access_control;
15958       tree partial_args;
15959
15960       /* Replace the innermost level of the TARGS with NULL_TREEs to
15961          let tsubst know not to substitute for those parameters.  */
15962       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15963       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15964         SET_TMPL_ARGS_LEVEL (partial_args, i,
15965                              TMPL_ARGS_LEVEL (targs, i));
15966       SET_TMPL_ARGS_LEVEL (partial_args,
15967                            TMPL_ARGS_DEPTH (targs),
15968                            make_tree_vec (DECL_NTPARMS (tmpl)));
15969
15970       /* Disable access control as this function is used only during
15971          name-mangling.  */
15972       save_access_control = flag_access_control;
15973       flag_access_control = 0;
15974
15975       ++processing_template_decl;
15976       /* Now, do the (partial) substitution to figure out the
15977          appropriate function type.  */
15978       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15979       --processing_template_decl;
15980
15981       /* Substitute into the template parameters to obtain the real
15982          innermost set of parameters.  This step is important if the
15983          innermost set of template parameters contains value
15984          parameters whose types depend on outer template parameters.  */
15985       TREE_VEC_LENGTH (partial_args)--;
15986       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15987
15988       flag_access_control = save_access_control;
15989     }
15990
15991   return fn_type;
15992 }
15993
15994 /* Return truthvalue if we're processing a template different from
15995    the last one involved in diagnostics.  */
15996 int
15997 problematic_instantiation_changed (void)
15998 {
15999   return last_template_error_tick != tinst_level_tick;
16000 }
16001
16002 /* Remember current template involved in diagnostics.  */
16003 void
16004 record_last_problematic_instantiation (void)
16005 {
16006   last_template_error_tick = tinst_level_tick;
16007 }
16008
16009 struct tinst_level *
16010 current_instantiation (void)
16011 {
16012   return current_tinst_level;
16013 }
16014
16015 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16016    type. Return zero for ok, nonzero for disallowed. Issue error and
16017    warning messages under control of COMPLAIN.  */
16018
16019 static int
16020 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16021 {
16022   if (INTEGRAL_TYPE_P (type))
16023     return 0;
16024   else if (POINTER_TYPE_P (type))
16025     return 0;
16026   else if (TYPE_PTR_TO_MEMBER_P (type))
16027     return 0;
16028   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16029     return 0;
16030   else if (TREE_CODE (type) == TYPENAME_TYPE)
16031     return 0;
16032
16033   if (complain & tf_error)
16034     error ("%q#T is not a valid type for a template constant parameter", type);
16035   return 1;
16036 }
16037
16038 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16039    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16040
16041 static bool
16042 dependent_type_p_r (tree type)
16043 {
16044   tree scope;
16045
16046   /* [temp.dep.type]
16047
16048      A type is dependent if it is:
16049
16050      -- a template parameter. Template template parameters are types
16051         for us (since TYPE_P holds true for them) so we handle
16052         them here.  */
16053   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16054       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
16055     return true;
16056   /* -- a qualified-id with a nested-name-specifier which contains a
16057         class-name that names a dependent type or whose unqualified-id
16058         names a dependent type.  */
16059   if (TREE_CODE (type) == TYPENAME_TYPE)
16060     return true;
16061   /* -- a cv-qualified type where the cv-unqualified type is
16062         dependent.  */
16063   type = TYPE_MAIN_VARIANT (type);
16064   /* -- a compound type constructed from any dependent type.  */
16065   if (TYPE_PTR_TO_MEMBER_P (type))
16066     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
16067             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
16068                                            (type)));
16069   else if (TREE_CODE (type) == POINTER_TYPE
16070            || TREE_CODE (type) == REFERENCE_TYPE)
16071     return dependent_type_p (TREE_TYPE (type));
16072   else if (TREE_CODE (type) == FUNCTION_TYPE
16073            || TREE_CODE (type) == METHOD_TYPE)
16074     {
16075       tree arg_type;
16076
16077       if (dependent_type_p (TREE_TYPE (type)))
16078         return true;
16079       for (arg_type = TYPE_ARG_TYPES (type);
16080            arg_type;
16081            arg_type = TREE_CHAIN (arg_type))
16082         if (dependent_type_p (TREE_VALUE (arg_type)))
16083           return true;
16084       return false;
16085     }
16086   /* -- an array type constructed from any dependent type or whose
16087         size is specified by a constant expression that is
16088         value-dependent.  */
16089   if (TREE_CODE (type) == ARRAY_TYPE)
16090     {
16091       if (TYPE_DOMAIN (type)
16092           && dependent_type_p (TYPE_DOMAIN (type)))
16093         return true;
16094       return dependent_type_p (TREE_TYPE (type));
16095     }
16096   else if (TREE_CODE (type) == INTEGER_TYPE
16097            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
16098     {
16099       /* If this is the TYPE_DOMAIN of an array type, consider it
16100          dependent.  We already checked for value-dependence in
16101          compute_array_index_type.  */
16102       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
16103     }
16104
16105   /* -- a template-id in which either the template name is a template
16106      parameter ...  */
16107   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
16108     return true;
16109   /* ... or any of the template arguments is a dependent type or
16110         an expression that is type-dependent or value-dependent.  */
16111   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
16112            && (any_dependent_template_arguments_p
16113                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
16114     return true;
16115
16116   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
16117      argument of the `typeof' expression is not type-dependent, then
16118      it should already been have resolved.  */
16119   if (TREE_CODE (type) == TYPEOF_TYPE
16120       || TREE_CODE (type) == DECLTYPE_TYPE)
16121     return true;
16122
16123   /* A template argument pack is dependent if any of its packed
16124      arguments are.  */
16125   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16126     {
16127       tree args = ARGUMENT_PACK_ARGS (type);
16128       int i, len = TREE_VEC_LENGTH (args);
16129       for (i = 0; i < len; ++i)
16130         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16131           return true;
16132     }
16133
16134   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16135      be template parameters.  */
16136   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16137     return true;
16138
16139   /* The standard does not specifically mention types that are local
16140      to template functions or local classes, but they should be
16141      considered dependent too.  For example:
16142
16143        template <int I> void f() {
16144          enum E { a = I };
16145          S<sizeof (E)> s;
16146        }
16147
16148      The size of `E' cannot be known until the value of `I' has been
16149      determined.  Therefore, `E' must be considered dependent.  */
16150   scope = TYPE_CONTEXT (type);
16151   if (scope && TYPE_P (scope))
16152     return dependent_type_p (scope);
16153   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16154     return type_dependent_expression_p (scope);
16155
16156   /* Other types are non-dependent.  */
16157   return false;
16158 }
16159
16160 /* Returns TRUE if TYPE is dependent, in the sense of
16161    [temp.dep.type].  */
16162
16163 bool
16164 dependent_type_p (tree type)
16165 {
16166   /* If there are no template parameters in scope, then there can't be
16167      any dependent types.  */
16168   if (!processing_template_decl)
16169     {
16170       /* If we are not processing a template, then nobody should be
16171          providing us with a dependent type.  */
16172       gcc_assert (type);
16173       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16174       return false;
16175     }
16176
16177   /* If the type is NULL, we have not computed a type for the entity
16178      in question; in that case, the type is dependent.  */
16179   if (!type)
16180     return true;
16181
16182   /* Erroneous types can be considered non-dependent.  */
16183   if (type == error_mark_node)
16184     return false;
16185
16186   /* If we have not already computed the appropriate value for TYPE,
16187      do so now.  */
16188   if (!TYPE_DEPENDENT_P_VALID (type))
16189     {
16190       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16191       TYPE_DEPENDENT_P_VALID (type) = 1;
16192     }
16193
16194   return TYPE_DEPENDENT_P (type);
16195 }
16196
16197 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16198    lookup.  In other words, a dependent type that is not the current
16199    instantiation.  */
16200
16201 bool
16202 dependent_scope_p (tree scope)
16203 {
16204   return (scope && TYPE_P (scope) && dependent_type_p (scope)
16205           && !currently_open_class (scope));
16206 }
16207
16208 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16209
16210 static bool
16211 dependent_scope_ref_p (tree expression, bool criterion (tree))
16212 {
16213   tree scope;
16214   tree name;
16215
16216   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16217
16218   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16219     return true;
16220
16221   scope = TREE_OPERAND (expression, 0);
16222   name = TREE_OPERAND (expression, 1);
16223
16224   /* [temp.dep.expr]
16225
16226      An id-expression is type-dependent if it contains a
16227      nested-name-specifier that contains a class-name that names a
16228      dependent type.  */
16229   /* The suggested resolution to Core Issue 224 implies that if the
16230      qualifying type is the current class, then we must peek
16231      inside it.  */
16232   if (DECL_P (name)
16233       && currently_open_class (scope)
16234       && !criterion (name))
16235     return false;
16236   if (dependent_type_p (scope))
16237     return true;
16238
16239   return false;
16240 }
16241
16242 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16243    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16244    expression.  */
16245
16246 bool
16247 value_dependent_expression_p (tree expression)
16248 {
16249   if (!processing_template_decl)
16250     return false;
16251
16252   /* A name declared with a dependent type.  */
16253   if (DECL_P (expression) && type_dependent_expression_p (expression))
16254     return true;
16255
16256   switch (TREE_CODE (expression))
16257     {
16258     case IDENTIFIER_NODE:
16259       /* A name that has not been looked up -- must be dependent.  */
16260       return true;
16261
16262     case TEMPLATE_PARM_INDEX:
16263       /* A non-type template parm.  */
16264       return true;
16265
16266     case CONST_DECL:
16267       /* A non-type template parm.  */
16268       if (DECL_TEMPLATE_PARM_P (expression))
16269         return true;
16270       return value_dependent_expression_p (DECL_INITIAL (expression));
16271
16272     case VAR_DECL:
16273        /* A constant with integral or enumeration type and is initialized
16274           with an expression that is value-dependent.  */
16275       if (DECL_INITIAL (expression)
16276           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16277           && value_dependent_expression_p (DECL_INITIAL (expression)))
16278         return true;
16279       return false;
16280
16281     case DYNAMIC_CAST_EXPR:
16282     case STATIC_CAST_EXPR:
16283     case CONST_CAST_EXPR:
16284     case REINTERPRET_CAST_EXPR:
16285     case CAST_EXPR:
16286       /* These expressions are value-dependent if the type to which
16287          the cast occurs is dependent or the expression being casted
16288          is value-dependent.  */
16289       {
16290         tree type = TREE_TYPE (expression);
16291
16292         if (dependent_type_p (type))
16293           return true;
16294
16295         /* A functional cast has a list of operands.  */
16296         expression = TREE_OPERAND (expression, 0);
16297         if (!expression)
16298           {
16299             /* If there are no operands, it must be an expression such
16300                as "int()". This should not happen for aggregate types
16301                because it would form non-constant expressions.  */
16302             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16303
16304             return false;
16305           }
16306
16307         if (TREE_CODE (expression) == TREE_LIST)
16308           return any_value_dependent_elements_p (expression);
16309
16310         return value_dependent_expression_p (expression);
16311       }
16312
16313     case SIZEOF_EXPR:
16314     case ALIGNOF_EXPR:
16315       /* A `sizeof' expression is value-dependent if the operand is
16316          type-dependent or is a pack expansion.  */
16317       expression = TREE_OPERAND (expression, 0);
16318       if (PACK_EXPANSION_P (expression))
16319         return true;
16320       else if (TYPE_P (expression))
16321         return dependent_type_p (expression);
16322       return type_dependent_expression_p (expression);
16323
16324     case SCOPE_REF:
16325       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16326
16327     case COMPONENT_REF:
16328       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16329               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16330
16331     case CALL_EXPR:
16332       /* A CALL_EXPR may appear in a constant expression if it is a
16333          call to a builtin function, e.g., __builtin_constant_p.  All
16334          such calls are value-dependent.  */
16335       return true;
16336
16337     case NONTYPE_ARGUMENT_PACK:
16338       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16339          is value-dependent.  */
16340       {
16341         tree values = ARGUMENT_PACK_ARGS (expression);
16342         int i, len = TREE_VEC_LENGTH (values);
16343         
16344         for (i = 0; i < len; ++i)
16345           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16346             return true;
16347         
16348         return false;
16349       }
16350
16351     case TRAIT_EXPR:
16352       {
16353         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16354         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16355                 || (type2 ? dependent_type_p (type2) : false));
16356       }
16357
16358     case MODOP_EXPR:
16359       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16360               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16361
16362     default:
16363       /* A constant expression is value-dependent if any subexpression is
16364          value-dependent.  */
16365       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16366         {
16367         case tcc_reference:
16368         case tcc_unary:
16369           return (value_dependent_expression_p
16370                   (TREE_OPERAND (expression, 0)));
16371
16372         case tcc_comparison:
16373         case tcc_binary:
16374           return ((value_dependent_expression_p
16375                    (TREE_OPERAND (expression, 0)))
16376                   || (value_dependent_expression_p
16377                       (TREE_OPERAND (expression, 1))));
16378
16379         case tcc_expression:
16380         case tcc_vl_exp:
16381           {
16382             int i;
16383             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16384               /* In some cases, some of the operands may be missing.
16385                  (For example, in the case of PREDECREMENT_EXPR, the
16386                  amount to increment by may be missing.)  That doesn't
16387                  make the expression dependent.  */
16388               if (TREE_OPERAND (expression, i)
16389                   && (value_dependent_expression_p
16390                       (TREE_OPERAND (expression, i))))
16391                 return true;
16392             return false;
16393           }
16394
16395         default:
16396           break;
16397         }
16398     }
16399
16400   /* The expression is not value-dependent.  */
16401   return false;
16402 }
16403
16404 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16405    [temp.dep.expr].  */
16406
16407 bool
16408 type_dependent_expression_p (tree expression)
16409 {
16410   if (!processing_template_decl)
16411     return false;
16412
16413   if (expression == error_mark_node)
16414     return false;
16415
16416   /* An unresolved name is always dependent.  */
16417   if (TREE_CODE (expression) == IDENTIFIER_NODE
16418       || TREE_CODE (expression) == USING_DECL)
16419     return true;
16420
16421   /* Some expression forms are never type-dependent.  */
16422   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16423       || TREE_CODE (expression) == SIZEOF_EXPR
16424       || TREE_CODE (expression) == ALIGNOF_EXPR
16425       || TREE_CODE (expression) == TRAIT_EXPR
16426       || TREE_CODE (expression) == TYPEID_EXPR
16427       || TREE_CODE (expression) == DELETE_EXPR
16428       || TREE_CODE (expression) == VEC_DELETE_EXPR
16429       || TREE_CODE (expression) == THROW_EXPR)
16430     return false;
16431
16432   /* The types of these expressions depends only on the type to which
16433      the cast occurs.  */
16434   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16435       || TREE_CODE (expression) == STATIC_CAST_EXPR
16436       || TREE_CODE (expression) == CONST_CAST_EXPR
16437       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16438       || TREE_CODE (expression) == CAST_EXPR)
16439     return dependent_type_p (TREE_TYPE (expression));
16440
16441   /* The types of these expressions depends only on the type created
16442      by the expression.  */
16443   if (TREE_CODE (expression) == NEW_EXPR
16444       || TREE_CODE (expression) == VEC_NEW_EXPR)
16445     {
16446       /* For NEW_EXPR tree nodes created inside a template, either
16447          the object type itself or a TREE_LIST may appear as the
16448          operand 1.  */
16449       tree type = TREE_OPERAND (expression, 1);
16450       if (TREE_CODE (type) == TREE_LIST)
16451         /* This is an array type.  We need to check array dimensions
16452            as well.  */
16453         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16454                || value_dependent_expression_p
16455                     (TREE_OPERAND (TREE_VALUE (type), 1));
16456       else
16457         return dependent_type_p (type);
16458     }
16459
16460   if (TREE_CODE (expression) == SCOPE_REF
16461       && dependent_scope_ref_p (expression,
16462                                 type_dependent_expression_p))
16463     return true;
16464
16465   if (TREE_CODE (expression) == FUNCTION_DECL
16466       && DECL_LANG_SPECIFIC (expression)
16467       && DECL_TEMPLATE_INFO (expression)
16468       && (any_dependent_template_arguments_p
16469           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16470     return true;
16471
16472   if (TREE_CODE (expression) == TEMPLATE_DECL
16473       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16474     return false;
16475
16476   if (TREE_CODE (expression) == STMT_EXPR)
16477     expression = stmt_expr_value_expr (expression);
16478
16479   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16480     {
16481       tree elt;
16482       unsigned i;
16483
16484       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16485         {
16486           if (type_dependent_expression_p (elt))
16487             return true;
16488         }
16489       return false;
16490     }
16491
16492   if (TREE_TYPE (expression) == unknown_type_node)
16493     {
16494       if (TREE_CODE (expression) == ADDR_EXPR)
16495         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16496       if (TREE_CODE (expression) == COMPONENT_REF
16497           || TREE_CODE (expression) == OFFSET_REF)
16498         {
16499           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16500             return true;
16501           expression = TREE_OPERAND (expression, 1);
16502           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16503             return false;
16504         }
16505       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16506       if (TREE_CODE (expression) == SCOPE_REF)
16507         return false;
16508
16509       if (TREE_CODE (expression) == BASELINK)
16510         expression = BASELINK_FUNCTIONS (expression);
16511
16512       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16513         {
16514           if (any_dependent_template_arguments_p
16515               (TREE_OPERAND (expression, 1)))
16516             return true;
16517           expression = TREE_OPERAND (expression, 0);
16518         }
16519       gcc_assert (TREE_CODE (expression) == OVERLOAD
16520                   || TREE_CODE (expression) == FUNCTION_DECL);
16521
16522       while (expression)
16523         {
16524           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16525             return true;
16526           expression = OVL_NEXT (expression);
16527         }
16528       return false;
16529     }
16530
16531   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16532
16533   return (dependent_type_p (TREE_TYPE (expression)));
16534 }
16535
16536 /* Like type_dependent_expression_p, but it also works while not processing
16537    a template definition, i.e. during substitution or mangling.  */
16538
16539 bool
16540 type_dependent_expression_p_push (tree expr)
16541 {
16542   bool b;
16543   ++processing_template_decl;
16544   b = type_dependent_expression_p (expr);
16545   --processing_template_decl;
16546   return b;
16547 }
16548
16549 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16550    contains a type-dependent expression.  */
16551
16552 bool
16553 any_type_dependent_arguments_p (const_tree args)
16554 {
16555   while (args)
16556     {
16557       tree arg = TREE_VALUE (args);
16558
16559       if (type_dependent_expression_p (arg))
16560         return true;
16561       args = TREE_CHAIN (args);
16562     }
16563   return false;
16564 }
16565
16566 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16567    expressions) contains any value-dependent expressions.  */
16568
16569 bool
16570 any_value_dependent_elements_p (const_tree list)
16571 {
16572   for (; list; list = TREE_CHAIN (list))
16573     if (value_dependent_expression_p (TREE_VALUE (list)))
16574       return true;
16575
16576   return false;
16577 }
16578
16579 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16580
16581 bool
16582 dependent_template_arg_p (tree arg)
16583 {
16584   if (!processing_template_decl)
16585     return false;
16586
16587   if (TREE_CODE (arg) == TEMPLATE_DECL
16588       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16589     return dependent_template_p (arg);
16590   else if (ARGUMENT_PACK_P (arg))
16591     {
16592       tree args = ARGUMENT_PACK_ARGS (arg);
16593       int i, len = TREE_VEC_LENGTH (args);
16594       for (i = 0; i < len; ++i)
16595         {
16596           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16597             return true;
16598         }
16599
16600       return false;
16601     }
16602   else if (TYPE_P (arg))
16603     return dependent_type_p (arg);
16604   else
16605     return (type_dependent_expression_p (arg)
16606             || value_dependent_expression_p (arg));
16607 }
16608
16609 /* Returns true if ARGS (a collection of template arguments) contains
16610    any types that require structural equality testing.  */
16611
16612 bool
16613 any_template_arguments_need_structural_equality_p (tree args)
16614 {
16615   int i;
16616   int j;
16617
16618   if (!args)
16619     return false;
16620   if (args == error_mark_node)
16621     return true;
16622
16623   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16624     {
16625       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16626       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16627         {
16628           tree arg = TREE_VEC_ELT (level, j);
16629           tree packed_args = NULL_TREE;
16630           int k, len = 1;
16631
16632           if (ARGUMENT_PACK_P (arg))
16633             {
16634               /* Look inside the argument pack.  */
16635               packed_args = ARGUMENT_PACK_ARGS (arg);
16636               len = TREE_VEC_LENGTH (packed_args);
16637             }
16638
16639           for (k = 0; k < len; ++k)
16640             {
16641               if (packed_args)
16642                 arg = TREE_VEC_ELT (packed_args, k);
16643
16644               if (error_operand_p (arg))
16645                 return true;
16646               else if (TREE_CODE (arg) == TEMPLATE_DECL
16647                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16648                 continue;
16649               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16650                 return true;
16651               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16652                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16653                 return true;
16654             }
16655         }
16656     }
16657
16658   return false;
16659 }
16660
16661 /* Returns true if ARGS (a collection of template arguments) contains
16662    any dependent arguments.  */
16663
16664 bool
16665 any_dependent_template_arguments_p (const_tree args)
16666 {
16667   int i;
16668   int j;
16669
16670   if (!args)
16671     return false;
16672   if (args == error_mark_node)
16673     return true;
16674
16675   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16676     {
16677       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16678       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16679         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16680           return true;
16681     }
16682
16683   return false;
16684 }
16685
16686 /* Returns TRUE if the template TMPL is dependent.  */
16687
16688 bool
16689 dependent_template_p (tree tmpl)
16690 {
16691   if (TREE_CODE (tmpl) == OVERLOAD)
16692     {
16693       while (tmpl)
16694         {
16695           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16696             return true;
16697           tmpl = OVL_CHAIN (tmpl);
16698         }
16699       return false;
16700     }
16701
16702   /* Template template parameters are dependent.  */
16703   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16704       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16705     return true;
16706   /* So are names that have not been looked up.  */
16707   if (TREE_CODE (tmpl) == SCOPE_REF
16708       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16709     return true;
16710   /* So are member templates of dependent classes.  */
16711   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16712     return dependent_type_p (DECL_CONTEXT (tmpl));
16713   return false;
16714 }
16715
16716 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16717
16718 bool
16719 dependent_template_id_p (tree tmpl, tree args)
16720 {
16721   return (dependent_template_p (tmpl)
16722           || any_dependent_template_arguments_p (args));
16723 }
16724
16725 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16726    is dependent.  */
16727
16728 bool
16729 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16730 {
16731   int i;
16732
16733   if (!processing_template_decl)
16734     return false;
16735
16736   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16737     {
16738       tree decl = TREE_VEC_ELT (declv, i);
16739       tree init = TREE_VEC_ELT (initv, i);
16740       tree cond = TREE_VEC_ELT (condv, i);
16741       tree incr = TREE_VEC_ELT (incrv, i);
16742
16743       if (type_dependent_expression_p (decl))
16744         return true;
16745
16746       if (init && type_dependent_expression_p (init))
16747         return true;
16748
16749       if (type_dependent_expression_p (cond))
16750         return true;
16751
16752       if (COMPARISON_CLASS_P (cond)
16753           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16754               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16755         return true;
16756
16757       if (TREE_CODE (incr) == MODOP_EXPR)
16758         {
16759           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16760               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16761             return true;
16762         }
16763       else if (type_dependent_expression_p (incr))
16764         return true;
16765       else if (TREE_CODE (incr) == MODIFY_EXPR)
16766         {
16767           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16768             return true;
16769           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16770             {
16771               tree t = TREE_OPERAND (incr, 1);
16772               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16773                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16774                 return true;
16775             }
16776         }
16777     }
16778
16779   return false;
16780 }
16781
16782 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16783    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16784    no such TYPE can be found.  Note that this function peers inside
16785    uninstantiated templates and therefore should be used only in
16786    extremely limited situations.  ONLY_CURRENT_P restricts this
16787    peering to the currently open classes hierarchy (which is required
16788    when comparing types).  */
16789
16790 tree
16791 resolve_typename_type (tree type, bool only_current_p)
16792 {
16793   tree scope;
16794   tree name;
16795   tree decl;
16796   int quals;
16797   tree pushed_scope;
16798   tree result;
16799
16800   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16801
16802   scope = TYPE_CONTEXT (type);
16803   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
16804      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
16805      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
16806      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
16807      identifier  of the TYPENAME_TYPE anymore.
16808      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
16809      TYPENAME_TYPE instead, we avoid messing up with a possible
16810      typedef variant case.  */
16811   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
16812
16813   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16814      it first before we can figure out what NAME refers to.  */
16815   if (TREE_CODE (scope) == TYPENAME_TYPE)
16816     scope = resolve_typename_type (scope, only_current_p);
16817   /* If we don't know what SCOPE refers to, then we cannot resolve the
16818      TYPENAME_TYPE.  */
16819   if (TREE_CODE (scope) == TYPENAME_TYPE)
16820     return type;
16821   /* If the SCOPE is a template type parameter, we have no way of
16822      resolving the name.  */
16823   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16824     return type;
16825   /* If the SCOPE is not the current instantiation, there's no reason
16826      to look inside it.  */
16827   if (only_current_p && !currently_open_class (scope))
16828     return type;
16829   /* If SCOPE isn't the template itself, it will not have a valid
16830      TYPE_FIELDS list.  */
16831   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16832     /* scope is either the template itself or a compatible instantiation
16833        like X<T>, so look up the name in the original template.  */
16834     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16835   else
16836     /* scope is a partial instantiation, so we can't do the lookup or we
16837        will lose the template arguments.  */
16838     return type;
16839   /* Enter the SCOPE so that name lookup will be resolved as if we
16840      were in the class definition.  In particular, SCOPE will no
16841      longer be considered a dependent type.  */
16842   pushed_scope = push_scope (scope);
16843   /* Look up the declaration.  */
16844   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16845
16846   result = NULL_TREE;
16847   
16848   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16849      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16850   if (!decl)
16851     /*nop*/;
16852   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16853            && TREE_CODE (decl) == TYPE_DECL)
16854     {
16855       result = TREE_TYPE (decl);
16856       if (result == error_mark_node)
16857         result = NULL_TREE;
16858     }
16859   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16860            && DECL_CLASS_TEMPLATE_P (decl))
16861     {
16862       tree tmpl;
16863       tree args;
16864       /* Obtain the template and the arguments.  */
16865       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16866       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16867       /* Instantiate the template.  */
16868       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16869                                       /*entering_scope=*/0,
16870                                       tf_error | tf_user);
16871       if (result == error_mark_node)
16872         result = NULL_TREE;
16873     }
16874   
16875   /* Leave the SCOPE.  */
16876   if (pushed_scope)
16877     pop_scope (pushed_scope);
16878
16879   /* If we failed to resolve it, return the original typename.  */
16880   if (!result)
16881     return type;
16882   
16883   /* If lookup found a typename type, resolve that too.  */
16884   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16885     {
16886       /* Ill-formed programs can cause infinite recursion here, so we
16887          must catch that.  */
16888       TYPENAME_IS_RESOLVING_P (type) = 1;
16889       result = resolve_typename_type (result, only_current_p);
16890       TYPENAME_IS_RESOLVING_P (type) = 0;
16891     }
16892   
16893   /* Qualify the resulting type.  */
16894   quals = cp_type_quals (type);
16895   if (quals)
16896     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16897
16898   return result;
16899 }
16900
16901 /* EXPR is an expression which is not type-dependent.  Return a proxy
16902    for EXPR that can be used to compute the types of larger
16903    expressions containing EXPR.  */
16904
16905 tree
16906 build_non_dependent_expr (tree expr)
16907 {
16908   tree inner_expr;
16909
16910   /* Preserve null pointer constants so that the type of things like
16911      "p == 0" where "p" is a pointer can be determined.  */
16912   if (null_ptr_cst_p (expr))
16913     return expr;
16914   /* Preserve OVERLOADs; the functions must be available to resolve
16915      types.  */
16916   inner_expr = expr;
16917   if (TREE_CODE (inner_expr) == STMT_EXPR)
16918     inner_expr = stmt_expr_value_expr (inner_expr);
16919   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16920     inner_expr = TREE_OPERAND (inner_expr, 0);
16921   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16922     inner_expr = TREE_OPERAND (inner_expr, 1);
16923   if (is_overloaded_fn (inner_expr)
16924       || TREE_CODE (inner_expr) == OFFSET_REF)
16925     return expr;
16926   /* There is no need to return a proxy for a variable.  */
16927   if (TREE_CODE (expr) == VAR_DECL)
16928     return expr;
16929   /* Preserve string constants; conversions from string constants to
16930      "char *" are allowed, even though normally a "const char *"
16931      cannot be used to initialize a "char *".  */
16932   if (TREE_CODE (expr) == STRING_CST)
16933     return expr;
16934   /* Preserve arithmetic constants, as an optimization -- there is no
16935      reason to create a new node.  */
16936   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16937     return expr;
16938   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16939      There is at least one place where we want to know that a
16940      particular expression is a throw-expression: when checking a ?:
16941      expression, there are special rules if the second or third
16942      argument is a throw-expression.  */
16943   if (TREE_CODE (expr) == THROW_EXPR)
16944     return expr;
16945
16946   if (TREE_CODE (expr) == COND_EXPR)
16947     return build3 (COND_EXPR,
16948                    TREE_TYPE (expr),
16949                    TREE_OPERAND (expr, 0),
16950                    (TREE_OPERAND (expr, 1)
16951                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16952                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16953                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16954   if (TREE_CODE (expr) == COMPOUND_EXPR
16955       && !COMPOUND_EXPR_OVERLOADED (expr))
16956     return build2 (COMPOUND_EXPR,
16957                    TREE_TYPE (expr),
16958                    TREE_OPERAND (expr, 0),
16959                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16960
16961   /* If the type is unknown, it can't really be non-dependent */
16962   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16963
16964   /* Otherwise, build a NON_DEPENDENT_EXPR.
16965
16966      REFERENCE_TYPEs are not stripped for expressions in templates
16967      because doing so would play havoc with mangling.  Consider, for
16968      example:
16969
16970        template <typename T> void f<T& g>() { g(); }
16971
16972      In the body of "f", the expression for "g" will have
16973      REFERENCE_TYPE, even though the standard says that it should
16974      not.  The reason is that we must preserve the syntactic form of
16975      the expression so that mangling (say) "f<g>" inside the body of
16976      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16977      stripped here.  */
16978   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16979 }
16980
16981 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16982    Return a new TREE_LIST with the various arguments replaced with
16983    equivalent non-dependent expressions.  */
16984
16985 tree
16986 build_non_dependent_args (tree args)
16987 {
16988   tree a;
16989   tree new_args;
16990
16991   new_args = NULL_TREE;
16992   for (a = args; a; a = TREE_CHAIN (a))
16993     new_args = tree_cons (NULL_TREE,
16994                           build_non_dependent_expr (TREE_VALUE (a)),
16995                           new_args);
16996   return nreverse (new_args);
16997 }
16998
16999 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17000    with a level one deeper than the actual template parms.  */
17001
17002 tree
17003 make_auto (void)
17004 {
17005   tree au;
17006
17007   /* ??? Is it worth caching this for multiple autos at the same level?  */
17008   au = cxx_make_type (TEMPLATE_TYPE_PARM);
17009   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
17010   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17011   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17012     (0, processing_template_decl + 1, processing_template_decl + 1,
17013      TYPE_NAME (au), NULL_TREE);
17014   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17015   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17016   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17017
17018   return au;
17019 }
17020
17021 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17022
17023 static tree
17024 listify_autos (tree type, tree auto_node)
17025 {
17026   tree std_init_list = namespace_binding
17027     (get_identifier ("initializer_list"), std_node);
17028   tree argvec;
17029   tree init_auto;
17030   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17031     {    
17032       error ("deducing auto from brace-enclosed initializer list requires "
17033              "#include <initializer_list>");
17034       return error_mark_node;
17035     }
17036   argvec = make_tree_vec (1);
17037   TREE_VEC_ELT (argvec, 0) = auto_node;
17038   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
17039                                      NULL_TREE, 0, tf_warning_or_error);
17040
17041   TREE_VEC_ELT (argvec, 0) = init_auto;
17042   if (processing_template_decl)
17043     argvec = add_to_template_args (current_template_args (), argvec);
17044   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17045 }
17046
17047 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
17048    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
17049
17050 tree
17051 do_auto_deduction (tree type, tree init, tree auto_node)
17052 {
17053   tree parms, args, tparms, targs;
17054   int val;
17055
17056   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
17057      with either a new invented type template parameter U or, if the
17058      initializer is a braced-init-list (8.5.4), with
17059      std::initializer_list<U>.  */
17060   if (BRACE_ENCLOSED_INITIALIZER_P (init))
17061     type = listify_autos (type, auto_node);
17062
17063   parms = build_tree_list (NULL_TREE, type);
17064   args = build_tree_list (NULL_TREE, init);
17065   tparms = make_tree_vec (1);
17066   targs = make_tree_vec (1);
17067   TREE_VEC_ELT (tparms, 0)
17068     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
17069   val = type_unification_real (tparms, targs, parms, args, 0,
17070                                DEDUCE_CALL, LOOKUP_NORMAL);
17071   if (val > 0)
17072     {
17073       error ("unable to deduce %qT from %qE", type, init);
17074       return error_mark_node;
17075     }
17076
17077   if (processing_template_decl)
17078     targs = add_to_template_args (current_template_args (), targs);
17079   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
17080 }
17081
17082 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
17083    result.  */
17084
17085 tree
17086 splice_late_return_type (tree type, tree late_return_type)
17087 {
17088   tree argvec;
17089
17090   if (late_return_type == NULL_TREE)
17091     return type;
17092   argvec = make_tree_vec (1);
17093   TREE_VEC_ELT (argvec, 0) = late_return_type;
17094   if (processing_template_decl)
17095     argvec = add_to_template_args (current_template_args (), argvec);
17096   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
17097 }
17098
17099 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
17100
17101 bool
17102 is_auto (const_tree type)
17103 {
17104   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17105       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
17106     return true;
17107   else
17108     return false;
17109 }
17110
17111 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
17112    appear as a type-specifier for the declaration in question, we don't
17113    have to look through the whole type.  */
17114
17115 tree
17116 type_uses_auto (tree type)
17117 {
17118   enum tree_code code;
17119   if (is_auto (type))
17120     return type;
17121
17122   code = TREE_CODE (type);
17123
17124   if (code == POINTER_TYPE || code == REFERENCE_TYPE
17125       || code == OFFSET_TYPE || code == FUNCTION_TYPE
17126       || code == METHOD_TYPE || code == ARRAY_TYPE)
17127     return type_uses_auto (TREE_TYPE (type));
17128
17129   if (TYPE_PTRMEMFUNC_P (type))
17130     return type_uses_auto (TREE_TYPE (TREE_TYPE
17131                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
17132
17133   return NULL_TREE;
17134 }
17135
17136 /* Append TYPE_DECL to the template TEMPL.
17137    TEMPL is either a class type or a FUNCTION_DECL associated
17138    to a TEMPLATE_DECL.
17139    At TEMPL instanciation time, TYPE_DECL will be checked to see
17140    if it can be accessed through SCOPE.  */
17141
17142 void
17143 append_type_to_template_for_access_check (tree templ,
17144                                           tree type_decl,
17145                                           tree scope)
17146 {
17147   tree node, templ_decl;
17148
17149   gcc_assert (templ
17150               && get_template_info (templ)
17151               && TI_TEMPLATE (get_template_info (templ))
17152               && type_decl
17153               && (TREE_CODE (type_decl) == TYPE_DECL));
17154
17155   templ_decl = TI_TEMPLATE (get_template_info (templ));
17156   gcc_assert (templ_decl);
17157
17158   /* Make sure we don't append the type to the template twice.
17159      If this appears to be too slow, the
17160      MEMBER_TYPE_NEEDING_ACCESS_CHECK property
17161      of templ should be a hash table instead.  */
17162   for (node = MEMBER_TYPES_NEEDING_ACCESS_CHECK (templ_decl);
17163        node;
17164        node = TREE_CHAIN (node))
17165     {
17166       tree decl = TREE_PURPOSE (node);
17167       tree type_scope = TREE_VALUE (node);
17168
17169       if (decl == type_decl && type_scope == scope)
17170         return;
17171     }
17172
17173   MEMBER_TYPES_NEEDING_ACCESS_CHECK (templ_decl) =
17174     tree_cons (type_decl, scope,
17175                MEMBER_TYPES_NEEDING_ACCESS_CHECK (templ_decl));
17176 }
17177
17178 #include "gt-cp-pt.h"