OSDN Git Service

2006-08-09 Lee Millward <lee.millward@codesourcery.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  Free Software Foundation, Inc.
4    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
5    Rewritten by Jason Merrill (jason@cygnus.com).
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to
21 the Free Software Foundation, 51 Franklin Street, Fifth Floor,
22 Boston, MA 02110-1301, USA.  */
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    The TREE_PURPOSE of each entry is either a DECL (for a function or
58    static data member), or a TYPE (for a class) indicating what we are
59    hoping to instantiate.  The TREE_VALUE is not used.  */
60 static GTY(()) tree pending_templates;
61 static GTY(()) tree last_pending_template;
62
63 int processing_template_parmlist;
64 static int template_header_count;
65
66 static GTY(()) tree saved_trees;
67 static VEC(int,heap) *inline_parm_levels;
68
69 static GTY(()) tree current_tinst_level;
70
71 static GTY(()) tree saved_access_scope;
72
73 /* Live only within one (recursive) call to tsubst_expr.  We use
74    this to pass the statement expression node from the STMT_EXPR
75    to the EXPR_STMT that is its result.  */
76 static tree cur_stmt_expr;
77
78 /* A map from local variable declarations in the body of the template
79    presently being instantiated to the corresponding instantiated
80    local variables.  */
81 static htab_t local_specializations;
82
83 #define UNIFY_ALLOW_NONE 0
84 #define UNIFY_ALLOW_MORE_CV_QUAL 1
85 #define UNIFY_ALLOW_LESS_CV_QUAL 2
86 #define UNIFY_ALLOW_DERIVED 4
87 #define UNIFY_ALLOW_INTEGER 8
88 #define UNIFY_ALLOW_OUTER_LEVEL 16
89 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
90 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
91
92 static void push_access_scope (tree);
93 static void pop_access_scope (tree);
94 static int resolve_overloaded_unification (tree, tree, tree, tree,
95                                            unification_kind_t, int);
96 static int try_one_overload (tree, tree, tree, tree, tree,
97                              unification_kind_t, int, bool);
98 static int unify (tree, tree, tree, tree, int);
99 static void add_pending_template (tree);
100 static int push_tinst_level (tree);
101 static void pop_tinst_level (void);
102 static void reopen_tinst_level (tree);
103 static tree classtype_mangled_name (tree);
104 static char* mangle_class_name_for_template (const char *, tree, tree);
105 static tree tsubst_initializer_list (tree, tree);
106 static tree get_class_bindings (tree, tree, tree);
107 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
108                                    bool, bool);
109 static void tsubst_enum (tree, tree, tree);
110 static tree add_to_template_args (tree, tree);
111 static tree add_outermost_template_args (tree, tree);
112 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
113 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*);
114 static int  type_unification_real (tree, tree, tree, tree,
115                                    int, unification_kind_t, int);
116 static void note_template_header (int);
117 static tree convert_nontype_argument_function (tree, tree);
118 static tree convert_nontype_argument (tree, tree);
119 static tree convert_template_argument (tree, tree, tree,
120                                        tsubst_flags_t, int, tree);
121 static int for_each_template_parm (tree, tree_fn_t, void*,
122                                    struct pointer_set_t*);
123 static tree build_template_parm_index (int, int, int, tree, tree);
124 static int inline_needs_template_parms (tree);
125 static void push_inline_template_parms_recursive (tree, int);
126 static tree retrieve_local_specialization (tree);
127 static void register_local_specialization (tree, tree);
128 static tree reduce_template_parm_level (tree, tree, int);
129 static int mark_template_parm (tree, void *);
130 static int template_parm_this_level_p (tree, void *);
131 static tree tsubst_friend_function (tree, tree);
132 static tree tsubst_friend_class (tree, tree);
133 static int can_complete_type_without_circularity (tree);
134 static tree get_bindings (tree, tree, tree, bool);
135 static int template_decl_level (tree);
136 static int check_cv_quals_for_unify (int, tree, tree);
137 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
138 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
139 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
140 static void regenerate_decl_from_template (tree, tree);
141 static tree most_specialized_class (tree, tree);
142 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
143 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
144 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
145 static void check_specialization_scope (void);
146 static tree process_partial_specialization (tree);
147 static void set_current_access_from_decl (tree);
148 static void check_default_tmpl_args (tree, tree, int, int);
149 static tree get_template_base (tree, tree, tree, tree);
150 static tree try_class_unification (tree, tree, tree, tree);
151 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
152                                            tree, tree);
153 static int template_args_equal (tree, tree);
154 static void tsubst_default_arguments (tree);
155 static tree for_each_template_parm_r (tree *, int *, void *);
156 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
157 static void copy_default_args_to_explicit_spec (tree);
158 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
159 static int eq_local_specializations (const void *, const void *);
160 static bool dependent_type_p_r (tree);
161 static tree tsubst (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree);
163 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
164
165 /* Make the current scope suitable for access checking when we are
166    processing T.  T can be FUNCTION_DECL for instantiated function
167    template, or VAR_DECL for static member variable (need by
168    instantiate_decl).  */
169
170 static void
171 push_access_scope (tree t)
172 {
173   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
174               || TREE_CODE (t) == VAR_DECL);
175
176   if (DECL_FRIEND_CONTEXT (t))
177     push_nested_class (DECL_FRIEND_CONTEXT (t));
178   else if (DECL_CLASS_SCOPE_P (t))
179     push_nested_class (DECL_CONTEXT (t));
180   else
181     push_to_top_level ();
182
183   if (TREE_CODE (t) == FUNCTION_DECL)
184     {
185       saved_access_scope = tree_cons
186         (NULL_TREE, current_function_decl, saved_access_scope);
187       current_function_decl = t;
188     }
189 }
190
191 /* Restore the scope set up by push_access_scope.  T is the node we
192    are processing.  */
193
194 static void
195 pop_access_scope (tree t)
196 {
197   if (TREE_CODE (t) == FUNCTION_DECL)
198     {
199       current_function_decl = TREE_VALUE (saved_access_scope);
200       saved_access_scope = TREE_CHAIN (saved_access_scope);
201     }
202
203   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
204     pop_nested_class ();
205   else
206     pop_from_top_level ();
207 }
208
209 /* Do any processing required when DECL (a member template
210    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
211    to DECL, unless it is a specialization, in which case the DECL
212    itself is returned.  */
213
214 tree
215 finish_member_template_decl (tree decl)
216 {
217   if (decl == error_mark_node)
218     return error_mark_node;
219
220   gcc_assert (DECL_P (decl));
221
222   if (TREE_CODE (decl) == TYPE_DECL)
223     {
224       tree type;
225
226       type = TREE_TYPE (decl);
227       if (IS_AGGR_TYPE (type)
228           && CLASSTYPE_TEMPLATE_INFO (type)
229           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
230         {
231           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
232           check_member_template (tmpl);
233           return tmpl;
234         }
235       return NULL_TREE;
236     }
237   else if (TREE_CODE (decl) == FIELD_DECL)
238     error ("data member %qD cannot be a member template", decl);
239   else if (DECL_TEMPLATE_INFO (decl))
240     {
241       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
242         {
243           check_member_template (DECL_TI_TEMPLATE (decl));
244           return DECL_TI_TEMPLATE (decl);
245         }
246       else
247         return decl;
248     }
249   else
250     error ("invalid member template declaration %qD", decl);
251
252   return error_mark_node;
253 }
254
255 /* Returns the template nesting level of the indicated class TYPE.
256
257    For example, in:
258      template <class T>
259      struct A
260      {
261        template <class U>
262        struct B {};
263      };
264
265    A<T>::B<U> has depth two, while A<T> has depth one.
266    Both A<T>::B<int> and A<int>::B<U> have depth one, if
267    they are instantiations, not specializations.
268
269    This function is guaranteed to return 0 if passed NULL_TREE so
270    that, for example, `template_class_depth (current_class_type)' is
271    always safe.  */
272
273 int
274 template_class_depth (tree type)
275 {
276   int depth;
277
278   for (depth = 0;
279        type && TREE_CODE (type) != NAMESPACE_DECL;
280        type = (TREE_CODE (type) == FUNCTION_DECL)
281          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
282     {
283       if (TREE_CODE (type) != FUNCTION_DECL)
284         {
285           if (CLASSTYPE_TEMPLATE_INFO (type)
286               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type))
287               && uses_template_parms (CLASSTYPE_TI_ARGS (type)))
288             ++depth;
289         }
290       else
291         {
292           if (DECL_TEMPLATE_INFO (type)
293               && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (type))
294               && uses_template_parms (DECL_TI_ARGS (type)))
295             ++depth;
296         }
297     }
298
299   return depth;
300 }
301
302 /* Returns 1 if processing DECL as part of do_pending_inlines
303    needs us to push template parms.  */
304
305 static int
306 inline_needs_template_parms (tree decl)
307 {
308   if (! DECL_TEMPLATE_INFO (decl))
309     return 0;
310
311   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
312           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
313 }
314
315 /* Subroutine of maybe_begin_member_template_processing.
316    Push the template parms in PARMS, starting from LEVELS steps into the
317    chain, and ending at the beginning, since template parms are listed
318    innermost first.  */
319
320 static void
321 push_inline_template_parms_recursive (tree parmlist, int levels)
322 {
323   tree parms = TREE_VALUE (parmlist);
324   int i;
325
326   if (levels > 1)
327     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
328
329   ++processing_template_decl;
330   current_template_parms
331     = tree_cons (size_int (processing_template_decl),
332                  parms, current_template_parms);
333   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
334
335   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
336                NULL);
337   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
338     {
339       tree parm;
340
341       if (TREE_VEC_ELT (parms, i) == error_mark_node)
342         continue;
343
344       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
345       gcc_assert (DECL_P (parm));
346
347       switch (TREE_CODE (parm))
348         {
349         case TYPE_DECL:
350         case TEMPLATE_DECL:
351           pushdecl (parm);
352           break;
353
354         case PARM_DECL:
355           {
356             /* Make a CONST_DECL as is done in process_template_parm.
357                It is ugly that we recreate this here; the original
358                version built in process_template_parm is no longer
359                available.  */
360             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
361                                     TREE_TYPE (parm));
362             DECL_ARTIFICIAL (decl) = 1;
363             TREE_CONSTANT (decl) = 1;
364             TREE_INVARIANT (decl) = 1;
365             TREE_READONLY (decl) = 1;
366             DECL_INITIAL (decl) = DECL_INITIAL (parm);
367             SET_DECL_TEMPLATE_PARM_P (decl);
368             pushdecl (decl);
369           }
370           break;
371
372         default:
373           gcc_unreachable ();
374         }
375     }
376 }
377
378 /* Restore the template parameter context for a member template or
379    a friend template defined in a class definition.  */
380
381 void
382 maybe_begin_member_template_processing (tree decl)
383 {
384   tree parms;
385   int levels = 0;
386
387   if (inline_needs_template_parms (decl))
388     {
389       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
390       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
391
392       if (DECL_TEMPLATE_SPECIALIZATION (decl))
393         {
394           --levels;
395           parms = TREE_CHAIN (parms);
396         }
397
398       push_inline_template_parms_recursive (parms, levels);
399     }
400
401   /* Remember how many levels of template parameters we pushed so that
402      we can pop them later.  */
403   VEC_safe_push (int, heap, inline_parm_levels, levels);
404 }
405
406 /* Undo the effects of maybe_begin_member_template_processing.  */
407
408 void
409 maybe_end_member_template_processing (void)
410 {
411   int i;
412   int last;
413
414   if (VEC_length (int, inline_parm_levels) == 0)
415     return;
416
417   last = VEC_pop (int, inline_parm_levels);
418   for (i = 0; i < last; ++i)
419     {
420       --processing_template_decl;
421       current_template_parms = TREE_CHAIN (current_template_parms);
422       poplevel (0, 0, 0);
423     }
424 }
425
426 /* Return a new template argument vector which contains all of ARGS,
427    but has as its innermost set of arguments the EXTRA_ARGS.  */
428
429 static tree
430 add_to_template_args (tree args, tree extra_args)
431 {
432   tree new_args;
433   int extra_depth;
434   int i;
435   int j;
436
437   extra_depth = TMPL_ARGS_DEPTH (extra_args);
438   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
439
440   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
441     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
442
443   for (j = 1; j <= extra_depth; ++j, ++i)
444     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
445
446   return new_args;
447 }
448
449 /* Like add_to_template_args, but only the outermost ARGS are added to
450    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
451    (EXTRA_ARGS) levels are added.  This function is used to combine
452    the template arguments from a partial instantiation with the
453    template arguments used to attain the full instantiation from the
454    partial instantiation.  */
455
456 static tree
457 add_outermost_template_args (tree args, tree extra_args)
458 {
459   tree new_args;
460
461   /* If there are more levels of EXTRA_ARGS than there are ARGS,
462      something very fishy is going on.  */
463   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
464
465   /* If *all* the new arguments will be the EXTRA_ARGS, just return
466      them.  */
467   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
468     return extra_args;
469
470   /* For the moment, we make ARGS look like it contains fewer levels.  */
471   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
472
473   new_args = add_to_template_args (args, extra_args);
474
475   /* Now, we restore ARGS to its full dimensions.  */
476   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
477
478   return new_args;
479 }
480
481 /* Return the N levels of innermost template arguments from the ARGS.  */
482
483 tree
484 get_innermost_template_args (tree args, int n)
485 {
486   tree new_args;
487   int extra_levels;
488   int i;
489
490   gcc_assert (n >= 0);
491
492   /* If N is 1, just return the innermost set of template arguments.  */
493   if (n == 1)
494     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
495
496   /* If we're not removing anything, just return the arguments we were
497      given.  */
498   extra_levels = TMPL_ARGS_DEPTH (args) - n;
499   gcc_assert (extra_levels >= 0);
500   if (extra_levels == 0)
501     return args;
502
503   /* Make a new set of arguments, not containing the outer arguments.  */
504   new_args = make_tree_vec (n);
505   for (i = 1; i <= n; ++i)
506     SET_TMPL_ARGS_LEVEL (new_args, i,
507                          TMPL_ARGS_LEVEL (args, i + extra_levels));
508
509   return new_args;
510 }
511
512 /* We've got a template header coming up; push to a new level for storing
513    the parms.  */
514
515 void
516 begin_template_parm_list (void)
517 {
518   /* We use a non-tag-transparent scope here, which causes pushtag to
519      put tags in this scope, rather than in the enclosing class or
520      namespace scope.  This is the right thing, since we want
521      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
522      global template class, push_template_decl handles putting the
523      TEMPLATE_DECL into top-level scope.  For a nested template class,
524      e.g.:
525
526        template <class T> struct S1 {
527          template <class T> struct S2 {};
528        };
529
530      pushtag contains special code to call pushdecl_with_scope on the
531      TEMPLATE_DECL for S2.  */
532   begin_scope (sk_template_parms, NULL);
533   ++processing_template_decl;
534   ++processing_template_parmlist;
535   note_template_header (0);
536 }
537
538 /* This routine is called when a specialization is declared.  If it is
539    invalid to declare a specialization here, an error is reported.  */
540
541 static void
542 check_specialization_scope (void)
543 {
544   tree scope = current_scope ();
545
546   /* [temp.expl.spec]
547
548      An explicit specialization shall be declared in the namespace of
549      which the template is a member, or, for member templates, in the
550      namespace of which the enclosing class or enclosing class
551      template is a member.  An explicit specialization of a member
552      function, member class or static data member of a class template
553      shall be declared in the namespace of which the class template
554      is a member.  */
555   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
556     error ("explicit specialization in non-namespace scope %qD", scope);
557
558   /* [temp.expl.spec]
559
560      In an explicit specialization declaration for a member of a class
561      template or a member template that appears in namespace scope,
562      the member template and some of its enclosing class templates may
563      remain unspecialized, except that the declaration shall not
564      explicitly specialize a class member template if its enclosing
565      class templates are not explicitly specialized as well.  */
566   if (current_template_parms)
567     error ("enclosing class templates are not explicitly specialized");
568 }
569
570 /* We've just seen template <>.  */
571
572 void
573 begin_specialization (void)
574 {
575   begin_scope (sk_template_spec, NULL);
576   note_template_header (1);
577   check_specialization_scope ();
578 }
579
580 /* Called at then end of processing a declaration preceded by
581    template<>.  */
582
583 void
584 end_specialization (void)
585 {
586   finish_scope ();
587   reset_specialization ();
588 }
589
590 /* Any template <>'s that we have seen thus far are not referring to a
591    function specialization.  */
592
593 void
594 reset_specialization (void)
595 {
596   processing_specialization = 0;
597   template_header_count = 0;
598 }
599
600 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
601    it was of the form template <>.  */
602
603 static void
604 note_template_header (int specialization)
605 {
606   processing_specialization = specialization;
607   template_header_count++;
608 }
609
610 /* We're beginning an explicit instantiation.  */
611
612 void
613 begin_explicit_instantiation (void)
614 {
615   gcc_assert (!processing_explicit_instantiation);
616   processing_explicit_instantiation = true;
617 }
618
619
620 void
621 end_explicit_instantiation (void)
622 {
623   gcc_assert (processing_explicit_instantiation);
624   processing_explicit_instantiation = false;
625 }
626
627 /* An explicit specialization or partial specialization TMPL is being
628    declared.  Check that the namespace in which the specialization is
629    occurring is permissible.  Returns false iff it is invalid to
630    specialize TMPL in the current namespace.  */
631
632 static bool
633 check_specialization_namespace (tree tmpl)
634 {
635   tree tpl_ns = decl_namespace_context (tmpl);
636
637   /* [tmpl.expl.spec]
638
639      An explicit specialization shall be declared in the namespace of
640      which the template is a member, or, for member templates, in the
641      namespace of which the enclosing class or enclosing class
642      template is a member.  An explicit specialization of a member
643      function, member class or static data member of a class template
644      shall be declared in the namespace of which the class template is
645      a member.  */
646   if (is_associated_namespace (current_namespace, tpl_ns))
647     /* Same or super-using namespace.  */
648     return true;
649   else
650     {
651       pedwarn ("specialization of %qD in different namespace", tmpl);
652       pedwarn ("  from definition of %q+#D", tmpl);
653       return false;
654     }
655 }
656
657 /* SPEC is an explicit instantiation.  Check that it is valid to
658    perform this explicit instantiation in the current namespace.  */
659
660 static void
661 check_explicit_instantiation_namespace (tree spec)
662 {
663   tree ns;
664
665   /* DR 275: An explicit instantiation shall appear in an enclosing
666      namespace of its template.  */
667   ns = decl_namespace_context (spec);
668   if (!is_ancestor (current_namespace, ns))
669     pedwarn ("explicit instantiation of %qD in namespace %qD "
670              "(which does not enclose namespace %qD)",
671              spec, current_namespace, ns);
672 }
673
674 /* The TYPE is being declared.  If it is a template type, that means it
675    is a partial specialization.  Do appropriate error-checking.  */
676
677 void
678 maybe_process_partial_specialization (tree type)
679 {
680   tree context;
681
682   if (type == error_mark_node)
683     return;
684
685   context = TYPE_CONTEXT (type);
686
687   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
688     {
689       /* This is for ordinary explicit specialization and partial
690          specialization of a template class such as:
691
692            template <> class C<int>;
693
694          or:
695
696            template <class T> class C<T*>;
697
698          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
699
700       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
701           && !COMPLETE_TYPE_P (type))
702         {
703           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
704           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
705           if (processing_template_decl)
706             push_template_decl (TYPE_MAIN_DECL (type));
707         }
708       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
709         error ("specialization of %qT after instantiation", type);
710     }
711   else if (CLASS_TYPE_P (type)
712            && !CLASSTYPE_USE_TEMPLATE (type)
713            && CLASSTYPE_TEMPLATE_INFO (type)
714            && context && CLASS_TYPE_P (context)
715            && CLASSTYPE_TEMPLATE_INFO (context))
716     {
717       /* This is for an explicit specialization of member class
718          template according to [temp.expl.spec/18]:
719
720            template <> template <class U> class C<int>::D;
721
722          The context `C<int>' must be an implicit instantiation.
723          Otherwise this is just a member class template declared
724          earlier like:
725
726            template <> class C<int> { template <class U> class D; };
727            template <> template <class U> class C<int>::D;
728
729          In the first case, `C<int>::D' is a specialization of `C<T>::D'
730          while in the second case, `C<int>::D' is a primary template
731          and `C<T>::D' may not exist.  */
732
733       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
734           && !COMPLETE_TYPE_P (type))
735         {
736           tree t;
737
738           if (current_namespace
739               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
740             {
741               pedwarn ("specializing %q#T in different namespace", type);
742               pedwarn ("  from definition of %q+#D",
743                        CLASSTYPE_TI_TEMPLATE (type));
744             }
745
746           /* Check for invalid specialization after instantiation:
747
748                template <> template <> class C<int>::D<int>;
749                template <> template <class U> class C<int>::D;  */
750
751           for (t = DECL_TEMPLATE_INSTANTIATIONS
752                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
753                t; t = TREE_CHAIN (t))
754             if (TREE_VALUE (t) != type
755                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
756               error ("specialization %qT after instantiation %qT",
757                      type, TREE_VALUE (t));
758
759           /* Mark TYPE as a specialization.  And as a result, we only
760              have one level of template argument for the innermost
761              class template.  */
762           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
763           CLASSTYPE_TI_ARGS (type)
764             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
765         }
766     }
767   else if (processing_specialization)
768     error ("explicit specialization of non-template %qT", type);
769 }
770
771 /* Returns nonzero if we can optimize the retrieval of specializations
772    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
773    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
774
775 static inline bool
776 optimize_specialization_lookup_p (tree tmpl)
777 {
778   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
779           && DECL_CLASS_SCOPE_P (tmpl)
780           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
781              parameter.  */
782           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
783           /* The optimized lookup depends on the fact that the
784              template arguments for the member function template apply
785              purely to the containing class, which is not true if the
786              containing class is an explicit or partial
787              specialization.  */
788           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
789           && !DECL_MEMBER_TEMPLATE_P (tmpl)
790           && !DECL_CONV_FN_P (tmpl)
791           /* It is possible to have a template that is not a member
792              template and is not a member of a template class:
793
794              template <typename T>
795              struct S { friend A::f(); };
796
797              Here, the friend function is a template, but the context does
798              not have template information.  The optimized lookup relies
799              on having ARGS be the template arguments for both the class
800              and the function template.  */
801           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
802 }
803
804 /* Retrieve the specialization (in the sense of [temp.spec] - a
805    specialization is either an instantiation or an explicit
806    specialization) of TMPL for the given template ARGS.  If there is
807    no such specialization, return NULL_TREE.  The ARGS are a vector of
808    arguments, or a vector of vectors of arguments, in the case of
809    templates with more than one level of parameters.
810
811    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
812    then we search for a partial specialization matching ARGS.  This
813    parameter is ignored if TMPL is not a class template.  */
814
815 static tree
816 retrieve_specialization (tree tmpl, tree args,
817                          bool class_specializations_p)
818 {
819   if (args == error_mark_node)
820     return NULL_TREE;
821
822   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
823
824   /* There should be as many levels of arguments as there are
825      levels of parameters.  */
826   gcc_assert (TMPL_ARGS_DEPTH (args)
827               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
828
829   if (optimize_specialization_lookup_p (tmpl))
830     {
831       tree class_template;
832       tree class_specialization;
833       VEC(tree,gc) *methods;
834       tree fns;
835       int idx;
836
837       /* The template arguments actually apply to the containing
838          class.  Find the class specialization with those
839          arguments.  */
840       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
841       class_specialization
842         = retrieve_specialization (class_template, args,
843                                    /*class_specializations_p=*/false);
844       if (!class_specialization)
845         return NULL_TREE;
846       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
847          for the specialization.  */
848       idx = class_method_index_for_fn (class_specialization, tmpl);
849       if (idx == -1)
850         return NULL_TREE;
851       /* Iterate through the methods with the indicated name, looking
852          for the one that has an instance of TMPL.  */
853       methods = CLASSTYPE_METHOD_VEC (class_specialization);
854       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
855         {
856           tree fn = OVL_CURRENT (fns);
857           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
858             return fn;
859         }
860       return NULL_TREE;
861     }
862   else
863     {
864       tree *sp;
865       tree *head;
866
867       /* Class templates store their instantiations on the
868          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
869          DECL_TEMPLATE_SPECIALIZATIONS list.  */
870       if (!class_specializations_p
871           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL)
872         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
873       else
874         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
875       head = sp;
876       /* Iterate through the list until we find a matching template.  */
877       while (*sp != NULL_TREE)
878         {
879           tree spec = *sp;
880
881           if (comp_template_args (TREE_PURPOSE (spec), args))
882             {
883               /* Use the move-to-front heuristic to speed up future
884                  searches.  */
885               if (spec != *head)
886                 {
887                   *sp = TREE_CHAIN (*sp);
888                   TREE_CHAIN (spec) = *head;
889                   *head = spec;
890                 }
891               return TREE_VALUE (spec);
892             }
893           sp = &TREE_CHAIN (spec);
894         }
895     }
896
897   return NULL_TREE;
898 }
899
900 /* Like retrieve_specialization, but for local declarations.  */
901
902 static tree
903 retrieve_local_specialization (tree tmpl)
904 {
905   tree spec = (tree) htab_find_with_hash (local_specializations, tmpl,
906                                           htab_hash_pointer (tmpl));
907   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
908 }
909
910 /* Returns nonzero iff DECL is a specialization of TMPL.  */
911
912 int
913 is_specialization_of (tree decl, tree tmpl)
914 {
915   tree t;
916
917   if (TREE_CODE (decl) == FUNCTION_DECL)
918     {
919       for (t = decl;
920            t != NULL_TREE;
921            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
922         if (t == tmpl)
923           return 1;
924     }
925   else
926     {
927       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
928
929       for (t = TREE_TYPE (decl);
930            t != NULL_TREE;
931            t = CLASSTYPE_USE_TEMPLATE (t)
932              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
933         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
934           return 1;
935     }
936
937   return 0;
938 }
939
940 /* Returns nonzero iff DECL is a specialization of friend declaration
941    FRIEND according to [temp.friend].  */
942
943 bool
944 is_specialization_of_friend (tree decl, tree friend)
945 {
946   bool need_template = true;
947   int template_depth;
948
949   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
950               || TREE_CODE (decl) == TYPE_DECL);
951
952   /* For [temp.friend/6] when FRIEND is an ordinary member function
953      of a template class, we want to check if DECL is a specialization
954      if this.  */
955   if (TREE_CODE (friend) == FUNCTION_DECL
956       && DECL_TEMPLATE_INFO (friend)
957       && !DECL_USE_TEMPLATE (friend))
958     {
959       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
960       friend = DECL_TI_TEMPLATE (friend);
961       need_template = false;
962     }
963   else if (TREE_CODE (friend) == TEMPLATE_DECL
964            && !PRIMARY_TEMPLATE_P (friend))
965     need_template = false;
966
967   /* There is nothing to do if this is not a template friend.  */
968   if (TREE_CODE (friend) != TEMPLATE_DECL)
969     return false;
970
971   if (is_specialization_of (decl, friend))
972     return true;
973
974   /* [temp.friend/6]
975      A member of a class template may be declared to be a friend of a
976      non-template class.  In this case, the corresponding member of
977      every specialization of the class template is a friend of the
978      class granting friendship.
979
980      For example, given a template friend declaration
981
982        template <class T> friend void A<T>::f();
983
984      the member function below is considered a friend
985
986        template <> struct A<int> {
987          void f();
988        };
989
990      For this type of template friend, TEMPLATE_DEPTH below will be
991      nonzero.  To determine if DECL is a friend of FRIEND, we first
992      check if the enclosing class is a specialization of another.  */
993
994   template_depth = template_class_depth (DECL_CONTEXT (friend));
995   if (template_depth
996       && DECL_CLASS_SCOPE_P (decl)
997       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
998                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend))))
999     {
1000       /* Next, we check the members themselves.  In order to handle
1001          a few tricky cases, such as when FRIEND's are
1002
1003            template <class T> friend void A<T>::g(T t);
1004            template <class T> template <T t> friend void A<T>::h();
1005
1006          and DECL's are
1007
1008            void A<int>::g(int);
1009            template <int> void A<int>::h();
1010
1011          we need to figure out ARGS, the template arguments from
1012          the context of DECL.  This is required for template substitution
1013          of `T' in the function parameter of `g' and template parameter
1014          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1015
1016       tree context = DECL_CONTEXT (decl);
1017       tree args = NULL_TREE;
1018       int current_depth = 0;
1019
1020       while (current_depth < template_depth)
1021         {
1022           if (CLASSTYPE_TEMPLATE_INFO (context))
1023             {
1024               if (current_depth == 0)
1025                 args = TYPE_TI_ARGS (context);
1026               else
1027                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1028               current_depth++;
1029             }
1030           context = TYPE_CONTEXT (context);
1031         }
1032
1033       if (TREE_CODE (decl) == FUNCTION_DECL)
1034         {
1035           bool is_template;
1036           tree friend_type;
1037           tree decl_type;
1038           tree friend_args_type;
1039           tree decl_args_type;
1040
1041           /* Make sure that both DECL and FRIEND are templates or
1042              non-templates.  */
1043           is_template = DECL_TEMPLATE_INFO (decl)
1044                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1045           if (need_template ^ is_template)
1046             return false;
1047           else if (is_template)
1048             {
1049               /* If both are templates, check template parameter list.  */
1050               tree friend_parms
1051                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1052                                          args, tf_none);
1053               if (!comp_template_parms
1054                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1055                       friend_parms))
1056                 return false;
1057
1058               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1059             }
1060           else
1061             decl_type = TREE_TYPE (decl);
1062
1063           friend_type = tsubst_function_type (TREE_TYPE (friend), args,
1064                                               tf_none, NULL_TREE);
1065           if (friend_type == error_mark_node)
1066             return false;
1067
1068           /* Check if return types match.  */
1069           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1070             return false;
1071
1072           /* Check if function parameter types match, ignoring the
1073              `this' parameter.  */
1074           friend_args_type = TYPE_ARG_TYPES (friend_type);
1075           decl_args_type = TYPE_ARG_TYPES (decl_type);
1076           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend))
1077             friend_args_type = TREE_CHAIN (friend_args_type);
1078           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1079             decl_args_type = TREE_CHAIN (decl_args_type);
1080
1081           return compparms (decl_args_type, friend_args_type);
1082         }
1083       else
1084         {
1085           /* DECL is a TYPE_DECL */
1086           bool is_template;
1087           tree decl_type = TREE_TYPE (decl);
1088
1089           /* Make sure that both DECL and FRIEND are templates or
1090              non-templates.  */
1091           is_template
1092             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1093               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1094
1095           if (need_template ^ is_template)
1096             return false;
1097           else if (is_template)
1098             {
1099               tree friend_parms;
1100               /* If both are templates, check the name of the two
1101                  TEMPLATE_DECL's first because is_friend didn't.  */
1102               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1103                   != DECL_NAME (friend))
1104                 return false;
1105
1106               /* Now check template parameter list.  */
1107               friend_parms
1108                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend),
1109                                          args, tf_none);
1110               return comp_template_parms
1111                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1112                  friend_parms);
1113             }
1114           else
1115             return (DECL_NAME (decl)
1116                     == DECL_NAME (friend));
1117         }
1118     }
1119   return false;
1120 }
1121
1122 /* Register the specialization SPEC as a specialization of TMPL with
1123    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1124    is actually just a friend declaration.  Returns SPEC, or an
1125    equivalent prior declaration, if available.  */
1126
1127 static tree
1128 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1129 {
1130   tree fn;
1131
1132   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1133
1134   if (TREE_CODE (spec) == FUNCTION_DECL
1135       && uses_template_parms (DECL_TI_ARGS (spec)))
1136     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1137        register it; we want the corresponding TEMPLATE_DECL instead.
1138        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1139        the more obvious `uses_template_parms (spec)' to avoid problems
1140        with default function arguments.  In particular, given
1141        something like this:
1142
1143           template <class T> void f(T t1, T t = T())
1144
1145        the default argument expression is not substituted for in an
1146        instantiation unless and until it is actually needed.  */
1147     return spec;
1148
1149   fn = retrieve_specialization (tmpl, args,
1150                                 /*class_specializations_p=*/false);
1151   /* We can sometimes try to re-register a specialization that we've
1152      already got.  In particular, regenerate_decl_from_template calls
1153      duplicate_decls which will update the specialization list.  But,
1154      we'll still get called again here anyhow.  It's more convenient
1155      to simply allow this than to try to prevent it.  */
1156   if (fn == spec)
1157     return spec;
1158   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1159     {
1160       if (DECL_TEMPLATE_INSTANTIATION (fn))
1161         {
1162           if (TREE_USED (fn)
1163               || DECL_EXPLICIT_INSTANTIATION (fn))
1164             {
1165               error ("specialization of %qD after instantiation",
1166                      fn);
1167               return spec;
1168             }
1169           else
1170             {
1171               tree clone;
1172               /* This situation should occur only if the first
1173                  specialization is an implicit instantiation, the
1174                  second is an explicit specialization, and the
1175                  implicit instantiation has not yet been used.  That
1176                  situation can occur if we have implicitly
1177                  instantiated a member function and then specialized
1178                  it later.
1179
1180                  We can also wind up here if a friend declaration that
1181                  looked like an instantiation turns out to be a
1182                  specialization:
1183
1184                    template <class T> void foo(T);
1185                    class S { friend void foo<>(int) };
1186                    template <> void foo(int);
1187
1188                  We transform the existing DECL in place so that any
1189                  pointers to it become pointers to the updated
1190                  declaration.
1191
1192                  If there was a definition for the template, but not
1193                  for the specialization, we want this to look as if
1194                  there were no definition, and vice versa.  */
1195               DECL_INITIAL (fn) = NULL_TREE;
1196               duplicate_decls (spec, fn, is_friend);
1197               /* The call to duplicate_decls will have applied
1198                  [temp.expl.spec]:
1199
1200                    An explicit specialization of a function template
1201                    is inline only if it is explicitly declared to be,
1202                    and independently of whether its function template
1203                    is.
1204
1205                 to the primary function; now copy the inline bits to
1206                 the various clones.  */
1207               FOR_EACH_CLONE (clone, fn)
1208                 {
1209                   DECL_DECLARED_INLINE_P (clone)
1210                     = DECL_DECLARED_INLINE_P (fn);
1211                   DECL_INLINE (clone)
1212                     = DECL_INLINE (fn);
1213                 }
1214               check_specialization_namespace (fn);
1215
1216               return fn;
1217             }
1218         }
1219       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1220         {
1221           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1222             /* Dup decl failed, but this is a new definition. Set the
1223                line number so any errors match this new
1224                definition.  */
1225             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1226
1227           return fn;
1228         }
1229     }
1230
1231   /* A specialization must be declared in the same namespace as the
1232      template it is specializing.  */
1233   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1234       && !check_specialization_namespace (tmpl))
1235     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1236
1237   if (!optimize_specialization_lookup_p (tmpl))
1238     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1239       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1240
1241   return spec;
1242 }
1243
1244 /* Unregister the specialization SPEC as a specialization of TMPL.
1245    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1246    if the SPEC was listed as a specialization of TMPL.  */
1247
1248 bool
1249 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1250 {
1251   tree* s;
1252
1253   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1254        *s != NULL_TREE;
1255        s = &TREE_CHAIN (*s))
1256     if (TREE_VALUE (*s) == spec)
1257       {
1258         if (!new_spec)
1259           *s = TREE_CHAIN (*s);
1260         else
1261           TREE_VALUE (*s) = new_spec;
1262         return 1;
1263       }
1264
1265   return 0;
1266 }
1267
1268 /* Compare an entry in the local specializations hash table P1 (which
1269    is really a pointer to a TREE_LIST) with P2 (which is really a
1270    DECL).  */
1271
1272 static int
1273 eq_local_specializations (const void *p1, const void *p2)
1274 {
1275   return TREE_VALUE ((tree) p1) == (tree) p2;
1276 }
1277
1278 /* Hash P1, an entry in the local specializations table.  */
1279
1280 static hashval_t
1281 hash_local_specialization (const void* p1)
1282 {
1283   return htab_hash_pointer (TREE_VALUE ((tree) p1));
1284 }
1285
1286 /* Like register_specialization, but for local declarations.  We are
1287    registering SPEC, an instantiation of TMPL.  */
1288
1289 static void
1290 register_local_specialization (tree spec, tree tmpl)
1291 {
1292   void **slot;
1293
1294   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1295                                    htab_hash_pointer (tmpl), INSERT);
1296   *slot = build_tree_list (spec, tmpl);
1297 }
1298
1299 /* Print the list of candidate FNS in an error message.  */
1300
1301 void
1302 print_candidates (tree fns)
1303 {
1304   tree fn;
1305
1306   const char *str = "candidates are:";
1307
1308   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1309     {
1310       tree f;
1311
1312       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1313         error ("%s %+#D", str, OVL_CURRENT (f));
1314       str = "               ";
1315     }
1316 }
1317
1318 /* Returns the template (one of the functions given by TEMPLATE_ID)
1319    which can be specialized to match the indicated DECL with the
1320    explicit template args given in TEMPLATE_ID.  The DECL may be
1321    NULL_TREE if none is available.  In that case, the functions in
1322    TEMPLATE_ID are non-members.
1323
1324    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1325    specialization of a member template.
1326
1327    The TEMPLATE_COUNT is the number of references to qualifying
1328    template classes that appeared in the name of the function. See
1329    check_explicit_specialization for a more accurate description.
1330
1331    TSK indicates what kind of template declaration (if any) is being
1332    declared.  TSK_TEMPLATE indicates that the declaration given by
1333    DECL, though a FUNCTION_DECL, has template parameters, and is
1334    therefore a template function.
1335
1336    The template args (those explicitly specified and those deduced)
1337    are output in a newly created vector *TARGS_OUT.
1338
1339    If it is impossible to determine the result, an error message is
1340    issued.  The error_mark_node is returned to indicate failure.  */
1341
1342 static tree
1343 determine_specialization (tree template_id,
1344                           tree decl,
1345                           tree* targs_out,
1346                           int need_member_template,
1347                           int template_count,
1348                           tmpl_spec_kind tsk)
1349 {
1350   tree fns;
1351   tree targs;
1352   tree explicit_targs;
1353   tree candidates = NULL_TREE;
1354   /* A TREE_LIST of templates of which DECL may be a specialization.
1355      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1356      corresponding TREE_PURPOSE is the set of template arguments that,
1357      when used to instantiate the template, would produce a function
1358      with the signature of DECL.  */
1359   tree templates = NULL_TREE;
1360   int header_count;
1361   struct cp_binding_level *b;
1362
1363   *targs_out = NULL_TREE;
1364
1365   if (template_id == error_mark_node || decl == error_mark_node)
1366     return error_mark_node;
1367
1368   fns = TREE_OPERAND (template_id, 0);
1369   explicit_targs = TREE_OPERAND (template_id, 1);
1370
1371   if (fns == error_mark_node)
1372     return error_mark_node;
1373
1374   /* Check for baselinks.  */
1375   if (BASELINK_P (fns))
1376     fns = BASELINK_FUNCTIONS (fns);
1377
1378   if (!is_overloaded_fn (fns))
1379     {
1380       error ("%qD is not a function template", fns);
1381       return error_mark_node;
1382     }
1383
1384   /* Count the number of template headers specified for this
1385      specialization.  */
1386   header_count = 0;
1387   for (b = current_binding_level;
1388        b->kind == sk_template_parms;
1389        b = b->level_chain)
1390     ++header_count;
1391
1392   for (; fns; fns = OVL_NEXT (fns))
1393     {
1394       tree fn = OVL_CURRENT (fns);
1395
1396       if (TREE_CODE (fn) == TEMPLATE_DECL)
1397         {
1398           tree decl_arg_types;
1399           tree fn_arg_types;
1400
1401           /* DECL might be a specialization of FN.  */
1402
1403           /* Adjust the type of DECL in case FN is a static member.  */
1404           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1405           if (DECL_STATIC_FUNCTION_P (fn)
1406               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1407             decl_arg_types = TREE_CHAIN (decl_arg_types);
1408
1409           /* Check that the number of function parameters matches.
1410              For example,
1411                template <class T> void f(int i = 0);
1412                template <> void f<int>();
1413              The specialization f<int> is invalid but is not caught
1414              by get_bindings below.  */
1415
1416           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1417           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1418             continue;
1419
1420           /* For a non-static member function, we need to make sure that
1421              the const qualification is the same. This can be done by
1422              checking the 'this' in the argument list.  */
1423           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1424               && !same_type_p (TREE_VALUE (fn_arg_types),
1425                                TREE_VALUE (decl_arg_types)))
1426             continue;
1427
1428           /* In case of explicit specialization, we need to check if
1429              the number of template headers appearing in the specialization
1430              is correct. This is usually done in check_explicit_specialization,
1431              but the check done there cannot be exhaustive when specializing
1432              member functions. Consider the following code:
1433
1434              template <> void A<int>::f(int);
1435              template <> template <> void A<int>::f(int);
1436
1437              Assuming that A<int> is not itself an explicit specialization
1438              already, the first line specializes "f" which is a non-template
1439              member function, whilst the second line specializes "f" which
1440              is a template member function. So both lines are syntactically
1441              correct, and check_explicit_specialization does not reject
1442              them.
1443
1444              Here, we can do better, as we are matching the specialization
1445              against the declarations. We count the number of template
1446              headers, and we check if they match TEMPLATE_COUNT + 1
1447              (TEMPLATE_COUNT is the number of qualifying template classes,
1448              plus there must be another header for the member template
1449              itself).
1450
1451              Notice that if header_count is zero, this is not a
1452              specialization but rather a template instantiation, so there
1453              is no check we can perform here.  */
1454           if (header_count && header_count != template_count + 1)
1455             continue;
1456
1457           /* Check that the number of template arguments at the
1458              innermost level for DECL is the same as for FN.  */
1459           if (current_binding_level->kind == sk_template_parms
1460               && !current_binding_level->explicit_spec_p
1461               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1462                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1463                                       (current_template_parms))))
1464             continue;
1465
1466           /* Function templates cannot be specializations; there are
1467              no partial specializations of functions.  Therefore, if
1468              the type of DECL does not match FN, there is no
1469              match.  */
1470           if (tsk == tsk_template)
1471             {
1472               if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1473                              decl_arg_types))
1474                 candidates = tree_cons (NULL_TREE, fn, candidates);
1475               continue;
1476             }
1477
1478           /* See whether this function might be a specialization of this
1479              template.  */
1480           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1481
1482           if (!targs)
1483             /* We cannot deduce template arguments that when used to
1484                specialize TMPL will produce DECL.  */
1485             continue;
1486
1487           /* Save this template, and the arguments deduced.  */
1488           templates = tree_cons (targs, fn, templates);
1489         }
1490       else if (need_member_template)
1491         /* FN is an ordinary member function, and we need a
1492            specialization of a member template.  */
1493         ;
1494       else if (TREE_CODE (fn) != FUNCTION_DECL)
1495         /* We can get IDENTIFIER_NODEs here in certain erroneous
1496            cases.  */
1497         ;
1498       else if (!DECL_FUNCTION_MEMBER_P (fn))
1499         /* This is just an ordinary non-member function.  Nothing can
1500            be a specialization of that.  */
1501         ;
1502       else if (DECL_ARTIFICIAL (fn))
1503         /* Cannot specialize functions that are created implicitly.  */
1504         ;
1505       else
1506         {
1507           tree decl_arg_types;
1508
1509           /* This is an ordinary member function.  However, since
1510              we're here, we can assume it's enclosing class is a
1511              template class.  For example,
1512
1513                template <typename T> struct S { void f(); };
1514                template <> void S<int>::f() {}
1515
1516              Here, S<int>::f is a non-template, but S<int> is a
1517              template class.  If FN has the same type as DECL, we
1518              might be in business.  */
1519
1520           if (!DECL_TEMPLATE_INFO (fn))
1521             /* Its enclosing class is an explicit specialization
1522                of a template class.  This is not a candidate.  */
1523             continue;
1524
1525           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1526                             TREE_TYPE (TREE_TYPE (fn))))
1527             /* The return types differ.  */
1528             continue;
1529
1530           /* Adjust the type of DECL in case FN is a static member.  */
1531           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1532           if (DECL_STATIC_FUNCTION_P (fn)
1533               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1534             decl_arg_types = TREE_CHAIN (decl_arg_types);
1535
1536           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1537                          decl_arg_types))
1538             /* They match!  */
1539             candidates = tree_cons (NULL_TREE, fn, candidates);
1540         }
1541     }
1542
1543   if (templates && TREE_CHAIN (templates))
1544     {
1545       /* We have:
1546
1547            [temp.expl.spec]
1548
1549            It is possible for a specialization with a given function
1550            signature to be instantiated from more than one function
1551            template.  In such cases, explicit specification of the
1552            template arguments must be used to uniquely identify the
1553            function template specialization being specialized.
1554
1555          Note that here, there's no suggestion that we're supposed to
1556          determine which of the candidate templates is most
1557          specialized.  However, we, also have:
1558
1559            [temp.func.order]
1560
1561            Partial ordering of overloaded function template
1562            declarations is used in the following contexts to select
1563            the function template to which a function template
1564            specialization refers:
1565
1566            -- when an explicit specialization refers to a function
1567               template.
1568
1569          So, we do use the partial ordering rules, at least for now.
1570          This extension can only serve to make invalid programs valid,
1571          so it's safe.  And, there is strong anecdotal evidence that
1572          the committee intended the partial ordering rules to apply;
1573          the EDG front-end has that behavior, and John Spicer claims
1574          that the committee simply forgot to delete the wording in
1575          [temp.expl.spec].  */
1576       tree tmpl = most_specialized_instantiation (templates);
1577       if (tmpl != error_mark_node)
1578         {
1579           templates = tmpl;
1580           TREE_CHAIN (templates) = NULL_TREE;
1581         }
1582     }
1583
1584   if (templates == NULL_TREE && candidates == NULL_TREE)
1585     {
1586       error ("template-id %qD for %q+D does not match any template "
1587              "declaration", template_id, decl);
1588       return error_mark_node;
1589     }
1590   else if ((templates && TREE_CHAIN (templates))
1591            || (candidates && TREE_CHAIN (candidates))
1592            || (templates && candidates))
1593     {
1594       error ("ambiguous template specialization %qD for %q+D",
1595              template_id, decl);
1596       chainon (candidates, templates);
1597       print_candidates (candidates);
1598       return error_mark_node;
1599     }
1600
1601   /* We have one, and exactly one, match.  */
1602   if (candidates)
1603     {
1604       tree fn = TREE_VALUE (candidates);
1605       /* DECL is a re-declaration of a template function.  */
1606       if (TREE_CODE (fn) == TEMPLATE_DECL)
1607         return fn;
1608       /* It was a specialization of an ordinary member function in a
1609          template class.  */
1610       *targs_out = copy_node (DECL_TI_ARGS (fn));
1611       return DECL_TI_TEMPLATE (fn);
1612     }
1613
1614   /* It was a specialization of a template.  */
1615   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1616   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1617     {
1618       *targs_out = copy_node (targs);
1619       SET_TMPL_ARGS_LEVEL (*targs_out,
1620                            TMPL_ARGS_DEPTH (*targs_out),
1621                            TREE_PURPOSE (templates));
1622     }
1623   else
1624     *targs_out = TREE_PURPOSE (templates);
1625   return TREE_VALUE (templates);
1626 }
1627
1628 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1629    but with the default argument values filled in from those in the
1630    TMPL_TYPES.  */
1631
1632 static tree
1633 copy_default_args_to_explicit_spec_1 (tree spec_types,
1634                                       tree tmpl_types)
1635 {
1636   tree new_spec_types;
1637
1638   if (!spec_types)
1639     return NULL_TREE;
1640
1641   if (spec_types == void_list_node)
1642     return void_list_node;
1643
1644   /* Substitute into the rest of the list.  */
1645   new_spec_types =
1646     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1647                                           TREE_CHAIN (tmpl_types));
1648
1649   /* Add the default argument for this parameter.  */
1650   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1651                          TREE_VALUE (spec_types),
1652                          new_spec_types);
1653 }
1654
1655 /* DECL is an explicit specialization.  Replicate default arguments
1656    from the template it specializes.  (That way, code like:
1657
1658      template <class T> void f(T = 3);
1659      template <> void f(double);
1660      void g () { f (); }
1661
1662    works, as required.)  An alternative approach would be to look up
1663    the correct default arguments at the call-site, but this approach
1664    is consistent with how implicit instantiations are handled.  */
1665
1666 static void
1667 copy_default_args_to_explicit_spec (tree decl)
1668 {
1669   tree tmpl;
1670   tree spec_types;
1671   tree tmpl_types;
1672   tree new_spec_types;
1673   tree old_type;
1674   tree new_type;
1675   tree t;
1676   tree object_type = NULL_TREE;
1677   tree in_charge = NULL_TREE;
1678   tree vtt = NULL_TREE;
1679
1680   /* See if there's anything we need to do.  */
1681   tmpl = DECL_TI_TEMPLATE (decl);
1682   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1683   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1684     if (TREE_PURPOSE (t))
1685       break;
1686   if (!t)
1687     return;
1688
1689   old_type = TREE_TYPE (decl);
1690   spec_types = TYPE_ARG_TYPES (old_type);
1691
1692   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1693     {
1694       /* Remove the this pointer, but remember the object's type for
1695          CV quals.  */
1696       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1697       spec_types = TREE_CHAIN (spec_types);
1698       tmpl_types = TREE_CHAIN (tmpl_types);
1699
1700       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1701         {
1702           /* DECL may contain more parameters than TMPL due to the extra
1703              in-charge parameter in constructors and destructors.  */
1704           in_charge = spec_types;
1705           spec_types = TREE_CHAIN (spec_types);
1706         }
1707       if (DECL_HAS_VTT_PARM_P (decl))
1708         {
1709           vtt = spec_types;
1710           spec_types = TREE_CHAIN (spec_types);
1711         }
1712     }
1713
1714   /* Compute the merged default arguments.  */
1715   new_spec_types =
1716     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1717
1718   /* Compute the new FUNCTION_TYPE.  */
1719   if (object_type)
1720     {
1721       if (vtt)
1722         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1723                                          TREE_VALUE (vtt),
1724                                          new_spec_types);
1725
1726       if (in_charge)
1727         /* Put the in-charge parameter back.  */
1728         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1729                                          TREE_VALUE (in_charge),
1730                                          new_spec_types);
1731
1732       new_type = build_method_type_directly (object_type,
1733                                              TREE_TYPE (old_type),
1734                                              new_spec_types);
1735     }
1736   else
1737     new_type = build_function_type (TREE_TYPE (old_type),
1738                                     new_spec_types);
1739   new_type = cp_build_type_attribute_variant (new_type,
1740                                               TYPE_ATTRIBUTES (old_type));
1741   new_type = build_exception_variant (new_type,
1742                                       TYPE_RAISES_EXCEPTIONS (old_type));
1743   TREE_TYPE (decl) = new_type;
1744 }
1745
1746 /* Check to see if the function just declared, as indicated in
1747    DECLARATOR, and in DECL, is a specialization of a function
1748    template.  We may also discover that the declaration is an explicit
1749    instantiation at this point.
1750
1751    Returns DECL, or an equivalent declaration that should be used
1752    instead if all goes well.  Issues an error message if something is
1753    amiss.  Returns error_mark_node if the error is not easily
1754    recoverable.
1755
1756    FLAGS is a bitmask consisting of the following flags:
1757
1758    2: The function has a definition.
1759    4: The function is a friend.
1760
1761    The TEMPLATE_COUNT is the number of references to qualifying
1762    template classes that appeared in the name of the function.  For
1763    example, in
1764
1765      template <class T> struct S { void f(); };
1766      void S<int>::f();
1767
1768    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1769    classes are not counted in the TEMPLATE_COUNT, so that in
1770
1771      template <class T> struct S {};
1772      template <> struct S<int> { void f(); }
1773      template <> void S<int>::f();
1774
1775    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1776    invalid; there should be no template <>.)
1777
1778    If the function is a specialization, it is marked as such via
1779    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1780    is set up correctly, and it is added to the list of specializations
1781    for that template.  */
1782
1783 tree
1784 check_explicit_specialization (tree declarator,
1785                                tree decl,
1786                                int template_count,
1787                                int flags)
1788 {
1789   int have_def = flags & 2;
1790   int is_friend = flags & 4;
1791   int specialization = 0;
1792   int explicit_instantiation = 0;
1793   int member_specialization = 0;
1794   tree ctype = DECL_CLASS_CONTEXT (decl);
1795   tree dname = DECL_NAME (decl);
1796   tmpl_spec_kind tsk;
1797
1798   if (is_friend)
1799     {
1800       if (!processing_specialization)
1801         tsk = tsk_none;
1802       else
1803         tsk = tsk_excessive_parms;
1804     }
1805   else
1806     tsk = current_tmpl_spec_kind (template_count);
1807
1808   switch (tsk)
1809     {
1810     case tsk_none:
1811       if (processing_specialization)
1812         {
1813           specialization = 1;
1814           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1815         }
1816       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1817         {
1818           if (is_friend)
1819             /* This could be something like:
1820
1821                template <class T> void f(T);
1822                class S { friend void f<>(int); }  */
1823             specialization = 1;
1824           else
1825             {
1826               /* This case handles bogus declarations like template <>
1827                  template <class T> void f<int>(); */
1828
1829               error ("template-id %qD in declaration of primary template",
1830                      declarator);
1831               return decl;
1832             }
1833         }
1834       break;
1835
1836     case tsk_invalid_member_spec:
1837       /* The error has already been reported in
1838          check_specialization_scope.  */
1839       return error_mark_node;
1840
1841     case tsk_invalid_expl_inst:
1842       error ("template parameter list used in explicit instantiation");
1843
1844       /* Fall through.  */
1845
1846     case tsk_expl_inst:
1847       if (have_def)
1848         error ("definition provided for explicit instantiation");
1849
1850       explicit_instantiation = 1;
1851       break;
1852
1853     case tsk_excessive_parms:
1854     case tsk_insufficient_parms:
1855       if (tsk == tsk_excessive_parms)
1856         error ("too many template parameter lists in declaration of %qD",
1857                decl);
1858       else if (template_header_count)
1859         error("too few template parameter lists in declaration of %qD", decl);
1860       else
1861         error("explicit specialization of %qD must be introduced by "
1862               "%<template <>%>", decl);
1863
1864       /* Fall through.  */
1865     case tsk_expl_spec:
1866       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1867       if (ctype)
1868         member_specialization = 1;
1869       else
1870         specialization = 1;
1871       break;
1872
1873     case tsk_template:
1874       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1875         {
1876           /* This case handles bogus declarations like template <>
1877              template <class T> void f<int>(); */
1878
1879           if (uses_template_parms (declarator))
1880             error ("function template partial specialization %qD "
1881                    "is not allowed", declarator);
1882           else
1883             error ("template-id %qD in declaration of primary template",
1884                    declarator);
1885           return decl;
1886         }
1887
1888       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1889         /* This is a specialization of a member template, without
1890            specialization the containing class.  Something like:
1891
1892              template <class T> struct S {
1893                template <class U> void f (U);
1894              };
1895              template <> template <class U> void S<int>::f(U) {}
1896
1897            That's a specialization -- but of the entire template.  */
1898         specialization = 1;
1899       break;
1900
1901     default:
1902       gcc_unreachable ();
1903     }
1904
1905   if (specialization || member_specialization)
1906     {
1907       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
1908       for (; t; t = TREE_CHAIN (t))
1909         if (TREE_PURPOSE (t))
1910           {
1911             pedwarn
1912               ("default argument specified in explicit specialization");
1913             break;
1914           }
1915     }
1916
1917   if (specialization || member_specialization || explicit_instantiation)
1918     {
1919       tree tmpl = NULL_TREE;
1920       tree targs = NULL_TREE;
1921
1922       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
1923       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
1924         {
1925           tree fns;
1926
1927           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
1928           if (ctype)
1929             fns = dname;
1930           else
1931             {
1932               /* If there is no class context, the explicit instantiation
1933                  must be at namespace scope.  */
1934               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
1935
1936               /* Find the namespace binding, using the declaration
1937                  context.  */
1938               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
1939                                            false, true);
1940               if (!fns || !is_overloaded_fn (fns))
1941                 {
1942                   error ("%qD is not a template function", dname);
1943                   fns = error_mark_node;
1944                 }
1945               else
1946                 {
1947                   tree fn = OVL_CURRENT (fns);
1948                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
1949                                                 CP_DECL_CONTEXT (fn)))
1950                     error ("%qD is not declared in %qD",
1951                            decl, current_namespace);
1952                 }
1953             }
1954
1955           declarator = lookup_template_function (fns, NULL_TREE);
1956         }
1957
1958       if (declarator == error_mark_node)
1959         return error_mark_node;
1960
1961       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
1962         {
1963           if (!explicit_instantiation)
1964             /* A specialization in class scope.  This is invalid,
1965                but the error will already have been flagged by
1966                check_specialization_scope.  */
1967             return error_mark_node;
1968           else
1969             {
1970               /* It's not valid to write an explicit instantiation in
1971                  class scope, e.g.:
1972
1973                    class C { template void f(); }
1974
1975                    This case is caught by the parser.  However, on
1976                    something like:
1977
1978                    template class C { void f(); };
1979
1980                    (which is invalid) we can get here.  The error will be
1981                    issued later.  */
1982               ;
1983             }
1984
1985           return decl;
1986         }
1987       else if (ctype != NULL_TREE
1988                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
1989                    IDENTIFIER_NODE))
1990         {
1991           /* Find the list of functions in ctype that have the same
1992              name as the declared function.  */
1993           tree name = TREE_OPERAND (declarator, 0);
1994           tree fns = NULL_TREE;
1995           int idx;
1996
1997           if (constructor_name_p (name, ctype))
1998             {
1999               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2000
2001               if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
2002                   : !CLASSTYPE_DESTRUCTORS (ctype))
2003                 {
2004                   /* From [temp.expl.spec]:
2005
2006                      If such an explicit specialization for the member
2007                      of a class template names an implicitly-declared
2008                      special member function (clause _special_), the
2009                      program is ill-formed.
2010
2011                      Similar language is found in [temp.explicit].  */
2012                   error ("specialization of implicitly-declared special member function");
2013                   return error_mark_node;
2014                 }
2015
2016               name = is_constructor ? ctor_identifier : dtor_identifier;
2017             }
2018
2019           if (!DECL_CONV_FN_P (decl))
2020             {
2021               idx = lookup_fnfields_1 (ctype, name);
2022               if (idx >= 0)
2023                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2024             }
2025           else
2026             {
2027               VEC(tree,gc) *methods;
2028               tree ovl;
2029
2030               /* For a type-conversion operator, we cannot do a
2031                  name-based lookup.  We might be looking for `operator
2032                  int' which will be a specialization of `operator T'.
2033                  So, we find *all* the conversion operators, and then
2034                  select from them.  */
2035               fns = NULL_TREE;
2036
2037               methods = CLASSTYPE_METHOD_VEC (ctype);
2038               if (methods)
2039                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2040                      VEC_iterate (tree, methods, idx, ovl);
2041                      ++idx)
2042                   {
2043                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2044                       /* There are no more conversion functions.  */
2045                       break;
2046
2047                     /* Glue all these conversion functions together
2048                        with those we already have.  */
2049                     for (; ovl; ovl = OVL_NEXT (ovl))
2050                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2051                   }
2052             }
2053
2054           if (fns == NULL_TREE)
2055             {
2056               error ("no member function %qD declared in %qT", name, ctype);
2057               return error_mark_node;
2058             }
2059           else
2060             TREE_OPERAND (declarator, 0) = fns;
2061         }
2062
2063       /* Figure out what exactly is being specialized at this point.
2064          Note that for an explicit instantiation, even one for a
2065          member function, we cannot tell apriori whether the
2066          instantiation is for a member template, or just a member
2067          function of a template class.  Even if a member template is
2068          being instantiated, the member template arguments may be
2069          elided if they can be deduced from the rest of the
2070          declaration.  */
2071       tmpl = determine_specialization (declarator, decl,
2072                                        &targs,
2073                                        member_specialization,
2074                                        template_count,
2075                                        tsk);
2076
2077       if (!tmpl || tmpl == error_mark_node)
2078         /* We couldn't figure out what this declaration was
2079            specializing.  */
2080         return error_mark_node;
2081       else
2082         {
2083           tree gen_tmpl = most_general_template (tmpl);
2084
2085           if (explicit_instantiation)
2086             {
2087               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2088                  is done by do_decl_instantiation later.  */
2089
2090               int arg_depth = TMPL_ARGS_DEPTH (targs);
2091               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2092
2093               if (arg_depth > parm_depth)
2094                 {
2095                   /* If TMPL is not the most general template (for
2096                      example, if TMPL is a friend template that is
2097                      injected into namespace scope), then there will
2098                      be too many levels of TARGS.  Remove some of them
2099                      here.  */
2100                   int i;
2101                   tree new_targs;
2102
2103                   new_targs = make_tree_vec (parm_depth);
2104                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2105                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2106                       = TREE_VEC_ELT (targs, i);
2107                   targs = new_targs;
2108                 }
2109
2110               return instantiate_template (tmpl, targs, tf_error);
2111             }
2112
2113           /* If we thought that the DECL was a member function, but it
2114              turns out to be specializing a static member function,
2115              make DECL a static member function as well.  */
2116           if (DECL_STATIC_FUNCTION_P (tmpl)
2117               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2118             revert_static_member_fn (decl);
2119
2120           /* If this is a specialization of a member template of a
2121              template class, we want to return the TEMPLATE_DECL, not
2122              the specialization of it.  */
2123           if (tsk == tsk_template)
2124             {
2125               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2126               DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
2127               if (have_def)
2128                 {
2129                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2130                   DECL_SOURCE_LOCATION (DECL_TEMPLATE_RESULT (tmpl))
2131                     = DECL_SOURCE_LOCATION (decl);
2132                   /* We want to use the argument list specified in the
2133                      definition, not in the original declaration.  */
2134                   DECL_ARGUMENTS (DECL_TEMPLATE_RESULT (tmpl))
2135                     = DECL_ARGUMENTS (decl);
2136                 }
2137               return tmpl;
2138             }
2139
2140           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2141           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2142
2143           /* Inherit default function arguments from the template
2144              DECL is specializing.  */
2145           copy_default_args_to_explicit_spec (decl);
2146
2147           /* This specialization has the same protection as the
2148              template it specializes.  */
2149           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2150           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2151
2152           /* If DECL is a friend declaration, declared using an
2153              unqualified name, the namespace associated with DECL may
2154              have been set incorrectly.  For example, in:
2155
2156                template <typename T> void f(T);
2157                namespace N {
2158                  struct S { friend void f<int>(int); }
2159                }
2160
2161              we will have set the DECL_CONTEXT for the friend
2162              declaration to N, rather than to the global namespace.  */
2163           if (DECL_NAMESPACE_SCOPE_P (decl))
2164             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2165
2166           if (is_friend && !have_def)
2167             /* This is not really a declaration of a specialization.
2168                It's just the name of an instantiation.  But, it's not
2169                a request for an instantiation, either.  */
2170             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2171           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2172             /* This is indeed a specialization.  In case of constructors
2173                and destructors, we need in-charge and not-in-charge
2174                versions in V3 ABI.  */
2175             clone_function_decl (decl, /*update_method_vec_p=*/0);
2176
2177           /* Register this specialization so that we can find it
2178              again.  */
2179           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2180         }
2181     }
2182
2183   return decl;
2184 }
2185
2186 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2187    parameters.  These are represented in the same format used for
2188    DECL_TEMPLATE_PARMS.  */
2189
2190 int
2191 comp_template_parms (tree parms1, tree parms2)
2192 {
2193   tree p1;
2194   tree p2;
2195
2196   if (parms1 == parms2)
2197     return 1;
2198
2199   for (p1 = parms1, p2 = parms2;
2200        p1 != NULL_TREE && p2 != NULL_TREE;
2201        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2202     {
2203       tree t1 = TREE_VALUE (p1);
2204       tree t2 = TREE_VALUE (p2);
2205       int i;
2206
2207       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2208       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2209
2210       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2211         return 0;
2212
2213       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2214         {
2215           tree parm1;
2216           tree parm2;
2217
2218           if (TREE_VEC_ELT (t1, i) == error_mark_node
2219               || TREE_VEC_ELT (t2, i) == error_mark_node)
2220             continue;
2221
2222           parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2223           parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2224
2225           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2226             return 0;
2227
2228           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM)
2229             continue;
2230           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2231             return 0;
2232         }
2233     }
2234
2235   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2236     /* One set of parameters has more parameters lists than the
2237        other.  */
2238     return 0;
2239
2240   return 1;
2241 }
2242
2243 /* Complain if DECL shadows a template parameter.
2244
2245    [temp.local]: A template-parameter shall not be redeclared within its
2246    scope (including nested scopes).  */
2247
2248 void
2249 check_template_shadow (tree decl)
2250 {
2251   tree olddecl;
2252
2253   /* If we're not in a template, we can't possibly shadow a template
2254      parameter.  */
2255   if (!current_template_parms)
2256     return;
2257
2258   /* Figure out what we're shadowing.  */
2259   if (TREE_CODE (decl) == OVERLOAD)
2260     decl = OVL_CURRENT (decl);
2261   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2262
2263   /* If there's no previous binding for this name, we're not shadowing
2264      anything, let alone a template parameter.  */
2265   if (!olddecl)
2266     return;
2267
2268   /* If we're not shadowing a template parameter, we're done.  Note
2269      that OLDDECL might be an OVERLOAD (or perhaps even an
2270      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2271      node.  */
2272   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2273     return;
2274
2275   /* We check for decl != olddecl to avoid bogus errors for using a
2276      name inside a class.  We check TPFI to avoid duplicate errors for
2277      inline member templates.  */
2278   if (decl == olddecl
2279       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2280     return;
2281
2282   error ("declaration of %q+#D", decl);
2283   error (" shadows template parm %q+#D", olddecl);
2284 }
2285
2286 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2287    ORIG_LEVEL, DECL, and TYPE.  */
2288
2289 static tree
2290 build_template_parm_index (int index,
2291                            int level,
2292                            int orig_level,
2293                            tree decl,
2294                            tree type)
2295 {
2296   tree t = make_node (TEMPLATE_PARM_INDEX);
2297   TEMPLATE_PARM_IDX (t) = index;
2298   TEMPLATE_PARM_LEVEL (t) = level;
2299   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2300   TEMPLATE_PARM_DECL (t) = decl;
2301   TREE_TYPE (t) = type;
2302   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2303   TREE_INVARIANT (t) = TREE_INVARIANT (decl);
2304   TREE_READONLY (t) = TREE_READONLY (decl);
2305
2306   return t;
2307 }
2308
2309 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2310    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2311    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2312    new one is created.  */
2313
2314 static tree
2315 reduce_template_parm_level (tree index, tree type, int levels)
2316 {
2317   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2318       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2319           != TEMPLATE_PARM_LEVEL (index) - levels))
2320     {
2321       tree orig_decl = TEMPLATE_PARM_DECL (index);
2322       tree decl, t;
2323
2324       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2325       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2326       TREE_INVARIANT (decl) = TREE_INVARIANT (orig_decl);
2327       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2328       DECL_ARTIFICIAL (decl) = 1;
2329       SET_DECL_TEMPLATE_PARM_P (decl);
2330
2331       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2332                                      TEMPLATE_PARM_LEVEL (index) - levels,
2333                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2334                                      decl, type);
2335       TEMPLATE_PARM_DESCENDANTS (index) = t;
2336
2337         /* Template template parameters need this.  */
2338       if (TREE_CODE (decl) != CONST_DECL)
2339         DECL_TEMPLATE_PARMS (decl)
2340           = DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index));
2341     }
2342
2343   return TEMPLATE_PARM_DESCENDANTS (index);
2344 }
2345
2346 /* Process information from new template parameter PARM and append it to the
2347    LIST being built.  This new parameter is a non-type parameter iff
2348    IS_NON_TYPE is true.  */
2349
2350 tree
2351 process_template_parm (tree list, tree parm, bool is_non_type)
2352 {
2353   tree decl = 0;
2354   tree defval;
2355   int idx;
2356
2357   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2358   defval = TREE_PURPOSE (parm);
2359
2360   if (list)
2361     {
2362       tree p = TREE_VALUE (tree_last (list));
2363
2364       if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2365         idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2366       else
2367         idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2368       ++idx;
2369     }
2370   else
2371     idx = 0;
2372
2373   if (is_non_type)
2374     {
2375       parm = TREE_VALUE (parm);
2376
2377       SET_DECL_TEMPLATE_PARM_P (parm);
2378
2379       if (TREE_TYPE (parm) == error_mark_node)
2380         return chainon(list, error_mark_node);
2381       else
2382       {
2383         /* [temp.param]
2384
2385            The top-level cv-qualifiers on the template-parameter are
2386            ignored when determining its type.  */
2387         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
2388         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
2389           return chainon(list, error_mark_node);
2390       }
2391
2392       /* A template parameter is not modifiable.  */
2393       TREE_CONSTANT (parm) = 1;
2394       TREE_INVARIANT (parm) = 1;
2395       TREE_READONLY (parm) = 1;
2396       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
2397       TREE_CONSTANT (decl) = 1;
2398       TREE_INVARIANT (decl) = 1;
2399       TREE_READONLY (decl) = 1;
2400       DECL_INITIAL (parm) = DECL_INITIAL (decl)
2401         = build_template_parm_index (idx, processing_template_decl,
2402                                      processing_template_decl,
2403                                      decl, TREE_TYPE (parm));
2404     }
2405   else
2406     {
2407       tree t;
2408       parm = TREE_VALUE (TREE_VALUE (parm));
2409
2410       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
2411         {
2412           t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
2413           /* This is for distinguishing between real templates and template
2414              template parameters */
2415           TREE_TYPE (parm) = t;
2416           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
2417           decl = parm;
2418         }
2419       else
2420         {
2421           t = make_aggr_type (TEMPLATE_TYPE_PARM);
2422           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
2423           decl = build_decl (TYPE_DECL, parm, t);
2424         }
2425
2426       TYPE_NAME (t) = decl;
2427       TYPE_STUB_DECL (t) = decl;
2428       parm = decl;
2429       TEMPLATE_TYPE_PARM_INDEX (t)
2430         = build_template_parm_index (idx, processing_template_decl,
2431                                      processing_template_decl,
2432                                      decl, TREE_TYPE (parm));
2433     }
2434   DECL_ARTIFICIAL (decl) = 1;
2435   SET_DECL_TEMPLATE_PARM_P (decl);
2436   pushdecl (decl);
2437   parm = build_tree_list (defval, parm);
2438   return chainon (list, parm);
2439 }
2440
2441 /* The end of a template parameter list has been reached.  Process the
2442    tree list into a parameter vector, converting each parameter into a more
2443    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
2444    as PARM_DECLs.  */
2445
2446 tree
2447 end_template_parm_list (tree parms)
2448 {
2449   int nparms;
2450   tree parm, next;
2451   tree saved_parmlist = make_tree_vec (list_length (parms));
2452
2453   current_template_parms
2454     = tree_cons (size_int (processing_template_decl),
2455                  saved_parmlist, current_template_parms);
2456
2457   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
2458     {
2459       next = TREE_CHAIN (parm);
2460       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
2461       TREE_CHAIN (parm) = NULL_TREE;
2462     }
2463
2464   --processing_template_parmlist;
2465
2466   return saved_parmlist;
2467 }
2468
2469 /* end_template_decl is called after a template declaration is seen.  */
2470
2471 void
2472 end_template_decl (void)
2473 {
2474   reset_specialization ();
2475
2476   if (! processing_template_decl)
2477     return;
2478
2479   /* This matches the pushlevel in begin_template_parm_list.  */
2480   finish_scope ();
2481
2482   --processing_template_decl;
2483   current_template_parms = TREE_CHAIN (current_template_parms);
2484 }
2485
2486 /* Given a template argument vector containing the template PARMS.
2487    The innermost PARMS are given first.  */
2488
2489 static tree
2490 current_template_args (void)
2491 {
2492   tree header;
2493   tree args = NULL_TREE;
2494   int length = TMPL_PARMS_DEPTH (current_template_parms);
2495   int l = length;
2496
2497   /* If there is only one level of template parameters, we do not
2498      create a TREE_VEC of TREE_VECs.  Instead, we return a single
2499      TREE_VEC containing the arguments.  */
2500   if (length > 1)
2501     args = make_tree_vec (length);
2502
2503   for (header = current_template_parms; header; header = TREE_CHAIN (header))
2504     {
2505       tree a = copy_node (TREE_VALUE (header));
2506       int i;
2507
2508       TREE_TYPE (a) = NULL_TREE;
2509       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
2510         {
2511           tree t = TREE_VEC_ELT (a, i);
2512
2513           /* T will be a list if we are called from within a
2514              begin/end_template_parm_list pair, but a vector directly
2515              if within a begin/end_member_template_processing pair.  */
2516           if (TREE_CODE (t) == TREE_LIST)
2517             {
2518               t = TREE_VALUE (t);
2519
2520               if (TREE_CODE (t) == TYPE_DECL
2521                   || TREE_CODE (t) == TEMPLATE_DECL)
2522                 t = TREE_TYPE (t);
2523               else
2524                 t = DECL_INITIAL (t);
2525               TREE_VEC_ELT (a, i) = t;
2526             }
2527         }
2528
2529       if (length > 1)
2530         TREE_VEC_ELT (args, --l) = a;
2531       else
2532         args = a;
2533     }
2534
2535   return args;
2536 }
2537
2538 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
2539    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
2540    a member template.  Used by push_template_decl below.  */
2541
2542 static tree
2543 build_template_decl (tree decl, tree parms, bool member_template_p)
2544 {
2545   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
2546   DECL_TEMPLATE_PARMS (tmpl) = parms;
2547   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
2548   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
2549   if (DECL_LANG_SPECIFIC (decl))
2550     {
2551       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
2552       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
2553       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
2554       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
2555       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
2556       if (DECL_OVERLOADED_OPERATOR_P (decl))
2557         SET_OVERLOADED_OPERATOR_CODE (tmpl,
2558                                       DECL_OVERLOADED_OPERATOR_P (decl));
2559     }
2560
2561   return tmpl;
2562 }
2563
2564 struct template_parm_data
2565 {
2566   /* The level of the template parameters we are currently
2567      processing.  */
2568   int level;
2569
2570   /* The index of the specialization argument we are currently
2571      processing.  */
2572   int current_arg;
2573
2574   /* An array whose size is the number of template parameters.  The
2575      elements are nonzero if the parameter has been used in any one
2576      of the arguments processed so far.  */
2577   int* parms;
2578
2579   /* An array whose size is the number of template arguments.  The
2580      elements are nonzero if the argument makes use of template
2581      parameters of this level.  */
2582   int* arg_uses_template_parms;
2583 };
2584
2585 /* Subroutine of push_template_decl used to see if each template
2586    parameter in a partial specialization is used in the explicit
2587    argument list.  If T is of the LEVEL given in DATA (which is
2588    treated as a template_parm_data*), then DATA->PARMS is marked
2589    appropriately.  */
2590
2591 static int
2592 mark_template_parm (tree t, void* data)
2593 {
2594   int level;
2595   int idx;
2596   struct template_parm_data* tpd = (struct template_parm_data*) data;
2597
2598   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
2599     {
2600       level = TEMPLATE_PARM_LEVEL (t);
2601       idx = TEMPLATE_PARM_IDX (t);
2602     }
2603   else
2604     {
2605       level = TEMPLATE_TYPE_LEVEL (t);
2606       idx = TEMPLATE_TYPE_IDX (t);
2607     }
2608
2609   if (level == tpd->level)
2610     {
2611       tpd->parms[idx] = 1;
2612       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
2613     }
2614
2615   /* Return zero so that for_each_template_parm will continue the
2616      traversal of the tree; we want to mark *every* template parm.  */
2617   return 0;
2618 }
2619
2620 /* Process the partial specialization DECL.  */
2621
2622 static tree
2623 process_partial_specialization (tree decl)
2624 {
2625   tree type = TREE_TYPE (decl);
2626   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
2627   tree specargs = CLASSTYPE_TI_ARGS (type);
2628   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
2629   tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
2630   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
2631   int nargs = TREE_VEC_LENGTH (inner_args);
2632   int ntparms = TREE_VEC_LENGTH (inner_parms);
2633   int  i;
2634   int did_error_intro = 0;
2635   struct template_parm_data tpd;
2636   struct template_parm_data tpd2;
2637
2638   /* We check that each of the template parameters given in the
2639      partial specialization is used in the argument list to the
2640      specialization.  For example:
2641
2642        template <class T> struct S;
2643        template <class T> struct S<T*>;
2644
2645      The second declaration is OK because `T*' uses the template
2646      parameter T, whereas
2647
2648        template <class T> struct S<int>;
2649
2650      is no good.  Even trickier is:
2651
2652        template <class T>
2653        struct S1
2654        {
2655           template <class U>
2656           struct S2;
2657           template <class U>
2658           struct S2<T>;
2659        };
2660
2661      The S2<T> declaration is actually invalid; it is a
2662      full-specialization.  Of course,
2663
2664           template <class U>
2665           struct S2<T (*)(U)>;
2666
2667      or some such would have been OK.  */
2668   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
2669   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
2670   memset (tpd.parms, 0, sizeof (int) * ntparms);
2671
2672   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
2673   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
2674   for (i = 0; i < nargs; ++i)
2675     {
2676       tpd.current_arg = i;
2677       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
2678                               &mark_template_parm,
2679                               &tpd,
2680                               NULL);
2681     }
2682   for (i = 0; i < ntparms; ++i)
2683     if (tpd.parms[i] == 0)
2684       {
2685         /* One of the template parms was not used in the
2686            specialization.  */
2687         if (!did_error_intro)
2688           {
2689             error ("template parameters not used in partial specialization:");
2690             did_error_intro = 1;
2691           }
2692
2693         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
2694       }
2695
2696   /* [temp.class.spec]
2697
2698      The argument list of the specialization shall not be identical to
2699      the implicit argument list of the primary template.  */
2700   if (comp_template_args
2701       (inner_args,
2702        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
2703                                                    (maintmpl)))))
2704     error ("partial specialization %qT does not specialize any template arguments", type);
2705
2706   /* [temp.class.spec]
2707
2708      A partially specialized non-type argument expression shall not
2709      involve template parameters of the partial specialization except
2710      when the argument expression is a simple identifier.
2711
2712      The type of a template parameter corresponding to a specialized
2713      non-type argument shall not be dependent on a parameter of the
2714      specialization.  */
2715   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
2716   tpd2.parms = 0;
2717   for (i = 0; i < nargs; ++i)
2718     {
2719       tree arg = TREE_VEC_ELT (inner_args, i);
2720       if (/* These first two lines are the `non-type' bit.  */
2721           !TYPE_P (arg)
2722           && TREE_CODE (arg) != TEMPLATE_DECL
2723           /* This next line is the `argument expression is not just a
2724              simple identifier' condition and also the `specialized
2725              non-type argument' bit.  */
2726           && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
2727         {
2728           if (tpd.arg_uses_template_parms[i])
2729             error ("template argument %qE involves template parameter(s)", arg);
2730           else
2731             {
2732               /* Look at the corresponding template parameter,
2733                  marking which template parameters its type depends
2734                  upon.  */
2735               tree type =
2736                 TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (main_inner_parms,
2737                                                      i)));
2738
2739               if (!tpd2.parms)
2740                 {
2741                   /* We haven't yet initialized TPD2.  Do so now.  */
2742                   tpd2.arg_uses_template_parms
2743                     = (int *) alloca (sizeof (int) * nargs);
2744                   /* The number of parameters here is the number in the
2745                      main template, which, as checked in the assertion
2746                      above, is NARGS.  */
2747                   tpd2.parms = (int *) alloca (sizeof (int) * nargs);
2748                   tpd2.level =
2749                     TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
2750                 }
2751
2752               /* Mark the template parameters.  But this time, we're
2753                  looking for the template parameters of the main
2754                  template, not in the specialization.  */
2755               tpd2.current_arg = i;
2756               tpd2.arg_uses_template_parms[i] = 0;
2757               memset (tpd2.parms, 0, sizeof (int) * nargs);
2758               for_each_template_parm (type,
2759                                       &mark_template_parm,
2760                                       &tpd2,
2761                                       NULL);
2762
2763               if (tpd2.arg_uses_template_parms [i])
2764                 {
2765                   /* The type depended on some template parameters.
2766                      If they are fully specialized in the
2767                      specialization, that's OK.  */
2768                   int j;
2769                   for (j = 0; j < nargs; ++j)
2770                     if (tpd2.parms[j] != 0
2771                         && tpd.arg_uses_template_parms [j])
2772                       {
2773                         error ("type %qT of template argument %qE depends "
2774                                "on template parameter(s)",
2775                                type,
2776                                arg);
2777                         break;
2778                       }
2779                 }
2780             }
2781         }
2782     }
2783
2784   if (retrieve_specialization (maintmpl, specargs,
2785                                /*class_specializations_p=*/true))
2786     /* We've already got this specialization.  */
2787     return decl;
2788
2789   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
2790     = tree_cons (specargs, inner_parms,
2791                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
2792   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
2793   return decl;
2794 }
2795
2796 /* Check that a template declaration's use of default arguments is not
2797    invalid.  Here, PARMS are the template parameters.  IS_PRIMARY is
2798    nonzero if DECL is the thing declared by a primary template.
2799    IS_PARTIAL is nonzero if DECL is a partial specialization.  */
2800
2801 static void
2802 check_default_tmpl_args (tree decl, tree parms, int is_primary, int is_partial)
2803 {
2804   const char *msg;
2805   int last_level_to_check;
2806   tree parm_level;
2807
2808   /* [temp.param]
2809
2810      A default template-argument shall not be specified in a
2811      function template declaration or a function template definition, nor
2812      in the template-parameter-list of the definition of a member of a
2813      class template.  */
2814
2815   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
2816     /* You can't have a function template declaration in a local
2817        scope, nor you can you define a member of a class template in a
2818        local scope.  */
2819     return;
2820
2821   if (current_class_type
2822       && !TYPE_BEING_DEFINED (current_class_type)
2823       && DECL_LANG_SPECIFIC (decl)
2824       /* If this is either a friend defined in the scope of the class
2825          or a member function.  */
2826       && (DECL_FUNCTION_MEMBER_P (decl)
2827           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
2828           : DECL_FRIEND_CONTEXT (decl)
2829           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
2830           : false)
2831       /* And, if it was a member function, it really was defined in
2832          the scope of the class.  */
2833       && (!DECL_FUNCTION_MEMBER_P (decl)
2834           || DECL_INITIALIZED_IN_CLASS_P (decl)))
2835     /* We already checked these parameters when the template was
2836        declared, so there's no need to do it again now.  This function
2837        was defined in class scope, but we're processing it's body now
2838        that the class is complete.  */
2839     return;
2840
2841   /* [temp.param]
2842
2843      If a template-parameter has a default template-argument, all
2844      subsequent template-parameters shall have a default
2845      template-argument supplied.  */
2846   for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
2847     {
2848       tree inner_parms = TREE_VALUE (parm_level);
2849       int ntparms = TREE_VEC_LENGTH (inner_parms);
2850       int seen_def_arg_p = 0;
2851       int i;
2852
2853       for (i = 0; i < ntparms; ++i)
2854         {
2855           tree parm = TREE_VEC_ELT (inner_parms, i);
2856
2857           if (parm == error_mark_node)
2858             continue;
2859
2860           if (TREE_PURPOSE (parm))
2861             seen_def_arg_p = 1;
2862           else if (seen_def_arg_p)
2863             {
2864               error ("no default argument for %qD", TREE_VALUE (parm));
2865               /* For better subsequent error-recovery, we indicate that
2866                  there should have been a default argument.  */
2867               TREE_PURPOSE (parm) = error_mark_node;
2868             }
2869         }
2870     }
2871
2872   if (TREE_CODE (decl) != TYPE_DECL || is_partial || !is_primary)
2873     /* For an ordinary class template, default template arguments are
2874        allowed at the innermost level, e.g.:
2875          template <class T = int>
2876          struct S {};
2877        but, in a partial specialization, they're not allowed even
2878        there, as we have in [temp.class.spec]:
2879
2880          The template parameter list of a specialization shall not
2881          contain default template argument values.
2882
2883        So, for a partial specialization, or for a function template,
2884        we look at all of them.  */
2885     ;
2886   else
2887     /* But, for a primary class template that is not a partial
2888        specialization we look at all template parameters except the
2889        innermost ones.  */
2890     parms = TREE_CHAIN (parms);
2891
2892   /* Figure out what error message to issue.  */
2893   if (TREE_CODE (decl) == FUNCTION_DECL)
2894     msg = "default template arguments may not be used in function templates";
2895   else if (is_partial)
2896     msg = "default template arguments may not be used in partial specializations";
2897   else
2898     msg = "default argument for template parameter for class enclosing %qD";
2899
2900   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
2901     /* If we're inside a class definition, there's no need to
2902        examine the parameters to the class itself.  On the one
2903        hand, they will be checked when the class is defined, and,
2904        on the other, default arguments are valid in things like:
2905          template <class T = double>
2906          struct S { template <class U> void f(U); };
2907        Here the default argument for `S' has no bearing on the
2908        declaration of `f'.  */
2909     last_level_to_check = template_class_depth (current_class_type) + 1;
2910   else
2911     /* Check everything.  */
2912     last_level_to_check = 0;
2913
2914   for (parm_level = parms;
2915        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
2916        parm_level = TREE_CHAIN (parm_level))
2917     {
2918       tree inner_parms = TREE_VALUE (parm_level);
2919       int i;
2920       int ntparms;
2921
2922       ntparms = TREE_VEC_LENGTH (inner_parms);
2923       for (i = 0; i < ntparms; ++i)
2924         {
2925           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
2926             continue;
2927
2928           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
2929             {
2930               if (msg)
2931                 {
2932                   error (msg, decl);
2933                   msg = 0;
2934                 }
2935
2936               /* Clear out the default argument so that we are not
2937                  confused later.  */
2938               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
2939             }
2940         }
2941
2942       /* At this point, if we're still interested in issuing messages,
2943          they must apply to classes surrounding the object declared.  */
2944       if (msg)
2945         msg = "default argument for template parameter for class enclosing %qD";
2946     }
2947 }
2948
2949 /* Worker for push_template_decl_real, called via
2950    for_each_template_parm.  DATA is really an int, indicating the
2951    level of the parameters we are interested in.  If T is a template
2952    parameter of that level, return nonzero.  */
2953
2954 static int
2955 template_parm_this_level_p (tree t, void* data)
2956 {
2957   int this_level = *(int *)data;
2958   int level;
2959
2960   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
2961     level = TEMPLATE_PARM_LEVEL (t);
2962   else
2963     level = TEMPLATE_TYPE_LEVEL (t);
2964   return level == this_level;
2965 }
2966
2967 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
2968    parameters given by current_template_args, or reuses a
2969    previously existing one, if appropriate.  Returns the DECL, or an
2970    equivalent one, if it is replaced via a call to duplicate_decls.
2971
2972    If IS_FRIEND is true, DECL is a friend declaration.  */
2973
2974 tree
2975 push_template_decl_real (tree decl, bool is_friend)
2976 {
2977   tree tmpl;
2978   tree args;
2979   tree info;
2980   tree ctx;
2981   int primary;
2982   int is_partial;
2983   int new_template_p = 0;
2984   /* True if the template is a member template, in the sense of
2985      [temp.mem].  */
2986   bool member_template_p = false;
2987
2988   if (decl == error_mark_node)
2989     return decl;
2990
2991   /* See if this is a partial specialization.  */
2992   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
2993                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
2994                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
2995
2996   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
2997     is_friend = true;
2998
2999   if (is_friend)
3000     /* For a friend, we want the context of the friend function, not
3001        the type of which it is a friend.  */
3002     ctx = DECL_CONTEXT (decl);
3003   else if (CP_DECL_CONTEXT (decl)
3004            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3005     /* In the case of a virtual function, we want the class in which
3006        it is defined.  */
3007     ctx = CP_DECL_CONTEXT (decl);
3008   else
3009     /* Otherwise, if we're currently defining some class, the DECL
3010        is assumed to be a member of the class.  */
3011     ctx = current_scope ();
3012
3013   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3014     ctx = NULL_TREE;
3015
3016   if (!DECL_CONTEXT (decl))
3017     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3018
3019   /* See if this is a primary template.  */
3020   primary = template_parm_scope_p ();
3021
3022   if (primary)
3023     {
3024       if (DECL_CLASS_SCOPE_P (decl))
3025         member_template_p = true;
3026       if (TREE_CODE (decl) == TYPE_DECL
3027           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3028         error ("template class without a name");
3029       else if (TREE_CODE (decl) == FUNCTION_DECL)
3030         {
3031           if (DECL_DESTRUCTOR_P (decl))
3032             {
3033               /* [temp.mem]
3034
3035                  A destructor shall not be a member template.  */
3036               error ("destructor %qD declared as member template", decl);
3037               return error_mark_node;
3038             }
3039           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3040               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3041                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3042                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3043                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3044                       == void_list_node)))
3045             {
3046               /* [basic.stc.dynamic.allocation]
3047
3048                  An allocation function can be a function
3049                  template. ... Template allocation functions shall
3050                  have two or more parameters.  */
3051               error ("invalid template declaration of %qD", decl);
3052               return error_mark_node;
3053             }
3054         }
3055       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3056                && CLASS_TYPE_P (TREE_TYPE (decl)))
3057         /* OK */;
3058       else
3059         {
3060           error ("template declaration of %q#D", decl);
3061           return error_mark_node;
3062         }
3063     }
3064
3065   /* Check to see that the rules regarding the use of default
3066      arguments are not being violated.  */
3067   check_default_tmpl_args (decl, current_template_parms,
3068                            primary, is_partial);
3069
3070   if (is_partial)
3071     return process_partial_specialization (decl);
3072
3073   args = current_template_args ();
3074
3075   if (!ctx
3076       || TREE_CODE (ctx) == FUNCTION_DECL
3077       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3078       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3079     {
3080       if (DECL_LANG_SPECIFIC (decl)
3081           && DECL_TEMPLATE_INFO (decl)
3082           && DECL_TI_TEMPLATE (decl))
3083         tmpl = DECL_TI_TEMPLATE (decl);
3084       /* If DECL is a TYPE_DECL for a class-template, then there won't
3085          be DECL_LANG_SPECIFIC.  The information equivalent to
3086          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3087       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3088                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3089                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3090         {
3091           /* Since a template declaration already existed for this
3092              class-type, we must be redeclaring it here.  Make sure
3093              that the redeclaration is valid.  */
3094           redeclare_class_template (TREE_TYPE (decl),
3095                                     current_template_parms);
3096           /* We don't need to create a new TEMPLATE_DECL; just use the
3097              one we already had.  */
3098           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3099         }
3100       else
3101         {
3102           tmpl = build_template_decl (decl, current_template_parms,
3103                                       member_template_p);
3104           new_template_p = 1;
3105
3106           if (DECL_LANG_SPECIFIC (decl)
3107               && DECL_TEMPLATE_SPECIALIZATION (decl))
3108             {
3109               /* A specialization of a member template of a template
3110                  class.  */
3111               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3112               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3113               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3114             }
3115         }
3116     }
3117   else
3118     {
3119       tree a, t, current, parms;
3120       int i;
3121
3122       if (TREE_CODE (decl) == TYPE_DECL)
3123         {
3124           if ((IS_AGGR_TYPE_CODE (TREE_CODE (TREE_TYPE (decl)))
3125                || TREE_CODE (TREE_TYPE (decl)) == ENUMERAL_TYPE)
3126               && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3127               && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3128             tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3129           else
3130             {
3131               error ("%qD does not declare a template type", decl);
3132               return decl;
3133             }
3134         }
3135       else if (!DECL_LANG_SPECIFIC (decl) || !DECL_TEMPLATE_INFO (decl))
3136         {
3137           error ("template definition of non-template %q#D", decl);
3138           return decl;
3139         }
3140       else
3141         tmpl = DECL_TI_TEMPLATE (decl);
3142
3143       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3144           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3145           && DECL_TEMPLATE_SPECIALIZATION (decl)
3146           && DECL_MEMBER_TEMPLATE_P (tmpl))
3147         {
3148           tree new_tmpl;
3149
3150           /* The declaration is a specialization of a member
3151              template, declared outside the class.  Therefore, the
3152              innermost template arguments will be NULL, so we
3153              replace them with the arguments determined by the
3154              earlier call to check_explicit_specialization.  */
3155           args = DECL_TI_ARGS (decl);
3156
3157           new_tmpl
3158             = build_template_decl (decl, current_template_parms,
3159                                    member_template_p);
3160           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3161           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3162           DECL_TI_TEMPLATE (decl) = new_tmpl;
3163           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3164           DECL_TEMPLATE_INFO (new_tmpl)
3165             = tree_cons (tmpl, args, NULL_TREE);
3166
3167           register_specialization (new_tmpl,
3168                                    most_general_template (tmpl),
3169                                    args,
3170                                    is_friend);
3171           return decl;
3172         }
3173
3174       /* Make sure the template headers we got make sense.  */
3175
3176       parms = DECL_TEMPLATE_PARMS (tmpl);
3177       i = TMPL_PARMS_DEPTH (parms);
3178       if (TMPL_ARGS_DEPTH (args) != i)
3179         {
3180           error ("expected %d levels of template parms for %q#D, got %d",
3181                  i, decl, TMPL_ARGS_DEPTH (args));
3182         }
3183       else
3184         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
3185           {
3186             a = TMPL_ARGS_LEVEL (args, i);
3187             t = INNERMOST_TEMPLATE_PARMS (parms);
3188
3189             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
3190               {
3191                 if (current == decl)
3192                   error ("got %d template parameters for %q#D",
3193                          TREE_VEC_LENGTH (a), decl);
3194                 else
3195                   error ("got %d template parameters for %q#T",
3196                          TREE_VEC_LENGTH (a), current);
3197                 error ("  but %d required", TREE_VEC_LENGTH (t));
3198                 return error_mark_node;
3199               }
3200
3201             /* Perhaps we should also check that the parms are used in the
3202                appropriate qualifying scopes in the declarator?  */
3203
3204             if (current == decl)
3205               current = ctx;
3206             else
3207               current = TYPE_CONTEXT (current);
3208           }
3209     }
3210
3211   DECL_TEMPLATE_RESULT (tmpl) = decl;
3212   TREE_TYPE (tmpl) = TREE_TYPE (decl);
3213
3214   /* Push template declarations for global functions and types.  Note
3215      that we do not try to push a global template friend declared in a
3216      template class; such a thing may well depend on the template
3217      parameters of the class.  */
3218   if (new_template_p && !ctx
3219       && !(is_friend && template_class_depth (current_class_type) > 0))
3220     {
3221       tmpl = pushdecl_namespace_level (tmpl, is_friend);
3222       if (tmpl == error_mark_node)
3223         return error_mark_node;
3224
3225       /* Hide template friend classes that haven't been declared yet.  */
3226       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
3227         {
3228           DECL_ANTICIPATED (tmpl) = 1;
3229           DECL_FRIEND_P (tmpl) = 1;
3230         }
3231     }
3232
3233   if (primary)
3234     {
3235       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
3236       if (DECL_CONV_FN_P (tmpl))
3237         {
3238           int depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3239
3240           /* It is a conversion operator. See if the type converted to
3241              depends on innermost template operands.  */
3242
3243           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
3244                                          depth))
3245             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
3246         }
3247     }
3248
3249   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
3250      back to its most general template.  If TMPL is a specialization,
3251      ARGS may only have the innermost set of arguments.  Add the missing
3252      argument levels if necessary.  */
3253   if (DECL_TEMPLATE_INFO (tmpl))
3254     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
3255
3256   info = tree_cons (tmpl, args, NULL_TREE);
3257
3258   if (DECL_IMPLICIT_TYPEDEF_P (decl))
3259     {
3260       SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
3261       if ((!ctx || TREE_CODE (ctx) != FUNCTION_DECL)
3262           && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3263           /* Don't change the name if we've already set it up.  */
3264           && !IDENTIFIER_TEMPLATE (DECL_NAME (decl)))
3265         DECL_NAME (decl) = classtype_mangled_name (TREE_TYPE (decl));
3266     }
3267   else if (DECL_LANG_SPECIFIC (decl))
3268     DECL_TEMPLATE_INFO (decl) = info;
3269
3270   return DECL_TEMPLATE_RESULT (tmpl);
3271 }
3272
3273 tree
3274 push_template_decl (tree decl)
3275 {
3276   return push_template_decl_real (decl, false);
3277 }
3278
3279 /* Called when a class template TYPE is redeclared with the indicated
3280    template PARMS, e.g.:
3281
3282      template <class T> struct S;
3283      template <class T> struct S {};  */
3284
3285 void
3286 redeclare_class_template (tree type, tree parms)
3287 {
3288   tree tmpl;
3289   tree tmpl_parms;
3290   int i;
3291
3292   if (!TYPE_TEMPLATE_INFO (type))
3293     {
3294       error ("%qT is not a template type", type);
3295       return;
3296     }
3297
3298   tmpl = TYPE_TI_TEMPLATE (type);
3299   if (!PRIMARY_TEMPLATE_P (tmpl))
3300     /* The type is nested in some template class.  Nothing to worry
3301        about here; there are no new template parameters for the nested
3302        type.  */
3303     return;
3304
3305   if (!parms)
3306     {
3307       error ("template specifiers not specified in declaration of %qD",
3308              tmpl);
3309       return;
3310     }
3311
3312   parms = INNERMOST_TEMPLATE_PARMS (parms);
3313   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
3314
3315   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
3316     {
3317       error ("previous declaration %q+D", tmpl);
3318       error ("used %d template parameter(s) instead of %d",
3319              TREE_VEC_LENGTH (tmpl_parms),
3320              TREE_VEC_LENGTH (parms));
3321       return;
3322     }
3323
3324   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
3325     {
3326       tree tmpl_parm;
3327       tree parm;
3328       tree tmpl_default;
3329       tree parm_default;
3330
3331       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
3332           || TREE_VEC_ELT (parms, i) == error_mark_node)
3333         continue;
3334
3335       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
3336       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
3337       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
3338       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
3339
3340       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
3341          TEMPLATE_DECL.  */
3342       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
3343           || (TREE_CODE (tmpl_parm) != TYPE_DECL
3344               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm))))
3345         {
3346           error ("template parameter %q+#D", tmpl_parm);
3347           error ("redeclared here as %q#D", parm);
3348           return;
3349         }
3350
3351       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
3352         {
3353           /* We have in [temp.param]:
3354
3355              A template-parameter may not be given default arguments
3356              by two different declarations in the same scope.  */
3357           error ("redefinition of default argument for %q#D", parm);
3358           error ("%J  original definition appeared here", tmpl_parm);
3359           return;
3360         }
3361
3362       if (parm_default != NULL_TREE)
3363         /* Update the previous template parameters (which are the ones
3364            that will really count) with the new default value.  */
3365         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
3366       else if (tmpl_default != NULL_TREE)
3367         /* Update the new parameters, too; they'll be used as the
3368            parameters for any members.  */
3369         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
3370     }
3371 }
3372
3373 /* Simplify EXPR if it is a non-dependent expression.  Returns the
3374    (possibly simplified) expression.  */
3375
3376 tree
3377 fold_non_dependent_expr (tree expr)
3378 {
3379   /* If we're in a template, but EXPR isn't value dependent, simplify
3380      it.  We're supposed to treat:
3381
3382        template <typename T> void f(T[1 + 1]);
3383        template <typename T> void f(T[2]);
3384
3385      as two declarations of the same function, for example.  */
3386   if (processing_template_decl
3387       && !type_dependent_expression_p (expr)
3388       && !value_dependent_expression_p (expr))
3389     {
3390       HOST_WIDE_INT saved_processing_template_decl;
3391
3392       saved_processing_template_decl = processing_template_decl;
3393       processing_template_decl = 0;
3394       expr = tsubst_copy_and_build (expr,
3395                                     /*args=*/NULL_TREE,
3396                                     tf_error,
3397                                     /*in_decl=*/NULL_TREE,
3398                                     /*function_p=*/false);
3399       processing_template_decl = saved_processing_template_decl;
3400     }
3401   return expr;
3402 }
3403
3404 /* EXPR is an expression which is used in a constant-expression context.
3405    For instance, it could be a VAR_DECL with a constant initializer.
3406    Extract the innest constant expression.
3407
3408    This is basically a more powerful version of
3409    integral_constant_value, which can be used also in templates where
3410    initializers can maintain a syntactic rather than semantic form
3411    (even if they are non-dependent, for access-checking purposes).  */
3412
3413 static tree
3414 fold_decl_constant_value (tree expr)
3415 {
3416   tree const_expr = expr;
3417   do
3418     {
3419       expr = fold_non_dependent_expr (const_expr);
3420       const_expr = integral_constant_value (expr);
3421     }
3422   while (expr != const_expr);
3423
3424   return expr;
3425 }
3426
3427 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
3428    must be a function or a pointer-to-function type, as specified
3429    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
3430    and check that the resulting function has external linkage.  */
3431
3432 static tree
3433 convert_nontype_argument_function (tree type, tree expr)
3434 {
3435   tree fns = expr;
3436   tree fn, fn_no_ptr;
3437
3438   fn = instantiate_type (type, fns, tf_none);
3439   if (fn == error_mark_node)
3440     return error_mark_node;
3441
3442   fn_no_ptr = fn;
3443   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
3444     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
3445
3446   /* [temp.arg.nontype]/1
3447
3448      A template-argument for a non-type, non-template template-parameter
3449      shall be one of:
3450      [...]
3451      -- the address of an object or function with external linkage.  */
3452   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
3453     {
3454       error ("%qE is not a valid template argument for type %qT "
3455              "because function %qD has not external linkage",
3456              expr, type, fn_no_ptr);
3457       return NULL_TREE;
3458     }
3459
3460   return fn;
3461 }
3462
3463 /* Attempt to convert the non-type template parameter EXPR to the
3464    indicated TYPE.  If the conversion is successful, return the
3465    converted value.  If the conversion is unsuccessful, return
3466    NULL_TREE if we issued an error message, or error_mark_node if we
3467    did not.  We issue error messages for out-and-out bad template
3468    parameters, but not simply because the conversion failed, since we
3469    might be just trying to do argument deduction.  Both TYPE and EXPR
3470    must be non-dependent.
3471
3472    The conversion follows the special rules described in
3473    [temp.arg.nontype], and it is much more strict than an implicit
3474    conversion.
3475
3476    This function is called twice for each template argument (see
3477    lookup_template_class for a more accurate description of this
3478    problem). This means that we need to handle expressions which
3479    are not valid in a C++ source, but can be created from the
3480    first call (for instance, casts to perform conversions). These
3481    hacks can go away after we fix the double coercion problem.  */
3482
3483 static tree
3484 convert_nontype_argument (tree type, tree expr)
3485 {
3486   tree expr_type;
3487
3488   /* Detect immediately string literals as invalid non-type argument.
3489      This special-case is not needed for correctness (we would easily
3490      catch this later), but only to provide better diagnostic for this
3491      common user mistake. As suggested by DR 100, we do not mention
3492      linkage issues in the diagnostic as this is not the point.  */
3493   if (TREE_CODE (expr) == STRING_CST)
3494     {
3495       error ("%qE is not a valid template argument for type %qT "
3496              "because string literals can never be used in this context",
3497              expr, type);
3498       return NULL_TREE;
3499     }
3500
3501   /* If we are in a template, EXPR may be non-dependent, but still
3502      have a syntactic, rather than semantic, form.  For example, EXPR
3503      might be a SCOPE_REF, rather than the VAR_DECL to which the
3504      SCOPE_REF refers.  Preserving the qualifying scope is necessary
3505      so that access checking can be performed when the template is
3506      instantiated -- but here we need the resolved form so that we can
3507      convert the argument.  */
3508   expr = fold_non_dependent_expr (expr);
3509   if (error_operand_p (expr))
3510     return error_mark_node;
3511   expr_type = TREE_TYPE (expr);
3512
3513   /* HACK: Due to double coercion, we can get a
3514      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
3515      which is the tree that we built on the first call (see
3516      below when coercing to reference to object or to reference to
3517      function). We just strip everything and get to the arg.
3518      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
3519      for examples.  */
3520   if (TREE_CODE (expr) == NOP_EXPR)
3521     {
3522       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
3523         {
3524           /* ??? Maybe we could use convert_from_reference here, but we
3525              would need to relax its constraints because the NOP_EXPR
3526              could actually change the type to something more cv-qualified,
3527              and this is not folded by convert_from_reference.  */
3528           tree addr = TREE_OPERAND (expr, 0);
3529           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
3530           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
3531           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
3532           gcc_assert (same_type_ignoring_top_level_qualifiers_p
3533                       (TREE_TYPE (expr_type),
3534                        TREE_TYPE (TREE_TYPE (addr))));
3535
3536           expr = TREE_OPERAND (addr, 0);
3537           expr_type = TREE_TYPE (expr);
3538         }
3539
3540       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
3541          parameter is a pointer to object, through decay and
3542          qualification conversion. Let's strip everything.  */
3543       else if (TYPE_PTROBV_P (type))
3544         {
3545           STRIP_NOPS (expr);
3546           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
3547           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
3548           /* Skip the ADDR_EXPR only if it is part of the decay for
3549              an array. Otherwise, it is part of the original argument
3550              in the source code.  */
3551           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
3552             expr = TREE_OPERAND (expr, 0);
3553           expr_type = TREE_TYPE (expr);
3554         }
3555     }
3556
3557   /* [temp.arg.nontype]/5, bullet 1
3558
3559      For a non-type template-parameter of integral or enumeration type,
3560      integral promotions (_conv.prom_) and integral conversions
3561      (_conv.integral_) are applied.  */
3562   if (INTEGRAL_TYPE_P (type))
3563     {
3564       if (!INTEGRAL_TYPE_P (expr_type))
3565         return error_mark_node;
3566
3567       expr = fold_decl_constant_value (expr);
3568       /* Notice that there are constant expressions like '4 % 0' which
3569          do not fold into integer constants.  */
3570       if (TREE_CODE (expr) != INTEGER_CST)
3571         {
3572           error ("%qE is not a valid template argument for type %qT "
3573                  "because it is a non-constant expression", expr, type);
3574           return NULL_TREE;
3575         }
3576
3577       /* At this point, an implicit conversion does what we want,
3578          because we already know that the expression is of integral
3579          type.  */
3580       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
3581       if (expr == error_mark_node)
3582         return error_mark_node;
3583
3584       /* Conversion was allowed: fold it to a bare integer constant.  */
3585       expr = fold (expr);
3586     }
3587   /* [temp.arg.nontype]/5, bullet 2
3588
3589      For a non-type template-parameter of type pointer to object,
3590      qualification conversions (_conv.qual_) and the array-to-pointer
3591      conversion (_conv.array_) are applied.  */
3592   else if (TYPE_PTROBV_P (type))
3593     {
3594       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
3595
3596          A template-argument for a non-type, non-template template-parameter
3597          shall be one of: [...]
3598
3599          -- the name of a non-type template-parameter;
3600          -- the address of an object or function with external linkage, [...]
3601             expressed as "& id-expression" where the & is optional if the name
3602             refers to a function or array, or if the corresponding
3603             template-parameter is a reference.
3604
3605         Here, we do not care about functions, as they are invalid anyway
3606         for a parameter of type pointer-to-object.  */
3607       bool constant_address_p =
3608         (TREE_CODE (expr) == ADDR_EXPR
3609          || TREE_CODE (expr_type) == ARRAY_TYPE
3610          || (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr)));
3611
3612       expr = decay_conversion (expr);
3613       if (expr == error_mark_node)
3614         return error_mark_node;
3615
3616       expr = perform_qualification_conversions (type, expr);
3617       if (expr == error_mark_node)
3618         return error_mark_node;
3619
3620       if (!constant_address_p)
3621         {
3622           error ("%qE is not a valid template argument for type %qT "
3623                  "because it is not a constant pointer", expr, type);
3624           return NULL_TREE;
3625         }
3626     }
3627   /* [temp.arg.nontype]/5, bullet 3
3628
3629      For a non-type template-parameter of type reference to object, no
3630      conversions apply. The type referred to by the reference may be more
3631      cv-qualified than the (otherwise identical) type of the
3632      template-argument. The template-parameter is bound directly to the
3633      template-argument, which must be an lvalue.  */
3634   else if (TYPE_REF_OBJ_P (type))
3635     {
3636       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
3637                                                       expr_type))
3638         return error_mark_node;
3639
3640       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
3641         {
3642           error ("%qE is not a valid template argument for type %qT "
3643                  "because of conflicts in cv-qualification", expr, type);
3644           return NULL_TREE;
3645         }
3646
3647       if (!real_lvalue_p (expr))
3648         {
3649           error ("%qE is not a valid template argument for type %qT "
3650                  "because it is not an lvalue", expr, type);
3651           return NULL_TREE;
3652         }
3653
3654       /* [temp.arg.nontype]/1
3655
3656          A template-argument for a non-type, non-template template-parameter
3657          shall be one of: [...]
3658
3659          -- the address of an object or function with external linkage.  */
3660       if (!DECL_EXTERNAL_LINKAGE_P (expr))
3661         {
3662           error ("%qE is not a valid template argument for type %qT "
3663                  "because object %qD has not external linkage",
3664                  expr, type, expr);
3665           return NULL_TREE;
3666         }
3667
3668       expr = build_nop (type, build_address (expr));
3669     }
3670   /* [temp.arg.nontype]/5, bullet 4
3671
3672      For a non-type template-parameter of type pointer to function, only
3673      the function-to-pointer conversion (_conv.func_) is applied. If the
3674      template-argument represents a set of overloaded functions (or a
3675      pointer to such), the matching function is selected from the set
3676      (_over.over_).  */
3677   else if (TYPE_PTRFN_P (type))
3678     {
3679       /* If the argument is a template-id, we might not have enough
3680          context information to decay the pointer.  */
3681       if (!type_unknown_p (expr_type))
3682         {
3683           expr = decay_conversion (expr);
3684           if (expr == error_mark_node)
3685             return error_mark_node;
3686         }
3687
3688       expr = convert_nontype_argument_function (type, expr);
3689       if (!expr || expr == error_mark_node)
3690         return expr;
3691     }
3692   /* [temp.arg.nontype]/5, bullet 5
3693
3694      For a non-type template-parameter of type reference to function, no
3695      conversions apply. If the template-argument represents a set of
3696      overloaded functions, the matching function is selected from the set
3697      (_over.over_).  */
3698   else if (TYPE_REFFN_P (type))
3699     {
3700       if (TREE_CODE (expr) == ADDR_EXPR)
3701         {
3702           error ("%qE is not a valid template argument for type %qT "
3703                  "because it is a pointer", expr, type);
3704           inform ("try using %qE instead", TREE_OPERAND (expr, 0));
3705           return NULL_TREE;
3706         }
3707
3708       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
3709       if (!expr || expr == error_mark_node)
3710         return expr;
3711
3712       expr = build_nop (type, build_address (expr));
3713     }
3714   /* [temp.arg.nontype]/5, bullet 6
3715
3716      For a non-type template-parameter of type pointer to member function,
3717      no conversions apply. If the template-argument represents a set of
3718      overloaded member functions, the matching member function is selected
3719      from the set (_over.over_).  */
3720   else if (TYPE_PTRMEMFUNC_P (type))
3721     {
3722       expr = instantiate_type (type, expr, tf_none);
3723       if (expr == error_mark_node)
3724         return error_mark_node;
3725
3726       /* There is no way to disable standard conversions in
3727          resolve_address_of_overloaded_function (called by
3728          instantiate_type). It is possible that the call succeeded by
3729          converting &B::I to &D::I (where B is a base of D), so we need
3730          to reject this conversion here.
3731
3732          Actually, even if there was a way to disable standard conversions,
3733          it would still be better to reject them here so that we can
3734          provide a superior diagnostic.  */
3735       if (!same_type_p (TREE_TYPE (expr), type))
3736         {
3737           /* Make sure we are just one standard conversion off.  */
3738           gcc_assert (can_convert (type, TREE_TYPE (expr)));
3739           error ("%qE is not a valid template argument for type %qT "
3740                  "because it is of type %qT", expr, type,
3741                  TREE_TYPE (expr));
3742           inform ("standard conversions are not allowed in this context");
3743           return NULL_TREE;
3744         }
3745     }
3746   /* [temp.arg.nontype]/5, bullet 7
3747
3748      For a non-type template-parameter of type pointer to data member,
3749      qualification conversions (_conv.qual_) are applied.  */
3750   else if (TYPE_PTRMEM_P (type))
3751     {
3752       expr = perform_qualification_conversions (type, expr);
3753       if (expr == error_mark_node)
3754         return expr;
3755     }
3756   /* A template non-type parameter must be one of the above.  */
3757   else
3758     gcc_unreachable ();
3759
3760   /* Sanity check: did we actually convert the argument to the
3761      right type?  */
3762   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
3763   return expr;
3764 }
3765
3766
3767 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
3768    template template parameters.  Both PARM_PARMS and ARG_PARMS are
3769    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
3770    or PARM_DECL.
3771
3772    Consider the example:
3773      template <class T> class A;
3774      template<template <class U> class TT> class B;
3775
3776    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
3777    the parameters to A, and OUTER_ARGS contains A.  */
3778
3779 static int
3780 coerce_template_template_parms (tree parm_parms,
3781                                 tree arg_parms,
3782                                 tsubst_flags_t complain,
3783                                 tree in_decl,
3784                                 tree outer_args)
3785 {
3786   int nparms, nargs, i;
3787   tree parm, arg;
3788
3789   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
3790   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
3791
3792   nparms = TREE_VEC_LENGTH (parm_parms);
3793   nargs = TREE_VEC_LENGTH (arg_parms);
3794
3795   if (nargs != nparms)
3796     return 0;
3797
3798   for (i = 0; i < nparms; ++i)
3799     {
3800       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
3801           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
3802         continue;
3803
3804       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
3805       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
3806
3807       if (arg == NULL_TREE || arg == error_mark_node
3808           || parm == NULL_TREE || parm == error_mark_node)
3809         return 0;
3810
3811       if (TREE_CODE (arg) != TREE_CODE (parm))
3812         return 0;
3813
3814       switch (TREE_CODE (parm))
3815         {
3816         case TYPE_DECL:
3817           break;
3818
3819         case TEMPLATE_DECL:
3820           /* We encounter instantiations of templates like
3821                template <template <template <class> class> class TT>
3822                class C;  */
3823           {
3824             tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
3825             tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
3826
3827             if (!coerce_template_template_parms
3828                 (parmparm, argparm, complain, in_decl, outer_args))
3829               return 0;
3830           }
3831           break;
3832
3833         case PARM_DECL:
3834           /* The tsubst call is used to handle cases such as
3835
3836                template <int> class C {};
3837                template <class T, template <T> class TT> class D {};
3838                D<int, C> d;
3839
3840              i.e. the parameter list of TT depends on earlier parameters.  */
3841           if (!dependent_type_p (TREE_TYPE (arg))
3842               && !same_type_p
3843                     (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
3844                              TREE_TYPE (arg)))
3845             return 0;
3846           break;
3847
3848         default:
3849           gcc_unreachable ();
3850         }
3851     }
3852   return 1;
3853 }
3854
3855 /* Convert the indicated template ARG as necessary to match the
3856    indicated template PARM.  Returns the converted ARG, or
3857    error_mark_node if the conversion was unsuccessful.  Error and
3858    warning messages are issued under control of COMPLAIN.  This
3859    conversion is for the Ith parameter in the parameter list.  ARGS is
3860    the full set of template arguments deduced so far.  */
3861
3862 static tree
3863 convert_template_argument (tree parm,
3864                            tree arg,
3865                            tree args,
3866                            tsubst_flags_t complain,
3867                            int i,
3868                            tree in_decl)
3869 {
3870   tree val;
3871   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
3872
3873   if (TREE_CODE (arg) == TREE_LIST
3874       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
3875     {
3876       /* The template argument was the name of some
3877          member function.  That's usually
3878          invalid, but static members are OK.  In any
3879          case, grab the underlying fields/functions
3880          and issue an error later if required.  */
3881       arg = TREE_VALUE (arg);
3882       TREE_TYPE (arg) = unknown_type_node;
3883     }
3884
3885   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
3886   requires_type = (TREE_CODE (parm) == TYPE_DECL
3887                    || requires_tmpl_type);
3888
3889   is_tmpl_type = ((TREE_CODE (arg) == TEMPLATE_DECL
3890                    && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
3891                   || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3892                   || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
3893
3894   if (is_tmpl_type
3895       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3896           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
3897     arg = TYPE_STUB_DECL (arg);
3898
3899   is_type = TYPE_P (arg) || is_tmpl_type;
3900
3901   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
3902       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
3903     {
3904       pedwarn ("to refer to a type member of a template parameter, "
3905                "use %<typename %E%>", arg);
3906
3907       arg = make_typename_type (TREE_OPERAND (arg, 0),
3908                                 TREE_OPERAND (arg, 1),
3909                                 typename_type,
3910                                 complain & tf_error);
3911       is_type = 1;
3912     }
3913   if (is_type != requires_type)
3914     {
3915       if (in_decl)
3916         {
3917           if (complain & tf_error)
3918             {
3919               error ("type/value mismatch at argument %d in template "
3920                      "parameter list for %qD",
3921                      i + 1, in_decl);
3922               if (is_type)
3923                 error ("  expected a constant of type %qT, got %qT",
3924                        TREE_TYPE (parm),
3925                        (is_tmpl_type ? DECL_NAME (arg) : arg));
3926               else if (requires_tmpl_type)
3927                 error ("  expected a class template, got %qE", arg);
3928               else
3929                 error ("  expected a type, got %qE", arg);
3930             }
3931         }
3932       return error_mark_node;
3933     }
3934   if (is_tmpl_type ^ requires_tmpl_type)
3935     {
3936       if (in_decl && (complain & tf_error))
3937         {
3938           error ("type/value mismatch at argument %d in template "
3939                  "parameter list for %qD",
3940                  i + 1, in_decl);
3941           if (is_tmpl_type)
3942             error ("  expected a type, got %qT", DECL_NAME (arg));
3943           else
3944             error ("  expected a class template, got %qT", arg);
3945         }
3946       return error_mark_node;
3947     }
3948
3949   if (is_type)
3950     {
3951       if (requires_tmpl_type)
3952         {
3953           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
3954             /* The number of argument required is not known yet.
3955                Just accept it for now.  */
3956             val = TREE_TYPE (arg);
3957           else
3958             {
3959               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
3960               tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
3961
3962               if (coerce_template_template_parms (parmparm, argparm,
3963                                                   complain, in_decl,
3964                                                   args))
3965                 {
3966                   val = arg;
3967
3968                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
3969                      TEMPLATE_DECL.  */
3970                   if (val != error_mark_node
3971                       && DECL_TEMPLATE_TEMPLATE_PARM_P (val))
3972                     val = TREE_TYPE (val);
3973                 }
3974               else
3975                 {
3976                   if (in_decl && (complain & tf_error))
3977                     {
3978                       error ("type/value mismatch at argument %d in "
3979                              "template parameter list for %qD",
3980                              i + 1, in_decl);
3981                       error ("  expected a template of type %qD, got %qD",
3982                              parm, arg);
3983                     }
3984
3985                   val = error_mark_node;
3986                 }
3987             }
3988         }
3989       else
3990         val = arg;
3991       /* We only form one instance of each template specialization.
3992          Therefore, if we use a non-canonical variant (i.e., a
3993          typedef), any future messages referring to the type will use
3994          the typedef, which is confusing if those future uses do not
3995          themselves also use the typedef.  */
3996       if (TYPE_P (val))
3997         val = canonical_type_variant (val);
3998     }
3999   else
4000     {
4001       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
4002
4003       if (invalid_nontype_parm_type_p (t, complain))
4004         return error_mark_node;
4005
4006       if (!uses_template_parms (arg) && !uses_template_parms (t))
4007         /* We used to call digest_init here.  However, digest_init
4008            will report errors, which we don't want when complain
4009            is zero.  More importantly, digest_init will try too
4010            hard to convert things: for example, `0' should not be
4011            converted to pointer type at this point according to
4012            the standard.  Accepting this is not merely an
4013            extension, since deciding whether or not these
4014            conversions can occur is part of determining which
4015            function template to call, or whether a given explicit
4016            argument specification is valid.  */
4017         val = convert_nontype_argument (t, arg);
4018       else
4019         val = arg;
4020
4021       if (val == NULL_TREE)
4022         val = error_mark_node;
4023       else if (val == error_mark_node && (complain & tf_error))
4024         error ("could not convert template argument %qE to %qT",  arg, t);
4025     }
4026
4027   return val;
4028 }
4029
4030 /* Convert all template arguments to their appropriate types, and
4031    return a vector containing the innermost resulting template
4032    arguments.  If any error occurs, return error_mark_node. Error and
4033    warning messages are issued under control of COMPLAIN.
4034
4035    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
4036    for arguments not specified in ARGS.  Otherwise, if
4037    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
4038    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
4039    USE_DEFAULT_ARGS is false, then all arguments must be specified in
4040    ARGS.  */
4041
4042 static tree
4043 coerce_template_parms (tree parms,
4044                        tree args,
4045                        tree in_decl,
4046                        tsubst_flags_t complain,
4047                        bool require_all_args,
4048                        bool use_default_args)
4049 {
4050   int nparms, nargs, i, lost = 0;
4051   tree inner_args;
4052   tree new_args;
4053   tree new_inner_args;
4054
4055   inner_args = INNERMOST_TEMPLATE_ARGS (args);
4056   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
4057   nparms = TREE_VEC_LENGTH (parms);
4058
4059   if (nargs > nparms
4060       || (nargs < nparms
4061           && require_all_args
4062           && (!use_default_args
4063               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
4064                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
4065     {
4066       if (complain & tf_error)
4067         {
4068           error ("wrong number of template arguments (%d, should be %d)",
4069                  nargs, nparms);
4070
4071           if (in_decl)
4072             error ("provided for %q+D", in_decl);
4073         }
4074
4075       return error_mark_node;
4076     }
4077
4078   new_inner_args = make_tree_vec (nparms);
4079   new_args = add_outermost_template_args (args, new_inner_args);
4080   for (i = 0; i < nparms; i++)
4081     {
4082       tree arg;
4083       tree parm;
4084
4085       /* Get the Ith template parameter.  */
4086       parm = TREE_VEC_ELT (parms, i);
4087  
4088       if (parm == error_mark_node)
4089       {
4090         TREE_VEC_ELT (new_inner_args, i) = error_mark_node;
4091         continue;
4092       }
4093
4094       /* Calculate the Ith argument.  */
4095       if (i < nargs)
4096         arg = TREE_VEC_ELT (inner_args, i);
4097       else if (require_all_args)
4098         /* There must be a default arg in this case.  */
4099         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
4100                                    complain, in_decl);
4101       else
4102         break;
4103
4104       gcc_assert (arg);
4105       if (arg == error_mark_node)
4106         {
4107           if (complain & tf_error)
4108             error ("template argument %d is invalid", i + 1);
4109         }
4110       else
4111         arg = convert_template_argument (TREE_VALUE (parm),
4112                                          arg, new_args, complain, i,
4113                                          in_decl);
4114
4115       if (arg == error_mark_node)
4116         lost++;
4117       TREE_VEC_ELT (new_inner_args, i) = arg;
4118     }
4119
4120   if (lost)
4121     return error_mark_node;
4122
4123   return new_inner_args;
4124 }
4125
4126 /* Returns 1 if template args OT and NT are equivalent.  */
4127
4128 static int
4129 template_args_equal (tree ot, tree nt)
4130 {
4131   if (nt == ot)
4132     return 1;
4133
4134   if (TREE_CODE (nt) == TREE_VEC)
4135     /* For member templates */
4136     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
4137   else if (TYPE_P (nt))
4138     return TYPE_P (ot) && same_type_p (ot, nt);
4139   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
4140     return 0;
4141   else
4142     return cp_tree_equal (ot, nt);
4143 }
4144
4145 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
4146    of template arguments.  Returns 0 otherwise.  */
4147
4148 int
4149 comp_template_args (tree oldargs, tree newargs)
4150 {
4151   int i;
4152
4153   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
4154     return 0;
4155
4156   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
4157     {
4158       tree nt = TREE_VEC_ELT (newargs, i);
4159       tree ot = TREE_VEC_ELT (oldargs, i);
4160
4161       if (! template_args_equal (ot, nt))
4162         return 0;
4163     }
4164   return 1;
4165 }
4166
4167 /* Given class template name and parameter list, produce a user-friendly name
4168    for the instantiation.  */
4169
4170 static char *
4171 mangle_class_name_for_template (const char* name, tree parms, tree arglist)
4172 {
4173   static struct obstack scratch_obstack;
4174   static char *scratch_firstobj;
4175   int i, nparms;
4176
4177   if (!scratch_firstobj)
4178     gcc_obstack_init (&scratch_obstack);
4179   else
4180     obstack_free (&scratch_obstack, scratch_firstobj);
4181   scratch_firstobj = (char *) obstack_alloc (&scratch_obstack, 1);
4182
4183 #define ccat(C) obstack_1grow (&scratch_obstack, (C));
4184 #define cat(S)  obstack_grow (&scratch_obstack, (S), strlen (S))
4185
4186   cat (name);
4187   ccat ('<');
4188   nparms = TREE_VEC_LENGTH (parms);
4189   arglist = INNERMOST_TEMPLATE_ARGS (arglist);
4190   gcc_assert (nparms == TREE_VEC_LENGTH (arglist));
4191   for (i = 0; i < nparms; i++)
4192     {
4193       tree parm;
4194       tree arg;
4195
4196       if (TREE_VEC_ELT (parms, i) == error_mark_node)
4197         continue;
4198
4199       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4200       arg = TREE_VEC_ELT (arglist, i);
4201
4202       if (i)
4203         ccat (',');
4204
4205       if (TREE_CODE (parm) == TYPE_DECL)
4206         {
4207           cat (type_as_string (arg, TFF_CHASE_TYPEDEF));
4208           continue;
4209         }
4210       else if (TREE_CODE (parm) == TEMPLATE_DECL)
4211         {
4212           if (TREE_CODE (arg) == TEMPLATE_DECL)
4213             {
4214               /* Already substituted with real template.  Just output
4215                  the template name here */
4216               tree context = DECL_CONTEXT (arg);
4217               if (context)
4218                 {
4219                   /* The template may be defined in a namespace, or
4220                      may be a member template.  */
4221                   gcc_assert (TREE_CODE (context) == NAMESPACE_DECL
4222                               || CLASS_TYPE_P (context));
4223                   cat (decl_as_string (DECL_CONTEXT (arg),
4224                                       TFF_PLAIN_IDENTIFIER));
4225                   cat ("::");
4226                 }
4227               cat (IDENTIFIER_POINTER (DECL_NAME (arg)));
4228             }
4229           else
4230             /* Output the parameter declaration.  */
4231             cat (type_as_string (arg, TFF_CHASE_TYPEDEF));
4232           continue;
4233         }
4234       else
4235         gcc_assert (TREE_CODE (parm) == PARM_DECL);
4236
4237       /* No need to check arglist against parmlist here; we did that
4238          in coerce_template_parms, called from lookup_template_class.  */
4239       cat (expr_as_string (arg, TFF_PLAIN_IDENTIFIER));
4240     }
4241   {
4242     char *bufp = obstack_next_free (&scratch_obstack);
4243     int offset = 0;
4244     while (bufp[offset - 1] == ' ')
4245       offset--;
4246     obstack_blank_fast (&scratch_obstack, offset);
4247
4248     /* B<C<char> >, not B<C<char>> */
4249     if (bufp[offset - 1] == '>')
4250       ccat (' ');
4251   }
4252   ccat ('>');
4253   ccat ('\0');
4254   return (char *) obstack_base (&scratch_obstack);
4255 }
4256
4257 static tree
4258 classtype_mangled_name (tree t)
4259 {
4260   if (CLASSTYPE_TEMPLATE_INFO (t)
4261       /* Specializations have already had their names set up in
4262          lookup_template_class.  */
4263       && !CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
4264     {
4265       tree tmpl = most_general_template (CLASSTYPE_TI_TEMPLATE (t));
4266
4267       /* For non-primary templates, the template parameters are
4268          implicit from their surrounding context.  */
4269       if (PRIMARY_TEMPLATE_P (tmpl))
4270         {
4271           tree name = DECL_NAME (tmpl);
4272           char *mangled_name = mangle_class_name_for_template
4273             (IDENTIFIER_POINTER (name),
4274              DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
4275              CLASSTYPE_TI_ARGS (t));
4276           tree id = get_identifier (mangled_name);
4277           IDENTIFIER_TEMPLATE (id) = name;
4278           return id;
4279         }
4280     }
4281
4282   return TYPE_IDENTIFIER (t);
4283 }
4284
4285 static void
4286 add_pending_template (tree d)
4287 {
4288   tree ti = (TYPE_P (d)
4289              ? CLASSTYPE_TEMPLATE_INFO (d)
4290              : DECL_TEMPLATE_INFO (d));
4291   tree pt;
4292   int level;
4293
4294   if (TI_PENDING_TEMPLATE_FLAG (ti))
4295     return;
4296
4297   /* We are called both from instantiate_decl, where we've already had a
4298      tinst_level pushed, and instantiate_template, where we haven't.
4299      Compensate.  */
4300   level = !(current_tinst_level && TINST_DECL (current_tinst_level) == d);
4301
4302   if (level)
4303     push_tinst_level (d);
4304
4305   pt = tree_cons (current_tinst_level, d, NULL_TREE);
4306   if (last_pending_template)
4307     TREE_CHAIN (last_pending_template) = pt;
4308   else
4309     pending_templates = pt;
4310
4311   last_pending_template = pt;
4312
4313   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
4314
4315   if (level)
4316     pop_tinst_level ();
4317 }
4318
4319
4320 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
4321    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
4322    documentation for TEMPLATE_ID_EXPR.  */
4323
4324 tree
4325 lookup_template_function (tree fns, tree arglist)
4326 {
4327   tree type;
4328
4329   if (fns == error_mark_node || arglist == error_mark_node)
4330     return error_mark_node;
4331
4332   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
4333   gcc_assert (fns && (is_overloaded_fn (fns)
4334                       || TREE_CODE (fns) == IDENTIFIER_NODE));
4335
4336   if (BASELINK_P (fns))
4337     {
4338       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
4339                                          unknown_type_node,
4340                                          BASELINK_FUNCTIONS (fns),
4341                                          arglist);
4342       return fns;
4343     }
4344
4345   type = TREE_TYPE (fns);
4346   if (TREE_CODE (fns) == OVERLOAD || !type)
4347     type = unknown_type_node;
4348
4349   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
4350 }
4351
4352 /* Within the scope of a template class S<T>, the name S gets bound
4353    (in build_self_reference) to a TYPE_DECL for the class, not a
4354    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
4355    or one of its enclosing classes, and that type is a template,
4356    return the associated TEMPLATE_DECL.  Otherwise, the original
4357    DECL is returned.  */
4358
4359 tree
4360 maybe_get_template_decl_from_type_decl (tree decl)
4361 {
4362   return (decl != NULL_TREE
4363           && TREE_CODE (decl) == TYPE_DECL
4364           && DECL_ARTIFICIAL (decl)
4365           && CLASS_TYPE_P (TREE_TYPE (decl))
4366           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
4367     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
4368 }
4369
4370 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
4371    parameters, find the desired type.
4372
4373    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
4374
4375    IN_DECL, if non-NULL, is the template declaration we are trying to
4376    instantiate.
4377
4378    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
4379    the class we are looking up.
4380
4381    Issue error and warning messages under control of COMPLAIN.
4382
4383    If the template class is really a local class in a template
4384    function, then the FUNCTION_CONTEXT is the function in which it is
4385    being instantiated.
4386
4387    ??? Note that this function is currently called *twice* for each
4388    template-id: the first time from the parser, while creating the
4389    incomplete type (finish_template_type), and the second type during the
4390    real instantiation (instantiate_template_class). This is surely something
4391    that we want to avoid. It also causes some problems with argument
4392    coercion (see convert_nontype_argument for more information on this).  */
4393
4394 tree
4395 lookup_template_class (tree d1,
4396                        tree arglist,
4397                        tree in_decl,
4398                        tree context,
4399                        int entering_scope,
4400                        tsubst_flags_t complain)
4401 {
4402   tree template = NULL_TREE, parmlist;
4403   tree t;
4404
4405   timevar_push (TV_NAME_LOOKUP);
4406
4407   if (TREE_CODE (d1) == IDENTIFIER_NODE)
4408     {
4409       tree value = innermost_non_namespace_value (d1);
4410       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
4411         template = value;
4412       else
4413         {
4414           if (context)
4415             push_decl_namespace (context);
4416           template = lookup_name (d1);
4417           template = maybe_get_template_decl_from_type_decl (template);
4418           if (context)
4419             pop_decl_namespace ();
4420         }
4421       if (template)
4422         context = DECL_CONTEXT (template);
4423     }
4424   else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
4425     {
4426       tree type = TREE_TYPE (d1);
4427
4428       /* If we are declaring a constructor, say A<T>::A<T>, we will get
4429          an implicit typename for the second A.  Deal with it.  */
4430       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
4431         type = TREE_TYPE (type);
4432
4433       if (CLASSTYPE_TEMPLATE_INFO (type))
4434         {
4435           template = CLASSTYPE_TI_TEMPLATE (type);
4436           d1 = DECL_NAME (template);
4437         }
4438     }
4439   else if (TREE_CODE (d1) == ENUMERAL_TYPE
4440            || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
4441     {
4442       template = TYPE_TI_TEMPLATE (d1);
4443       d1 = DECL_NAME (template);
4444     }
4445   else if (TREE_CODE (d1) == TEMPLATE_DECL
4446            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
4447     {
4448       template = d1;
4449       d1 = DECL_NAME (template);
4450       context = DECL_CONTEXT (template);
4451     }
4452
4453   /* Issue an error message if we didn't find a template.  */
4454   if (! template)
4455     {
4456       if (complain & tf_error)
4457         error ("%qT is not a template", d1);
4458       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4459     }
4460
4461   if (TREE_CODE (template) != TEMPLATE_DECL
4462          /* Make sure it's a user visible template, if it was named by
4463             the user.  */
4464       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (template)
4465           && !PRIMARY_TEMPLATE_P (template)))
4466     {
4467       if (complain & tf_error)
4468         {
4469           error ("non-template type %qT used as a template", d1);
4470           if (in_decl)
4471             error ("for template declaration %q+D", in_decl);
4472         }
4473       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4474     }
4475
4476   complain &= ~tf_user;
4477
4478   if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
4479     {
4480       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
4481          template arguments */
4482
4483       tree parm;
4484       tree arglist2;
4485
4486       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
4487
4488       /* Consider an example where a template template parameter declared as
4489
4490            template <class T, class U = std::allocator<T> > class TT
4491
4492          The template parameter level of T and U are one level larger than
4493          of TT.  To proper process the default argument of U, say when an
4494          instantiation `TT<int>' is seen, we need to build the full
4495          arguments containing {int} as the innermost level.  Outer levels,
4496          available when not appearing as default template argument, can be
4497          obtained from `current_template_args ()'.
4498
4499          Suppose that TT is later substituted with std::vector.  The above
4500          instantiation is `TT<int, std::allocator<T> >' with TT at
4501          level 1, and T at level 2, while the template arguments at level 1
4502          becomes {std::vector} and the inner level 2 is {int}.  */
4503
4504       if (current_template_parms)
4505         arglist = add_to_template_args (current_template_args (), arglist);
4506
4507       arglist2 = coerce_template_parms (parmlist, arglist, template,
4508                                         complain,
4509                                         /*require_all_args=*/true,
4510                                         /*use_default_args=*/true);
4511       if (arglist2 == error_mark_node
4512           || (!uses_template_parms (arglist2)
4513               && check_instantiated_args (template, arglist2, complain)))
4514         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4515
4516       parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
4517       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
4518     }
4519   else
4520     {
4521       tree template_type = TREE_TYPE (template);
4522       tree gen_tmpl;
4523       tree type_decl;
4524       tree found = NULL_TREE;
4525       int arg_depth;
4526       int parm_depth;
4527       int is_partial_instantiation;
4528
4529       gen_tmpl = most_general_template (template);
4530       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
4531       parm_depth = TMPL_PARMS_DEPTH (parmlist);
4532       arg_depth = TMPL_ARGS_DEPTH (arglist);
4533
4534       if (arg_depth == 1 && parm_depth > 1)
4535         {
4536           /* We've been given an incomplete set of template arguments.
4537              For example, given:
4538
4539                template <class T> struct S1 {
4540                  template <class U> struct S2 {};
4541                  template <class U> struct S2<U*> {};
4542                 };
4543
4544              we will be called with an ARGLIST of `U*', but the
4545              TEMPLATE will be `template <class T> template
4546              <class U> struct S1<T>::S2'.  We must fill in the missing
4547              arguments.  */
4548           arglist
4549             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
4550                                            arglist);
4551           arg_depth = TMPL_ARGS_DEPTH (arglist);
4552         }
4553
4554       /* Now we should have enough arguments.  */
4555       gcc_assert (parm_depth == arg_depth);
4556
4557       /* From here on, we're only interested in the most general
4558          template.  */
4559       template = gen_tmpl;
4560
4561       /* Calculate the BOUND_ARGS.  These will be the args that are
4562          actually tsubst'd into the definition to create the
4563          instantiation.  */
4564       if (parm_depth > 1)
4565         {
4566           /* We have multiple levels of arguments to coerce, at once.  */
4567           int i;
4568           int saved_depth = TMPL_ARGS_DEPTH (arglist);
4569
4570           tree bound_args = make_tree_vec (parm_depth);
4571
4572           for (i = saved_depth,
4573                  t = DECL_TEMPLATE_PARMS (template);
4574                i > 0 && t != NULL_TREE;
4575                --i, t = TREE_CHAIN (t))
4576             {
4577               tree a = coerce_template_parms (TREE_VALUE (t),
4578                                               arglist, template,
4579                                               complain,
4580                                               /*require_all_args=*/true,
4581                                               /*use_default_args=*/true);
4582
4583               /* Don't process further if one of the levels fails.  */
4584               if (a == error_mark_node)
4585                 {
4586                   /* Restore the ARGLIST to its full size.  */
4587                   TREE_VEC_LENGTH (arglist) = saved_depth;
4588                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4589                 }
4590
4591               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
4592
4593               /* We temporarily reduce the length of the ARGLIST so
4594                  that coerce_template_parms will see only the arguments
4595                  corresponding to the template parameters it is
4596                  examining.  */
4597               TREE_VEC_LENGTH (arglist)--;
4598             }
4599
4600           /* Restore the ARGLIST to its full size.  */
4601           TREE_VEC_LENGTH (arglist) = saved_depth;
4602
4603           arglist = bound_args;
4604         }
4605       else
4606         arglist
4607           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
4608                                    INNERMOST_TEMPLATE_ARGS (arglist),
4609                                    template,
4610                                    complain,
4611                                    /*require_all_args=*/true,
4612                                    /*use_default_args=*/true);
4613
4614       if (arglist == error_mark_node)
4615         /* We were unable to bind the arguments.  */
4616         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4617
4618       /* In the scope of a template class, explicit references to the
4619          template class refer to the type of the template, not any
4620          instantiation of it.  For example, in:
4621
4622            template <class T> class C { void f(C<T>); }
4623
4624          the `C<T>' is just the same as `C'.  Outside of the
4625          class, however, such a reference is an instantiation.  */
4626       if (comp_template_args (TYPE_TI_ARGS (template_type),
4627                               arglist))
4628         {
4629           found = template_type;
4630
4631           if (!entering_scope && PRIMARY_TEMPLATE_P (template))
4632             {
4633               tree ctx;
4634
4635               for (ctx = current_class_type;
4636                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
4637                    ctx = (TYPE_P (ctx)
4638                           ? TYPE_CONTEXT (ctx)
4639                           : DECL_CONTEXT (ctx)))
4640                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
4641                   goto found_ctx;
4642
4643               /* We're not in the scope of the class, so the
4644                  TEMPLATE_TYPE is not the type we want after all.  */
4645               found = NULL_TREE;
4646             found_ctx:;
4647             }
4648         }
4649       if (found)
4650         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
4651
4652       /* If we already have this specialization, return it.  */
4653       found = retrieve_specialization (template, arglist,
4654                                        /*class_specializations_p=*/false);
4655       if (found)
4656         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
4657
4658       /* This type is a "partial instantiation" if any of the template
4659          arguments still involve template parameters.  Note that we set
4660          IS_PARTIAL_INSTANTIATION for partial specializations as
4661          well.  */
4662       is_partial_instantiation = uses_template_parms (arglist);
4663
4664       /* If the deduced arguments are invalid, then the binding
4665          failed.  */
4666       if (!is_partial_instantiation
4667           && check_instantiated_args (template,
4668                                       INNERMOST_TEMPLATE_ARGS (arglist),
4669                                       complain))
4670         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
4671
4672       if (!is_partial_instantiation
4673           && !PRIMARY_TEMPLATE_P (template)
4674           && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
4675         {
4676           found = xref_tag_from_type (TREE_TYPE (template),
4677                                       DECL_NAME (template),
4678                                       /*tag_scope=*/ts_global);
4679           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
4680         }
4681
4682       context = tsubst (DECL_CONTEXT (template), arglist,
4683                         complain, in_decl);
4684       if (!context)
4685         context = global_namespace;
4686
4687       /* Create the type.  */
4688       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
4689         {
4690           if (!is_partial_instantiation)
4691             {
4692               set_current_access_from_decl (TYPE_NAME (template_type));
4693               t = start_enum (TYPE_IDENTIFIER (template_type));
4694             }
4695           else
4696             /* We don't want to call start_enum for this type, since
4697                the values for the enumeration constants may involve
4698                template parameters.  And, no one should be interested
4699                in the enumeration constants for such a type.  */
4700             t = make_node (ENUMERAL_TYPE);
4701         }
4702       else
4703         {
4704           t = make_aggr_type (TREE_CODE (template_type));
4705           CLASSTYPE_DECLARED_CLASS (t)
4706             = CLASSTYPE_DECLARED_CLASS (template_type);
4707           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
4708           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
4709
4710           /* A local class.  Make sure the decl gets registered properly.  */
4711           if (context == current_function_decl)
4712             pushtag (DECL_NAME (template), t, /*tag_scope=*/ts_current);
4713         }
4714
4715       /* If we called start_enum or pushtag above, this information
4716          will already be set up.  */
4717       if (!TYPE_NAME (t))
4718         {
4719           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4720
4721           type_decl = create_implicit_typedef (DECL_NAME (template), t);
4722           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
4723           TYPE_STUB_DECL (t) = type_decl;
4724           DECL_SOURCE_LOCATION (type_decl)
4725             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
4726         }
4727       else
4728         type_decl = TYPE_NAME (t);
4729
4730       TREE_PRIVATE (type_decl)
4731         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
4732       TREE_PROTECTED (type_decl)
4733         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
4734       DECL_IN_SYSTEM_HEADER (type_decl)
4735         = DECL_IN_SYSTEM_HEADER (template);
4736       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
4737         {
4738           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
4739           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
4740         }
4741
4742       /* Set up the template information.  We have to figure out which
4743          template is the immediate parent if this is a full
4744          instantiation.  */
4745       if (parm_depth == 1 || is_partial_instantiation
4746           || !PRIMARY_TEMPLATE_P (template))
4747         /* This case is easy; there are no member templates involved.  */
4748         found = template;
4749       else
4750         {
4751           /* This is a full instantiation of a member template.  Look
4752              for a partial instantiation of which this is an instance.  */
4753
4754           for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
4755                found; found = TREE_CHAIN (found))
4756             {
4757               int success;
4758               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
4759
4760               /* We only want partial instantiations, here, not
4761                  specializations or full instantiations.  */
4762               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
4763                   || !uses_template_parms (TREE_VALUE (found)))
4764                 continue;
4765
4766               /* Temporarily reduce by one the number of levels in the
4767                  ARGLIST and in FOUND so as to avoid comparing the
4768                  last set of arguments.  */
4769               TREE_VEC_LENGTH (arglist)--;
4770               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
4771
4772               /* See if the arguments match.  If they do, then TMPL is
4773                  the partial instantiation we want.  */
4774               success = comp_template_args (TREE_PURPOSE (found), arglist);
4775
4776               /* Restore the argument vectors to their full size.  */
4777               TREE_VEC_LENGTH (arglist)++;
4778               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
4779
4780               if (success)
4781                 {
4782                   found = tmpl;
4783                   break;
4784                 }
4785             }
4786
4787           if (!found)
4788             {
4789               /* There was no partial instantiation. This happens
4790                  where C<T> is a member template of A<T> and it's used
4791                  in something like
4792
4793                   template <typename T> struct B { A<T>::C<int> m; };
4794                   B<float>;
4795
4796                  Create the partial instantiation.
4797                */
4798               TREE_VEC_LENGTH (arglist)--;
4799               found = tsubst (template, arglist, complain, NULL_TREE);
4800               TREE_VEC_LENGTH (arglist)++;
4801             }
4802         }
4803
4804       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
4805       DECL_TEMPLATE_INSTANTIATIONS (template)
4806         = tree_cons (arglist, t,
4807                      DECL_TEMPLATE_INSTANTIATIONS (template));
4808
4809       if (TREE_CODE (t) == ENUMERAL_TYPE
4810           && !is_partial_instantiation)
4811         /* Now that the type has been registered on the instantiations
4812            list, we set up the enumerators.  Because the enumeration
4813            constants may involve the enumeration type itself, we make
4814            sure to register the type first, and then create the
4815            constants.  That way, doing tsubst_expr for the enumeration
4816            constants won't result in recursive calls here; we'll find
4817            the instantiation and exit above.  */
4818         tsubst_enum (template_type, t, arglist);
4819
4820       /* Reset the name of the type, now that CLASSTYPE_TEMPLATE_INFO
4821          is set up.  */
4822       if (TREE_CODE (t) != ENUMERAL_TYPE)
4823         DECL_NAME (type_decl) = classtype_mangled_name (t);
4824       if (is_partial_instantiation)
4825         /* If the type makes use of template parameters, the
4826            code that generates debugging information will crash.  */
4827         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
4828
4829       /* Possibly limit visibility based on template args.  */
4830       TREE_PUBLIC (type_decl) = 1;
4831       determine_visibility (type_decl);
4832
4833       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
4834     }
4835   timevar_pop (TV_NAME_LOOKUP);
4836 }
4837 \f
4838 struct pair_fn_data
4839 {
4840   tree_fn_t fn;
4841   void *data;
4842   struct pointer_set_t *visited;
4843 };
4844
4845 /* Called from for_each_template_parm via walk_tree.  */
4846
4847 static tree
4848 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
4849 {
4850   tree t = *tp;
4851   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
4852   tree_fn_t fn = pfd->fn;
4853   void *data = pfd->data;
4854
4855   if (TYPE_P (t)
4856       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited))
4857     return error_mark_node;
4858
4859   switch (TREE_CODE (t))
4860     {
4861     case RECORD_TYPE:
4862       if (TYPE_PTRMEMFUNC_P (t))
4863         break;
4864       /* Fall through.  */
4865
4866     case UNION_TYPE:
4867     case ENUMERAL_TYPE:
4868       if (!TYPE_TEMPLATE_INFO (t))
4869         *walk_subtrees = 0;
4870       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
4871                                        fn, data, pfd->visited))
4872         return error_mark_node;
4873       break;
4874
4875     case METHOD_TYPE:
4876       /* Since we're not going to walk subtrees, we have to do this
4877          explicitly here.  */
4878       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
4879                                   pfd->visited))
4880         return error_mark_node;
4881       /* Fall through.  */
4882
4883     case FUNCTION_TYPE:
4884       /* Check the return type.  */
4885       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
4886         return error_mark_node;
4887
4888       /* Check the parameter types.  Since default arguments are not
4889          instantiated until they are needed, the TYPE_ARG_TYPES may
4890          contain expressions that involve template parameters.  But,
4891          no-one should be looking at them yet.  And, once they're
4892          instantiated, they don't contain template parameters, so
4893          there's no point in looking at them then, either.  */
4894       {
4895         tree parm;
4896
4897         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
4898           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
4899                                       pfd->visited))
4900             return error_mark_node;
4901
4902         /* Since we've already handled the TYPE_ARG_TYPES, we don't
4903            want walk_tree walking into them itself.  */
4904         *walk_subtrees = 0;
4905       }
4906       break;
4907
4908     case TYPEOF_TYPE:
4909       if (for_each_template_parm (TYPE_FIELDS (t), fn, data,
4910                                   pfd->visited))
4911         return error_mark_node;
4912       break;
4913
4914     case FUNCTION_DECL:
4915     case VAR_DECL:
4916       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
4917           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
4918                                      pfd->visited))
4919         return error_mark_node;
4920       /* Fall through.  */
4921
4922     case PARM_DECL:
4923     case CONST_DECL:
4924       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
4925           && for_each_template_parm (DECL_INITIAL (t), fn, data,
4926                                      pfd->visited))
4927         return error_mark_node;
4928       if (DECL_CONTEXT (t)
4929           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
4930                                      pfd->visited))
4931         return error_mark_node;
4932       break;
4933
4934     case BOUND_TEMPLATE_TEMPLATE_PARM:
4935       /* Record template parameters such as `T' inside `TT<T>'.  */
4936       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited))
4937         return error_mark_node;
4938       /* Fall through.  */
4939
4940     case TEMPLATE_TEMPLATE_PARM:
4941     case TEMPLATE_TYPE_PARM:
4942     case TEMPLATE_PARM_INDEX:
4943       if (fn && (*fn)(t, data))
4944         return error_mark_node;
4945       else if (!fn)
4946         return error_mark_node;
4947       break;
4948
4949     case TEMPLATE_DECL:
4950       /* A template template parameter is encountered.  */
4951       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
4952           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited))
4953         return error_mark_node;
4954
4955       /* Already substituted template template parameter */
4956       *walk_subtrees = 0;
4957       break;
4958
4959     case TYPENAME_TYPE:
4960       if (!fn
4961           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
4962                                      data, pfd->visited))
4963         return error_mark_node;
4964       break;
4965
4966     case CONSTRUCTOR:
4967       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
4968           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
4969                                      (TREE_TYPE (t)), fn, data,
4970                                      pfd->visited))
4971         return error_mark_node;
4972       break;
4973
4974     case INDIRECT_REF:
4975     case COMPONENT_REF:
4976       /* If there's no type, then this thing must be some expression
4977          involving template parameters.  */
4978       if (!fn && !TREE_TYPE (t))
4979         return error_mark_node;
4980       break;
4981
4982     case MODOP_EXPR:
4983     case CAST_EXPR:
4984     case REINTERPRET_CAST_EXPR:
4985     case CONST_CAST_EXPR:
4986     case STATIC_CAST_EXPR:
4987     case DYNAMIC_CAST_EXPR:
4988     case ARROW_EXPR:
4989     case DOTSTAR_EXPR:
4990     case TYPEID_EXPR:
4991     case PSEUDO_DTOR_EXPR:
4992       if (!fn)
4993         return error_mark_node;
4994       break;
4995
4996     case BASELINK:
4997       /* If we do not handle this case specially, we end up walking
4998          the BINFO hierarchy, which is circular, and therefore
4999          confuses walk_tree.  */
5000       *walk_subtrees = 0;
5001       if (for_each_template_parm (BASELINK_FUNCTIONS (*tp), fn, data,
5002                                   pfd->visited))
5003         return error_mark_node;
5004       break;
5005
5006     default:
5007       break;
5008     }
5009
5010   /* We didn't find any template parameters we liked.  */
5011   return NULL_TREE;
5012 }
5013
5014 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
5015    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
5016    call FN with the parameter and the DATA.
5017    If FN returns nonzero, the iteration is terminated, and
5018    for_each_template_parm returns 1.  Otherwise, the iteration
5019    continues.  If FN never returns a nonzero value, the value
5020    returned by for_each_template_parm is 0.  If FN is NULL, it is
5021    considered to be the function which always returns 1.  */
5022
5023 static int
5024 for_each_template_parm (tree t, tree_fn_t fn, void* data,
5025                         struct pointer_set_t *visited)
5026 {
5027   struct pair_fn_data pfd;
5028   int result;
5029
5030   /* Set up.  */
5031   pfd.fn = fn;
5032   pfd.data = data;
5033
5034   /* Walk the tree.  (Conceptually, we would like to walk without
5035      duplicates, but for_each_template_parm_r recursively calls
5036      for_each_template_parm, so we would need to reorganize a fair
5037      bit to use walk_tree_without_duplicates, so we keep our own
5038      visited list.)  */
5039   if (visited)
5040     pfd.visited = visited;
5041   else
5042     pfd.visited = pointer_set_create ();
5043   result = walk_tree (&t,
5044                       for_each_template_parm_r,
5045                       &pfd,
5046                       pfd.visited) != NULL_TREE;
5047
5048   /* Clean up.  */
5049   if (!visited)
5050     {
5051       pointer_set_destroy (pfd.visited);
5052       pfd.visited = 0;
5053     }
5054
5055   return result;
5056 }
5057
5058 /* Returns true if T depends on any template parameter.  */
5059
5060 int
5061 uses_template_parms (tree t)
5062 {
5063   bool dependent_p;
5064   int saved_processing_template_decl;
5065
5066   saved_processing_template_decl = processing_template_decl;
5067   if (!saved_processing_template_decl)
5068     processing_template_decl = 1;
5069   if (TYPE_P (t))
5070     dependent_p = dependent_type_p (t);
5071   else if (TREE_CODE (t) == TREE_VEC)
5072     dependent_p = any_dependent_template_arguments_p (t);
5073   else if (TREE_CODE (t) == TREE_LIST)
5074     dependent_p = (uses_template_parms (TREE_VALUE (t))
5075                    || uses_template_parms (TREE_CHAIN (t)));
5076   else if (TREE_CODE (t) == TYPE_DECL)
5077     dependent_p = dependent_type_p (TREE_TYPE (t));
5078   else if (DECL_P (t)
5079            || EXPR_P (t)
5080            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
5081            || TREE_CODE (t) == OVERLOAD
5082            || TREE_CODE (t) == BASELINK
5083            || TREE_CODE (t) == IDENTIFIER_NODE
5084            || CONSTANT_CLASS_P (t))
5085     dependent_p = (type_dependent_expression_p (t)
5086                    || value_dependent_expression_p (t));
5087   else
5088     {
5089       gcc_assert (t == error_mark_node);
5090       dependent_p = false;
5091     }
5092
5093   processing_template_decl = saved_processing_template_decl;
5094
5095   return dependent_p;
5096 }
5097
5098 /* Returns true if T depends on any template parameter with level LEVEL.  */
5099
5100 int
5101 uses_template_parms_level (tree t, int level)
5102 {
5103   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL);
5104 }
5105
5106 static int tinst_depth;
5107 extern int max_tinst_depth;
5108 #ifdef GATHER_STATISTICS
5109 int depth_reached;
5110 #endif
5111 static int tinst_level_tick;
5112 static int last_template_error_tick;
5113
5114 /* We're starting to instantiate D; record the template instantiation context
5115    for diagnostics and to restore it later.  */
5116
5117 static int
5118 push_tinst_level (tree d)
5119 {
5120   tree new;
5121
5122   if (tinst_depth >= max_tinst_depth)
5123     {
5124       /* If the instantiation in question still has unbound template parms,
5125          we don't really care if we can't instantiate it, so just return.
5126          This happens with base instantiation for implicit `typename'.  */
5127       if (uses_template_parms (d))
5128         return 0;
5129
5130       last_template_error_tick = tinst_level_tick;
5131       error ("template instantiation depth exceeds maximum of %d (use "
5132              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
5133              max_tinst_depth, d);
5134
5135       print_instantiation_context ();
5136
5137       return 0;
5138     }
5139
5140   new = make_node (TINST_LEVEL);
5141   TINST_DECL (new) = d;
5142   TINST_LOCATION (new) = input_location;
5143   TINST_IN_SYSTEM_HEADER_P (new) = in_system_header;
5144   TREE_CHAIN (new) = current_tinst_level;
5145   current_tinst_level = new;
5146
5147   ++tinst_depth;
5148 #ifdef GATHER_STATISTICS
5149   if (tinst_depth > depth_reached)
5150     depth_reached = tinst_depth;
5151 #endif
5152
5153   ++tinst_level_tick;
5154   return 1;
5155 }
5156
5157 /* We're done instantiating this template; return to the instantiation
5158    context.  */
5159
5160 static void
5161 pop_tinst_level (void)
5162 {
5163   tree old = current_tinst_level;
5164
5165   /* Restore the filename and line number stashed away when we started
5166      this instantiation.  */
5167   input_location = TINST_LOCATION (old);
5168   in_system_header = TINST_IN_SYSTEM_HEADER_P (old);
5169   current_tinst_level = TREE_CHAIN (old);
5170   --tinst_depth;
5171   ++tinst_level_tick;
5172 }
5173
5174 /* We're instantiating a deferred template; restore the template
5175    instantiation context in which the instantiation was requested, which
5176    is one step out from LEVEL.  */
5177
5178 static void
5179 reopen_tinst_level (tree level)
5180 {
5181   tree t;
5182
5183   tinst_depth = 0;
5184   for (t = level; t; t = TREE_CHAIN (t))
5185     ++tinst_depth;
5186
5187   current_tinst_level = level;
5188   pop_tinst_level ();
5189 }
5190
5191 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
5192    vector of template arguments, as for tsubst.
5193
5194    Returns an appropriate tsubst'd friend declaration.  */
5195
5196 static tree
5197 tsubst_friend_function (tree decl, tree args)
5198 {
5199   tree new_friend;
5200
5201   if (TREE_CODE (decl) == FUNCTION_DECL
5202       && DECL_TEMPLATE_INSTANTIATION (decl)
5203       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
5204     /* This was a friend declared with an explicit template
5205        argument list, e.g.:
5206
5207        friend void f<>(T);
5208
5209        to indicate that f was a template instantiation, not a new
5210        function declaration.  Now, we have to figure out what
5211        instantiation of what template.  */
5212     {
5213       tree template_id, arglist, fns;
5214       tree new_args;
5215       tree tmpl;
5216       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
5217
5218       /* Friend functions are looked up in the containing namespace scope.
5219          We must enter that scope, to avoid finding member functions of the
5220          current cless with same name.  */
5221       push_nested_namespace (ns);
5222       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
5223                          tf_warning_or_error, NULL_TREE);
5224       pop_nested_namespace (ns);
5225       arglist = tsubst (DECL_TI_ARGS (decl), args,
5226                         tf_warning_or_error, NULL_TREE);
5227       template_id = lookup_template_function (fns, arglist);
5228
5229       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
5230       tmpl = determine_specialization (template_id, new_friend,
5231                                        &new_args,
5232                                        /*need_member_template=*/0,
5233                                        TREE_VEC_LENGTH (args),
5234                                        tsk_none);
5235       return instantiate_template (tmpl, new_args, tf_error);
5236     }
5237
5238   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
5239
5240   /* The NEW_FRIEND will look like an instantiation, to the
5241      compiler, but is not an instantiation from the point of view of
5242      the language.  For example, we might have had:
5243
5244      template <class T> struct S {
5245        template <class U> friend void f(T, U);
5246      };
5247
5248      Then, in S<int>, template <class U> void f(int, U) is not an
5249      instantiation of anything.  */
5250   if (new_friend == error_mark_node)
5251     return error_mark_node;
5252
5253   DECL_USE_TEMPLATE (new_friend) = 0;
5254   if (TREE_CODE (decl) == TEMPLATE_DECL)
5255     {
5256       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
5257       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
5258         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
5259     }
5260
5261   /* The mangled name for the NEW_FRIEND is incorrect.  The function
5262      is not a template instantiation and should not be mangled like
5263      one.  Therefore, we forget the mangling here; we'll recompute it
5264      later if we need it.  */
5265   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
5266     {
5267       SET_DECL_RTL (new_friend, NULL_RTX);
5268       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
5269     }
5270
5271   if (DECL_NAMESPACE_SCOPE_P (new_friend))
5272     {
5273       tree old_decl;
5274       tree new_friend_template_info;
5275       tree new_friend_result_template_info;
5276       tree ns;
5277       int  new_friend_is_defn;
5278
5279       /* We must save some information from NEW_FRIEND before calling
5280          duplicate decls since that function will free NEW_FRIEND if
5281          possible.  */
5282       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
5283       new_friend_is_defn =
5284             (DECL_INITIAL (DECL_TEMPLATE_RESULT
5285                            (template_for_substitution (new_friend)))
5286              != NULL_TREE);
5287       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
5288         {
5289           /* This declaration is a `primary' template.  */
5290           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
5291
5292           new_friend_result_template_info
5293             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
5294         }
5295       else
5296         new_friend_result_template_info = NULL_TREE;
5297
5298       /* Inside pushdecl_namespace_level, we will push into the
5299          current namespace. However, the friend function should go
5300          into the namespace of the template.  */
5301       ns = decl_namespace_context (new_friend);
5302       push_nested_namespace (ns);
5303       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
5304       pop_nested_namespace (ns);
5305
5306       if (old_decl == error_mark_node)
5307         return error_mark_node;
5308
5309       if (old_decl != new_friend)
5310         {
5311           /* This new friend declaration matched an existing
5312              declaration.  For example, given:
5313
5314                template <class T> void f(T);
5315                template <class U> class C {
5316                  template <class T> friend void f(T) {}
5317                };
5318
5319              the friend declaration actually provides the definition
5320              of `f', once C has been instantiated for some type.  So,
5321              old_decl will be the out-of-class template declaration,
5322              while new_friend is the in-class definition.
5323
5324              But, if `f' was called before this point, the
5325              instantiation of `f' will have DECL_TI_ARGS corresponding
5326              to `T' but not to `U', references to which might appear
5327              in the definition of `f'.  Previously, the most general
5328              template for an instantiation of `f' was the out-of-class
5329              version; now it is the in-class version.  Therefore, we
5330              run through all specialization of `f', adding to their
5331              DECL_TI_ARGS appropriately.  In particular, they need a
5332              new set of outer arguments, corresponding to the
5333              arguments for this class instantiation.
5334
5335              The same situation can arise with something like this:
5336
5337                friend void f(int);
5338                template <class T> class C {
5339                  friend void f(T) {}
5340                };
5341
5342              when `C<int>' is instantiated.  Now, `f(int)' is defined
5343              in the class.  */
5344
5345           if (!new_friend_is_defn)
5346             /* On the other hand, if the in-class declaration does
5347                *not* provide a definition, then we don't want to alter
5348                existing definitions.  We can just leave everything
5349                alone.  */
5350             ;
5351           else
5352             {
5353               /* Overwrite whatever template info was there before, if
5354                  any, with the new template information pertaining to
5355                  the declaration.  */
5356               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
5357
5358               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
5359                 reregister_specialization (new_friend,
5360                                            most_general_template (old_decl),
5361                                            old_decl);
5362               else
5363                 {
5364                   tree t;
5365                   tree new_friend_args;
5366
5367                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
5368                     = new_friend_result_template_info;
5369
5370                   new_friend_args = TI_ARGS (new_friend_template_info);
5371                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
5372                        t != NULL_TREE;
5373                        t = TREE_CHAIN (t))
5374                     {
5375                       tree spec = TREE_VALUE (t);
5376
5377                       DECL_TI_ARGS (spec)
5378                         = add_outermost_template_args (new_friend_args,
5379                                                        DECL_TI_ARGS (spec));
5380                     }
5381
5382                   /* Now, since specializations are always supposed to
5383                      hang off of the most general template, we must move
5384                      them.  */
5385                   t = most_general_template (old_decl);
5386                   if (t != old_decl)
5387                     {
5388                       DECL_TEMPLATE_SPECIALIZATIONS (t)
5389                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
5390                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
5391                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
5392                     }
5393                 }
5394             }
5395
5396           /* The information from NEW_FRIEND has been merged into OLD_DECL
5397              by duplicate_decls.  */
5398           new_friend = old_decl;
5399         }
5400     }
5401   else
5402     {
5403       tree context = DECL_CONTEXT (new_friend);
5404       bool dependent_p;
5405
5406       /* In the code
5407            template <class T> class C {
5408              template <class U> friend void C1<U>::f (); // case 1
5409              friend void C2<T>::f ();                    // case 2
5410            };
5411          we only need to make sure CONTEXT is a complete type for
5412          case 2.  To distinguish between the two cases, we note that
5413          CONTEXT of case 1 remains dependent type after tsubst while
5414          this isn't true for case 2.  */
5415       ++processing_template_decl;
5416       dependent_p = dependent_type_p (context);
5417       --processing_template_decl;
5418
5419       if (!dependent_p
5420           && !complete_type_or_else (context, NULL_TREE))
5421         return error_mark_node;
5422
5423       if (COMPLETE_TYPE_P (context))
5424         {
5425           /* Check to see that the declaration is really present, and,
5426              possibly obtain an improved declaration.  */
5427           tree fn = check_classfn (context,
5428                                    new_friend, NULL_TREE);
5429
5430           if (fn)
5431             new_friend = fn;
5432         }
5433     }
5434
5435   return new_friend;
5436 }
5437
5438 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
5439    template arguments, as for tsubst.
5440
5441    Returns an appropriate tsubst'd friend type or error_mark_node on
5442    failure.  */
5443
5444 static tree
5445 tsubst_friend_class (tree friend_tmpl, tree args)
5446 {
5447   tree friend_type;
5448   tree tmpl;
5449   tree context;
5450
5451   context = DECL_CONTEXT (friend_tmpl);
5452
5453   if (context)
5454     {
5455       if (TREE_CODE (context) == NAMESPACE_DECL)
5456         push_nested_namespace (context);
5457       else
5458         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
5459     }
5460
5461   /* Look for a class template declaration.  We look for hidden names
5462      because two friend declarations of the same template are the
5463      same.  For example, in:
5464
5465        struct A { 
5466          template <typename> friend class F;
5467        };
5468        template <typename> struct B { 
5469          template <typename> friend class F;
5470        };
5471
5472      both F templates are the same.  */
5473   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
5474                            /*block_p=*/true, 0, 
5475                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
5476
5477   /* But, if we don't find one, it might be because we're in a
5478      situation like this:
5479
5480        template <class T>
5481        struct S {
5482          template <class U>
5483          friend struct S;
5484        };
5485
5486      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
5487      for `S<int>', not the TEMPLATE_DECL.  */
5488   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
5489     {
5490       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
5491       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
5492     }
5493
5494   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
5495     {
5496       /* The friend template has already been declared.  Just
5497          check to see that the declarations match, and install any new
5498          default parameters.  We must tsubst the default parameters,
5499          of course.  We only need the innermost template parameters
5500          because that is all that redeclare_class_template will look
5501          at.  */
5502       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
5503           > TMPL_ARGS_DEPTH (args))
5504         {
5505           tree parms;
5506           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
5507                                          args, tf_warning_or_error);
5508           redeclare_class_template (TREE_TYPE (tmpl), parms);
5509         }
5510
5511       friend_type = TREE_TYPE (tmpl);
5512     }
5513   else
5514     {
5515       /* The friend template has not already been declared.  In this
5516          case, the instantiation of the template class will cause the
5517          injection of this template into the global scope.  */
5518       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
5519       if (tmpl == error_mark_node)
5520         return error_mark_node;
5521
5522       /* The new TMPL is not an instantiation of anything, so we
5523          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
5524          the new type because that is supposed to be the corresponding
5525          template decl, i.e., TMPL.  */
5526       DECL_USE_TEMPLATE (tmpl) = 0;
5527       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
5528       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
5529       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
5530         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
5531
5532       /* Inject this template into the global scope.  */
5533       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
5534     }
5535
5536   if (context)
5537     {
5538       if (TREE_CODE (context) == NAMESPACE_DECL)
5539         pop_nested_namespace (context);
5540       else
5541         pop_nested_class ();
5542     }
5543
5544   return friend_type;
5545 }
5546
5547 /* Returns zero if TYPE cannot be completed later due to circularity.
5548    Otherwise returns one.  */
5549
5550 static int
5551 can_complete_type_without_circularity (tree type)
5552 {
5553   if (type == NULL_TREE || type == error_mark_node)
5554     return 0;
5555   else if (COMPLETE_TYPE_P (type))
5556     return 1;
5557   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
5558     return can_complete_type_without_circularity (TREE_TYPE (type));
5559   else if (CLASS_TYPE_P (type)
5560            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
5561     return 0;
5562   else
5563     return 1;
5564 }
5565
5566 tree
5567 instantiate_class_template (tree type)
5568 {
5569   tree template, args, pattern, t, member;
5570   tree typedecl;
5571   tree pbinfo;
5572   tree base_list;
5573
5574   if (type == error_mark_node)
5575     return error_mark_node;
5576
5577   if (TYPE_BEING_DEFINED (type)
5578       || COMPLETE_TYPE_P (type)
5579       || dependent_type_p (type))
5580     return type;
5581
5582   /* Figure out which template is being instantiated.  */
5583   template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
5584   gcc_assert (TREE_CODE (template) == TEMPLATE_DECL);
5585
5586   /* Determine what specialization of the original template to
5587      instantiate.  */
5588   t = most_specialized_class (type, template);
5589   if (t == error_mark_node)
5590     {
5591       TYPE_BEING_DEFINED (type) = 1;
5592       return error_mark_node;
5593     }
5594   else if (t)
5595     {
5596       /* This TYPE is actually an instantiation of a partial
5597          specialization.  We replace the innermost set of ARGS with
5598          the arguments appropriate for substitution.  For example,
5599          given:
5600
5601            template <class T> struct S {};
5602            template <class T> struct S<T*> {};
5603
5604          and supposing that we are instantiating S<int*>, ARGS will
5605          presently be {int*} -- but we need {int}.  */
5606       pattern = TREE_TYPE (t);
5607       args = TREE_PURPOSE (t);
5608     }
5609   else
5610     {
5611       pattern = TREE_TYPE (template);
5612       args = CLASSTYPE_TI_ARGS (type);
5613     }
5614
5615   /* If the template we're instantiating is incomplete, then clearly
5616      there's nothing we can do.  */
5617   if (!COMPLETE_TYPE_P (pattern))
5618     return type;
5619
5620   /* If we've recursively instantiated too many templates, stop.  */
5621   if (! push_tinst_level (type))
5622     return type;
5623
5624   /* Now we're really doing the instantiation.  Mark the type as in
5625      the process of being defined.  */
5626   TYPE_BEING_DEFINED (type) = 1;
5627
5628   /* We may be in the middle of deferred access check.  Disable
5629      it now.  */
5630   push_deferring_access_checks (dk_no_deferred);
5631
5632   push_to_top_level ();
5633
5634   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
5635
5636   /* Set the input location to the template definition. This is needed
5637      if tsubsting causes an error.  */
5638   typedecl = TYPE_MAIN_DECL (type);
5639   input_location = DECL_SOURCE_LOCATION (typedecl);
5640   in_system_header = DECL_IN_SYSTEM_HEADER (typedecl);
5641
5642   TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
5643   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
5644   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
5645   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
5646   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
5647   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
5648   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
5649   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
5650   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
5651   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
5652   TYPE_PACKED (type) = TYPE_PACKED (pattern);
5653   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
5654   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
5655   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
5656   if (ANON_AGGR_TYPE_P (pattern))
5657     SET_ANON_AGGR_TYPE_P (type);
5658   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
5659     {
5660       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
5661       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
5662     }
5663
5664   pbinfo = TYPE_BINFO (pattern);
5665
5666   /* We should never instantiate a nested class before its enclosing
5667      class; we need to look up the nested class by name before we can
5668      instantiate it, and that lookup should instantiate the enclosing
5669      class.  */
5670   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
5671               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
5672               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
5673
5674   base_list = NULL_TREE;
5675   if (BINFO_N_BASE_BINFOS (pbinfo))
5676     {
5677       tree pbase_binfo;
5678       tree context = TYPE_CONTEXT (type);
5679       tree pushed_scope;
5680       int i;
5681
5682       /* We must enter the scope containing the type, as that is where
5683          the accessibility of types named in dependent bases are
5684          looked up from.  */
5685       pushed_scope = push_scope (context ? context : global_namespace);
5686
5687       /* Substitute into each of the bases to determine the actual
5688          basetypes.  */
5689       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
5690         {
5691           tree base;
5692           tree access = BINFO_BASE_ACCESS (pbinfo, i);
5693
5694           /* Substitute to figure out the base class.  */
5695           base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, NULL_TREE);
5696           if (base == error_mark_node)
5697             continue;
5698
5699           base_list = tree_cons (access, base, base_list);
5700           if (BINFO_VIRTUAL_P (pbase_binfo))
5701             TREE_TYPE (base_list) = integer_type_node;
5702         }
5703
5704       /* The list is now in reverse order; correct that.  */
5705       base_list = nreverse (base_list);
5706
5707       if (pushed_scope)
5708         pop_scope (pushed_scope);
5709     }
5710   /* Now call xref_basetypes to set up all the base-class
5711      information.  */
5712   xref_basetypes (type, base_list);
5713
5714
5715   /* Now that our base classes are set up, enter the scope of the
5716      class, so that name lookups into base classes, etc. will work
5717      correctly.  This is precisely analogous to what we do in
5718      begin_class_definition when defining an ordinary non-template
5719      class.  */
5720   pushclass (type);
5721
5722   /* Now members are processed in the order of declaration.  */
5723   for (member = CLASSTYPE_DECL_LIST (pattern);
5724        member; member = TREE_CHAIN (member))
5725     {
5726       tree t = TREE_VALUE (member);
5727
5728       if (TREE_PURPOSE (member))
5729         {
5730           if (TYPE_P (t))
5731             {
5732               /* Build new CLASSTYPE_NESTED_UTDS.  */
5733
5734               tree newtag;
5735               bool class_template_p;
5736
5737               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
5738                                   && TYPE_LANG_SPECIFIC (t)
5739                                   && CLASSTYPE_IS_TEMPLATE (t));
5740               /* If the member is a class template, then -- even after
5741                  substitution -- there may be dependent types in the
5742                  template argument list for the class.  We increment
5743                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
5744                  that function will assume that no types are dependent
5745                  when outside of a template.  */
5746               if (class_template_p)
5747                 ++processing_template_decl;
5748               newtag = tsubst (t, args, tf_error, NULL_TREE);
5749               if (class_template_p)
5750                 --processing_template_decl;
5751               if (newtag == error_mark_node)
5752                 continue;
5753
5754               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
5755                 {
5756                   tree name = TYPE_IDENTIFIER (t);
5757
5758                   if (class_template_p)
5759                     /* Unfortunately, lookup_template_class sets
5760                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
5761                        instantiation (i.e., for the type of a member
5762                        template class nested within a template class.)
5763                        This behavior is required for
5764                        maybe_process_partial_specialization to work
5765                        correctly, but is not accurate in this case;
5766                        the TAG is not an instantiation of anything.
5767                        (The corresponding TEMPLATE_DECL is an
5768                        instantiation, but the TYPE is not.) */
5769                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
5770
5771                   /* Now, we call pushtag to put this NEWTAG into the scope of
5772                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
5773                      pushtag calling push_template_decl.  We don't have to do
5774                      this for enums because it will already have been done in
5775                      tsubst_enum.  */
5776                   if (name)
5777                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
5778                   pushtag (name, newtag, /*tag_scope=*/ts_current);
5779                 }
5780             }
5781           else if (TREE_CODE (t) == FUNCTION_DECL
5782                    || DECL_FUNCTION_TEMPLATE_P (t))
5783             {
5784               /* Build new TYPE_METHODS.  */
5785               tree r;
5786
5787               if (TREE_CODE (t) == TEMPLATE_DECL)
5788                 ++processing_template_decl;
5789               r = tsubst (t, args, tf_error, NULL_TREE);
5790               if (TREE_CODE (t) == TEMPLATE_DECL)
5791                 --processing_template_decl;
5792               set_current_access_from_decl (r);
5793               finish_member_declaration (r);
5794             }
5795           else
5796             {
5797               /* Build new TYPE_FIELDS.  */
5798
5799               if (TREE_CODE (t) != CONST_DECL)
5800                 {
5801                   tree r;
5802
5803                   /* The the file and line for this declaration, to
5804                      assist in error message reporting.  Since we
5805                      called push_tinst_level above, we don't need to
5806                      restore these.  */
5807                   input_location = DECL_SOURCE_LOCATION (t);
5808
5809                   if (TREE_CODE (t) == TEMPLATE_DECL)
5810                     ++processing_template_decl;
5811                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
5812                   if (TREE_CODE (t) == TEMPLATE_DECL)
5813                     --processing_template_decl;
5814                   if (TREE_CODE (r) == VAR_DECL)
5815                     {
5816                       /* In [temp.inst]:
5817
5818                            [t]he initialization (and any associated
5819                            side-effects) of a static data member does
5820                            not occur unless the static data member is
5821                            itself used in a way that requires the
5822                            definition of the static data member to
5823                            exist.
5824
5825                          Therefore, we do not substitute into the
5826                          initialized for the static data member here.  */
5827                       finish_static_data_member_decl
5828                         (r,
5829                          /*init=*/NULL_TREE,
5830                          /*init_const_expr_p=*/false,
5831                          /*asmspec_tree=*/NULL_TREE,
5832                          /*flags=*/0);
5833                       if (DECL_INITIALIZED_IN_CLASS_P (r))
5834                         check_static_variable_definition (r, TREE_TYPE (r));
5835                     }
5836                   else if (TREE_CODE (r) == FIELD_DECL)
5837                     {
5838                       /* Determine whether R has a valid type and can be
5839                          completed later.  If R is invalid, then it is
5840                          replaced by error_mark_node so that it will not be
5841                          added to TYPE_FIELDS.  */
5842                       tree rtype = TREE_TYPE (r);
5843                       if (can_complete_type_without_circularity (rtype))
5844                         complete_type (rtype);
5845
5846                       if (!COMPLETE_TYPE_P (rtype))
5847                         {
5848                           cxx_incomplete_type_error (r, rtype);
5849                           r = error_mark_node;
5850                         }
5851                     }
5852
5853                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
5854                      such a thing will already have been added to the field
5855                      list by tsubst_enum in finish_member_declaration in the
5856                      CLASSTYPE_NESTED_UTDS case above.  */
5857                   if (!(TREE_CODE (r) == TYPE_DECL
5858                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
5859                         && DECL_ARTIFICIAL (r)))
5860                     {
5861                       set_current_access_from_decl (r);
5862                       finish_member_declaration (r);
5863                     }
5864                 }
5865             }
5866         }
5867       else
5868         {
5869           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
5870             {
5871               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
5872
5873               tree friend_type = t;
5874               bool adjust_processing_template_decl = false;
5875
5876               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5877                 {
5878                   /* template <class T> friend class C;  */
5879                   friend_type = tsubst_friend_class (friend_type, args);
5880                   adjust_processing_template_decl = true;
5881                 }
5882               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
5883                 {
5884                   /* template <class T> friend class C::D;  */
5885                   friend_type = tsubst (friend_type, args,
5886                                         tf_warning_or_error, NULL_TREE);
5887                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5888                     friend_type = TREE_TYPE (friend_type);
5889                   adjust_processing_template_decl = true;
5890                 }
5891               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
5892                 {
5893                   /* This could be either
5894
5895                        friend class T::C;
5896
5897                      when dependent_type_p is false or
5898
5899                        template <class U> friend class T::C;
5900
5901                      otherwise.  */
5902                   friend_type = tsubst (friend_type, args,
5903                                         tf_warning_or_error, NULL_TREE);
5904                   /* Bump processing_template_decl for correct
5905                      dependent_type_p calculation.  */
5906                   ++processing_template_decl;
5907                   if (dependent_type_p (friend_type))
5908                     adjust_processing_template_decl = true;
5909                   --processing_template_decl;
5910                 }
5911               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
5912                        && hidden_name_p (TYPE_NAME (friend_type)))
5913                 {
5914                   /* friend class C;
5915
5916                      where C hasn't been declared yet.  Let's lookup name
5917                      from namespace scope directly, bypassing any name that
5918                      come from dependent base class.  */
5919                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
5920
5921                   /* The call to xref_tag_from_type does injection for friend
5922                      classes.  */
5923                   push_nested_namespace (ns);
5924                   friend_type =
5925                     xref_tag_from_type (friend_type, NULL_TREE,
5926                                         /*tag_scope=*/ts_current);
5927                   pop_nested_namespace (ns);
5928                 }
5929               else if (uses_template_parms (friend_type))
5930                 /* friend class C<T>;  */
5931                 friend_type = tsubst (friend_type, args,
5932                                       tf_warning_or_error, NULL_TREE);
5933               /* Otherwise it's
5934
5935                    friend class C;
5936
5937                  where C is already declared or
5938
5939                    friend class C<int>;
5940
5941                  We don't have to do anything in these cases.  */
5942
5943               if (adjust_processing_template_decl)
5944                 /* Trick make_friend_class into realizing that the friend
5945                    we're adding is a template, not an ordinary class.  It's
5946                    important that we use make_friend_class since it will
5947                    perform some error-checking and output cross-reference
5948                    information.  */
5949                 ++processing_template_decl;
5950
5951               if (friend_type != error_mark_node)
5952                 make_friend_class (type, friend_type, /*complain=*/false);
5953
5954               if (adjust_processing_template_decl)
5955                 --processing_template_decl;
5956             }
5957           else
5958             {
5959               /* Build new DECL_FRIENDLIST.  */
5960               tree r;
5961
5962               /* The the file and line for this declaration, to
5963                  assist in error message reporting.  Since we
5964                  called push_tinst_level above, we don't need to
5965                  restore these.  */
5966               input_location = DECL_SOURCE_LOCATION (t);
5967
5968               if (TREE_CODE (t) == TEMPLATE_DECL)
5969                 {
5970                   ++processing_template_decl;
5971                   push_deferring_access_checks (dk_no_check);
5972                 }
5973
5974               r = tsubst_friend_function (t, args);
5975               add_friend (type, r, /*complain=*/false);
5976               if (TREE_CODE (t) == TEMPLATE_DECL)
5977                 {
5978                   pop_deferring_access_checks ();
5979                   --processing_template_decl;
5980                 }
5981             }
5982         }
5983     }
5984
5985   /* Set the file and line number information to whatever is given for
5986      the class itself.  This puts error messages involving generated
5987      implicit functions at a predictable point, and the same point
5988      that would be used for non-template classes.  */
5989   input_location = DECL_SOURCE_LOCATION (typedecl);
5990
5991   unreverse_member_declarations (type);
5992   finish_struct_1 (type);
5993   TYPE_BEING_DEFINED (type) = 0;
5994
5995   /* Now that the class is complete, instantiate default arguments for
5996      any member functions.  We don't do this earlier because the
5997      default arguments may reference members of the class.  */
5998   if (!PRIMARY_TEMPLATE_P (template))
5999     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
6000       if (TREE_CODE (t) == FUNCTION_DECL
6001           /* Implicitly generated member functions will not have template
6002              information; they are not instantiations, but instead are
6003              created "fresh" for each instantiation.  */
6004           && DECL_TEMPLATE_INFO (t))
6005         tsubst_default_arguments (t);
6006
6007   popclass ();
6008   pop_from_top_level ();
6009   pop_deferring_access_checks ();
6010   pop_tinst_level ();
6011
6012   /* The vtable for a template class can be emitted in any translation
6013      unit in which the class is instantiated.  When there is no key
6014      method, however, finish_struct_1 will already have added TYPE to
6015      the keyed_classes list.  */
6016   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
6017     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
6018
6019   return type;
6020 }
6021
6022 static tree
6023 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
6024 {
6025   tree r;
6026
6027   if (!t)
6028     r = t;
6029   else if (TYPE_P (t))
6030     r = tsubst (t, args, complain, in_decl);
6031   else
6032     {
6033       r = tsubst_expr (t, args, complain, in_decl);
6034       r = fold_non_dependent_expr (r);
6035     }
6036   return r;
6037 }
6038
6039 /* Substitute ARGS into the vector or list of template arguments T.  */
6040
6041 static tree
6042 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
6043 {
6044   int len = TREE_VEC_LENGTH (t);
6045   int need_new = 0, i;
6046   tree *elts = (tree *) alloca (len * sizeof (tree));
6047
6048   for (i = 0; i < len; i++)
6049     {
6050       tree orig_arg = TREE_VEC_ELT (t, i);
6051       tree new_arg;
6052
6053       if (TREE_CODE (orig_arg) == TREE_VEC)
6054         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
6055       else
6056         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
6057
6058       if (new_arg == error_mark_node)
6059         return error_mark_node;
6060
6061       elts[i] = new_arg;
6062       if (new_arg != orig_arg)
6063         need_new = 1;
6064     }
6065
6066   if (!need_new)
6067     return t;
6068
6069   t = make_tree_vec (len);
6070   for (i = 0; i < len; i++)
6071     TREE_VEC_ELT (t, i) = elts[i];
6072
6073   return t;
6074 }
6075
6076 /* Return the result of substituting ARGS into the template parameters
6077    given by PARMS.  If there are m levels of ARGS and m + n levels of
6078    PARMS, then the result will contain n levels of PARMS.  For
6079    example, if PARMS is `template <class T> template <class U>
6080    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
6081    result will be `template <int*, double, class V>'.  */
6082
6083 static tree
6084 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
6085 {
6086   tree r = NULL_TREE;
6087   tree* new_parms;
6088
6089   /* When substituting into a template, we must set
6090      PROCESSING_TEMPLATE_DECL as the template parameters may be
6091      dependent if they are based on one-another, and the dependency
6092      predicates are short-circuit outside of templates.  */
6093   ++processing_template_decl;
6094
6095   for (new_parms = &r;
6096        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
6097        new_parms = &(TREE_CHAIN (*new_parms)),
6098          parms = TREE_CHAIN (parms))
6099     {
6100       tree new_vec =
6101         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
6102       int i;
6103
6104       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
6105         {
6106           tree tuple;
6107           tree default_value;
6108           tree parm_decl;
6109
6110           if (parms == error_mark_node)
6111             continue;
6112
6113           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
6114
6115           if (tuple == error_mark_node)
6116             continue;
6117
6118           default_value = TREE_PURPOSE (tuple);
6119           parm_decl = TREE_VALUE (tuple);
6120
6121           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
6122           if (TREE_CODE (parm_decl) == PARM_DECL
6123               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
6124             parm_decl = error_mark_node;
6125           default_value = tsubst_template_arg (default_value, args,
6126                                                complain, NULL_TREE);
6127
6128           tuple = build_tree_list (default_value, parm_decl);
6129           TREE_VEC_ELT (new_vec, i) = tuple;
6130         }
6131
6132       *new_parms =
6133         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
6134                              - TMPL_ARGS_DEPTH (args)),
6135                    new_vec, NULL_TREE);
6136     }
6137
6138   --processing_template_decl;
6139
6140   return r;
6141 }
6142
6143 /* Substitute the ARGS into the indicated aggregate (or enumeration)
6144    type T.  If T is not an aggregate or enumeration type, it is
6145    handled as if by tsubst.  IN_DECL is as for tsubst.  If
6146    ENTERING_SCOPE is nonzero, T is the context for a template which
6147    we are presently tsubst'ing.  Return the substituted value.  */
6148
6149 static tree
6150 tsubst_aggr_type (tree t,
6151                   tree args,
6152                   tsubst_flags_t complain,
6153                   tree in_decl,
6154                   int entering_scope)
6155 {
6156   if (t == NULL_TREE)
6157     return NULL_TREE;
6158
6159   switch (TREE_CODE (t))
6160     {
6161     case RECORD_TYPE:
6162       if (TYPE_PTRMEMFUNC_P (t))
6163         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
6164
6165       /* Else fall through.  */
6166     case ENUMERAL_TYPE:
6167     case UNION_TYPE:
6168       if (TYPE_TEMPLATE_INFO (t))
6169         {
6170           tree argvec;
6171           tree context;
6172           tree r;
6173           bool saved_skip_evaluation;
6174
6175           /* In "sizeof(X<I>)" we need to evaluate "I".  */
6176           saved_skip_evaluation = skip_evaluation;
6177           skip_evaluation = false;
6178
6179           /* First, determine the context for the type we are looking
6180              up.  */
6181           context = TYPE_CONTEXT (t);
6182           if (context)
6183             context = tsubst_aggr_type (context, args, complain,
6184                                         in_decl, /*entering_scope=*/1);
6185
6186           /* Then, figure out what arguments are appropriate for the
6187              type we are trying to find.  For example, given:
6188
6189                template <class T> struct S;
6190                template <class T, class U> void f(T, U) { S<U> su; }
6191
6192              and supposing that we are instantiating f<int, double>,
6193              then our ARGS will be {int, double}, but, when looking up
6194              S we only want {double}.  */
6195           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
6196                                          complain, in_decl);
6197           if (argvec == error_mark_node)
6198             r = error_mark_node;
6199           else
6200             {
6201               r = lookup_template_class (t, argvec, in_decl, context,
6202                                          entering_scope, complain);
6203               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
6204             }
6205
6206           skip_evaluation = saved_skip_evaluation;
6207
6208           return r;
6209         }
6210       else
6211         /* This is not a template type, so there's nothing to do.  */
6212         return t;
6213
6214     default:
6215       return tsubst (t, args, complain, in_decl);
6216     }
6217 }
6218
6219 /* Substitute into the default argument ARG (a default argument for
6220    FN), which has the indicated TYPE.  */
6221
6222 tree
6223 tsubst_default_argument (tree fn, tree type, tree arg)
6224 {
6225   tree saved_class_ptr = NULL_TREE;
6226   tree saved_class_ref = NULL_TREE;
6227
6228   /* This default argument came from a template.  Instantiate the
6229      default argument here, not in tsubst.  In the case of
6230      something like:
6231
6232        template <class T>
6233        struct S {
6234          static T t();
6235          void f(T = t());
6236        };
6237
6238      we must be careful to do name lookup in the scope of S<T>,
6239      rather than in the current class.  */
6240   push_access_scope (fn);
6241   /* The "this" pointer is not valid in a default argument.  */
6242   if (cfun)
6243     {
6244       saved_class_ptr = current_class_ptr;
6245       cp_function_chain->x_current_class_ptr = NULL_TREE;
6246       saved_class_ref = current_class_ref;
6247       cp_function_chain->x_current_class_ref = NULL_TREE;
6248     }
6249
6250   push_deferring_access_checks(dk_no_deferred);
6251   /* The default argument expression may cause implicitly defined
6252      member functions to be synthesized, which will result in garbage
6253      collection.  We must treat this situation as if we were within
6254      the body of function so as to avoid collecting live data on the
6255      stack.  */
6256   ++function_depth;
6257   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
6258                      tf_warning_or_error, NULL_TREE);
6259   --function_depth;
6260   pop_deferring_access_checks();
6261
6262   /* Restore the "this" pointer.  */
6263   if (cfun)
6264     {
6265       cp_function_chain->x_current_class_ptr = saved_class_ptr;
6266       cp_function_chain->x_current_class_ref = saved_class_ref;
6267     }
6268
6269   pop_access_scope (fn);
6270
6271   /* Make sure the default argument is reasonable.  */
6272   arg = check_default_argument (type, arg);
6273
6274   return arg;
6275 }
6276
6277 /* Substitute into all the default arguments for FN.  */
6278
6279 static void
6280 tsubst_default_arguments (tree fn)
6281 {
6282   tree arg;
6283   tree tmpl_args;
6284
6285   tmpl_args = DECL_TI_ARGS (fn);
6286
6287   /* If this function is not yet instantiated, we certainly don't need
6288      its default arguments.  */
6289   if (uses_template_parms (tmpl_args))
6290     return;
6291
6292   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
6293        arg;
6294        arg = TREE_CHAIN (arg))
6295     if (TREE_PURPOSE (arg))
6296       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
6297                                                     TREE_VALUE (arg),
6298                                                     TREE_PURPOSE (arg));
6299 }
6300
6301 /* Substitute the ARGS into the T, which is a _DECL.  Return the
6302    result of the substitution.  Issue error and warning messages under
6303    control of COMPLAIN.  */
6304
6305 static tree
6306 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
6307 {
6308   location_t saved_loc;
6309   tree r = NULL_TREE;
6310   tree in_decl = t;
6311
6312   /* Set the filename and linenumber to improve error-reporting.  */
6313   saved_loc = input_location;
6314   input_location = DECL_SOURCE_LOCATION (t);
6315
6316   switch (TREE_CODE (t))
6317     {
6318     case TEMPLATE_DECL:
6319       {
6320         /* We can get here when processing a member function template,
6321            member class template, and template template parameter of
6322            a template class.  */
6323         tree decl = DECL_TEMPLATE_RESULT (t);
6324         tree spec;
6325         tree tmpl_args;
6326         tree full_args;
6327
6328         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
6329           {
6330             /* Template template parameter is treated here.  */
6331             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6332             if (new_type == error_mark_node)
6333               return error_mark_node;
6334
6335             r = copy_decl (t);
6336             TREE_CHAIN (r) = NULL_TREE;
6337             TREE_TYPE (r) = new_type;
6338             DECL_TEMPLATE_RESULT (r)
6339               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
6340             DECL_TEMPLATE_PARMS (r)
6341               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
6342                                        complain);
6343             TYPE_NAME (new_type) = r;
6344             break;
6345           }
6346
6347         /* We might already have an instance of this template.
6348            The ARGS are for the surrounding class type, so the
6349            full args contain the tsubst'd args for the context,
6350            plus the innermost args from the template decl.  */
6351         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
6352           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
6353           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
6354         /* Because this is a template, the arguments will still be
6355            dependent, even after substitution.  If
6356            PROCESSING_TEMPLATE_DECL is not set, the dependency
6357            predicates will short-circuit.  */
6358         ++processing_template_decl;
6359         full_args = tsubst_template_args (tmpl_args, args,
6360                                           complain, in_decl);
6361         --processing_template_decl;
6362         if (full_args == error_mark_node)
6363           return error_mark_node;
6364
6365         /* tsubst_template_args doesn't copy the vector if
6366            nothing changed.  But, *something* should have
6367            changed.  */
6368         gcc_assert (full_args != tmpl_args);
6369
6370         spec = retrieve_specialization (t, full_args,
6371                                         /*class_specializations_p=*/true);
6372         if (spec != NULL_TREE)
6373           {
6374             r = spec;
6375             break;
6376           }
6377
6378         /* Make a new template decl.  It will be similar to the
6379            original, but will record the current template arguments.
6380            We also create a new function declaration, which is just
6381            like the old one, but points to this new template, rather
6382            than the old one.  */
6383         r = copy_decl (t);
6384         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
6385         TREE_CHAIN (r) = NULL_TREE;
6386
6387         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
6388
6389         if (TREE_CODE (decl) == TYPE_DECL)
6390           {
6391             tree new_type;
6392             ++processing_template_decl;
6393             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6394             --processing_template_decl;
6395             if (new_type == error_mark_node)
6396               return error_mark_node;
6397
6398             TREE_TYPE (r) = new_type;
6399             CLASSTYPE_TI_TEMPLATE (new_type) = r;
6400             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
6401             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
6402             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
6403           }
6404         else
6405           {
6406             tree new_decl;
6407             ++processing_template_decl;
6408             new_decl = tsubst (decl, args, complain, in_decl);
6409             --processing_template_decl;
6410             if (new_decl == error_mark_node)
6411               return error_mark_node;
6412
6413             DECL_TEMPLATE_RESULT (r) = new_decl;
6414             DECL_TI_TEMPLATE (new_decl) = r;
6415             TREE_TYPE (r) = TREE_TYPE (new_decl);
6416             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
6417             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
6418           }
6419
6420         SET_DECL_IMPLICIT_INSTANTIATION (r);
6421         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
6422         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
6423
6424         /* The template parameters for this new template are all the
6425            template parameters for the old template, except the
6426            outermost level of parameters.  */
6427         DECL_TEMPLATE_PARMS (r)
6428           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
6429                                    complain);
6430
6431         if (PRIMARY_TEMPLATE_P (t))
6432           DECL_PRIMARY_TEMPLATE (r) = r;
6433
6434         if (TREE_CODE (decl) != TYPE_DECL)
6435           /* Record this non-type partial instantiation.  */
6436           register_specialization (r, t,
6437                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
6438                                    false);
6439       }
6440       break;
6441
6442     case FUNCTION_DECL:
6443       {
6444         tree ctx;
6445         tree argvec = NULL_TREE;
6446         tree *friends;
6447         tree gen_tmpl;
6448         tree type;
6449         int member;
6450         int args_depth;
6451         int parms_depth;
6452
6453         /* Nobody should be tsubst'ing into non-template functions.  */
6454         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
6455
6456         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
6457           {
6458             tree spec;
6459             bool dependent_p;
6460
6461             /* If T is not dependent, just return it.  We have to
6462                increment PROCESSING_TEMPLATE_DECL because
6463                value_dependent_expression_p assumes that nothing is
6464                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
6465             ++processing_template_decl;
6466             dependent_p = value_dependent_expression_p (t);
6467             --processing_template_decl;
6468             if (!dependent_p)
6469               return t;
6470
6471             /* Calculate the most general template of which R is a
6472                specialization, and the complete set of arguments used to
6473                specialize R.  */
6474             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
6475             argvec = tsubst_template_args (DECL_TI_ARGS
6476                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
6477                                            args, complain, in_decl);
6478
6479             /* Check to see if we already have this specialization.  */
6480             spec = retrieve_specialization (gen_tmpl, argvec,
6481                                             /*class_specializations_p=*/false);
6482
6483             if (spec)
6484               {
6485                 r = spec;
6486                 break;
6487               }
6488
6489             /* We can see more levels of arguments than parameters if
6490                there was a specialization of a member template, like
6491                this:
6492
6493                  template <class T> struct S { template <class U> void f(); }
6494                  template <> template <class U> void S<int>::f(U);
6495
6496                Here, we'll be substituting into the specialization,
6497                because that's where we can find the code we actually
6498                want to generate, but we'll have enough arguments for
6499                the most general template.
6500
6501                We also deal with the peculiar case:
6502
6503                  template <class T> struct S {
6504                    template <class U> friend void f();
6505                  };
6506                  template <class U> void f() {}
6507                  template S<int>;
6508                  template void f<double>();
6509
6510                Here, the ARGS for the instantiation of will be {int,
6511                double}.  But, we only need as many ARGS as there are
6512                levels of template parameters in CODE_PATTERN.  We are
6513                careful not to get fooled into reducing the ARGS in
6514                situations like:
6515
6516                  template <class T> struct S { template <class U> void f(U); }
6517                  template <class T> template <> void S<T>::f(int) {}
6518
6519                which we can spot because the pattern will be a
6520                specialization in this case.  */
6521             args_depth = TMPL_ARGS_DEPTH (args);
6522             parms_depth =
6523               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
6524             if (args_depth > parms_depth
6525                 && !DECL_TEMPLATE_SPECIALIZATION (t))
6526               args = get_innermost_template_args (args, parms_depth);
6527           }
6528         else
6529           {
6530             /* This special case arises when we have something like this:
6531
6532                  template <class T> struct S {
6533                    friend void f<int>(int, double);
6534                  };
6535
6536                Here, the DECL_TI_TEMPLATE for the friend declaration
6537                will be an IDENTIFIER_NODE.  We are being called from
6538                tsubst_friend_function, and we want only to create a
6539                new decl (R) with appropriate types so that we can call
6540                determine_specialization.  */
6541             gen_tmpl = NULL_TREE;
6542           }
6543
6544         if (DECL_CLASS_SCOPE_P (t))
6545           {
6546             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
6547               member = 2;
6548             else
6549               member = 1;
6550             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
6551                                     complain, t, /*entering_scope=*/1);
6552           }
6553         else
6554           {
6555             member = 0;
6556             ctx = DECL_CONTEXT (t);
6557           }
6558         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6559         if (type == error_mark_node)
6560           return error_mark_node;
6561
6562         /* We do NOT check for matching decls pushed separately at this
6563            point, as they may not represent instantiations of this
6564            template, and in any case are considered separate under the
6565            discrete model.  */
6566         r = copy_decl (t);
6567         DECL_USE_TEMPLATE (r) = 0;
6568         TREE_TYPE (r) = type;
6569         /* Clear out the mangled name and RTL for the instantiation.  */
6570         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
6571         SET_DECL_RTL (r, NULL_RTX);
6572         DECL_INITIAL (r) = NULL_TREE;
6573         DECL_CONTEXT (r) = ctx;
6574
6575         if (member && DECL_CONV_FN_P (r))
6576           /* Type-conversion operator.  Reconstruct the name, in
6577              case it's the name of one of the template's parameters.  */
6578           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
6579
6580         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
6581                                      complain, t);
6582         DECL_RESULT (r) = NULL_TREE;
6583
6584         TREE_STATIC (r) = 0;
6585         TREE_PUBLIC (r) = TREE_PUBLIC (t);
6586         DECL_EXTERNAL (r) = 1;
6587         /* If this is an instantiation of a function with internal
6588            linkage, we already know what object file linkage will be
6589            assigned to the instantiation.  */
6590         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
6591         DECL_DEFER_OUTPUT (r) = 0;
6592         TREE_CHAIN (r) = NULL_TREE;
6593         DECL_PENDING_INLINE_INFO (r) = 0;
6594         DECL_PENDING_INLINE_P (r) = 0;
6595         DECL_SAVED_TREE (r) = NULL_TREE;
6596         TREE_USED (r) = 0;
6597         if (DECL_CLONED_FUNCTION (r))
6598           {
6599             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
6600                                                args, complain, t);
6601             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
6602             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
6603           }
6604
6605         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
6606            this in the special friend case mentioned above where
6607            GEN_TMPL is NULL.  */
6608         if (gen_tmpl)
6609           {
6610             DECL_TEMPLATE_INFO (r)
6611               = tree_cons (gen_tmpl, argvec, NULL_TREE);
6612             SET_DECL_IMPLICIT_INSTANTIATION (r);
6613             register_specialization (r, gen_tmpl, argvec, false);
6614
6615             /* We're not supposed to instantiate default arguments
6616                until they are called, for a template.  But, for a
6617                declaration like:
6618
6619                  template <class T> void f ()
6620                  { extern void g(int i = T()); }
6621
6622                we should do the substitution when the template is
6623                instantiated.  We handle the member function case in
6624                instantiate_class_template since the default arguments
6625                might refer to other members of the class.  */
6626             if (!member
6627                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
6628                 && !uses_template_parms (argvec))
6629               tsubst_default_arguments (r);
6630           }
6631         else
6632           DECL_TEMPLATE_INFO (r) = NULL_TREE;
6633
6634         /* Copy the list of befriending classes.  */
6635         for (friends = &DECL_BEFRIENDING_CLASSES (r);
6636              *friends;
6637              friends = &TREE_CHAIN (*friends))
6638           {
6639             *friends = copy_node (*friends);
6640             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
6641                                             args, complain,
6642                                             in_decl);
6643           }
6644
6645         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
6646           {
6647             maybe_retrofit_in_chrg (r);
6648             if (DECL_CONSTRUCTOR_P (r))
6649               grok_ctor_properties (ctx, r);
6650             /* If this is an instantiation of a member template, clone it.
6651                If it isn't, that'll be handled by
6652                clone_constructors_and_destructors.  */
6653             if (PRIMARY_TEMPLATE_P (gen_tmpl))
6654               clone_function_decl (r, /*update_method_vec_p=*/0);
6655           }
6656         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r)))
6657           grok_op_properties (r, (complain & tf_error) != 0);
6658
6659         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
6660           SET_DECL_FRIEND_CONTEXT (r,
6661                                    tsubst (DECL_FRIEND_CONTEXT (t),
6662                                             args, complain, in_decl));
6663
6664         /* Possibly limit visibility based on template args.  */
6665         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
6666         if (DECL_VISIBILITY_SPECIFIED (t))
6667           {
6668             DECL_VISIBILITY_SPECIFIED (r) = 0;
6669             DECL_ATTRIBUTES (r)
6670               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
6671           }
6672         determine_visibility (r);
6673       }
6674       break;
6675
6676     case PARM_DECL:
6677       {
6678         tree type;
6679
6680         r = copy_node (t);
6681         if (DECL_TEMPLATE_PARM_P (t))
6682           SET_DECL_TEMPLATE_PARM_P (r);
6683
6684         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6685         type = type_decays_to (type);
6686         TREE_TYPE (r) = type;
6687         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
6688
6689         if (DECL_INITIAL (r))
6690           {
6691             if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
6692               DECL_INITIAL (r) = TREE_TYPE (r);
6693             else
6694               DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
6695                                          complain, in_decl);
6696           }
6697
6698         DECL_CONTEXT (r) = NULL_TREE;
6699
6700         if (!DECL_TEMPLATE_PARM_P (r))
6701           DECL_ARG_TYPE (r) = type_passed_as (type);
6702         if (TREE_CHAIN (t))
6703           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
6704                                    complain, TREE_CHAIN (t));
6705       }
6706       break;
6707
6708     case FIELD_DECL:
6709       {
6710         tree type;
6711
6712         r = copy_decl (t);
6713         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6714         if (type == error_mark_node)
6715           return error_mark_node;
6716         TREE_TYPE (r) = type;
6717         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
6718
6719         /* We don't have to set DECL_CONTEXT here; it is set by
6720            finish_member_declaration.  */
6721         DECL_INITIAL (r) = tsubst_expr (DECL_INITIAL (t), args,
6722                                         complain, in_decl);
6723         TREE_CHAIN (r) = NULL_TREE;
6724         if (VOID_TYPE_P (type))
6725           error ("instantiation of %q+D as type %qT", r, type);
6726       }
6727       break;
6728
6729     case USING_DECL:
6730       /* We reach here only for member using decls.  */
6731       if (DECL_DEPENDENT_P (t))
6732         {
6733           r = do_class_using_decl
6734             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
6735              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
6736           if (!r)
6737             r = error_mark_node;
6738         }
6739       else
6740         {
6741           r = copy_node (t);
6742           TREE_CHAIN (r) = NULL_TREE;
6743         }
6744       break;
6745
6746     case TYPE_DECL:
6747     case VAR_DECL:
6748       {
6749         tree argvec = NULL_TREE;
6750         tree gen_tmpl = NULL_TREE;
6751         tree spec;
6752         tree tmpl = NULL_TREE;
6753         tree ctx;
6754         tree type = NULL_TREE;
6755         bool local_p;
6756
6757         if (TREE_CODE (t) == TYPE_DECL)
6758           {
6759             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6760             if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM
6761                 || t == TYPE_MAIN_DECL (TREE_TYPE (t)))
6762               {
6763                 /* If this is the canonical decl, we don't have to
6764                    mess with instantiations, and often we can't (for
6765                    typename, template type parms and such).  Note that
6766                    TYPE_NAME is not correct for the above test if
6767                    we've copied the type for a typedef.  */
6768                 r = TYPE_NAME (type);
6769                 break;
6770               }
6771           }
6772
6773         /* Check to see if we already have the specialization we
6774            need.  */
6775         spec = NULL_TREE;
6776         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
6777           {
6778             /* T is a static data member or namespace-scope entity.
6779                We have to substitute into namespace-scope variables
6780                (even though such entities are never templates) because
6781                of cases like:
6782                
6783                  template <class T> void f() { extern T t; }
6784
6785                where the entity referenced is not known until
6786                instantiation time.  */
6787             local_p = false;
6788             ctx = DECL_CONTEXT (t);
6789             if (DECL_CLASS_SCOPE_P (t))
6790               {
6791                 ctx = tsubst_aggr_type (ctx, args,
6792                                         complain,
6793                                         in_decl, /*entering_scope=*/1);
6794                 /* If CTX is unchanged, then T is in fact the
6795                    specialization we want.  That situation occurs when
6796                    referencing a static data member within in its own
6797                    class.  We can use pointer equality, rather than
6798                    same_type_p, because DECL_CONTEXT is always
6799                    canonical.  */
6800                 if (ctx == DECL_CONTEXT (t))
6801                   spec = t;
6802               }
6803
6804             if (!spec)
6805               {
6806                 tmpl = DECL_TI_TEMPLATE (t);
6807                 gen_tmpl = most_general_template (tmpl);
6808                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
6809                 spec = (retrieve_specialization 
6810                         (gen_tmpl, argvec,
6811                          /*class_specializations_p=*/false));
6812               }
6813           }
6814         else
6815           {
6816             /* A local variable.  */
6817             local_p = true;
6818             /* Subsequent calls to pushdecl will fill this in.  */
6819             ctx = NULL_TREE;
6820             spec = retrieve_local_specialization (t);
6821           }
6822         /* If we already have the specialization we need, there is
6823            nothing more to do.  */ 
6824         if (spec)
6825           {
6826             r = spec;
6827             break;
6828           }
6829
6830         /* Create a new node for the specialization we need.  */
6831         r = copy_decl (t);
6832         if (TREE_CODE (r) == VAR_DECL)
6833           {
6834             /* Even if the original location is out of scope, the
6835                newly substituted one is not.  */
6836             DECL_DEAD_FOR_LOCAL (r) = 0;
6837             DECL_INITIALIZED_P (r) = 0;
6838             DECL_TEMPLATE_INSTANTIATED (r) = 0;
6839             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6840             if (type == error_mark_node)
6841               return error_mark_node;
6842             type = complete_type (type);
6843             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
6844               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
6845             type = check_var_type (DECL_NAME (r), type);
6846
6847             if (DECL_HAS_VALUE_EXPR_P (t))
6848               {
6849                 tree ve = DECL_VALUE_EXPR (t);
6850                 ve = tsubst_expr (ve, args, complain, in_decl);
6851                 SET_DECL_VALUE_EXPR (r, ve);
6852               }
6853           }
6854         else if (DECL_SELF_REFERENCE_P (t))
6855           SET_DECL_SELF_REFERENCE_P (r);
6856         TREE_TYPE (r) = type;
6857         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
6858         DECL_CONTEXT (r) = ctx;
6859         /* Clear out the mangled name and RTL for the instantiation.  */
6860         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
6861         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
6862           SET_DECL_RTL (r, NULL_RTX);
6863         /* The initializer must not be expanded until it is required;
6864            see [temp.inst].  */
6865         DECL_INITIAL (r) = NULL_TREE;
6866         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
6867           SET_DECL_RTL (r, NULL_RTX);
6868         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
6869         if (TREE_CODE (r) == VAR_DECL)
6870           {
6871             /* Possibly limit visibility based on template args.  */
6872             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
6873             if (DECL_VISIBILITY_SPECIFIED (t))
6874               {
6875                 DECL_VISIBILITY_SPECIFIED (r) = 0;
6876                 DECL_ATTRIBUTES (r)
6877                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
6878               }
6879             determine_visibility (r);
6880           }
6881
6882         if (!local_p)
6883           {
6884             /* A static data member declaration is always marked
6885                external when it is declared in-class, even if an
6886                initializer is present.  We mimic the non-template
6887                processing here.  */
6888             DECL_EXTERNAL (r) = 1;
6889
6890             register_specialization (r, gen_tmpl, argvec, false);
6891             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
6892             SET_DECL_IMPLICIT_INSTANTIATION (r);
6893           }
6894         else
6895           register_local_specialization (r, t);
6896
6897         TREE_CHAIN (r) = NULL_TREE;
6898         layout_decl (r, 0);
6899       }
6900       break;
6901
6902     default:
6903       gcc_unreachable ();
6904     }
6905
6906   /* Restore the file and line information.  */
6907   input_location = saved_loc;
6908
6909   return r;
6910 }
6911
6912 /* Substitute into the ARG_TYPES of a function type.  */
6913
6914 static tree
6915 tsubst_arg_types (tree arg_types,
6916                   tree args,
6917                   tsubst_flags_t complain,
6918                   tree in_decl)
6919 {
6920   tree remaining_arg_types;
6921   tree type;
6922   tree default_arg;
6923   tree result = NULL_TREE;
6924
6925   if (!arg_types || arg_types == void_list_node)
6926     return arg_types;
6927
6928   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
6929                                           args, complain, in_decl);
6930   if (remaining_arg_types == error_mark_node)
6931     return error_mark_node;
6932
6933   type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
6934   if (type == error_mark_node)
6935     return error_mark_node;
6936   if (VOID_TYPE_P (type))
6937     {
6938       if (complain & tf_error)
6939         {
6940           error ("invalid parameter type %qT", type);
6941           if (in_decl)
6942             error ("in declaration %q+D", in_decl);
6943         }
6944       return error_mark_node;
6945     }
6946
6947   /* Do array-to-pointer, function-to-pointer conversion, and ignore
6948      top-level qualifiers as required.  */
6949   type = TYPE_MAIN_VARIANT (type_decays_to (type));
6950
6951   /* We do not substitute into default arguments here.  The standard
6952      mandates that they be instantiated only when needed, which is
6953      done in build_over_call.  */
6954   default_arg = TREE_PURPOSE (arg_types);
6955
6956   if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
6957     {
6958       /* We've instantiated a template before its default arguments
6959          have been parsed.  This can happen for a nested template
6960          class, and is not an error unless we require the default
6961          argument in a call of this function.  */
6962       result = tree_cons (default_arg, type, remaining_arg_types);
6963       VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), result);
6964     }
6965   else
6966     result = hash_tree_cons (default_arg, type, remaining_arg_types);
6967
6968   return result;
6969 }
6970
6971 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
6972    *not* handle the exception-specification for FNTYPE, because the
6973    initial substitution of explicitly provided template parameters
6974    during argument deduction forbids substitution into the
6975    exception-specification:
6976
6977      [temp.deduct]
6978
6979      All references in the function type of the function template to  the
6980      corresponding template parameters are replaced by the specified tem-
6981      plate argument values.  If a substitution in a template parameter or
6982      in  the function type of the function template results in an invalid
6983      type, type deduction fails.  [Note: The equivalent  substitution  in
6984      exception specifications is done only when the function is instanti-
6985      ated, at which point a program is  ill-formed  if  the  substitution
6986      results in an invalid type.]  */
6987
6988 static tree
6989 tsubst_function_type (tree t,
6990                       tree args,
6991                       tsubst_flags_t complain,
6992                       tree in_decl)
6993 {
6994   tree return_type;
6995   tree arg_types;
6996   tree fntype;
6997
6998   /* The TYPE_CONTEXT is not used for function/method types.  */
6999   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
7000
7001   /* Substitute the return type.  */
7002   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7003   if (return_type == error_mark_node)
7004     return error_mark_node;
7005   /* The standard does not presently indicate that creation of a
7006      function type with an invalid return type is a deduction failure.
7007      However, that is clearly analogous to creating an array of "void"
7008      or a reference to a reference.  This is core issue #486.  */
7009   if (TREE_CODE (return_type) == ARRAY_TYPE
7010       || TREE_CODE (return_type) == FUNCTION_TYPE)
7011     {
7012       if (complain & tf_error)
7013         {
7014           if (TREE_CODE (return_type) == ARRAY_TYPE)
7015             error ("function returning an array");
7016           else
7017             error ("function returning a function");
7018         }
7019       return error_mark_node;
7020     }
7021
7022   /* Substitute the argument types.  */
7023   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
7024                                 complain, in_decl);
7025   if (arg_types == error_mark_node)
7026     return error_mark_node;
7027
7028   /* Construct a new type node and return it.  */
7029   if (TREE_CODE (t) == FUNCTION_TYPE)
7030     fntype = build_function_type (return_type, arg_types);
7031   else
7032     {
7033       tree r = TREE_TYPE (TREE_VALUE (arg_types));
7034       if (! IS_AGGR_TYPE (r))
7035         {
7036           /* [temp.deduct]
7037
7038              Type deduction may fail for any of the following
7039              reasons:
7040
7041              -- Attempting to create "pointer to member of T" when T
7042              is not a class type.  */
7043           if (complain & tf_error)
7044             error ("creating pointer to member function of non-class type %qT",
7045                       r);
7046           return error_mark_node;
7047         }
7048
7049       fntype = build_method_type_directly (r, return_type,
7050                                            TREE_CHAIN (arg_types));
7051     }
7052   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
7053   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
7054
7055   return fntype;
7056 }
7057
7058 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
7059    ARGS into that specification, and return the substituted
7060    specification.  If there is no specification, return NULL_TREE.  */
7061
7062 static tree
7063 tsubst_exception_specification (tree fntype,
7064                                 tree args,
7065                                 tsubst_flags_t complain,
7066                                 tree in_decl)
7067 {
7068   tree specs;
7069   tree new_specs;
7070
7071   specs = TYPE_RAISES_EXCEPTIONS (fntype);
7072   new_specs = NULL_TREE;
7073   if (specs)
7074     {
7075       if (! TREE_VALUE (specs))
7076         new_specs = specs;
7077       else
7078         while (specs)
7079           {
7080             tree spec;
7081             spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
7082             if (spec == error_mark_node)
7083               return spec;
7084             new_specs = add_exception_specifier (new_specs, spec, complain);
7085             specs = TREE_CHAIN (specs);
7086           }
7087     }
7088   return new_specs;
7089 }
7090
7091 /* Take the tree structure T and replace template parameters used
7092    therein with the argument vector ARGS.  IN_DECL is an associated
7093    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
7094    Issue error and warning messages under control of COMPLAIN.  Note
7095    that we must be relatively non-tolerant of extensions here, in
7096    order to preserve conformance; if we allow substitutions that
7097    should not be allowed, we may allow argument deductions that should
7098    not succeed, and therefore report ambiguous overload situations
7099    where there are none.  In theory, we could allow the substitution,
7100    but indicate that it should have failed, and allow our caller to
7101    make sure that the right thing happens, but we don't try to do this
7102    yet.
7103
7104    This function is used for dealing with types, decls and the like;
7105    for expressions, use tsubst_expr or tsubst_copy.  */
7106
7107 static tree
7108 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7109 {
7110   tree type, r;
7111
7112   if (t == NULL_TREE || t == error_mark_node
7113       || t == integer_type_node
7114       || t == void_type_node
7115       || t == char_type_node
7116       || t == unknown_type_node
7117       || TREE_CODE (t) == NAMESPACE_DECL)
7118     return t;
7119
7120   if (DECL_P (t))
7121     return tsubst_decl (t, args, complain);
7122
7123   if (TREE_CODE (t) == IDENTIFIER_NODE)
7124     type = IDENTIFIER_TYPE_VALUE (t);
7125   else
7126     type = TREE_TYPE (t);
7127
7128   gcc_assert (type != unknown_type_node);
7129
7130   if (type
7131       && TREE_CODE (t) != TYPENAME_TYPE
7132       && TREE_CODE (t) != IDENTIFIER_NODE
7133       && TREE_CODE (t) != FUNCTION_TYPE
7134       && TREE_CODE (t) != METHOD_TYPE)
7135     type = tsubst (type, args, complain, in_decl);
7136   if (type == error_mark_node)
7137     return error_mark_node;
7138
7139   switch (TREE_CODE (t))
7140     {
7141     case RECORD_TYPE:
7142     case UNION_TYPE:
7143     case ENUMERAL_TYPE:
7144       return tsubst_aggr_type (t, args, complain, in_decl,
7145                                /*entering_scope=*/0);
7146
7147     case ERROR_MARK:
7148     case IDENTIFIER_NODE:
7149     case VOID_TYPE:
7150     case REAL_TYPE:
7151     case COMPLEX_TYPE:
7152     case VECTOR_TYPE:
7153     case BOOLEAN_TYPE:
7154     case INTEGER_CST:
7155     case REAL_CST:
7156     case STRING_CST:
7157       return t;
7158
7159     case INTEGER_TYPE:
7160       if (t == integer_type_node)
7161         return t;
7162
7163       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
7164           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
7165         return t;
7166
7167       {
7168         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
7169
7170         /* The array dimension behaves like a non-type template arg,
7171            in that we want to fold it as much as possible.  */
7172         max = tsubst_template_arg (omax, args, complain, in_decl);
7173         max = fold_decl_constant_value (max);
7174
7175         /* [temp.deduct]
7176
7177            Type deduction may fail for any of the following
7178            reasons:
7179
7180              Attempting to create an array with a size that is
7181              zero or negative.  */
7182         if (integer_zerop (max) && !(complain & tf_error))
7183           /* We must fail if performing argument deduction (as
7184              indicated by the state of complain), so that
7185              another substitution can be found.  */
7186           return error_mark_node;
7187
7188         else if (TREE_CODE (max) == INTEGER_CST
7189                  && INT_CST_LT (max, integer_zero_node))
7190           {
7191             if (complain & tf_error)
7192               error ("creating array with negative size (%qE)", max);
7193
7194             return error_mark_node;
7195           }
7196
7197         return compute_array_index_type (NULL_TREE, max);
7198       }
7199
7200     case TEMPLATE_TYPE_PARM:
7201     case TEMPLATE_TEMPLATE_PARM:
7202     case BOUND_TEMPLATE_TEMPLATE_PARM:
7203     case TEMPLATE_PARM_INDEX:
7204       {
7205         int idx;
7206         int level;
7207         int levels;
7208         tree arg = NULL_TREE;
7209
7210         r = NULL_TREE;
7211
7212         gcc_assert (TREE_VEC_LENGTH (args) > 0);
7213         if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
7214             || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
7215             || TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
7216           {
7217             idx = TEMPLATE_TYPE_IDX (t);
7218             level = TEMPLATE_TYPE_LEVEL (t);
7219           }
7220         else
7221           {
7222             idx = TEMPLATE_PARM_IDX (t);
7223             level = TEMPLATE_PARM_LEVEL (t);
7224           }
7225
7226         levels = TMPL_ARGS_DEPTH (args);
7227         if (level <= levels)
7228           arg = TMPL_ARG (args, level, idx);
7229
7230         if (arg == error_mark_node)
7231           return error_mark_node;
7232         else if (arg != NULL_TREE)
7233           {
7234             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
7235               {
7236                 gcc_assert (TYPE_P (arg));
7237                 return cp_build_qualified_type_real
7238                   (arg, cp_type_quals (arg) | cp_type_quals (t),
7239                    complain | tf_ignore_bad_quals);
7240               }
7241             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
7242               {
7243                 /* We are processing a type constructed from a
7244                    template template parameter.  */
7245                 tree argvec = tsubst (TYPE_TI_ARGS (t),
7246                                       args, complain, in_decl);
7247                 if (argvec == error_mark_node)
7248                   return error_mark_node;
7249
7250                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
7251                    are resolving nested-types in the signature of a
7252                    member function templates.  Otherwise ARG is a
7253                    TEMPLATE_DECL and is the real template to be
7254                    instantiated.  */
7255                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
7256                   arg = TYPE_NAME (arg);
7257
7258                 r = lookup_template_class (arg,
7259                                            argvec, in_decl,
7260                                            DECL_CONTEXT (arg),
7261                                             /*entering_scope=*/0,
7262                                            complain);
7263                 return cp_build_qualified_type_real
7264                   (r, TYPE_QUALS (t), complain);
7265               }
7266             else
7267               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
7268               return arg;
7269           }
7270
7271         if (level == 1)
7272           /* This can happen during the attempted tsubst'ing in
7273              unify.  This means that we don't yet have any information
7274              about the template parameter in question.  */
7275           return t;
7276
7277         /* If we get here, we must have been looking at a parm for a
7278            more deeply nested template.  Make a new version of this
7279            template parameter, but with a lower level.  */
7280         switch (TREE_CODE (t))
7281           {
7282           case TEMPLATE_TYPE_PARM:
7283           case TEMPLATE_TEMPLATE_PARM:
7284           case BOUND_TEMPLATE_TEMPLATE_PARM:
7285             if (cp_type_quals (t))
7286               {
7287                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
7288                 r = cp_build_qualified_type_real
7289                   (r, cp_type_quals (t),
7290                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
7291                                ? tf_ignore_bad_quals : 0));
7292               }
7293             else
7294               {
7295                 r = copy_type (t);
7296                 TEMPLATE_TYPE_PARM_INDEX (r)
7297                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
7298                                                 r, levels);
7299                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
7300                 TYPE_MAIN_VARIANT (r) = r;
7301                 TYPE_POINTER_TO (r) = NULL_TREE;
7302                 TYPE_REFERENCE_TO (r) = NULL_TREE;
7303
7304                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
7305                   {
7306                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
7307                                           complain, in_decl);
7308                     if (argvec == error_mark_node)
7309                       return error_mark_node;
7310
7311                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
7312                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
7313                   }
7314               }
7315             break;
7316
7317           case TEMPLATE_PARM_INDEX:
7318             r = reduce_template_parm_level (t, type, levels);
7319             break;
7320
7321           default:
7322             gcc_unreachable ();
7323           }
7324
7325         return r;
7326       }
7327
7328     case TREE_LIST:
7329       {
7330         tree purpose, value, chain;
7331
7332         if (t == void_list_node)
7333           return t;
7334
7335         purpose = TREE_PURPOSE (t);
7336         if (purpose)
7337           {
7338             purpose = tsubst (purpose, args, complain, in_decl);
7339             if (purpose == error_mark_node)
7340               return error_mark_node;
7341           }
7342         value = TREE_VALUE (t);
7343         if (value)
7344           {
7345             value = tsubst (value, args, complain, in_decl);
7346             if (value == error_mark_node)
7347               return error_mark_node;
7348           }
7349         chain = TREE_CHAIN (t);
7350         if (chain && chain != void_type_node)
7351           {
7352             chain = tsubst (chain, args, complain, in_decl);
7353             if (chain == error_mark_node)
7354               return error_mark_node;
7355           }
7356         if (purpose == TREE_PURPOSE (t)
7357             && value == TREE_VALUE (t)
7358             && chain == TREE_CHAIN (t))
7359           return t;
7360         return hash_tree_cons (purpose, value, chain);
7361       }
7362
7363     case TREE_BINFO:
7364       /* We should never be tsubsting a binfo.  */
7365       gcc_unreachable ();
7366
7367     case TREE_VEC:
7368       /* A vector of template arguments.  */
7369       gcc_assert (!type);
7370       return tsubst_template_args (t, args, complain, in_decl);
7371
7372     case POINTER_TYPE:
7373     case REFERENCE_TYPE:
7374       {
7375         enum tree_code code;
7376
7377         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
7378           return t;
7379
7380         code = TREE_CODE (t);
7381
7382
7383         /* [temp.deduct]
7384
7385            Type deduction may fail for any of the following
7386            reasons:
7387
7388            -- Attempting to create a pointer to reference type.
7389            -- Attempting to create a reference to a reference type or
7390               a reference to void.  */
7391         if (TREE_CODE (type) == REFERENCE_TYPE
7392             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
7393           {
7394             static location_t last_loc;
7395
7396             /* We keep track of the last time we issued this error
7397                message to avoid spewing a ton of messages during a
7398                single bad template instantiation.  */
7399             if (complain & tf_error
7400 #ifdef USE_MAPPED_LOCATION
7401                 && last_loc != input_location
7402 #else
7403                 && (last_loc.line != input_line
7404                     || last_loc.file != input_filename)
7405 #endif
7406                   )
7407               {
7408                 if (TREE_CODE (type) == VOID_TYPE)
7409                   error ("forming reference to void");
7410                 else
7411                   error ("forming %s to reference type %qT",
7412                          (code == POINTER_TYPE) ? "pointer" : "reference",
7413                          type);
7414                 last_loc = input_location;
7415               }
7416
7417             return error_mark_node;
7418           }
7419         else if (code == POINTER_TYPE)
7420           {
7421             r = build_pointer_type (type);
7422             if (TREE_CODE (type) == METHOD_TYPE)
7423               r = build_ptrmemfunc_type (r);
7424           }
7425         else
7426           r = build_reference_type (type);
7427         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7428
7429         if (r != error_mark_node)
7430           /* Will this ever be needed for TYPE_..._TO values?  */
7431           layout_type (r);
7432
7433         return r;
7434       }
7435     case OFFSET_TYPE:
7436       {
7437         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
7438         if (r == error_mark_node || !IS_AGGR_TYPE (r))
7439           {
7440             /* [temp.deduct]
7441
7442                Type deduction may fail for any of the following
7443                reasons:
7444
7445                -- Attempting to create "pointer to member of T" when T
7446                   is not a class type.  */
7447             if (complain & tf_error)
7448               error ("creating pointer to member of non-class type %qT", r);
7449             return error_mark_node;
7450           }
7451         if (TREE_CODE (type) == REFERENCE_TYPE)
7452           {
7453             if (complain & tf_error)
7454               error ("creating pointer to member reference type %qT", type);
7455             return error_mark_node;
7456           }
7457         if (TREE_CODE (type) == VOID_TYPE)
7458           {
7459             if (complain & tf_error)
7460               error ("creating pointer to member of type void");
7461             return error_mark_node;
7462           }
7463         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
7464         if (TREE_CODE (type) == FUNCTION_TYPE)
7465           {
7466             /* The type of the implicit object parameter gets its
7467                cv-qualifiers from the FUNCTION_TYPE. */
7468             tree method_type;
7469             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
7470                                                       cp_type_quals (type));
7471             tree memptr;
7472             method_type = build_method_type_directly (this_type,
7473                                                       TREE_TYPE (type),
7474                                                       TYPE_ARG_TYPES (type));
7475             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
7476             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
7477                                                  complain);
7478           }
7479         else
7480           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
7481                                                TYPE_QUALS (t),
7482                                                complain);
7483       }
7484     case FUNCTION_TYPE:
7485     case METHOD_TYPE:
7486       {
7487         tree fntype;
7488         tree specs;
7489         fntype = tsubst_function_type (t, args, complain, in_decl);
7490         if (fntype == error_mark_node)
7491           return error_mark_node;
7492
7493         /* Substitute the exception specification.  */
7494         specs = tsubst_exception_specification (t, args, complain,
7495                                                 in_decl);
7496         if (specs == error_mark_node)
7497           return error_mark_node;
7498         if (specs)
7499           fntype = build_exception_variant (fntype, specs);
7500         return fntype;
7501       }
7502     case ARRAY_TYPE:
7503       {
7504         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
7505         if (domain == error_mark_node)
7506           return error_mark_node;
7507
7508         /* As an optimization, we avoid regenerating the array type if
7509            it will obviously be the same as T.  */
7510         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
7511           return t;
7512
7513         /* These checks should match the ones in grokdeclarator.
7514
7515            [temp.deduct]
7516
7517            The deduction may fail for any of the following reasons:
7518
7519            -- Attempting to create an array with an element type that
7520               is void, a function type, or a reference type, or [DR337]
7521               an abstract class type.  */
7522         if (TREE_CODE (type) == VOID_TYPE
7523             || TREE_CODE (type) == FUNCTION_TYPE
7524             || TREE_CODE (type) == REFERENCE_TYPE)
7525           {
7526             if (complain & tf_error)
7527               error ("creating array of %qT", type);
7528             return error_mark_node;
7529           }
7530         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
7531           {
7532             if (complain & tf_error)
7533               error ("creating array of %qT, which is an abstract class type",
7534                      type);
7535             return error_mark_node;
7536           }
7537
7538         r = build_cplus_array_type (type, domain);
7539         return r;
7540       }
7541
7542     case PLUS_EXPR:
7543     case MINUS_EXPR:
7544       {
7545         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7546         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
7547
7548         if (e1 == error_mark_node || e2 == error_mark_node)
7549           return error_mark_node;
7550
7551         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
7552       }
7553
7554     case NEGATE_EXPR:
7555     case NOP_EXPR:
7556       {
7557         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7558         if (e == error_mark_node)
7559           return error_mark_node;
7560
7561         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
7562       }
7563
7564     case TYPENAME_TYPE:
7565       {
7566         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
7567                                      in_decl, /*entering_scope=*/1);
7568         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
7569                               complain, in_decl);
7570
7571         if (ctx == error_mark_node || f == error_mark_node)
7572           return error_mark_node;
7573
7574         if (!IS_AGGR_TYPE (ctx))
7575           {
7576             if (complain & tf_error)
7577               error ("%qT is not a class, struct, or union type", ctx);
7578             return error_mark_node;
7579           }
7580         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
7581           {
7582             /* Normally, make_typename_type does not require that the CTX
7583                have complete type in order to allow things like:
7584
7585                  template <class T> struct S { typename S<T>::X Y; };
7586
7587                But, such constructs have already been resolved by this
7588                point, so here CTX really should have complete type, unless
7589                it's a partial instantiation.  */
7590             ctx = complete_type (ctx);
7591             if (!COMPLETE_TYPE_P (ctx))
7592               {
7593                 if (complain & tf_error)
7594                   cxx_incomplete_type_error (NULL_TREE, ctx);
7595                 return error_mark_node;
7596               }
7597           }
7598
7599         f = make_typename_type (ctx, f, typename_type,
7600                                 (complain & tf_error) | tf_keep_type_decl);
7601         if (f == error_mark_node)
7602           return f;
7603         if (TREE_CODE (f) == TYPE_DECL)
7604           {
7605             complain |= tf_ignore_bad_quals;
7606             f = TREE_TYPE (f);
7607           }
7608
7609         if (TREE_CODE (f) != TYPENAME_TYPE)
7610           {
7611             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
7612               error ("%qT resolves to %qT, which is not an enumeration type",
7613                      t, f);
7614             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
7615               error ("%qT resolves to %qT, which is is not a class type",
7616                      t, f);
7617           }
7618
7619         return cp_build_qualified_type_real
7620           (f, cp_type_quals (f) | cp_type_quals (t), complain);
7621       }
7622
7623     case UNBOUND_CLASS_TEMPLATE:
7624       {
7625         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
7626                                      in_decl, /*entering_scope=*/1);
7627         tree name = TYPE_IDENTIFIER (t);
7628         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
7629
7630         if (ctx == error_mark_node || name == error_mark_node)
7631           return error_mark_node;
7632
7633         if (parm_list)
7634           parm_list = tsubst_template_parms (parm_list, args, complain);
7635         return make_unbound_class_template (ctx, name, parm_list, complain);
7636       }
7637
7638     case INDIRECT_REF:
7639     case ADDR_EXPR:
7640     case CALL_EXPR:
7641       gcc_unreachable ();
7642
7643     case ARRAY_REF:
7644       {
7645         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7646         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
7647         if (e1 == error_mark_node || e2 == error_mark_node)
7648           return error_mark_node;
7649
7650         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
7651       }
7652
7653     case SCOPE_REF:
7654       {
7655         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
7656         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
7657         if (e1 == error_mark_node || e2 == error_mark_node)
7658           return error_mark_node;
7659
7660         return build_qualified_name (/*type=*/NULL_TREE,
7661                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
7662       }
7663
7664     case TYPEOF_TYPE:
7665       {
7666         tree type;
7667
7668         type = finish_typeof (tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
7669                                            complain, in_decl));
7670         return cp_build_qualified_type_real (type,
7671                                              cp_type_quals (t)
7672                                              | cp_type_quals (type),
7673                                              complain);
7674       }
7675
7676     default:
7677       sorry ("use of %qs in template",
7678              tree_code_name [(int) TREE_CODE (t)]);
7679       return error_mark_node;
7680     }
7681 }
7682
7683 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
7684    type of the expression on the left-hand side of the "." or "->"
7685    operator.  */
7686
7687 static tree
7688 tsubst_baselink (tree baselink, tree object_type,
7689                  tree args, tsubst_flags_t complain, tree in_decl)
7690 {
7691     tree name;
7692     tree qualifying_scope;
7693     tree fns;
7694     tree optype;
7695     tree template_args = 0;
7696     bool template_id_p = false;
7697
7698     /* A baselink indicates a function from a base class.  The
7699        BASELINK_ACCESS_BINFO and BASELINK_BINFO are going to have
7700        non-dependent types; otherwise, the lookup could not have
7701        succeeded.  However, they may indicate bases of the template
7702        class, rather than the instantiated class.
7703
7704        In addition, lookups that were not ambiguous before may be
7705        ambiguous now.  Therefore, we perform the lookup again.  */
7706     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
7707     fns = BASELINK_FUNCTIONS (baselink);
7708     optype = BASELINK_OPTYPE (baselink);
7709     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
7710       {
7711         template_id_p = true;
7712         template_args = TREE_OPERAND (fns, 1);
7713         fns = TREE_OPERAND (fns, 0);
7714         if (template_args)
7715           template_args = tsubst_template_args (template_args, args,
7716                                                 complain, in_decl);
7717       }
7718     name = DECL_NAME (get_first_fn (fns));
7719     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
7720
7721     /* If lookup found a single function, mark it as used at this
7722        point.  (If it lookup found multiple functions the one selected
7723        later by overload resolution will be marked as used at that
7724        point.)  */
7725     if (BASELINK_P (baselink))
7726       fns = BASELINK_FUNCTIONS (baselink);
7727     if (!template_id_p && !really_overloaded_fn (fns))
7728       mark_used (OVL_CURRENT (fns));
7729
7730     /* Add back the template arguments, if present.  */
7731     if (BASELINK_P (baselink) && template_id_p)
7732       BASELINK_FUNCTIONS (baselink)
7733         = build_nt (TEMPLATE_ID_EXPR,
7734                     BASELINK_FUNCTIONS (baselink),
7735                     template_args);
7736     /* Update the conversion operator type.  */
7737     BASELINK_OPTYPE (baselink) 
7738       = tsubst (optype, args, complain, in_decl);
7739
7740     if (!object_type)
7741       object_type = current_class_type;
7742     return adjust_result_of_qualified_name_lookup (baselink,
7743                                                    qualifying_scope,
7744                                                    object_type);
7745 }
7746
7747 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
7748    true if the qualified-id will be a postfix-expression in-and-of
7749    itself; false if more of the postfix-expression follows the
7750    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
7751    of "&".  */
7752
7753 static tree
7754 tsubst_qualified_id (tree qualified_id, tree args,
7755                      tsubst_flags_t complain, tree in_decl,
7756                      bool done, bool address_p)
7757 {
7758   tree expr;
7759   tree scope;
7760   tree name;
7761   bool is_template;
7762   tree template_args;
7763
7764   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
7765
7766   /* Figure out what name to look up.  */
7767   name = TREE_OPERAND (qualified_id, 1);
7768   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
7769     {
7770       is_template = true;
7771       template_args = TREE_OPERAND (name, 1);
7772       if (template_args)
7773         template_args = tsubst_template_args (template_args, args,
7774                                               complain, in_decl);
7775       name = TREE_OPERAND (name, 0);
7776     }
7777   else
7778     {
7779       is_template = false;
7780       template_args = NULL_TREE;
7781     }
7782
7783   /* Substitute into the qualifying scope.  When there are no ARGS, we
7784      are just trying to simplify a non-dependent expression.  In that
7785      case the qualifying scope may be dependent, and, in any case,
7786      substituting will not help.  */
7787   scope = TREE_OPERAND (qualified_id, 0);
7788   if (args)
7789     {
7790       scope = tsubst (scope, args, complain, in_decl);
7791       expr = tsubst_copy (name, args, complain, in_decl);
7792     }
7793   else
7794     expr = name;
7795
7796   if (dependent_type_p (scope))
7797     return build_qualified_name (/*type=*/NULL_TREE,
7798                                  scope, expr,
7799                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
7800
7801   if (!BASELINK_P (name) && !DECL_P (expr))
7802     {
7803       if (TREE_CODE (expr) == BIT_NOT_EXPR)
7804         /* If this were actually a destructor call, it would have been
7805            parsed as such by the parser.  */
7806         expr = error_mark_node;
7807       else
7808         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
7809       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
7810                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
7811         {
7812           if (complain & tf_error)
7813             {
7814               error ("dependent-name %qE is parsed as a non-type, but "
7815                      "instantiation yields a type", qualified_id);
7816               inform ("say %<typename %E%> if a type is meant", qualified_id);
7817             }
7818           return error_mark_node;
7819         }
7820     }
7821
7822   if (DECL_P (expr))
7823     {
7824       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
7825                                            scope);
7826       /* Remember that there was a reference to this entity.  */
7827       mark_used (expr);
7828     }
7829
7830   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
7831     {
7832       if (complain & tf_error)
7833         qualified_name_lookup_error (scope,
7834                                      TREE_OPERAND (qualified_id, 1),
7835                                      expr);
7836       return error_mark_node;
7837     }
7838
7839   if (is_template)
7840     expr = lookup_template_function (expr, template_args);
7841
7842   if (expr == error_mark_node && complain & tf_error)
7843     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
7844                                  expr);
7845   else if (TYPE_P (scope))
7846     {
7847       expr = (adjust_result_of_qualified_name_lookup
7848               (expr, scope, current_class_type));
7849       expr = (finish_qualified_id_expr
7850               (scope, expr, done, address_p,
7851                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
7852                /*template_arg_p=*/false));
7853     }
7854
7855   if (TREE_CODE (expr) != SCOPE_REF)
7856     expr = convert_from_reference (expr);
7857
7858   return expr;
7859 }
7860
7861 /* Like tsubst, but deals with expressions.  This function just replaces
7862    template parms; to finish processing the resultant expression, use
7863    tsubst_expr.  */
7864
7865 static tree
7866 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7867 {
7868   enum tree_code code;
7869   tree r;
7870
7871   if (t == NULL_TREE || t == error_mark_node)
7872     return t;
7873
7874   code = TREE_CODE (t);
7875
7876   switch (code)
7877     {
7878     case PARM_DECL:
7879       r = retrieve_local_specialization (t);
7880       gcc_assert (r != NULL);
7881       mark_used (r);
7882       return r;
7883
7884     case CONST_DECL:
7885       {
7886         tree enum_type;
7887         tree v;
7888
7889         if (DECL_TEMPLATE_PARM_P (t))
7890           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
7891         /* There is no need to substitute into namespace-scope
7892            enumerators.  */
7893         if (DECL_NAMESPACE_SCOPE_P (t))
7894           return t;
7895         /* If ARGS is NULL, then T is known to be non-dependent.  */
7896         if (args == NULL_TREE)
7897           return integral_constant_value (t);
7898
7899         /* Unfortunately, we cannot just call lookup_name here.
7900            Consider:
7901
7902              template <int I> int f() {
7903              enum E { a = I };
7904              struct S { void g() { E e = a; } };
7905              };
7906
7907            When we instantiate f<7>::S::g(), say, lookup_name is not
7908            clever enough to find f<7>::a.  */
7909         enum_type
7910           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
7911                               /*entering_scope=*/0);
7912
7913         for (v = TYPE_VALUES (enum_type);
7914              v != NULL_TREE;
7915              v = TREE_CHAIN (v))
7916           if (TREE_PURPOSE (v) == DECL_NAME (t))
7917             return TREE_VALUE (v);
7918
7919           /* We didn't find the name.  That should never happen; if
7920              name-lookup found it during preliminary parsing, we
7921              should find it again here during instantiation.  */
7922         gcc_unreachable ();
7923       }
7924       return t;
7925
7926     case FIELD_DECL:
7927       if (DECL_CONTEXT (t))
7928         {
7929           tree ctx;
7930
7931           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
7932                                   /*entering_scope=*/1);
7933           if (ctx != DECL_CONTEXT (t))
7934             {
7935               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
7936               if (!r)
7937                 {
7938                   if (complain & tf_error)
7939                     error ("using invalid field %qD", t);
7940                   return error_mark_node;
7941                 }
7942               return r;
7943             }
7944         }
7945
7946       return t;
7947
7948     case VAR_DECL:
7949     case FUNCTION_DECL:
7950       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
7951           || local_variable_p (t))
7952         t = tsubst (t, args, complain, in_decl);
7953       mark_used (t);
7954       return t;
7955
7956     case BASELINK:
7957       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
7958
7959     case TEMPLATE_DECL:
7960       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
7961         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
7962                        args, complain, in_decl);
7963       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
7964         return tsubst (t, args, complain, in_decl);
7965       else if (DECL_CLASS_SCOPE_P (t)
7966                && uses_template_parms (DECL_CONTEXT (t)))
7967         {
7968           /* Template template argument like the following example need
7969              special treatment:
7970
7971                template <template <class> class TT> struct C {};
7972                template <class T> struct D {
7973                  template <class U> struct E {};
7974                  C<E> c;                                // #1
7975                };
7976                D<int> d;                                // #2
7977
7978              We are processing the template argument `E' in #1 for
7979              the template instantiation #2.  Originally, `E' is a
7980              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
7981              have to substitute this with one having context `D<int>'.  */
7982
7983           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
7984           return lookup_field (context, DECL_NAME(t), 0, false);
7985         }
7986       else
7987         /* Ordinary template template argument.  */
7988         return t;
7989
7990     case CAST_EXPR:
7991     case REINTERPRET_CAST_EXPR:
7992     case CONST_CAST_EXPR:
7993     case STATIC_CAST_EXPR:
7994     case DYNAMIC_CAST_EXPR:
7995     case NOP_EXPR:
7996       return build1
7997         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
7998          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
7999
8000     case INDIRECT_REF:
8001     case NEGATE_EXPR:
8002     case TRUTH_NOT_EXPR:
8003     case BIT_NOT_EXPR:
8004     case ADDR_EXPR:
8005     case UNARY_PLUS_EXPR:      /* Unary + */
8006     case SIZEOF_EXPR:
8007     case ALIGNOF_EXPR:
8008     case ARROW_EXPR:
8009     case THROW_EXPR:
8010     case TYPEID_EXPR:
8011     case REALPART_EXPR:
8012     case IMAGPART_EXPR:
8013       return build1
8014         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
8015          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
8016
8017     case COMPONENT_REF:
8018       {
8019         tree object;
8020         tree name;
8021
8022         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
8023         name = TREE_OPERAND (t, 1);
8024         if (TREE_CODE (name) == BIT_NOT_EXPR)
8025           {
8026             name = tsubst_copy (TREE_OPERAND (name, 0), args,
8027                                 complain, in_decl);
8028             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
8029           }
8030         else if (TREE_CODE (name) == SCOPE_REF
8031                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
8032           {
8033             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
8034                                      complain, in_decl);
8035             name = TREE_OPERAND (name, 1);
8036             name = tsubst_copy (TREE_OPERAND (name, 0), args,
8037                                 complain, in_decl);
8038             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
8039             name = build_qualified_name (/*type=*/NULL_TREE,
8040                                          base, name,
8041                                          /*template_p=*/false);
8042           }
8043         else if (TREE_CODE (name) == BASELINK)
8044           name = tsubst_baselink (name,
8045                                   non_reference (TREE_TYPE (object)),
8046                                   args, complain,
8047                                   in_decl);
8048         else
8049           name = tsubst_copy (name, args, complain, in_decl);
8050         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
8051       }
8052
8053     case PLUS_EXPR:
8054     case MINUS_EXPR:
8055     case MULT_EXPR:
8056     case TRUNC_DIV_EXPR:
8057     case CEIL_DIV_EXPR:
8058     case FLOOR_DIV_EXPR:
8059     case ROUND_DIV_EXPR:
8060     case EXACT_DIV_EXPR:
8061     case BIT_AND_EXPR:
8062     case BIT_IOR_EXPR:
8063     case BIT_XOR_EXPR:
8064     case TRUNC_MOD_EXPR:
8065     case FLOOR_MOD_EXPR:
8066     case TRUTH_ANDIF_EXPR:
8067     case TRUTH_ORIF_EXPR:
8068     case TRUTH_AND_EXPR:
8069     case TRUTH_OR_EXPR:
8070     case RSHIFT_EXPR:
8071     case LSHIFT_EXPR:
8072     case RROTATE_EXPR:
8073     case LROTATE_EXPR:
8074     case EQ_EXPR:
8075     case NE_EXPR:
8076     case MAX_EXPR:
8077     case MIN_EXPR:
8078     case LE_EXPR:
8079     case GE_EXPR:
8080     case LT_EXPR:
8081     case GT_EXPR:
8082     case COMPOUND_EXPR:
8083     case DOTSTAR_EXPR:
8084     case MEMBER_REF:
8085     case PREDECREMENT_EXPR:
8086     case PREINCREMENT_EXPR:
8087     case POSTDECREMENT_EXPR:
8088     case POSTINCREMENT_EXPR:
8089       return build_nt
8090         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8091          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
8092
8093     case SCOPE_REF:
8094       return build_qualified_name (/*type=*/NULL_TREE,
8095                                    tsubst_copy (TREE_OPERAND (t, 0),
8096                                                 args, complain, in_decl),
8097                                    tsubst_copy (TREE_OPERAND (t, 1),
8098                                                 args, complain, in_decl),
8099                                    QUALIFIED_NAME_IS_TEMPLATE (t));
8100
8101     case ARRAY_REF:
8102       return build_nt
8103         (ARRAY_REF,
8104          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8105          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
8106          NULL_TREE, NULL_TREE);
8107
8108     case CALL_EXPR:
8109       return build_nt (code,
8110                        tsubst_copy (TREE_OPERAND (t, 0), args,
8111                                     complain, in_decl),
8112                        tsubst_copy (TREE_OPERAND (t, 1), args, complain,
8113                                     in_decl),
8114                        NULL_TREE);
8115
8116     case COND_EXPR:
8117     case MODOP_EXPR:
8118     case PSEUDO_DTOR_EXPR:
8119       {
8120         r = build_nt
8121           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8122            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
8123            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
8124         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
8125         return r;
8126       }
8127
8128     case NEW_EXPR:
8129       {
8130         r = build_nt
8131         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8132          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
8133          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
8134         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
8135         return r;
8136       }
8137
8138     case DELETE_EXPR:
8139       {
8140         r = build_nt
8141         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
8142          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
8143         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
8144         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
8145         return r;
8146       }
8147
8148     case TEMPLATE_ID_EXPR:
8149       {
8150         /* Substituted template arguments */
8151         tree fn = TREE_OPERAND (t, 0);
8152         tree targs = TREE_OPERAND (t, 1);
8153
8154         fn = tsubst_copy (fn, args, complain, in_decl);
8155         if (targs)
8156           targs = tsubst_template_args (targs, args, complain, in_decl);
8157
8158         return lookup_template_function (fn, targs);
8159       }
8160
8161     case TREE_LIST:
8162       {
8163         tree purpose, value, chain;
8164
8165         if (t == void_list_node)
8166           return t;
8167
8168         purpose = TREE_PURPOSE (t);
8169         if (purpose)
8170           purpose = tsubst_copy (purpose, args, complain, in_decl);
8171         value = TREE_VALUE (t);
8172         if (value)
8173           value = tsubst_copy (value, args, complain, in_decl);
8174         chain = TREE_CHAIN (t);
8175         if (chain && chain != void_type_node)
8176           chain = tsubst_copy (chain, args, complain, in_decl);
8177         if (purpose == TREE_PURPOSE (t)
8178             && value == TREE_VALUE (t)
8179             && chain == TREE_CHAIN (t))
8180           return t;
8181         return tree_cons (purpose, value, chain);
8182       }
8183
8184     case RECORD_TYPE:
8185     case UNION_TYPE:
8186     case ENUMERAL_TYPE:
8187     case INTEGER_TYPE:
8188     case TEMPLATE_TYPE_PARM:
8189     case TEMPLATE_TEMPLATE_PARM:
8190     case BOUND_TEMPLATE_TEMPLATE_PARM:
8191     case TEMPLATE_PARM_INDEX:
8192     case POINTER_TYPE:
8193     case REFERENCE_TYPE:
8194     case OFFSET_TYPE:
8195     case FUNCTION_TYPE:
8196     case METHOD_TYPE:
8197     case ARRAY_TYPE:
8198     case TYPENAME_TYPE:
8199     case UNBOUND_CLASS_TEMPLATE:
8200     case TYPEOF_TYPE:
8201     case TYPE_DECL:
8202       return tsubst (t, args, complain, in_decl);
8203
8204     case IDENTIFIER_NODE:
8205       if (IDENTIFIER_TYPENAME_P (t))
8206         {
8207           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8208           return mangle_conv_op_name_for_type (new_type);
8209         }
8210       else
8211         return t;
8212
8213     case CONSTRUCTOR:
8214       /* This is handled by tsubst_copy_and_build.  */
8215       gcc_unreachable ();
8216
8217     case VA_ARG_EXPR:
8218       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
8219                                           in_decl),
8220                              tsubst (TREE_TYPE (t), args, complain, in_decl));
8221
8222     case CLEANUP_POINT_EXPR:
8223       /* We shouldn't have built any of these during initial template
8224          generation.  Instead, they should be built during instantiation
8225          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
8226       gcc_unreachable ();
8227
8228     case OFFSET_REF:
8229       mark_used (TREE_OPERAND (t, 1));
8230       return t;
8231
8232     default:
8233       return t;
8234     }
8235 }
8236
8237 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
8238
8239 static tree
8240 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
8241                     tree in_decl)
8242 {
8243   tree new_clauses = NULL, nc, oc;
8244
8245   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
8246     {
8247       nc = copy_node (oc);
8248       OMP_CLAUSE_CHAIN (nc) = new_clauses;
8249       new_clauses = nc;
8250
8251       switch (OMP_CLAUSE_CODE (nc))
8252         {
8253         case OMP_CLAUSE_PRIVATE:
8254         case OMP_CLAUSE_SHARED:
8255         case OMP_CLAUSE_FIRSTPRIVATE:
8256         case OMP_CLAUSE_LASTPRIVATE:
8257         case OMP_CLAUSE_REDUCTION:
8258         case OMP_CLAUSE_COPYIN:
8259         case OMP_CLAUSE_COPYPRIVATE:
8260         case OMP_CLAUSE_IF:
8261         case OMP_CLAUSE_NUM_THREADS:
8262         case OMP_CLAUSE_SCHEDULE:
8263           OMP_CLAUSE_OPERAND (nc, 0)
8264             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, in_decl);
8265           break;
8266         case OMP_CLAUSE_NOWAIT:
8267         case OMP_CLAUSE_ORDERED:
8268         case OMP_CLAUSE_DEFAULT:
8269           break;
8270         default:
8271           gcc_unreachable ();
8272         }
8273     }
8274
8275   return finish_omp_clauses (nreverse (new_clauses));
8276 }
8277
8278 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
8279
8280 static tree
8281 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
8282                           tree in_decl)
8283 {
8284 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
8285
8286   tree purpose, value, chain;
8287
8288   if (t == NULL)
8289     return t;
8290
8291   if (TREE_CODE (t) != TREE_LIST)
8292     return tsubst_copy_and_build (t, args, complain, in_decl,
8293                                   /*function_p=*/false);
8294
8295   if (t == void_list_node)
8296     return t;
8297
8298   purpose = TREE_PURPOSE (t);
8299   if (purpose)
8300     purpose = RECUR (purpose);
8301   value = TREE_VALUE (t);
8302   if (value)
8303     value = RECUR (value);
8304   chain = TREE_CHAIN (t);
8305   if (chain && chain != void_type_node)
8306     chain = RECUR (chain);
8307   return tree_cons (purpose, value, chain);
8308 #undef RECUR
8309 }
8310
8311 /* Like tsubst_copy for expressions, etc. but also does semantic
8312    processing.  */
8313
8314 static tree
8315 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8316 {
8317   tree stmt, tmp;
8318
8319   if (t == NULL_TREE || t == error_mark_node)
8320     return t;
8321
8322   if (EXPR_HAS_LOCATION (t))
8323     input_location = EXPR_LOCATION (t);
8324   if (STATEMENT_CODE_P (TREE_CODE (t)))
8325     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
8326
8327   switch (TREE_CODE (t))
8328     {
8329     case STATEMENT_LIST:
8330       {
8331         tree_stmt_iterator i;
8332         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
8333           tsubst_expr (tsi_stmt (i), args, complain, in_decl);
8334         break;
8335       }
8336
8337     case CTOR_INITIALIZER:
8338       finish_mem_initializers (tsubst_initializer_list
8339                                (TREE_OPERAND (t, 0), args));
8340       break;
8341
8342     case RETURN_EXPR:
8343       finish_return_stmt (tsubst_expr (TREE_OPERAND (t, 0),
8344                                        args, complain, in_decl));
8345       break;
8346
8347     case EXPR_STMT:
8348       tmp = tsubst_expr (EXPR_STMT_EXPR (t), args, complain, in_decl);
8349       if (EXPR_STMT_STMT_EXPR_RESULT (t))
8350         finish_stmt_expr_expr (tmp, cur_stmt_expr);
8351       else
8352         finish_expr_stmt (tmp);
8353       break;
8354
8355     case USING_STMT:
8356       do_using_directive (tsubst_expr (USING_STMT_NAMESPACE (t),
8357                                        args, complain, in_decl));
8358       break;
8359
8360     case DECL_EXPR:
8361       {
8362         tree decl;
8363         tree init;
8364
8365         decl = DECL_EXPR_DECL (t);
8366         if (TREE_CODE (decl) == LABEL_DECL)
8367           finish_label_decl (DECL_NAME (decl));
8368         else if (TREE_CODE (decl) == USING_DECL)
8369           {
8370             tree scope = USING_DECL_SCOPE (decl);
8371             tree name = DECL_NAME (decl);
8372             tree decl;
8373
8374             scope = tsubst_expr (scope, args, complain, in_decl);
8375             decl = lookup_qualified_name (scope, name,
8376                                           /*is_type_p=*/false,
8377                                           /*complain=*/false);
8378             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
8379               qualified_name_lookup_error (scope, name, decl);
8380             else
8381               do_local_using_decl (decl, scope, name);
8382           }
8383         else
8384           {
8385             init = DECL_INITIAL (decl);
8386             decl = tsubst (decl, args, complain, in_decl);
8387             if (decl != error_mark_node)
8388               {
8389                 /* By marking the declaration as instantiated, we avoid
8390                    trying to instantiate it.  Since instantiate_decl can't
8391                    handle local variables, and since we've already done
8392                    all that needs to be done, that's the right thing to
8393                    do.  */
8394                 if (TREE_CODE (decl) == VAR_DECL)
8395                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
8396                 if (TREE_CODE (decl) == VAR_DECL
8397                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
8398                   /* Anonymous aggregates are a special case.  */
8399                   finish_anon_union (decl);
8400                 else
8401                   {
8402                     maybe_push_decl (decl);
8403                     if (TREE_CODE (decl) == VAR_DECL
8404                         && DECL_PRETTY_FUNCTION_P (decl))
8405                       {
8406                         /* For __PRETTY_FUNCTION__ we have to adjust the
8407                            initializer.  */
8408                         const char *const name
8409                           = cxx_printable_name (current_function_decl, 2);
8410                         init = cp_fname_init (name, &TREE_TYPE (decl));
8411                       }
8412                     else
8413                       init = tsubst_expr (init, args, complain, in_decl);
8414                     finish_decl (decl, init, NULL_TREE);
8415                   }
8416               }
8417           }
8418
8419         /* A DECL_EXPR can also be used as an expression, in the condition
8420            clause of an if/for/while construct.  */
8421         return decl;
8422       }
8423
8424     case FOR_STMT:
8425       stmt = begin_for_stmt ();
8426       tsubst_expr (FOR_INIT_STMT (t), args, complain, in_decl);
8427       finish_for_init_stmt (stmt);
8428       tmp = tsubst_expr (FOR_COND (t), args, complain, in_decl);
8429       finish_for_cond (tmp, stmt);
8430       tmp = tsubst_expr (FOR_EXPR (t), args, complain, in_decl);
8431       finish_for_expr (tmp, stmt);
8432       tsubst_expr (FOR_BODY (t), args, complain, in_decl);
8433       finish_for_stmt (stmt);
8434       break;
8435
8436     case WHILE_STMT:
8437       stmt = begin_while_stmt ();
8438       tmp = tsubst_expr (WHILE_COND (t), args, complain, in_decl);
8439       finish_while_stmt_cond (tmp, stmt);
8440       tsubst_expr (WHILE_BODY (t), args, complain, in_decl);
8441       finish_while_stmt (stmt);
8442       break;
8443
8444     case DO_STMT:
8445       stmt = begin_do_stmt ();
8446       tsubst_expr (DO_BODY (t), args, complain, in_decl);
8447       finish_do_body (stmt);
8448       tmp = tsubst_expr (DO_COND (t), args, complain, in_decl);
8449       finish_do_stmt (tmp, stmt);
8450       break;
8451
8452     case IF_STMT:
8453       stmt = begin_if_stmt ();
8454       tmp = tsubst_expr (IF_COND (t), args, complain, in_decl);
8455       finish_if_stmt_cond (tmp, stmt);
8456       tsubst_expr (THEN_CLAUSE (t), args, complain, in_decl);
8457       finish_then_clause (stmt);
8458
8459       if (ELSE_CLAUSE (t))
8460         {
8461           begin_else_clause (stmt);
8462           tsubst_expr (ELSE_CLAUSE (t), args, complain, in_decl);
8463           finish_else_clause (stmt);
8464         }
8465
8466       finish_if_stmt (stmt);
8467       break;
8468
8469     case BIND_EXPR:
8470       if (BIND_EXPR_BODY_BLOCK (t))
8471         stmt = begin_function_body ();
8472       else
8473         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
8474                                     ? BCS_TRY_BLOCK : 0);
8475
8476       tsubst_expr (BIND_EXPR_BODY (t), args, complain, in_decl);
8477
8478       if (BIND_EXPR_BODY_BLOCK (t))
8479         finish_function_body (stmt);
8480       else
8481         finish_compound_stmt (stmt);
8482       break;
8483
8484     case BREAK_STMT:
8485       finish_break_stmt ();
8486       break;
8487
8488     case CONTINUE_STMT:
8489       finish_continue_stmt ();
8490       break;
8491
8492     case SWITCH_STMT:
8493       stmt = begin_switch_stmt ();
8494       tmp = tsubst_expr (SWITCH_STMT_COND (t), args, complain, in_decl);
8495       finish_switch_cond (tmp, stmt);
8496       tsubst_expr (SWITCH_STMT_BODY (t), args, complain, in_decl);
8497       finish_switch_stmt (stmt);
8498       break;
8499
8500     case CASE_LABEL_EXPR:
8501       finish_case_label (tsubst_expr (CASE_LOW (t), args, complain, in_decl),
8502                          tsubst_expr (CASE_HIGH (t), args, complain,
8503                                       in_decl));
8504       break;
8505
8506     case LABEL_EXPR:
8507       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
8508       break;
8509
8510     case GOTO_EXPR:
8511       tmp = GOTO_DESTINATION (t);
8512       if (TREE_CODE (tmp) != LABEL_DECL)
8513         /* Computed goto's must be tsubst'd into.  On the other hand,
8514            non-computed gotos must not be; the identifier in question
8515            will have no binding.  */
8516         tmp = tsubst_expr (tmp, args, complain, in_decl);
8517       else
8518         tmp = DECL_NAME (tmp);
8519       finish_goto_stmt (tmp);
8520       break;
8521
8522     case ASM_EXPR:
8523       tmp = finish_asm_stmt
8524         (ASM_VOLATILE_P (t),
8525          tsubst_expr (ASM_STRING (t), args, complain, in_decl),
8526          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
8527          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
8528          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
8529       {
8530         tree asm_expr = tmp;
8531         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
8532           asm_expr = TREE_OPERAND (asm_expr, 0);
8533         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
8534       }
8535       break;
8536
8537     case TRY_BLOCK:
8538       if (CLEANUP_P (t))
8539         {
8540           stmt = begin_try_block ();
8541           tsubst_expr (TRY_STMTS (t), args, complain, in_decl);
8542           finish_cleanup_try_block (stmt);
8543           finish_cleanup (tsubst_expr (TRY_HANDLERS (t), args,
8544                                        complain, in_decl),
8545                           stmt);
8546         }
8547       else
8548         {
8549           tree compound_stmt = NULL_TREE;
8550
8551           if (FN_TRY_BLOCK_P (t))
8552             stmt = begin_function_try_block (&compound_stmt);
8553           else
8554             stmt = begin_try_block ();
8555
8556           tsubst_expr (TRY_STMTS (t), args, complain, in_decl);
8557
8558           if (FN_TRY_BLOCK_P (t))
8559             finish_function_try_block (stmt);
8560           else
8561             finish_try_block (stmt);
8562
8563           tsubst_expr (TRY_HANDLERS (t), args, complain, in_decl);
8564           if (FN_TRY_BLOCK_P (t))
8565             finish_function_handler_sequence (stmt, compound_stmt);
8566           else
8567             finish_handler_sequence (stmt);
8568         }
8569       break;
8570
8571     case HANDLER:
8572       {
8573         tree decl = HANDLER_PARMS (t);
8574
8575         if (decl)
8576           {
8577             decl = tsubst (decl, args, complain, in_decl);
8578             /* Prevent instantiate_decl from trying to instantiate
8579                this variable.  We've already done all that needs to be
8580                done.  */
8581             if (decl != error_mark_node)
8582               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
8583           }
8584         stmt = begin_handler ();
8585         finish_handler_parms (decl, stmt);
8586         tsubst_expr (HANDLER_BODY (t), args, complain, in_decl);
8587         finish_handler (stmt);
8588       }
8589       break;
8590
8591     case TAG_DEFN:
8592       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
8593       break;
8594
8595     case OMP_PARALLEL:
8596       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
8597                                 args, complain, in_decl);
8598       stmt = begin_omp_parallel ();
8599       tsubst_expr (OMP_PARALLEL_BODY (t), args, complain, in_decl);
8600       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
8601         = OMP_PARALLEL_COMBINED (t);
8602       break;
8603
8604     case OMP_FOR:
8605       {
8606         tree clauses, decl, init, cond, incr, body, pre_body;
8607
8608         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
8609                                       args, complain, in_decl);
8610         init = OMP_FOR_INIT (t);
8611         gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
8612         decl = tsubst_expr (TREE_OPERAND (init, 0), args, complain, in_decl);
8613         init = tsubst_expr (TREE_OPERAND (init, 1), args, complain, in_decl);
8614         cond = tsubst_expr (OMP_FOR_COND (t), args, complain, in_decl);
8615         incr = tsubst_expr (OMP_FOR_INCR (t), args, complain, in_decl);
8616
8617         stmt = begin_omp_structured_block ();
8618
8619         pre_body = push_stmt_list ();
8620         tsubst_expr (OMP_FOR_PRE_BODY (t), args, complain, in_decl);
8621         pre_body = pop_stmt_list (pre_body);
8622
8623         body = push_stmt_list ();
8624         tsubst_expr (OMP_FOR_BODY (t), args, complain, in_decl);
8625         body = pop_stmt_list (body);
8626
8627         t = finish_omp_for (EXPR_LOCATION (t), decl, init, cond, incr, body,
8628                             pre_body);
8629         if (t)
8630           OMP_FOR_CLAUSES (t) = clauses;
8631
8632         add_stmt (finish_omp_structured_block (stmt));
8633       }
8634       break;
8635
8636     case OMP_SECTIONS:
8637     case OMP_SINGLE:
8638       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
8639       stmt = push_stmt_list ();
8640       tsubst_expr (OMP_BODY (t), args, complain, in_decl);
8641       stmt = pop_stmt_list (stmt);
8642
8643       t = copy_node (t);
8644       OMP_BODY (t) = stmt;
8645       OMP_CLAUSES (t) = tmp;
8646       add_stmt (t);
8647       break;
8648
8649     case OMP_SECTION:
8650     case OMP_CRITICAL:
8651     case OMP_MASTER:
8652     case OMP_ORDERED:
8653       stmt = push_stmt_list ();
8654       tsubst_expr (OMP_BODY (t), args, complain, in_decl);
8655       stmt = pop_stmt_list (stmt);
8656
8657       t = copy_node (t);
8658       OMP_BODY (t) = stmt;
8659       add_stmt (t);
8660       break;
8661
8662     case OMP_ATOMIC:
8663       {
8664         tree op0, op1;
8665         op0 = tsubst_expr (TREE_OPERAND (t, 0), args, complain, in_decl);
8666         op1 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
8667         finish_omp_atomic (OMP_ATOMIC_CODE (t), op0, op1);
8668       }
8669       break;
8670
8671     default:
8672       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
8673
8674       return tsubst_copy_and_build (t, args, complain, in_decl,
8675                                     /*function_p=*/false);
8676     }
8677
8678   return NULL_TREE;
8679 }
8680
8681 /* T is a postfix-expression that is not being used in a function
8682    call.  Return the substituted version of T.  */
8683
8684 static tree
8685 tsubst_non_call_postfix_expression (tree t, tree args,
8686                                     tsubst_flags_t complain,
8687                                     tree in_decl)
8688 {
8689   if (TREE_CODE (t) == SCOPE_REF)
8690     t = tsubst_qualified_id (t, args, complain, in_decl,
8691                              /*done=*/false, /*address_p=*/false);
8692   else
8693     t = tsubst_copy_and_build (t, args, complain, in_decl,
8694                                /*function_p=*/false);
8695
8696   return t;
8697 }
8698
8699 /* Like tsubst but deals with expressions and performs semantic
8700    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
8701
8702 tree
8703 tsubst_copy_and_build (tree t,
8704                        tree args,
8705                        tsubst_flags_t complain,
8706                        tree in_decl,
8707                        bool function_p)
8708 {
8709 #define RECUR(NODE) \
8710   tsubst_copy_and_build (NODE, args, complain, in_decl, /*function_p=*/false)
8711
8712   tree op1;
8713
8714   if (t == NULL_TREE || t == error_mark_node)
8715     return t;
8716
8717   switch (TREE_CODE (t))
8718     {
8719     case USING_DECL:
8720       t = DECL_NAME (t);
8721       /* Fall through.  */
8722     case IDENTIFIER_NODE:
8723       {
8724         tree decl;
8725         cp_id_kind idk;
8726         bool non_integral_constant_expression_p;
8727         const char *error_msg;
8728
8729         if (IDENTIFIER_TYPENAME_P (t))
8730           {
8731             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8732             t = mangle_conv_op_name_for_type (new_type);
8733           }
8734
8735         /* Look up the name.  */
8736         decl = lookup_name (t);
8737
8738         /* By convention, expressions use ERROR_MARK_NODE to indicate
8739            failure, not NULL_TREE.  */
8740         if (decl == NULL_TREE)
8741           decl = error_mark_node;
8742
8743         decl = finish_id_expression (t, decl, NULL_TREE,
8744                                      &idk,
8745                                      /*integral_constant_expression_p=*/false,
8746                                      /*allow_non_integral_constant_expression_p=*/false,
8747                                      &non_integral_constant_expression_p,
8748                                      /*template_p=*/false,
8749                                      /*done=*/true,
8750                                      /*address_p=*/false,
8751                                      /*template_arg_p=*/false,
8752                                      &error_msg);
8753         if (error_msg)
8754           error (error_msg);
8755         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
8756           decl = unqualified_name_lookup_error (decl);
8757         return decl;
8758       }
8759
8760     case TEMPLATE_ID_EXPR:
8761       {
8762         tree object;
8763         tree template = RECUR (TREE_OPERAND (t, 0));
8764         tree targs = TREE_OPERAND (t, 1);
8765
8766         if (targs)
8767           targs = tsubst_template_args (targs, args, complain, in_decl);
8768
8769         if (TREE_CODE (template) == COMPONENT_REF)
8770           {
8771             object = TREE_OPERAND (template, 0);
8772             template = TREE_OPERAND (template, 1);
8773           }
8774         else
8775           object = NULL_TREE;
8776         template = lookup_template_function (template, targs);
8777
8778         if (object)
8779           return build3 (COMPONENT_REF, TREE_TYPE (template),
8780                          object, template, NULL_TREE);
8781         else
8782           return template;
8783       }
8784
8785     case INDIRECT_REF:
8786       {
8787         tree r = RECUR (TREE_OPERAND (t, 0));
8788
8789         if (REFERENCE_REF_P (t))
8790           {
8791             /* A type conversion to reference type will be enclosed in
8792                such an indirect ref, but the substitution of the cast
8793                will have also added such an indirect ref.  */
8794             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
8795               r = convert_from_reference (r);
8796           }
8797         else
8798           r = build_x_indirect_ref (r, "unary *");
8799         return r;
8800       }
8801
8802     case NOP_EXPR:
8803       return build_nop
8804         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8805          RECUR (TREE_OPERAND (t, 0)));
8806
8807     case CAST_EXPR:
8808       return build_functional_cast
8809         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8810          RECUR (TREE_OPERAND (t, 0)));
8811
8812     case REINTERPRET_CAST_EXPR:
8813       return build_reinterpret_cast
8814         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8815          RECUR (TREE_OPERAND (t, 0)));
8816
8817     case CONST_CAST_EXPR:
8818       return build_const_cast
8819         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8820          RECUR (TREE_OPERAND (t, 0)));
8821
8822     case DYNAMIC_CAST_EXPR:
8823       return build_dynamic_cast
8824         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8825          RECUR (TREE_OPERAND (t, 0)));
8826
8827     case STATIC_CAST_EXPR:
8828       return build_static_cast
8829         (tsubst (TREE_TYPE (t), args, complain, in_decl),
8830          RECUR (TREE_OPERAND (t, 0)));
8831
8832     case POSTDECREMENT_EXPR:
8833     case POSTINCREMENT_EXPR:
8834       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
8835                                                 args, complain, in_decl);
8836       return build_x_unary_op (TREE_CODE (t), op1);
8837
8838     case PREDECREMENT_EXPR:
8839     case PREINCREMENT_EXPR:
8840     case NEGATE_EXPR:
8841     case BIT_NOT_EXPR:
8842     case ABS_EXPR:
8843     case TRUTH_NOT_EXPR:
8844     case UNARY_PLUS_EXPR:  /* Unary + */
8845     case REALPART_EXPR:
8846     case IMAGPART_EXPR:
8847       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)));
8848
8849     case ADDR_EXPR:
8850       op1 = TREE_OPERAND (t, 0);
8851       if (TREE_CODE (op1) == SCOPE_REF)
8852         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
8853                                    /*done=*/true, /*address_p=*/true);
8854       else
8855         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
8856                                                   in_decl);
8857       if (TREE_CODE (op1) == LABEL_DECL)
8858         return finish_label_address_expr (DECL_NAME (op1));
8859       return build_x_unary_op (ADDR_EXPR, op1);
8860
8861     case PLUS_EXPR:
8862     case MINUS_EXPR:
8863     case MULT_EXPR:
8864     case TRUNC_DIV_EXPR:
8865     case CEIL_DIV_EXPR:
8866     case FLOOR_DIV_EXPR:
8867     case ROUND_DIV_EXPR:
8868     case EXACT_DIV_EXPR:
8869     case BIT_AND_EXPR:
8870     case BIT_IOR_EXPR:
8871     case BIT_XOR_EXPR:
8872     case TRUNC_MOD_EXPR:
8873     case FLOOR_MOD_EXPR:
8874     case TRUTH_ANDIF_EXPR:
8875     case TRUTH_ORIF_EXPR:
8876     case TRUTH_AND_EXPR:
8877     case TRUTH_OR_EXPR:
8878     case RSHIFT_EXPR:
8879     case LSHIFT_EXPR:
8880     case RROTATE_EXPR:
8881     case LROTATE_EXPR:
8882     case EQ_EXPR:
8883     case NE_EXPR:
8884     case MAX_EXPR:
8885     case MIN_EXPR:
8886     case LE_EXPR:
8887     case GE_EXPR:
8888     case LT_EXPR:
8889     case GT_EXPR:
8890     case MEMBER_REF:
8891     case DOTSTAR_EXPR:
8892       return build_x_binary_op
8893         (TREE_CODE (t),
8894          RECUR (TREE_OPERAND (t, 0)),
8895          RECUR (TREE_OPERAND (t, 1)),
8896          /*overloaded_p=*/NULL);
8897
8898     case SCOPE_REF:
8899       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
8900                                   /*address_p=*/false);
8901     case ARRAY_REF:
8902       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
8903                                                 args, complain, in_decl);
8904       return build_x_binary_op (ARRAY_REF, op1, RECUR (TREE_OPERAND (t, 1)),
8905                                 /*overloaded_p=*/NULL);
8906
8907     case SIZEOF_EXPR:
8908     case ALIGNOF_EXPR:
8909       op1 = TREE_OPERAND (t, 0);
8910       if (!args)
8911         {
8912           /* When there are no ARGS, we are trying to evaluate a
8913              non-dependent expression from the parser.  Trying to do
8914              the substitutions may not work.  */
8915           if (!TYPE_P (op1))
8916             op1 = TREE_TYPE (op1);
8917         }
8918       else
8919         {
8920           ++skip_evaluation;
8921           op1 = RECUR (op1);
8922           --skip_evaluation;
8923         }
8924       if (TYPE_P (op1))
8925         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), true);
8926       else
8927         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t));
8928
8929     case MODOP_EXPR:
8930       {
8931         tree r = build_x_modify_expr
8932           (RECUR (TREE_OPERAND (t, 0)),
8933            TREE_CODE (TREE_OPERAND (t, 1)),
8934            RECUR (TREE_OPERAND (t, 2)));
8935         /* TREE_NO_WARNING must be set if either the expression was
8936            parenthesized or it uses an operator such as >>= rather
8937            than plain assignment.  In the former case, it was already
8938            set and must be copied.  In the latter case,
8939            build_x_modify_expr sets it and it must not be reset
8940            here.  */
8941         if (TREE_NO_WARNING (t))
8942           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
8943         return r;
8944       }
8945
8946     case ARROW_EXPR:
8947       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
8948                                                 args, complain, in_decl);
8949       /* Remember that there was a reference to this entity.  */
8950       if (DECL_P (op1))
8951         mark_used (op1);
8952       return build_x_arrow (op1);
8953
8954     case NEW_EXPR:
8955       return build_new
8956         (RECUR (TREE_OPERAND (t, 0)),
8957          RECUR (TREE_OPERAND (t, 1)),
8958          RECUR (TREE_OPERAND (t, 2)),
8959          RECUR (TREE_OPERAND (t, 3)),
8960          NEW_EXPR_USE_GLOBAL (t));
8961
8962     case DELETE_EXPR:
8963      return delete_sanity
8964        (RECUR (TREE_OPERAND (t, 0)),
8965         RECUR (TREE_OPERAND (t, 1)),
8966         DELETE_EXPR_USE_VEC (t),
8967         DELETE_EXPR_USE_GLOBAL (t));
8968
8969     case COMPOUND_EXPR:
8970       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
8971                                     RECUR (TREE_OPERAND (t, 1)));
8972
8973     case CALL_EXPR:
8974       {
8975         tree function;
8976         tree call_args;
8977         bool qualified_p;
8978         bool koenig_p;
8979
8980         function = TREE_OPERAND (t, 0);
8981         /* When we parsed the expression,  we determined whether or
8982            not Koenig lookup should be performed.  */
8983         koenig_p = KOENIG_LOOKUP_P (t);
8984         if (TREE_CODE (function) == SCOPE_REF)
8985           {
8986             qualified_p = true;
8987             function = tsubst_qualified_id (function, args, complain, in_decl,
8988                                             /*done=*/false,
8989                                             /*address_p=*/false);
8990           }
8991         else
8992           {
8993             if (TREE_CODE (function) == COMPONENT_REF)
8994               {
8995                 tree op = TREE_OPERAND (function, 1);
8996
8997                 qualified_p = (TREE_CODE (op) == SCOPE_REF
8998                                || (BASELINK_P (op)
8999                                    && BASELINK_QUALIFIED_P (op)));
9000               }
9001             else
9002               qualified_p = false;
9003
9004             function = tsubst_copy_and_build (function, args, complain,
9005                                               in_decl,
9006                                               !qualified_p);
9007             if (BASELINK_P (function))
9008               qualified_p = true;
9009           }
9010
9011         call_args = RECUR (TREE_OPERAND (t, 1));
9012
9013         /* We do not perform argument-dependent lookup if normal
9014            lookup finds a non-function, in accordance with the
9015            expected resolution of DR 218.  */
9016         if (koenig_p
9017             && ((is_overloaded_fn (function)
9018                  /* If lookup found a member function, the Koenig lookup is
9019                     not appropriate, even if an unqualified-name was used
9020                     to denote the function.  */
9021                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
9022                 || TREE_CODE (function) == IDENTIFIER_NODE))
9023           function = perform_koenig_lookup (function, call_args);
9024
9025         if (TREE_CODE (function) == IDENTIFIER_NODE)
9026           {
9027             unqualified_name_lookup_error (function);
9028             return error_mark_node;
9029           }
9030
9031         /* Remember that there was a reference to this entity.  */
9032         if (DECL_P (function))
9033           mark_used (function);
9034
9035         if (TREE_CODE (function) == OFFSET_REF)
9036           return build_offset_ref_call_from_tree (function, call_args);
9037         if (TREE_CODE (function) == COMPONENT_REF)
9038           {
9039             if (!BASELINK_P (TREE_OPERAND (function, 1)))
9040               return finish_call_expr (function, call_args,
9041                                        /*disallow_virtual=*/false,
9042                                        /*koenig_p=*/false);
9043             else
9044               return (build_new_method_call
9045                       (TREE_OPERAND (function, 0),
9046                        TREE_OPERAND (function, 1),
9047                        call_args, NULL_TREE,
9048                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
9049                        /*fn_p=*/NULL));
9050           }
9051         return finish_call_expr (function, call_args,
9052                                  /*disallow_virtual=*/qualified_p,
9053                                  koenig_p);
9054       }
9055
9056     case COND_EXPR:
9057       return build_x_conditional_expr
9058         (RECUR (TREE_OPERAND (t, 0)),
9059          RECUR (TREE_OPERAND (t, 1)),
9060          RECUR (TREE_OPERAND (t, 2)));
9061
9062     case PSEUDO_DTOR_EXPR:
9063       return finish_pseudo_destructor_expr
9064         (RECUR (TREE_OPERAND (t, 0)),
9065          RECUR (TREE_OPERAND (t, 1)),
9066          RECUR (TREE_OPERAND (t, 2)));
9067
9068     case TREE_LIST:
9069       {
9070         tree purpose, value, chain;
9071
9072         if (t == void_list_node)
9073           return t;
9074
9075         purpose = TREE_PURPOSE (t);
9076         if (purpose)
9077           purpose = RECUR (purpose);
9078         value = TREE_VALUE (t);
9079         if (value)
9080           value = RECUR (value);
9081         chain = TREE_CHAIN (t);
9082         if (chain && chain != void_type_node)
9083           chain = RECUR (chain);
9084         if (purpose == TREE_PURPOSE (t)
9085             && value == TREE_VALUE (t)
9086             && chain == TREE_CHAIN (t))
9087           return t;
9088         return tree_cons (purpose, value, chain);
9089       }
9090
9091     case COMPONENT_REF:
9092       {
9093         tree object;
9094         tree object_type;
9095         tree member;
9096
9097         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
9098                                                      args, complain, in_decl);
9099         /* Remember that there was a reference to this entity.  */
9100         if (DECL_P (object))
9101           mark_used (object);
9102         object_type = TREE_TYPE (object);
9103
9104         member = TREE_OPERAND (t, 1);
9105         if (BASELINK_P (member))
9106           member = tsubst_baselink (member,
9107                                     non_reference (TREE_TYPE (object)),
9108                                     args, complain, in_decl);
9109         else
9110           member = tsubst_copy (member, args, complain, in_decl);
9111         if (member == error_mark_node)
9112           return error_mark_node;
9113
9114         if (object_type && !CLASS_TYPE_P (object_type))
9115           {
9116             if (TREE_CODE (member) == BIT_NOT_EXPR)
9117               return finish_pseudo_destructor_expr (object,
9118                                                     NULL_TREE,
9119                                                     object_type);
9120             else if (TREE_CODE (member) == SCOPE_REF
9121                      && (TREE_CODE (TREE_OPERAND (member, 1)) == BIT_NOT_EXPR))
9122               return finish_pseudo_destructor_expr (object,
9123                                                     object,
9124                                                     object_type);
9125           }
9126         else if (TREE_CODE (member) == SCOPE_REF
9127                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
9128           {
9129             tree tmpl;
9130             tree args;
9131
9132             /* Lookup the template functions now that we know what the
9133                scope is.  */
9134             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
9135             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
9136             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
9137                                             /*is_type_p=*/false,
9138                                             /*complain=*/false);
9139             if (BASELINK_P (member))
9140               {
9141                 BASELINK_FUNCTIONS (member)
9142                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
9143                               args);
9144                 member = (adjust_result_of_qualified_name_lookup
9145                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
9146                            object_type));
9147               }
9148             else
9149               {
9150                 qualified_name_lookup_error (object_type, tmpl, member);
9151                 return error_mark_node;
9152               }
9153           }
9154         else if (TREE_CODE (member) == SCOPE_REF
9155                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
9156                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
9157           {
9158             if (complain & tf_error)
9159               {
9160                 if (TYPE_P (TREE_OPERAND (member, 0)))
9161                   error ("%qT is not a class or namespace",
9162                          TREE_OPERAND (member, 0));
9163                 else
9164                   error ("%qD is not a class or namespace",
9165                          TREE_OPERAND (member, 0));
9166               }
9167             return error_mark_node;
9168           }
9169         else if (TREE_CODE (member) == FIELD_DECL)
9170           return finish_non_static_data_member (member, object, NULL_TREE);
9171
9172         return finish_class_member_access_expr (object, member,
9173                                                 /*template_p=*/false);
9174       }
9175
9176     case THROW_EXPR:
9177       return build_throw
9178         (RECUR (TREE_OPERAND (t, 0)));
9179
9180     case CONSTRUCTOR:
9181       {
9182         VEC(constructor_elt,gc) *n;
9183         constructor_elt *ce;
9184         unsigned HOST_WIDE_INT idx;
9185         tree r;
9186         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9187         bool process_index_p;
9188
9189         /* digest_init will do the wrong thing if we let it.  */
9190         if (type && TYPE_PTRMEMFUNC_P (type))
9191           return t;
9192
9193         /* We do not want to process the index of aggregate
9194            initializers as they are identifier nodes which will be
9195            looked up by digest_init.  */
9196         process_index_p = !(type && IS_AGGR_TYPE (type));
9197
9198         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
9199         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
9200           {
9201             if (ce->index && process_index_p)
9202               ce->index = RECUR (ce->index);
9203             ce->value = RECUR (ce->value);
9204           }
9205
9206         r = build_constructor (NULL_TREE, n);
9207         TREE_HAS_CONSTRUCTOR (r) = TREE_HAS_CONSTRUCTOR (t);
9208
9209         if (type)
9210           return digest_init (type, r);
9211         return r;
9212       }
9213
9214     case TYPEID_EXPR:
9215       {
9216         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
9217         if (TYPE_P (operand_0))
9218           return get_typeid (operand_0);
9219         return build_typeid (operand_0);
9220       }
9221
9222     case VAR_DECL:
9223       if (!args)
9224         return t;
9225       /* Fall through */
9226
9227     case PARM_DECL:
9228       {
9229         tree r = tsubst_copy (t, args, complain, in_decl);
9230
9231         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
9232           /* If the original type was a reference, we'll be wrapped in
9233              the appropriate INDIRECT_REF.  */
9234           r = convert_from_reference (r);
9235         return r;
9236       }
9237
9238     case VA_ARG_EXPR:
9239       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
9240                              tsubst_copy (TREE_TYPE (t), args, complain,
9241                                           in_decl));
9242
9243     case OFFSETOF_EXPR:
9244       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
9245
9246     case STMT_EXPR:
9247       {
9248         tree old_stmt_expr = cur_stmt_expr;
9249         tree stmt_expr = begin_stmt_expr ();
9250
9251         cur_stmt_expr = stmt_expr;
9252         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
9253         stmt_expr = finish_stmt_expr (stmt_expr, false);
9254         cur_stmt_expr = old_stmt_expr;
9255
9256         return stmt_expr;
9257       }
9258
9259     case CONST_DECL:
9260       t = tsubst_copy (t, args, complain, in_decl);
9261       /* As in finish_id_expression, we resolve enumeration constants
9262          to their underlying values.  */
9263       if (TREE_CODE (t) == CONST_DECL)
9264         {
9265           used_types_insert (TREE_TYPE (t));
9266           return DECL_INITIAL (t);
9267         }
9268       return t;
9269
9270     default:
9271       /* Handle Objective-C++ constructs, if appropriate.  */
9272       {
9273         tree subst
9274           = objcp_tsubst_copy_and_build (t, args, complain,
9275                                          in_decl, /*function_p=*/false);
9276         if (subst)
9277           return subst;
9278       }
9279       return tsubst_copy (t, args, complain, in_decl);
9280     }
9281
9282 #undef RECUR
9283 }
9284
9285 /* Verify that the instantiated ARGS are valid. For type arguments,
9286    make sure that the type's linkage is ok. For non-type arguments,
9287    make sure they are constants if they are integral or enumerations.
9288    Emit an error under control of COMPLAIN, and return TRUE on error.  */
9289
9290 static bool
9291 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
9292 {
9293   int ix, len = DECL_NTPARMS (tmpl);
9294   bool result = false;
9295
9296   for (ix = 0; ix != len; ix++)
9297     {
9298       tree t = TREE_VEC_ELT (args, ix);
9299
9300       if (TYPE_P (t))
9301         {
9302           /* [basic.link]: A name with no linkage (notably, the name
9303              of a class or enumeration declared in a local scope)
9304              shall not be used to declare an entity with linkage.
9305              This implies that names with no linkage cannot be used as
9306              template arguments.  */
9307           tree nt = no_linkage_check (t, /*relaxed_p=*/false);
9308
9309           if (nt)
9310             {
9311               /* DR 488 makes use of a type with no linkage cause
9312                  type deduction to fail.  */
9313               if (complain & tf_error)
9314                 {
9315                   if (TYPE_ANONYMOUS_P (nt))
9316                     error ("%qT is/uses anonymous type", t);
9317                   else
9318                     error ("template argument for %qD uses local type %qT",
9319                            tmpl, t);
9320                 }
9321               result = true;
9322             }
9323           /* In order to avoid all sorts of complications, we do not
9324              allow variably-modified types as template arguments.  */
9325           else if (variably_modified_type_p (t, NULL_TREE))
9326             {
9327               if (complain & tf_error)
9328                 error ("%qT is a variably modified type", t);
9329               result = true;
9330             }
9331         }
9332       /* A non-type argument of integral or enumerated type must be a
9333          constant.  */
9334       else if (TREE_TYPE (t)
9335                && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
9336                && !TREE_CONSTANT (t))
9337         {
9338           if (complain & tf_error)
9339             error ("integral expression %qE is not constant", t);
9340           result = true;
9341         }
9342     }
9343   if (result && (complain & tf_error))
9344     error ("  trying to instantiate %qD", tmpl);
9345   return result;
9346 }
9347
9348 /* Instantiate the indicated variable or function template TMPL with
9349    the template arguments in TARG_PTR.  */
9350
9351 tree
9352 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
9353 {
9354   tree fndecl;
9355   tree gen_tmpl;
9356   tree spec;
9357   HOST_WIDE_INT saved_processing_template_decl;
9358
9359   if (tmpl == error_mark_node)
9360     return error_mark_node;
9361
9362   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
9363
9364   /* If this function is a clone, handle it specially.  */
9365   if (DECL_CLONED_FUNCTION_P (tmpl))
9366     {
9367       tree spec;
9368       tree clone;
9369
9370       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
9371                                    complain);
9372       if (spec == error_mark_node)
9373         return error_mark_node;
9374
9375       /* Look for the clone.  */
9376       FOR_EACH_CLONE (clone, spec)
9377         if (DECL_NAME (clone) == DECL_NAME (tmpl))
9378           return clone;
9379       /* We should always have found the clone by now.  */
9380       gcc_unreachable ();
9381       return NULL_TREE;
9382     }
9383
9384   /* Check to see if we already have this specialization.  */
9385   spec = retrieve_specialization (tmpl, targ_ptr,
9386                                   /*class_specializations_p=*/false);
9387   if (spec != NULL_TREE)
9388     return spec;
9389
9390   gen_tmpl = most_general_template (tmpl);
9391   if (tmpl != gen_tmpl)
9392     {
9393       /* The TMPL is a partial instantiation.  To get a full set of
9394          arguments we must add the arguments used to perform the
9395          partial instantiation.  */
9396       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
9397                                               targ_ptr);
9398
9399       /* Check to see if we already have this specialization.  */
9400       spec = retrieve_specialization (gen_tmpl, targ_ptr,
9401                                       /*class_specializations_p=*/false);
9402       if (spec != NULL_TREE)
9403         return spec;
9404     }
9405
9406   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
9407                                complain))
9408     return error_mark_node;
9409
9410   /* We are building a FUNCTION_DECL, during which the access of its
9411      parameters and return types have to be checked.  However this
9412      FUNCTION_DECL which is the desired context for access checking
9413      is not built yet.  We solve this chicken-and-egg problem by
9414      deferring all checks until we have the FUNCTION_DECL.  */
9415   push_deferring_access_checks (dk_deferred);
9416
9417   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
9418      (because, for example, we have encountered a non-dependent
9419      function call in the body of a template function and must now
9420      determine which of several overloaded functions will be called),
9421      within the instantiation itself we are not processing a
9422      template.  */  
9423   saved_processing_template_decl = processing_template_decl;
9424   processing_template_decl = 0;
9425   /* Substitute template parameters to obtain the specialization.  */
9426   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
9427                    targ_ptr, complain, gen_tmpl);
9428   processing_template_decl = saved_processing_template_decl;
9429   if (fndecl == error_mark_node)
9430     return error_mark_node;
9431
9432   /* Now we know the specialization, compute access previously
9433      deferred.  */
9434   push_access_scope (fndecl);
9435   perform_deferred_access_checks ();
9436   pop_access_scope (fndecl);
9437   pop_deferring_access_checks ();
9438
9439   /* The DECL_TI_TEMPLATE should always be the immediate parent
9440      template, not the most general template.  */
9441   DECL_TI_TEMPLATE (fndecl) = tmpl;
9442
9443   /* If we've just instantiated the main entry point for a function,
9444      instantiate all the alternate entry points as well.  We do this
9445      by cloning the instantiation of the main entry point, not by
9446      instantiating the template clones.  */
9447   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
9448     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
9449
9450   return fndecl;
9451 }
9452
9453 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
9454    arguments that are being used when calling it.  TARGS is a vector
9455    into which the deduced template arguments are placed.
9456
9457    Return zero for success, 2 for an incomplete match that doesn't resolve
9458    all the types, and 1 for complete failure.  An error message will be
9459    printed only for an incomplete match.
9460
9461    If FN is a conversion operator, or we are trying to produce a specific
9462    specialization, RETURN_TYPE is the return type desired.
9463
9464    The EXPLICIT_TARGS are explicit template arguments provided via a
9465    template-id.
9466
9467    The parameter STRICT is one of:
9468
9469    DEDUCE_CALL:
9470      We are deducing arguments for a function call, as in
9471      [temp.deduct.call].
9472
9473    DEDUCE_CONV:
9474      We are deducing arguments for a conversion function, as in
9475      [temp.deduct.conv].
9476
9477    DEDUCE_EXACT:
9478      We are deducing arguments when doing an explicit instantiation
9479      as in [temp.explicit], when determining an explicit specialization
9480      as in [temp.expl.spec], or when taking the address of a function
9481      template, as in [temp.deduct.funcaddr].  */
9482
9483 int
9484 fn_type_unification (tree fn,
9485                      tree explicit_targs,
9486                      tree targs,
9487                      tree args,
9488                      tree return_type,
9489                      unification_kind_t strict,
9490                      int flags)
9491 {
9492   tree parms;
9493   tree fntype;
9494   int result;
9495
9496   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
9497
9498   fntype = TREE_TYPE (fn);
9499   if (explicit_targs)
9500     {
9501       /* [temp.deduct]
9502
9503          The specified template arguments must match the template
9504          parameters in kind (i.e., type, nontype, template), and there
9505          must not be more arguments than there are parameters;
9506          otherwise type deduction fails.
9507
9508          Nontype arguments must match the types of the corresponding
9509          nontype template parameters, or must be convertible to the
9510          types of the corresponding nontype parameters as specified in
9511          _temp.arg.nontype_, otherwise type deduction fails.
9512
9513          All references in the function type of the function template
9514          to the corresponding template parameters are replaced by the
9515          specified template argument values.  If a substitution in a
9516          template parameter or in the function type of the function
9517          template results in an invalid type, type deduction fails.  */
9518       int i;
9519       tree converted_args;
9520       bool incomplete;
9521
9522       if (explicit_targs == error_mark_node)
9523         return 1;
9524
9525       converted_args
9526         = (coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
9527                                   explicit_targs, NULL_TREE, tf_none,
9528                                   /*require_all_args=*/false,
9529                                   /*use_default_args=*/false));
9530       if (converted_args == error_mark_node)
9531         return 1;
9532
9533       /* Substitute the explicit args into the function type.  This is
9534          necessary so that, for instance, explicitly declared function
9535          arguments can match null pointed constants.  If we were given
9536          an incomplete set of explicit args, we must not do semantic
9537          processing during substitution as we could create partial
9538          instantiations.  */
9539       incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
9540       processing_template_decl += incomplete;
9541       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
9542       processing_template_decl -= incomplete;
9543
9544       if (fntype == error_mark_node)
9545         return 1;
9546
9547       /* Place the explicitly specified arguments in TARGS.  */
9548       for (i = NUM_TMPL_ARGS (converted_args); i--;)
9549         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
9550     }
9551
9552   parms = TYPE_ARG_TYPES (fntype);
9553   /* Never do unification on the 'this' parameter.  */
9554   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
9555     parms = TREE_CHAIN (parms);
9556
9557   if (return_type)
9558     {
9559       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
9560       args = tree_cons (NULL_TREE, return_type, args);
9561     }
9562
9563   /* We allow incomplete unification without an error message here
9564      because the standard doesn't seem to explicitly prohibit it.  Our
9565      callers must be ready to deal with unification failures in any
9566      event.  */
9567   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
9568                                   targs, parms, args, /*subr=*/0,
9569                                   strict, flags);
9570
9571   if (result == 0)
9572     /* All is well so far.  Now, check:
9573
9574        [temp.deduct]
9575
9576        When all template arguments have been deduced, all uses of
9577        template parameters in nondeduced contexts are replaced with
9578        the corresponding deduced argument values.  If the
9579        substitution results in an invalid type, as described above,
9580        type deduction fails.  */
9581     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
9582         == error_mark_node)
9583       return 1;
9584
9585   return result;
9586 }
9587
9588 /* Adjust types before performing type deduction, as described in
9589    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
9590    sections are symmetric.  PARM is the type of a function parameter
9591    or the return type of the conversion function.  ARG is the type of
9592    the argument passed to the call, or the type of the value
9593    initialized with the result of the conversion function.  */
9594
9595 static int
9596 maybe_adjust_types_for_deduction (unification_kind_t strict,
9597                                   tree* parm,
9598                                   tree* arg)
9599 {
9600   int result = 0;
9601
9602   switch (strict)
9603     {
9604     case DEDUCE_CALL:
9605       break;
9606
9607     case DEDUCE_CONV:
9608       {
9609         /* Swap PARM and ARG throughout the remainder of this
9610            function; the handling is precisely symmetric since PARM
9611            will initialize ARG rather than vice versa.  */
9612         tree* temp = parm;
9613         parm = arg;
9614         arg = temp;
9615         break;
9616       }
9617
9618     case DEDUCE_EXACT:
9619       /* There is nothing to do in this case.  */
9620       return 0;
9621
9622     default:
9623       gcc_unreachable ();
9624     }
9625
9626   if (TREE_CODE (*parm) != REFERENCE_TYPE)
9627     {
9628       /* [temp.deduct.call]
9629
9630          If P is not a reference type:
9631
9632          --If A is an array type, the pointer type produced by the
9633          array-to-pointer standard conversion (_conv.array_) is
9634          used in place of A for type deduction; otherwise,
9635
9636          --If A is a function type, the pointer type produced by
9637          the function-to-pointer standard conversion
9638          (_conv.func_) is used in place of A for type deduction;
9639          otherwise,
9640
9641          --If A is a cv-qualified type, the top level
9642          cv-qualifiers of A's type are ignored for type
9643          deduction.  */
9644       if (TREE_CODE (*arg) == ARRAY_TYPE)
9645         *arg = build_pointer_type (TREE_TYPE (*arg));
9646       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
9647         *arg = build_pointer_type (*arg);
9648       else
9649         *arg = TYPE_MAIN_VARIANT (*arg);
9650     }
9651
9652   /* [temp.deduct.call]
9653
9654      If P is a cv-qualified type, the top level cv-qualifiers
9655      of P's type are ignored for type deduction.  If P is a
9656      reference type, the type referred to by P is used for
9657      type deduction.  */
9658   *parm = TYPE_MAIN_VARIANT (*parm);
9659   if (TREE_CODE (*parm) == REFERENCE_TYPE)
9660     {
9661       *parm = TREE_TYPE (*parm);
9662       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
9663     }
9664
9665   /* DR 322. For conversion deduction, remove a reference type on parm
9666      too (which has been swapped into ARG).  */
9667   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
9668     *arg = TREE_TYPE (*arg);
9669
9670   return result;
9671 }
9672
9673 /* Most parms like fn_type_unification.
9674
9675    If SUBR is 1, we're being called recursively (to unify the
9676    arguments of a function or method parameter of a function
9677    template). */
9678
9679 static int
9680 type_unification_real (tree tparms,
9681                        tree targs,
9682                        tree xparms,
9683                        tree xargs,
9684                        int subr,
9685                        unification_kind_t strict,
9686                        int flags)
9687 {
9688   tree parm, arg;
9689   int i;
9690   int ntparms = TREE_VEC_LENGTH (tparms);
9691   int sub_strict;
9692   int saw_undeduced = 0;
9693   tree parms, args;
9694
9695   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
9696   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
9697   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
9698   gcc_assert (ntparms > 0);
9699
9700   switch (strict)
9701     {
9702     case DEDUCE_CALL:
9703       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
9704                     | UNIFY_ALLOW_DERIVED);
9705       break;
9706
9707     case DEDUCE_CONV:
9708       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
9709       break;
9710
9711     case DEDUCE_EXACT:
9712       sub_strict = UNIFY_ALLOW_NONE;
9713       break;
9714
9715     default:
9716       gcc_unreachable ();
9717     }
9718
9719  again:
9720   parms = xparms;
9721   args = xargs;
9722
9723   while (parms && parms != void_list_node
9724          && args && args != void_list_node)
9725     {
9726       parm = TREE_VALUE (parms);
9727       parms = TREE_CHAIN (parms);
9728       arg = TREE_VALUE (args);
9729       args = TREE_CHAIN (args);
9730
9731       if (arg == error_mark_node)
9732         return 1;
9733       if (arg == unknown_type_node)
9734         /* We can't deduce anything from this, but we might get all the
9735            template args from other function args.  */
9736         continue;
9737
9738       /* Conversions will be performed on a function argument that
9739          corresponds with a function parameter that contains only
9740          non-deducible template parameters and explicitly specified
9741          template parameters.  */
9742       if (!uses_template_parms (parm))
9743         {
9744           tree type;
9745
9746           if (!TYPE_P (arg))
9747             type = TREE_TYPE (arg);
9748           else
9749             type = arg;
9750
9751           if (same_type_p (parm, type))
9752             continue;
9753           if (strict != DEDUCE_EXACT
9754               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
9755                                   flags))
9756             continue;
9757
9758           return 1;
9759         }
9760
9761       if (!TYPE_P (arg))
9762         {
9763           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
9764           if (type_unknown_p (arg))
9765             {
9766               /* [temp.deduct.type] A template-argument can be deduced from
9767                  a pointer to function or pointer to member function
9768                  argument if the set of overloaded functions does not
9769                  contain function templates and at most one of a set of
9770                  overloaded functions provides a unique match.  */
9771
9772               if (resolve_overloaded_unification
9773                   (tparms, targs, parm, arg, strict, sub_strict)
9774                   != 0)
9775                 return 1;
9776               continue;
9777             }
9778           arg = TREE_TYPE (arg);
9779           if (arg == error_mark_node)
9780             return 1;
9781         }
9782
9783       {
9784         int arg_strict = sub_strict;
9785
9786         if (!subr)
9787           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg);
9788
9789         if (unify (tparms, targs, parm, arg, arg_strict))
9790           return 1;
9791       }
9792     }
9793
9794   /* Fail if we've reached the end of the parm list, and more args
9795      are present, and the parm list isn't variadic.  */
9796   if (args && args != void_list_node && parms == void_list_node)
9797     return 1;
9798   /* Fail if parms are left and they don't have default values.  */
9799   if (parms && parms != void_list_node
9800       && TREE_PURPOSE (parms) == NULL_TREE)
9801     return 1;
9802
9803   if (!subr)
9804     for (i = 0; i < ntparms; i++)
9805       if (!TREE_VEC_ELT (targs, i))
9806         {
9807           tree tparm;
9808
9809           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
9810             continue;
9811
9812           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
9813
9814           /* If this is an undeduced nontype parameter that depends on
9815              a type parameter, try another pass; its type may have been
9816              deduced from a later argument than the one from which
9817              this parameter can be deduced.  */
9818           if (TREE_CODE (tparm) == PARM_DECL
9819               && uses_template_parms (TREE_TYPE (tparm))
9820               && !saw_undeduced++)
9821             goto again;
9822
9823           return 2;
9824         }
9825
9826   return 0;
9827 }
9828
9829 /* Subroutine of type_unification_real.  Args are like the variables at the
9830    call site.  ARG is an overloaded function (or template-id); we try
9831    deducing template args from each of the overloads, and if only one
9832    succeeds, we go with that.  Modifies TARGS and returns 0 on success.  */
9833
9834 static int
9835 resolve_overloaded_unification (tree tparms,
9836                                 tree targs,
9837                                 tree parm,
9838                                 tree arg,
9839                                 unification_kind_t strict,
9840                                 int sub_strict)
9841 {
9842   tree tempargs = copy_node (targs);
9843   int good = 0;
9844   bool addr_p;
9845
9846   if (TREE_CODE (arg) == ADDR_EXPR)
9847     {
9848       arg = TREE_OPERAND (arg, 0);
9849       addr_p = true;
9850     }
9851   else
9852     addr_p = false;
9853
9854   if (TREE_CODE (arg) == COMPONENT_REF)
9855     /* Handle `&x' where `x' is some static or non-static member
9856        function name.  */
9857     arg = TREE_OPERAND (arg, 1);
9858
9859   if (TREE_CODE (arg) == OFFSET_REF)
9860     arg = TREE_OPERAND (arg, 1);
9861
9862   /* Strip baselink information.  */
9863   if (BASELINK_P (arg))
9864     arg = BASELINK_FUNCTIONS (arg);
9865
9866   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
9867     {
9868       /* If we got some explicit template args, we need to plug them into
9869          the affected templates before we try to unify, in case the
9870          explicit args will completely resolve the templates in question.  */
9871
9872       tree expl_subargs = TREE_OPERAND (arg, 1);
9873       arg = TREE_OPERAND (arg, 0);
9874
9875       for (; arg; arg = OVL_NEXT (arg))
9876         {
9877           tree fn = OVL_CURRENT (arg);
9878           tree subargs, elem;
9879
9880           if (TREE_CODE (fn) != TEMPLATE_DECL)
9881             continue;
9882
9883           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
9884                                   expl_subargs, /*check_ret=*/false);
9885           if (subargs)
9886             {
9887               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
9888               good += try_one_overload (tparms, targs, tempargs, parm,
9889                                         elem, strict, sub_strict, addr_p);
9890             }
9891         }
9892     }
9893   else
9894     {
9895       gcc_assert (TREE_CODE (arg) == OVERLOAD
9896                   || TREE_CODE (arg) == FUNCTION_DECL);
9897
9898       for (; arg; arg = OVL_NEXT (arg))
9899         good += try_one_overload (tparms, targs, tempargs, parm,
9900                                   TREE_TYPE (OVL_CURRENT (arg)),
9901                                   strict, sub_strict, addr_p);
9902     }
9903
9904   /* [temp.deduct.type] A template-argument can be deduced from a pointer
9905      to function or pointer to member function argument if the set of
9906      overloaded functions does not contain function templates and at most
9907      one of a set of overloaded functions provides a unique match.
9908
9909      So if we found multiple possibilities, we return success but don't
9910      deduce anything.  */
9911
9912   if (good == 1)
9913     {
9914       int i = TREE_VEC_LENGTH (targs);
9915       for (; i--; )
9916         if (TREE_VEC_ELT (tempargs, i))
9917           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
9918     }
9919   if (good)
9920     return 0;
9921
9922   return 1;
9923 }
9924
9925 /* Subroutine of resolve_overloaded_unification; does deduction for a single
9926    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
9927    different overloads deduce different arguments for a given parm.
9928    ADDR_P is true if the expression for which deduction is being
9929    performed was of the form "& fn" rather than simply "fn".
9930
9931    Returns 1 on success.  */
9932
9933 static int
9934 try_one_overload (tree tparms,
9935                   tree orig_targs,
9936                   tree targs,
9937                   tree parm,
9938                   tree arg,
9939                   unification_kind_t strict,
9940                   int sub_strict,
9941                   bool addr_p)
9942 {
9943   int nargs;
9944   tree tempargs;
9945   int i;
9946
9947   /* [temp.deduct.type] A template-argument can be deduced from a pointer
9948      to function or pointer to member function argument if the set of
9949      overloaded functions does not contain function templates and at most
9950      one of a set of overloaded functions provides a unique match.
9951
9952      So if this is a template, just return success.  */
9953
9954   if (uses_template_parms (arg))
9955     return 1;
9956
9957   if (TREE_CODE (arg) == METHOD_TYPE)
9958     arg = build_ptrmemfunc_type (build_pointer_type (arg));
9959   else if (addr_p)
9960     arg = build_pointer_type (arg);
9961
9962   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg);
9963
9964   /* We don't copy orig_targs for this because if we have already deduced
9965      some template args from previous args, unify would complain when we
9966      try to deduce a template parameter for the same argument, even though
9967      there isn't really a conflict.  */
9968   nargs = TREE_VEC_LENGTH (targs);
9969   tempargs = make_tree_vec (nargs);
9970
9971   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
9972     return 0;
9973
9974   /* First make sure we didn't deduce anything that conflicts with
9975      explicitly specified args.  */
9976   for (i = nargs; i--; )
9977     {
9978       tree elt = TREE_VEC_ELT (tempargs, i);
9979       tree oldelt = TREE_VEC_ELT (orig_targs, i);
9980
9981       if (!elt)
9982         /*NOP*/;
9983       else if (uses_template_parms (elt))
9984         /* Since we're unifying against ourselves, we will fill in
9985            template args used in the function parm list with our own
9986            template parms.  Discard them.  */
9987         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
9988       else if (oldelt && !template_args_equal (oldelt, elt))
9989         return 0;
9990     }
9991
9992   for (i = nargs; i--; )
9993     {
9994       tree elt = TREE_VEC_ELT (tempargs, i);
9995
9996       if (elt)
9997         TREE_VEC_ELT (targs, i) = elt;
9998     }
9999
10000   return 1;
10001 }
10002
10003 /* PARM is a template class (perhaps with unbound template
10004    parameters).  ARG is a fully instantiated type.  If ARG can be
10005    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
10006    TARGS are as for unify.  */
10007
10008 static tree
10009 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
10010 {
10011   tree copy_of_targs;
10012
10013   if (!CLASSTYPE_TEMPLATE_INFO (arg)
10014       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
10015           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
10016     return NULL_TREE;
10017
10018   /* We need to make a new template argument vector for the call to
10019      unify.  If we used TARGS, we'd clutter it up with the result of
10020      the attempted unification, even if this class didn't work out.
10021      We also don't want to commit ourselves to all the unifications
10022      we've already done, since unification is supposed to be done on
10023      an argument-by-argument basis.  In other words, consider the
10024      following pathological case:
10025
10026        template <int I, int J, int K>
10027        struct S {};
10028
10029        template <int I, int J>
10030        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
10031
10032        template <int I, int J, int K>
10033        void f(S<I, J, K>, S<I, I, I>);
10034
10035        void g() {
10036          S<0, 0, 0> s0;
10037          S<0, 1, 2> s2;
10038
10039          f(s0, s2);
10040        }
10041
10042      Now, by the time we consider the unification involving `s2', we
10043      already know that we must have `f<0, 0, 0>'.  But, even though
10044      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
10045      because there are two ways to unify base classes of S<0, 1, 2>
10046      with S<I, I, I>.  If we kept the already deduced knowledge, we
10047      would reject the possibility I=1.  */
10048   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
10049
10050   /* If unification failed, we're done.  */
10051   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
10052              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
10053     return NULL_TREE;
10054
10055   return arg;
10056 }
10057
10058 /* Given a template type PARM and a class type ARG, find the unique
10059    base type in ARG that is an instance of PARM.  We do not examine
10060    ARG itself; only its base-classes.  If there is not exactly one
10061    appropriate base class, return NULL_TREE.  PARM may be the type of
10062    a partial specialization, as well as a plain template type.  Used
10063    by unify.  */
10064
10065 static tree
10066 get_template_base (tree tparms, tree targs, tree parm, tree arg)
10067 {
10068   tree rval = NULL_TREE;
10069   tree binfo;
10070
10071   gcc_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)));
10072
10073   binfo = TYPE_BINFO (complete_type (arg));
10074   if (!binfo)
10075     /* The type could not be completed.  */
10076     return NULL_TREE;
10077
10078   /* Walk in inheritance graph order.  The search order is not
10079      important, and this avoids multiple walks of virtual bases.  */
10080   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
10081     {
10082       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
10083
10084       if (r)
10085         {
10086           /* If there is more than one satisfactory baseclass, then:
10087
10088                [temp.deduct.call]
10089
10090               If they yield more than one possible deduced A, the type
10091               deduction fails.
10092
10093              applies.  */
10094           if (rval && !same_type_p (r, rval))
10095             return NULL_TREE;
10096
10097           rval = r;
10098         }
10099     }
10100
10101   return rval;
10102 }
10103
10104 /* Returns the level of DECL, which declares a template parameter.  */
10105
10106 static int
10107 template_decl_level (tree decl)
10108 {
10109   switch (TREE_CODE (decl))
10110     {
10111     case TYPE_DECL:
10112     case TEMPLATE_DECL:
10113       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
10114
10115     case PARM_DECL:
10116       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
10117
10118     default:
10119       gcc_unreachable ();
10120     }
10121   return 0;
10122 }
10123
10124 /* Decide whether ARG can be unified with PARM, considering only the
10125    cv-qualifiers of each type, given STRICT as documented for unify.
10126    Returns nonzero iff the unification is OK on that basis.  */
10127
10128 static int
10129 check_cv_quals_for_unify (int strict, tree arg, tree parm)
10130 {
10131   int arg_quals = cp_type_quals (arg);
10132   int parm_quals = cp_type_quals (parm);
10133
10134   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
10135       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
10136     {
10137       /*  Although a CVR qualifier is ignored when being applied to a
10138           substituted template parameter ([8.3.2]/1 for example), that
10139           does not apply during deduction [14.8.2.4]/1, (even though
10140           that is not explicitly mentioned, [14.8.2.4]/9 indicates
10141           this).  Except when we're allowing additional CV qualifiers
10142           at the outer level [14.8.2.1]/3,1st bullet.  */
10143       if ((TREE_CODE (arg) == REFERENCE_TYPE
10144            || TREE_CODE (arg) == FUNCTION_TYPE
10145            || TREE_CODE (arg) == METHOD_TYPE)
10146           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
10147         return 0;
10148
10149       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
10150           && (parm_quals & TYPE_QUAL_RESTRICT))
10151         return 0;
10152     }
10153
10154   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
10155       && (arg_quals & parm_quals) != parm_quals)
10156     return 0;
10157
10158   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
10159       && (parm_quals & arg_quals) != arg_quals)
10160     return 0;
10161
10162   return 1;
10163 }
10164
10165 /* Deduce the value of template parameters.  TPARMS is the (innermost)
10166    set of template parameters to a template.  TARGS is the bindings
10167    for those template parameters, as determined thus far; TARGS may
10168    include template arguments for outer levels of template parameters
10169    as well.  PARM is a parameter to a template function, or a
10170    subcomponent of that parameter; ARG is the corresponding argument.
10171    This function attempts to match PARM with ARG in a manner
10172    consistent with the existing assignments in TARGS.  If more values
10173    are deduced, then TARGS is updated.
10174
10175    Returns 0 if the type deduction succeeds, 1 otherwise.  The
10176    parameter STRICT is a bitwise or of the following flags:
10177
10178      UNIFY_ALLOW_NONE:
10179        Require an exact match between PARM and ARG.
10180      UNIFY_ALLOW_MORE_CV_QUAL:
10181        Allow the deduced ARG to be more cv-qualified (by qualification
10182        conversion) than ARG.
10183      UNIFY_ALLOW_LESS_CV_QUAL:
10184        Allow the deduced ARG to be less cv-qualified than ARG.
10185      UNIFY_ALLOW_DERIVED:
10186        Allow the deduced ARG to be a template base class of ARG,
10187        or a pointer to a template base class of the type pointed to by
10188        ARG.
10189      UNIFY_ALLOW_INTEGER:
10190        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
10191        case for more information.
10192      UNIFY_ALLOW_OUTER_LEVEL:
10193        This is the outermost level of a deduction. Used to determine validity
10194        of qualification conversions. A valid qualification conversion must
10195        have const qualified pointers leading up to the inner type which
10196        requires additional CV quals, except at the outer level, where const
10197        is not required [conv.qual]. It would be normal to set this flag in
10198        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
10199      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
10200        This is the outermost level of a deduction, and PARM can be more CV
10201        qualified at this point.
10202      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
10203        This is the outermost level of a deduction, and PARM can be less CV
10204        qualified at this point.  */
10205
10206 static int
10207 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
10208 {
10209   int idx;
10210   tree targ;
10211   tree tparm;
10212   int strict_in = strict;
10213
10214   /* I don't think this will do the right thing with respect to types.
10215      But the only case I've seen it in so far has been array bounds, where
10216      signedness is the only information lost, and I think that will be
10217      okay.  */
10218   while (TREE_CODE (parm) == NOP_EXPR)
10219     parm = TREE_OPERAND (parm, 0);
10220
10221   if (arg == error_mark_node)
10222     return 1;
10223   if (arg == unknown_type_node)
10224     /* We can't deduce anything from this, but we might get all the
10225        template args from other function args.  */
10226     return 0;
10227
10228   /* If PARM uses template parameters, then we can't bail out here,
10229      even if ARG == PARM, since we won't record unifications for the
10230      template parameters.  We might need them if we're trying to
10231      figure out which of two things is more specialized.  */
10232   if (arg == parm && !uses_template_parms (parm))
10233     return 0;
10234
10235   /* Immediately reject some pairs that won't unify because of
10236      cv-qualification mismatches.  */
10237   if (TREE_CODE (arg) == TREE_CODE (parm)
10238       && TYPE_P (arg)
10239       /* It is the elements of the array which hold the cv quals of an array
10240          type, and the elements might be template type parms. We'll check
10241          when we recurse.  */
10242       && TREE_CODE (arg) != ARRAY_TYPE
10243       /* We check the cv-qualifiers when unifying with template type
10244          parameters below.  We want to allow ARG `const T' to unify with
10245          PARM `T' for example, when computing which of two templates
10246          is more specialized, for example.  */
10247       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
10248       && !check_cv_quals_for_unify (strict_in, arg, parm))
10249     return 1;
10250
10251   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
10252       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
10253     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
10254   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
10255   strict &= ~UNIFY_ALLOW_DERIVED;
10256   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
10257   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
10258
10259   switch (TREE_CODE (parm))
10260     {
10261     case TYPENAME_TYPE:
10262     case SCOPE_REF:
10263     case UNBOUND_CLASS_TEMPLATE:
10264       /* In a type which contains a nested-name-specifier, template
10265          argument values cannot be deduced for template parameters used
10266          within the nested-name-specifier.  */
10267       return 0;
10268
10269     case TEMPLATE_TYPE_PARM:
10270     case TEMPLATE_TEMPLATE_PARM:
10271     case BOUND_TEMPLATE_TEMPLATE_PARM:
10272       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
10273
10274       if (TEMPLATE_TYPE_LEVEL (parm)
10275           != template_decl_level (tparm))
10276         /* The PARM is not one we're trying to unify.  Just check
10277            to see if it matches ARG.  */
10278         return (TREE_CODE (arg) == TREE_CODE (parm)
10279                 && same_type_p (parm, arg)) ? 0 : 1;
10280       idx = TEMPLATE_TYPE_IDX (parm);
10281       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
10282       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
10283
10284       /* Check for mixed types and values.  */
10285       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
10286            && TREE_CODE (tparm) != TYPE_DECL)
10287           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
10288               && TREE_CODE (tparm) != TEMPLATE_DECL))
10289         return 1;
10290
10291       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
10292         {
10293           /* ARG must be constructed from a template class or a template
10294              template parameter.  */
10295           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
10296               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
10297             return 1;
10298
10299           {
10300             tree parmvec = TYPE_TI_ARGS (parm);
10301             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
10302             tree argtmplvec
10303               = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_TI_TEMPLATE (arg));
10304             int i;
10305
10306             /* The resolution to DR150 makes clear that default
10307                arguments for an N-argument may not be used to bind T
10308                to a template template parameter with fewer than N
10309                parameters.  It is not safe to permit the binding of
10310                default arguments as an extension, as that may change
10311                the meaning of a conforming program.  Consider:
10312
10313                   struct Dense { static const unsigned int dim = 1; };
10314
10315                   template <template <typename> class View,
10316                             typename Block>
10317                   void operator+(float, View<Block> const&);
10318
10319                   template <typename Block,
10320                             unsigned int Dim = Block::dim>
10321                   struct Lvalue_proxy { operator float() const; };
10322
10323                   void
10324                   test_1d (void) {
10325                     Lvalue_proxy<Dense> p;
10326                     float b;
10327                     b + p;
10328                   }
10329
10330               Here, if Lvalue_proxy is permitted to bind to View, then
10331               the global operator+ will be used; if they are not, the
10332               Lvalue_proxy will be converted to float.  */
10333             if (coerce_template_parms (argtmplvec, parmvec,
10334                                        TYPE_TI_TEMPLATE (parm),
10335                                        tf_none,
10336                                        /*require_all_args=*/true,
10337                                        /*use_default_args=*/false)
10338                 == error_mark_node)
10339               return 1;
10340
10341             /* Deduce arguments T, i from TT<T> or TT<i>.
10342                We check each element of PARMVEC and ARGVEC individually
10343                rather than the whole TREE_VEC since they can have
10344                different number of elements.  */
10345
10346             for (i = 0; i < TREE_VEC_LENGTH (parmvec); ++i)
10347               {
10348                 if (unify (tparms, targs,
10349                            TREE_VEC_ELT (parmvec, i),
10350                            TREE_VEC_ELT (argvec, i),
10351                            UNIFY_ALLOW_NONE))
10352                   return 1;
10353               }
10354           }
10355           arg = TYPE_TI_TEMPLATE (arg);
10356
10357           /* Fall through to deduce template name.  */
10358         }
10359
10360       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
10361           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
10362         {
10363           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
10364
10365           /* Simple cases: Value already set, does match or doesn't.  */
10366           if (targ != NULL_TREE && template_args_equal (targ, arg))
10367             return 0;
10368           else if (targ)
10369             return 1;
10370         }
10371       else
10372         {
10373           /* If PARM is `const T' and ARG is only `int', we don't have
10374              a match unless we are allowing additional qualification.
10375              If ARG is `const int' and PARM is just `T' that's OK;
10376              that binds `const int' to `T'.  */
10377           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
10378                                          arg, parm))
10379             return 1;
10380
10381           /* Consider the case where ARG is `const volatile int' and
10382              PARM is `const T'.  Then, T should be `volatile int'.  */
10383           arg = cp_build_qualified_type_real
10384             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
10385           if (arg == error_mark_node)
10386             return 1;
10387
10388           /* Simple cases: Value already set, does match or doesn't.  */
10389           if (targ != NULL_TREE && same_type_p (targ, arg))
10390             return 0;
10391           else if (targ)
10392             return 1;
10393
10394           /* Make sure that ARG is not a variable-sized array.  (Note
10395              that were talking about variable-sized arrays (like
10396              `int[n]'), rather than arrays of unknown size (like
10397              `int[]').)  We'll get very confused by such a type since
10398              the bound of the array will not be computable in an
10399              instantiation.  Besides, such types are not allowed in
10400              ISO C++, so we can do as we please here.  */
10401           if (variably_modified_type_p (arg, NULL_TREE))
10402             return 1;
10403         }
10404
10405       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
10406       return 0;
10407
10408     case TEMPLATE_PARM_INDEX:
10409       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
10410       if (tparm == error_mark_node)
10411         return 1;
10412
10413       if (TEMPLATE_PARM_LEVEL (parm)
10414           != template_decl_level (tparm))
10415         /* The PARM is not one we're trying to unify.  Just check
10416            to see if it matches ARG.  */
10417         return !(TREE_CODE (arg) == TREE_CODE (parm)
10418                  && cp_tree_equal (parm, arg));
10419
10420       idx = TEMPLATE_PARM_IDX (parm);
10421       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
10422
10423       if (targ)
10424         return !cp_tree_equal (targ, arg);
10425
10426       /* [temp.deduct.type] If, in the declaration of a function template
10427          with a non-type template-parameter, the non-type
10428          template-parameter is used in an expression in the function
10429          parameter-list and, if the corresponding template-argument is
10430          deduced, the template-argument type shall match the type of the
10431          template-parameter exactly, except that a template-argument
10432          deduced from an array bound may be of any integral type.
10433          The non-type parameter might use already deduced type parameters.  */
10434       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
10435       if (!TREE_TYPE (arg))
10436         /* Template-parameter dependent expression.  Just accept it for now.
10437            It will later be processed in convert_template_argument.  */
10438         ;
10439       else if (same_type_p (TREE_TYPE (arg), tparm))
10440         /* OK */;
10441       else if ((strict & UNIFY_ALLOW_INTEGER)
10442                && (TREE_CODE (tparm) == INTEGER_TYPE
10443                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
10444         /* Convert the ARG to the type of PARM; the deduced non-type
10445            template argument must exactly match the types of the
10446            corresponding parameter.  */
10447         arg = fold (build_nop (TREE_TYPE (parm), arg));
10448       else if (uses_template_parms (tparm))
10449         /* We haven't deduced the type of this parameter yet.  Try again
10450            later.  */
10451         return 0;
10452       else
10453         return 1;
10454
10455       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
10456       return 0;
10457
10458     case PTRMEM_CST:
10459      {
10460         /* A pointer-to-member constant can be unified only with
10461          another constant.  */
10462       if (TREE_CODE (arg) != PTRMEM_CST)
10463         return 1;
10464
10465       /* Just unify the class member. It would be useless (and possibly
10466          wrong, depending on the strict flags) to unify also
10467          PTRMEM_CST_CLASS, because we want to be sure that both parm and
10468          arg refer to the same variable, even if through different
10469          classes. For instance:
10470
10471          struct A { int x; };
10472          struct B : A { };
10473
10474          Unification of &A::x and &B::x must succeed.  */
10475       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
10476                     PTRMEM_CST_MEMBER (arg), strict);
10477      }
10478
10479     case POINTER_TYPE:
10480       {
10481         if (TREE_CODE (arg) != POINTER_TYPE)
10482           return 1;
10483
10484         /* [temp.deduct.call]
10485
10486            A can be another pointer or pointer to member type that can
10487            be converted to the deduced A via a qualification
10488            conversion (_conv.qual_).
10489
10490            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
10491            This will allow for additional cv-qualification of the
10492            pointed-to types if appropriate.  */
10493
10494         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
10495           /* The derived-to-base conversion only persists through one
10496              level of pointers.  */
10497           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
10498
10499         return unify (tparms, targs, TREE_TYPE (parm),
10500                       TREE_TYPE (arg), strict);
10501       }
10502
10503     case REFERENCE_TYPE:
10504       if (TREE_CODE (arg) != REFERENCE_TYPE)
10505         return 1;
10506       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
10507                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
10508
10509     case ARRAY_TYPE:
10510       if (TREE_CODE (arg) != ARRAY_TYPE)
10511         return 1;
10512       if ((TYPE_DOMAIN (parm) == NULL_TREE)
10513           != (TYPE_DOMAIN (arg) == NULL_TREE))
10514         return 1;
10515       if (TYPE_DOMAIN (parm) != NULL_TREE)
10516         {
10517           tree parm_max;
10518           tree arg_max;
10519
10520           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
10521           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
10522
10523           /* Our representation of array types uses "N - 1" as the
10524              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
10525              not an integer constant.  */
10526           if (TREE_CODE (parm_max) == MINUS_EXPR)
10527             {
10528               arg_max = fold_build2 (PLUS_EXPR,
10529                                      integer_type_node,
10530                                      arg_max,
10531                                      TREE_OPERAND (parm_max, 1));
10532               parm_max = TREE_OPERAND (parm_max, 0);
10533             }
10534
10535           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
10536             return 1;
10537         }
10538       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
10539                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
10540
10541     case REAL_TYPE:
10542     case COMPLEX_TYPE:
10543     case VECTOR_TYPE:
10544     case INTEGER_TYPE:
10545     case BOOLEAN_TYPE:
10546     case ENUMERAL_TYPE:
10547     case VOID_TYPE:
10548       if (TREE_CODE (arg) != TREE_CODE (parm))
10549         return 1;
10550
10551       /* We have already checked cv-qualification at the top of the
10552          function.  */
10553       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
10554         return 1;
10555
10556       /* As far as unification is concerned, this wins.  Later checks
10557          will invalidate it if necessary.  */
10558       return 0;
10559
10560       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
10561       /* Type INTEGER_CST can come from ordinary constant template args.  */
10562     case INTEGER_CST:
10563       while (TREE_CODE (arg) == NOP_EXPR)
10564         arg = TREE_OPERAND (arg, 0);
10565
10566       if (TREE_CODE (arg) != INTEGER_CST)
10567         return 1;
10568       return !tree_int_cst_equal (parm, arg);
10569
10570     case TREE_VEC:
10571       {
10572         int i;
10573         if (TREE_CODE (arg) != TREE_VEC)
10574           return 1;
10575         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
10576           return 1;
10577         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
10578           if (unify (tparms, targs,
10579                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
10580                      UNIFY_ALLOW_NONE))
10581             return 1;
10582         return 0;
10583       }
10584
10585     case RECORD_TYPE:
10586     case UNION_TYPE:
10587       if (TREE_CODE (arg) != TREE_CODE (parm))
10588         return 1;
10589
10590       if (TYPE_PTRMEMFUNC_P (parm))
10591         {
10592           if (!TYPE_PTRMEMFUNC_P (arg))
10593             return 1;
10594
10595           return unify (tparms, targs,
10596                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
10597                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
10598                         strict);
10599         }
10600
10601       if (CLASSTYPE_TEMPLATE_INFO (parm))
10602         {
10603           tree t = NULL_TREE;
10604
10605           if (strict_in & UNIFY_ALLOW_DERIVED)
10606             {
10607               /* First, we try to unify the PARM and ARG directly.  */
10608               t = try_class_unification (tparms, targs,
10609                                          parm, arg);
10610
10611               if (!t)
10612                 {
10613                   /* Fallback to the special case allowed in
10614                      [temp.deduct.call]:
10615
10616                        If P is a class, and P has the form
10617                        template-id, then A can be a derived class of
10618                        the deduced A.  Likewise, if P is a pointer to
10619                        a class of the form template-id, A can be a
10620                        pointer to a derived class pointed to by the
10621                        deduced A.  */
10622                   t = get_template_base (tparms, targs, parm, arg);
10623
10624                   if (!t)
10625                     return 1;
10626                 }
10627             }
10628           else if (CLASSTYPE_TEMPLATE_INFO (arg)
10629                    && (CLASSTYPE_TI_TEMPLATE (parm)
10630                        == CLASSTYPE_TI_TEMPLATE (arg)))
10631             /* Perhaps PARM is something like S<U> and ARG is S<int>.
10632                Then, we should unify `int' and `U'.  */
10633             t = arg;
10634           else
10635             /* There's no chance of unification succeeding.  */
10636             return 1;
10637
10638           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
10639                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
10640         }
10641       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
10642         return 1;
10643       return 0;
10644
10645     case METHOD_TYPE:
10646     case FUNCTION_TYPE:
10647       if (TREE_CODE (arg) != TREE_CODE (parm))
10648         return 1;
10649
10650       /* CV qualifications for methods can never be deduced, they must
10651          match exactly.  We need to check them explicitly here,
10652          because type_unification_real treats them as any other
10653          cvqualified parameter.  */
10654       if (TREE_CODE (parm) == METHOD_TYPE
10655           && (!check_cv_quals_for_unify
10656               (UNIFY_ALLOW_NONE,
10657                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
10658                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
10659         return 1;
10660
10661       if (unify (tparms, targs, TREE_TYPE (parm),
10662                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
10663         return 1;
10664       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
10665                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
10666                                     LOOKUP_NORMAL);
10667
10668     case OFFSET_TYPE:
10669       /* Unify a pointer to member with a pointer to member function, which
10670          deduces the type of the member as a function type. */
10671       if (TYPE_PTRMEMFUNC_P (arg))
10672         {
10673           tree method_type;
10674           tree fntype;
10675           cp_cv_quals cv_quals;
10676
10677           /* Check top-level cv qualifiers */
10678           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
10679             return 1;
10680
10681           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
10682                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
10683             return 1;
10684
10685           /* Determine the type of the function we are unifying against. */
10686           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
10687           fntype =
10688             build_function_type (TREE_TYPE (method_type),
10689                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
10690
10691           /* Extract the cv-qualifiers of the member function from the
10692              implicit object parameter and place them on the function
10693              type to be restored later. */
10694           cv_quals =
10695             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
10696           fntype = build_qualified_type (fntype, cv_quals);
10697           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
10698         }
10699
10700       if (TREE_CODE (arg) != OFFSET_TYPE)
10701         return 1;
10702       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
10703                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
10704         return 1;
10705       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
10706                     strict);
10707
10708     case CONST_DECL:
10709       if (DECL_TEMPLATE_PARM_P (parm))
10710         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
10711       if (arg != integral_constant_value (parm))
10712         return 1;
10713       return 0;
10714
10715     case FIELD_DECL:
10716     case TEMPLATE_DECL:
10717       /* Matched cases are handled by the ARG == PARM test above.  */
10718       return 1;
10719
10720     default:
10721       gcc_assert (EXPR_P (parm));
10722
10723       /* We must be looking at an expression.  This can happen with
10724          something like:
10725
10726            template <int I>
10727            void foo(S<I>, S<I + 2>);
10728
10729          This is a "nondeduced context":
10730
10731            [deduct.type]
10732
10733            The nondeduced contexts are:
10734
10735            --A type that is a template-id in which one or more of
10736              the template-arguments is an expression that references
10737              a template-parameter.
10738
10739          In these cases, we assume deduction succeeded, but don't
10740          actually infer any unifications.  */
10741
10742       if (!uses_template_parms (parm)
10743           && !template_args_equal (parm, arg))
10744         return 1;
10745       else
10746         return 0;
10747     }
10748 }
10749 \f
10750 /* Note that DECL can be defined in this translation unit, if
10751    required.  */
10752
10753 static void
10754 mark_definable (tree decl)
10755 {
10756   tree clone;
10757   DECL_NOT_REALLY_EXTERN (decl) = 1;
10758   FOR_EACH_CLONE (clone, decl)
10759     DECL_NOT_REALLY_EXTERN (clone) = 1;
10760 }
10761
10762 /* Called if RESULT is explicitly instantiated, or is a member of an
10763    explicitly instantiated class.  */
10764
10765 void
10766 mark_decl_instantiated (tree result, int extern_p)
10767 {
10768   SET_DECL_EXPLICIT_INSTANTIATION (result);
10769
10770   /* If this entity has already been written out, it's too late to
10771      make any modifications.  */
10772   if (TREE_ASM_WRITTEN (result))
10773     return;
10774
10775   if (TREE_CODE (result) != FUNCTION_DECL)
10776     /* The TREE_PUBLIC flag for function declarations will have been
10777        set correctly by tsubst.  */
10778     TREE_PUBLIC (result) = 1;
10779
10780   /* This might have been set by an earlier implicit instantiation.  */
10781   DECL_COMDAT (result) = 0;
10782
10783   if (extern_p)
10784     DECL_NOT_REALLY_EXTERN (result) = 0;
10785   else
10786     {
10787       mark_definable (result);
10788       /* Always make artificials weak.  */
10789       if (DECL_ARTIFICIAL (result) && flag_weak)
10790         comdat_linkage (result);
10791       /* For WIN32 we also want to put explicit instantiations in
10792          linkonce sections.  */
10793       else if (TREE_PUBLIC (result))
10794         maybe_make_one_only (result);
10795     }
10796
10797   /* If EXTERN_P, then this function will not be emitted -- unless
10798      followed by an explicit instantiation, at which point its linkage
10799      will be adjusted.  If !EXTERN_P, then this function will be
10800      emitted here.  In neither circumstance do we want
10801      import_export_decl to adjust the linkage.  */
10802   DECL_INTERFACE_KNOWN (result) = 1;
10803 }
10804
10805 /* Given two function templates PAT1 and PAT2, return:
10806
10807    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
10808    -1 if PAT2 is more specialized than PAT1.
10809    0 if neither is more specialized.
10810
10811    LEN indicates the number of parameters we should consider
10812    (defaulted parameters should not be considered).
10813
10814    The 1998 std underspecified function template partial ordering, and
10815    DR214 addresses the issue.  We take pairs of arguments, one from
10816    each of the templates, and deduce them against each other.  One of
10817    the templates will be more specialized if all the *other*
10818    template's arguments deduce against its arguments and at least one
10819    of its arguments *does* *not* deduce against the other template's
10820    corresponding argument.  Deduction is done as for class templates.
10821    The arguments used in deduction have reference and top level cv
10822    qualifiers removed.  Iff both arguments were originally reference
10823    types *and* deduction succeeds in both directions, the template
10824    with the more cv-qualified argument wins for that pairing (if
10825    neither is more cv-qualified, they both are equal).  Unlike regular
10826    deduction, after all the arguments have been deduced in this way,
10827    we do *not* verify the deduced template argument values can be
10828    substituted into non-deduced contexts, nor do we have to verify
10829    that all template arguments have been deduced.  */
10830
10831 int
10832 more_specialized_fn (tree pat1, tree pat2, int len)
10833 {
10834   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
10835   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
10836   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
10837   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
10838   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
10839   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
10840   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
10841   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
10842   int better1 = 0;
10843   int better2 = 0;
10844
10845   /* Remove the this parameter from non-static member functions.  If
10846      one is a non-static member function and the other is not a static
10847      member function, remove the first parameter from that function
10848      also.  This situation occurs for operator functions where we
10849      locate both a member function (with this pointer) and non-member
10850      operator (with explicit first operand).  */
10851   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
10852     {
10853       len--; /* LEN is the number of significant arguments for DECL1 */
10854       args1 = TREE_CHAIN (args1);
10855       if (!DECL_STATIC_FUNCTION_P (decl2))
10856         args2 = TREE_CHAIN (args2);
10857     }
10858   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
10859     {
10860       args2 = TREE_CHAIN (args2);
10861       if (!DECL_STATIC_FUNCTION_P (decl1))
10862         {
10863           len--;
10864           args1 = TREE_CHAIN (args1);
10865         }
10866     }
10867
10868   /* If only one is a conversion operator, they are unordered.  */
10869   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
10870     return 0;
10871
10872   /* Consider the return type for a conversion function */
10873   if (DECL_CONV_FN_P (decl1))
10874     {
10875       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
10876       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
10877       len++;
10878     }
10879
10880   processing_template_decl++;
10881
10882   while (len--)
10883     {
10884       tree arg1 = TREE_VALUE (args1);
10885       tree arg2 = TREE_VALUE (args2);
10886       int deduce1, deduce2;
10887       int quals1 = -1;
10888       int quals2 = -1;
10889
10890       if (TREE_CODE (arg1) == REFERENCE_TYPE)
10891         {
10892           arg1 = TREE_TYPE (arg1);
10893           quals1 = cp_type_quals (arg1);
10894         }
10895
10896       if (TREE_CODE (arg2) == REFERENCE_TYPE)
10897         {
10898           arg2 = TREE_TYPE (arg2);
10899           quals2 = cp_type_quals (arg2);
10900         }
10901
10902       if ((quals1 < 0) != (quals2 < 0))
10903         {
10904           /* Only of the args is a reference, see if we should apply
10905              array/function pointer decay to it.  This is not part of
10906              DR214, but is, IMHO, consistent with the deduction rules
10907              for the function call itself, and with our earlier
10908              implementation of the underspecified partial ordering
10909              rules.  (nathan).  */
10910           if (quals1 >= 0)
10911             {
10912               switch (TREE_CODE (arg1))
10913                 {
10914                 case ARRAY_TYPE:
10915                   arg1 = TREE_TYPE (arg1);
10916                   /* FALLTHROUGH. */
10917                 case FUNCTION_TYPE:
10918                   arg1 = build_pointer_type (arg1);
10919                   break;
10920
10921                 default:
10922                   break;
10923                 }
10924             }
10925           else
10926             {
10927               switch (TREE_CODE (arg2))
10928                 {
10929                 case ARRAY_TYPE:
10930                   arg2 = TREE_TYPE (arg2);
10931                   /* FALLTHROUGH. */
10932                 case FUNCTION_TYPE:
10933                   arg2 = build_pointer_type (arg2);
10934                   break;
10935
10936                 default:
10937                   break;
10938                 }
10939             }
10940         }
10941
10942       arg1 = TYPE_MAIN_VARIANT (arg1);
10943       arg2 = TYPE_MAIN_VARIANT (arg2);
10944
10945       deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
10946       deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
10947
10948       if (!deduce1)
10949         better2 = -1;
10950       if (!deduce2)
10951         better1 = -1;
10952       if (better1 < 0 && better2 < 0)
10953         /* We've failed to deduce something in either direction.
10954            These must be unordered.  */
10955         break;
10956
10957       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
10958         {
10959           /* Deduces in both directions, see if quals can
10960              disambiguate.  Pretend the worse one failed to deduce. */
10961           if ((quals1 & quals2) == quals2)
10962             deduce1 = 0;
10963           if ((quals1 & quals2) == quals1)
10964             deduce2 = 0;
10965         }
10966       if (deduce1 && !deduce2 && !better2)
10967         better2 = 1;
10968       if (deduce2 && !deduce1 && !better1)
10969         better1 = 1;
10970
10971       args1 = TREE_CHAIN (args1);
10972       args2 = TREE_CHAIN (args2);
10973     }
10974
10975   processing_template_decl--;
10976
10977   return (better1 > 0) - (better2 > 0);
10978 }
10979
10980 /* Determine which of two partial specializations is more specialized.
10981
10982    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
10983    to the first partial specialization.  The TREE_VALUE is the
10984    innermost set of template parameters for the partial
10985    specialization.  PAT2 is similar, but for the second template.
10986
10987    Return 1 if the first partial specialization is more specialized;
10988    -1 if the second is more specialized; 0 if neither is more
10989    specialized.
10990
10991    See [temp.class.order] for information about determining which of
10992    two templates is more specialized.  */
10993
10994 static int
10995 more_specialized_class (tree pat1, tree pat2)
10996 {
10997   tree targs;
10998   tree tmpl1, tmpl2;
10999   int winner = 0;
11000
11001   tmpl1 = TREE_TYPE (pat1);
11002   tmpl2 = TREE_TYPE (pat2);
11003
11004   /* Just like what happens for functions, if we are ordering between
11005      different class template specializations, we may encounter dependent
11006      types in the arguments, and we need our dependency check functions
11007      to behave correctly.  */
11008   ++processing_template_decl;
11009   targs = get_class_bindings (TREE_VALUE (pat1),
11010                               CLASSTYPE_TI_ARGS (tmpl1),
11011                               CLASSTYPE_TI_ARGS (tmpl2));
11012   if (targs)
11013     --winner;
11014
11015   targs = get_class_bindings (TREE_VALUE (pat2),
11016                               CLASSTYPE_TI_ARGS (tmpl2),
11017                               CLASSTYPE_TI_ARGS (tmpl1));
11018   if (targs)
11019     ++winner;
11020   --processing_template_decl;
11021
11022   return winner;
11023 }
11024
11025 /* Return the template arguments that will produce the function signature
11026    DECL from the function template FN, with the explicit template
11027    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
11028    also match.  Return NULL_TREE if no satisfactory arguments could be
11029    found.  */
11030
11031 static tree
11032 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
11033 {
11034   int ntparms = DECL_NTPARMS (fn);
11035   tree targs = make_tree_vec (ntparms);
11036   tree decl_type;
11037   tree decl_arg_types;
11038
11039   /* Substitute the explicit template arguments into the type of DECL.
11040      The call to fn_type_unification will handle substitution into the
11041      FN.  */
11042   decl_type = TREE_TYPE (decl);
11043   if (explicit_args && uses_template_parms (decl_type))
11044     {
11045       tree tmpl;
11046       tree converted_args;
11047
11048       if (DECL_TEMPLATE_INFO (decl))
11049         tmpl = DECL_TI_TEMPLATE (decl);
11050       else
11051         /* We can get here for some invalid specializations.  */
11052         return NULL_TREE;
11053
11054       converted_args
11055         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
11056                                  explicit_args, NULL_TREE,
11057                                  tf_none,
11058                                  /*require_all_args=*/false,
11059                                  /*use_default_args=*/false);
11060       if (converted_args == error_mark_node)
11061         return NULL_TREE;
11062
11063       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
11064       if (decl_type == error_mark_node)
11065         return NULL_TREE;
11066     }
11067
11068   decl_arg_types = TYPE_ARG_TYPES (decl_type);
11069   /* Never do unification on the 'this' parameter.  */
11070   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
11071     decl_arg_types = TREE_CHAIN (decl_arg_types);
11072
11073   if (fn_type_unification (fn, explicit_args, targs,
11074                            decl_arg_types,
11075                            (check_rettype || DECL_CONV_FN_P (fn)
11076                             ? TREE_TYPE (decl_type) : NULL_TREE),
11077                            DEDUCE_EXACT, LOOKUP_NORMAL))
11078     return NULL_TREE;
11079
11080   return targs;
11081 }
11082
11083 /* Return the innermost template arguments that, when applied to a
11084    template specialization whose innermost template parameters are
11085    TPARMS, and whose specialization arguments are PARMS, yield the
11086    ARGS.
11087
11088    For example, suppose we have:
11089
11090      template <class T, class U> struct S {};
11091      template <class T> struct S<T*, int> {};
11092
11093    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
11094    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
11095    int}.  The resulting vector will be {double}, indicating that `T'
11096    is bound to `double'.  */
11097
11098 static tree
11099 get_class_bindings (tree tparms, tree spec_args, tree args)
11100 {
11101   int i, ntparms = TREE_VEC_LENGTH (tparms);
11102   tree deduced_args;
11103   tree innermost_deduced_args;
11104
11105   innermost_deduced_args = make_tree_vec (ntparms);
11106   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
11107     {
11108       deduced_args = copy_node (args);
11109       SET_TMPL_ARGS_LEVEL (deduced_args,
11110                            TMPL_ARGS_DEPTH (deduced_args),
11111                            innermost_deduced_args);
11112     }
11113   else
11114     deduced_args = innermost_deduced_args;
11115
11116   if (unify (tparms, deduced_args,
11117              INNERMOST_TEMPLATE_ARGS (spec_args),
11118              INNERMOST_TEMPLATE_ARGS (args),
11119              UNIFY_ALLOW_NONE))
11120     return NULL_TREE;
11121
11122   for (i =  0; i < ntparms; ++i)
11123     if (! TREE_VEC_ELT (innermost_deduced_args, i))
11124       return NULL_TREE;
11125
11126   /* Verify that nondeduced template arguments agree with the type
11127      obtained from argument deduction.
11128
11129      For example:
11130
11131        struct A { typedef int X; };
11132        template <class T, class U> struct C {};
11133        template <class T> struct C<T, typename T::X> {};
11134
11135      Then with the instantiation `C<A, int>', we can deduce that
11136      `T' is `A' but unify () does not check whether `typename T::X'
11137      is `int'.  */
11138   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
11139   if (spec_args == error_mark_node
11140       /* We only need to check the innermost arguments; the other
11141          arguments will always agree.  */
11142       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
11143                               INNERMOST_TEMPLATE_ARGS (args)))
11144     return NULL_TREE;
11145
11146   return deduced_args;
11147 }
11148
11149 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
11150    Return the TREE_LIST node with the most specialized template, if
11151    any.  If there is no most specialized template, the error_mark_node
11152    is returned.
11153
11154    Note that this function does not look at, or modify, the
11155    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
11156    returned is one of the elements of INSTANTIATIONS, callers may
11157    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
11158    and retrieve it from the value returned.  */
11159
11160 tree
11161 most_specialized_instantiation (tree templates)
11162 {
11163   tree fn, champ;
11164
11165   ++processing_template_decl;
11166
11167   champ = templates;
11168   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
11169     {
11170       int fate = 0;
11171
11172       if (get_bindings (TREE_VALUE (champ),
11173                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
11174                         NULL_TREE, /*check_ret=*/false))
11175         fate--;
11176
11177       if (get_bindings (TREE_VALUE (fn),
11178                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
11179                         NULL_TREE, /*check_ret=*/false))
11180         fate++;
11181
11182       if (fate == -1)
11183         champ = fn;
11184       else if (!fate)
11185         {
11186           /* Equally specialized, move to next function.  If there
11187              is no next function, nothing's most specialized.  */
11188           fn = TREE_CHAIN (fn);
11189           champ = fn;
11190           if (!fn)
11191             break;
11192         }
11193     }
11194
11195   if (champ)
11196     /* Now verify that champ is better than everything earlier in the
11197        instantiation list.  */
11198     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
11199       if (get_bindings (TREE_VALUE (champ),
11200                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
11201                         NULL_TREE, /*check_ret=*/false)
11202           || !get_bindings (TREE_VALUE (fn),
11203                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
11204                             NULL_TREE, /*check_ret=*/false))
11205         {
11206           champ = NULL_TREE;
11207           break;
11208         }
11209
11210   processing_template_decl--;
11211
11212   if (!champ)
11213     return error_mark_node;
11214
11215   return champ;
11216 }
11217
11218 /* If DECL is a specialization of some template, return the most
11219    general such template.  Otherwise, returns NULL_TREE.
11220
11221    For example, given:
11222
11223      template <class T> struct S { template <class U> void f(U); };
11224
11225    if TMPL is `template <class U> void S<int>::f(U)' this will return
11226    the full template.  This function will not trace past partial
11227    specializations, however.  For example, given in addition:
11228
11229      template <class T> struct S<T*> { template <class U> void f(U); };
11230
11231    if TMPL is `template <class U> void S<int*>::f(U)' this will return
11232    `template <class T> template <class U> S<T*>::f(U)'.  */
11233
11234 tree
11235 most_general_template (tree decl)
11236 {
11237   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
11238      an immediate specialization.  */
11239   if (TREE_CODE (decl) == FUNCTION_DECL)
11240     {
11241       if (DECL_TEMPLATE_INFO (decl)) {
11242         decl = DECL_TI_TEMPLATE (decl);
11243
11244         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
11245            template friend.  */
11246         if (TREE_CODE (decl) != TEMPLATE_DECL)
11247           return NULL_TREE;
11248       } else
11249         return NULL_TREE;
11250     }
11251
11252   /* Look for more and more general templates.  */
11253   while (DECL_TEMPLATE_INFO (decl))
11254     {
11255       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
11256          (See cp-tree.h for details.)  */
11257       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
11258         break;
11259
11260       if (CLASS_TYPE_P (TREE_TYPE (decl))
11261           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
11262         break;
11263
11264       /* Stop if we run into an explicitly specialized class template.  */
11265       if (!DECL_NAMESPACE_SCOPE_P (decl)
11266           && DECL_CONTEXT (decl)
11267           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
11268         break;
11269
11270       decl = DECL_TI_TEMPLATE (decl);
11271     }
11272
11273   return decl;
11274 }
11275
11276 /* Return the most specialized of the class template partial
11277    specializations of TMPL which can produce TYPE, a specialization of
11278    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
11279    a _TYPE node corresponding to the partial specialization, while the
11280    TREE_PURPOSE is the set of template arguments that must be
11281    substituted into the TREE_TYPE in order to generate TYPE.
11282
11283    If the choice of partial specialization is ambiguous, a diagnostic
11284    is issued, and the error_mark_node is returned.  If there are no
11285    partial specializations of TMPL matching TYPE, then NULL_TREE is
11286    returned.  */
11287
11288 static tree
11289 most_specialized_class (tree type, tree tmpl)
11290 {
11291   tree list = NULL_TREE;
11292   tree t;
11293   tree champ;
11294   int fate;
11295   bool ambiguous_p;
11296   tree args;
11297
11298   tmpl = most_general_template (tmpl);
11299   args = CLASSTYPE_TI_ARGS (type);
11300   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
11301     {
11302       tree partial_spec_args;
11303       tree spec_args;
11304
11305       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
11306       spec_args = get_class_bindings (TREE_VALUE (t),
11307                                       partial_spec_args,
11308                                       args);
11309       if (spec_args)
11310         {
11311           list = tree_cons (spec_args, TREE_VALUE (t), list);
11312           TREE_TYPE (list) = TREE_TYPE (t);
11313         }
11314     }
11315
11316   if (! list)
11317     return NULL_TREE;
11318
11319   ambiguous_p = false;
11320   t = list;
11321   champ = t;
11322   t = TREE_CHAIN (t);
11323   for (; t; t = TREE_CHAIN (t))
11324     {
11325       fate = more_specialized_class (champ, t);
11326       if (fate == 1)
11327         ;
11328       else
11329         {
11330           if (fate == 0)
11331             {
11332               t = TREE_CHAIN (t);
11333               if (! t)
11334                 {
11335                   ambiguous_p = true;
11336                   break;
11337                 }
11338             }
11339           champ = t;
11340         }
11341     }
11342
11343   if (!ambiguous_p)
11344     for (t = list; t && t != champ; t = TREE_CHAIN (t))
11345       {
11346         fate = more_specialized_class (champ, t);
11347         if (fate != 1)
11348           {
11349             ambiguous_p = true;
11350             break;
11351           }
11352       }
11353
11354   if (ambiguous_p)
11355     {
11356       const char *str = "candidates are:";
11357       error ("ambiguous class template instantiation for %q#T", type);
11358       for (t = list; t; t = TREE_CHAIN (t))
11359         {
11360           error ("%s %+#T", str, TREE_TYPE (t));
11361           str = "               ";
11362         }
11363       return error_mark_node;
11364     }
11365
11366   return champ;
11367 }
11368
11369 /* Explicitly instantiate DECL.  */
11370
11371 void
11372 do_decl_instantiation (tree decl, tree storage)
11373 {
11374   tree result = NULL_TREE;
11375   int extern_p = 0;
11376
11377   if (!decl || decl == error_mark_node)
11378     /* An error occurred, for which grokdeclarator has already issued
11379        an appropriate message.  */
11380     return;
11381   else if (! DECL_LANG_SPECIFIC (decl))
11382     {
11383       error ("explicit instantiation of non-template %q#D", decl);
11384       return;
11385     }
11386   else if (TREE_CODE (decl) == VAR_DECL)
11387     {
11388       /* There is an asymmetry here in the way VAR_DECLs and
11389          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
11390          the latter, the DECL we get back will be marked as a
11391          template instantiation, and the appropriate
11392          DECL_TEMPLATE_INFO will be set up.  This does not happen for
11393          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
11394          should handle VAR_DECLs as it currently handles
11395          FUNCTION_DECLs.  */
11396       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
11397       if (!result || TREE_CODE (result) != VAR_DECL)
11398         {
11399           error ("no matching template for %qD found", decl);
11400           return;
11401         }
11402     }
11403   else if (TREE_CODE (decl) != FUNCTION_DECL)
11404     {
11405       error ("explicit instantiation of %q#D", decl);
11406       return;
11407     }
11408   else
11409     result = decl;
11410
11411   /* Check for various error cases.  Note that if the explicit
11412      instantiation is valid the RESULT will currently be marked as an
11413      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
11414      until we get here.  */
11415
11416   if (DECL_TEMPLATE_SPECIALIZATION (result))
11417     {
11418       /* DR 259 [temp.spec].
11419
11420          Both an explicit instantiation and a declaration of an explicit
11421          specialization shall not appear in a program unless the explicit
11422          instantiation follows a declaration of the explicit specialization.
11423
11424          For a given set of template parameters, if an explicit
11425          instantiation of a template appears after a declaration of an
11426          explicit specialization for that template, the explicit
11427          instantiation has no effect.  */
11428       return;
11429     }
11430   else if (DECL_EXPLICIT_INSTANTIATION (result))
11431     {
11432       /* [temp.spec]
11433
11434          No program shall explicitly instantiate any template more
11435          than once.
11436
11437          We check DECL_NOT_REALLY_EXTERN so as not to complain when
11438          the first instantiation was `extern' and the second is not,
11439          and EXTERN_P for the opposite case.  */
11440       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
11441         pedwarn ("duplicate explicit instantiation of %q#D", result);
11442       /* If an "extern" explicit instantiation follows an ordinary
11443          explicit instantiation, the template is instantiated.  */
11444       if (extern_p)
11445         return;
11446     }
11447   else if (!DECL_IMPLICIT_INSTANTIATION (result))
11448     {
11449       error ("no matching template for %qD found", result);
11450       return;
11451     }
11452   else if (!DECL_TEMPLATE_INFO (result))
11453     {
11454       pedwarn ("explicit instantiation of non-template %q#D", result);
11455       return;
11456     }
11457
11458   if (storage == NULL_TREE)
11459     ;
11460   else if (storage == ridpointers[(int) RID_EXTERN])
11461     {
11462       if (pedantic && !in_system_header)
11463         pedwarn ("ISO C++ forbids the use of %<extern%> on explicit "
11464                  "instantiations");
11465       extern_p = 1;
11466     }
11467   else
11468     error ("storage class %qD applied to template instantiation", storage);
11469
11470   check_explicit_instantiation_namespace (result);
11471   mark_decl_instantiated (result, extern_p);
11472   if (! extern_p)
11473     instantiate_decl (result, /*defer_ok=*/1,
11474                       /*expl_inst_class_mem_p=*/false);
11475 }
11476
11477 static void
11478 mark_class_instantiated (tree t, int extern_p)
11479 {
11480   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
11481   SET_CLASSTYPE_INTERFACE_KNOWN (t);
11482   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
11483   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
11484   if (! extern_p)
11485     {
11486       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
11487       rest_of_type_compilation (t, 1);
11488     }
11489 }
11490
11491 /* Called from do_type_instantiation through binding_table_foreach to
11492    do recursive instantiation for the type bound in ENTRY.  */
11493 static void
11494 bt_instantiate_type_proc (binding_entry entry, void *data)
11495 {
11496   tree storage = *(tree *) data;
11497
11498   if (IS_AGGR_TYPE (entry->type)
11499       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
11500     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
11501 }
11502
11503 /* Called from do_type_instantiation to instantiate a member
11504    (a member function or a static member variable) of an
11505    explicitly instantiated class template.  */
11506 static void
11507 instantiate_class_member (tree decl, int extern_p)
11508 {
11509   mark_decl_instantiated (decl, extern_p);
11510   if (! extern_p)
11511     instantiate_decl (decl, /*defer_ok=*/1,
11512                       /*expl_inst_class_mem_p=*/true);
11513 }
11514
11515 /* Perform an explicit instantiation of template class T.  STORAGE, if
11516    non-null, is the RID for extern, inline or static.  COMPLAIN is
11517    nonzero if this is called from the parser, zero if called recursively,
11518    since the standard is unclear (as detailed below).  */
11519
11520 void
11521 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
11522 {
11523   int extern_p = 0;
11524   int nomem_p = 0;
11525   int static_p = 0;
11526   int previous_instantiation_extern_p = 0;
11527
11528   if (TREE_CODE (t) == TYPE_DECL)
11529     t = TREE_TYPE (t);
11530
11531   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
11532     {
11533       error ("explicit instantiation of non-template type %qT", t);
11534       return;
11535     }
11536
11537   complete_type (t);
11538
11539   if (!COMPLETE_TYPE_P (t))
11540     {
11541       if (complain & tf_error)
11542         error ("explicit instantiation of %q#T before definition of template",
11543                t);
11544       return;
11545     }
11546
11547   if (storage != NULL_TREE)
11548     {
11549       if (pedantic && !in_system_header)
11550         pedwarn("ISO C++ forbids the use of %qE on explicit instantiations",
11551                 storage);
11552
11553       if (storage == ridpointers[(int) RID_INLINE])
11554         nomem_p = 1;
11555       else if (storage == ridpointers[(int) RID_EXTERN])
11556         extern_p = 1;
11557       else if (storage == ridpointers[(int) RID_STATIC])
11558         static_p = 1;
11559       else
11560         {
11561           error ("storage class %qD applied to template instantiation",
11562                  storage);
11563           extern_p = 0;
11564         }
11565     }
11566
11567   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
11568     {
11569       /* DR 259 [temp.spec].
11570
11571          Both an explicit instantiation and a declaration of an explicit
11572          specialization shall not appear in a program unless the explicit
11573          instantiation follows a declaration of the explicit specialization.
11574
11575          For a given set of template parameters, if an explicit
11576          instantiation of a template appears after a declaration of an
11577          explicit specialization for that template, the explicit
11578          instantiation has no effect.  */
11579       return;
11580     }
11581   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
11582     {
11583       /* [temp.spec]
11584
11585          No program shall explicitly instantiate any template more
11586          than once.
11587
11588          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
11589          instantiation was `extern'.  If EXTERN_P then the second is.
11590          These cases are OK.  */
11591       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
11592
11593       if (!previous_instantiation_extern_p && !extern_p
11594           && (complain & tf_error))
11595         pedwarn ("duplicate explicit instantiation of %q#T", t);
11596
11597       /* If we've already instantiated the template, just return now.  */
11598       if (!CLASSTYPE_INTERFACE_ONLY (t))
11599         return;
11600     }
11601
11602   check_explicit_instantiation_namespace (TYPE_NAME (t));
11603   mark_class_instantiated (t, extern_p);
11604
11605   if (nomem_p)
11606     return;
11607
11608   {
11609     tree tmp;
11610
11611     /* In contrast to implicit instantiation, where only the
11612        declarations, and not the definitions, of members are
11613        instantiated, we have here:
11614
11615          [temp.explicit]
11616
11617          The explicit instantiation of a class template specialization
11618          implies the instantiation of all of its members not
11619          previously explicitly specialized in the translation unit
11620          containing the explicit instantiation.
11621
11622        Of course, we can't instantiate member template classes, since
11623        we don't have any arguments for them.  Note that the standard
11624        is unclear on whether the instantiation of the members are
11625        *explicit* instantiations or not.  However, the most natural
11626        interpretation is that it should be an explicit instantiation.  */
11627
11628     if (! static_p)
11629       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
11630         if (TREE_CODE (tmp) == FUNCTION_DECL
11631             && DECL_TEMPLATE_INSTANTIATION (tmp))
11632           instantiate_class_member (tmp, extern_p);
11633
11634     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
11635       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
11636         instantiate_class_member (tmp, extern_p);
11637
11638     if (CLASSTYPE_NESTED_UTDS (t))
11639       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
11640                              bt_instantiate_type_proc, &storage);
11641   }
11642 }
11643
11644 /* Given a function DECL, which is a specialization of TMPL, modify
11645    DECL to be a re-instantiation of TMPL with the same template
11646    arguments.  TMPL should be the template into which tsubst'ing
11647    should occur for DECL, not the most general template.
11648
11649    One reason for doing this is a scenario like this:
11650
11651      template <class T>
11652      void f(const T&, int i);
11653
11654      void g() { f(3, 7); }
11655
11656      template <class T>
11657      void f(const T& t, const int i) { }
11658
11659    Note that when the template is first instantiated, with
11660    instantiate_template, the resulting DECL will have no name for the
11661    first parameter, and the wrong type for the second.  So, when we go
11662    to instantiate the DECL, we regenerate it.  */
11663
11664 static void
11665 regenerate_decl_from_template (tree decl, tree tmpl)
11666 {
11667   /* The arguments used to instantiate DECL, from the most general
11668      template.  */
11669   tree args;
11670   tree code_pattern;
11671
11672   args = DECL_TI_ARGS (decl);
11673   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
11674
11675   /* Make sure that we can see identifiers, and compute access
11676      correctly.  */
11677   push_access_scope (decl);
11678
11679   if (TREE_CODE (decl) == FUNCTION_DECL)
11680     {
11681       tree decl_parm;
11682       tree pattern_parm;
11683       tree specs;
11684       int args_depth;
11685       int parms_depth;
11686
11687       args_depth = TMPL_ARGS_DEPTH (args);
11688       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
11689       if (args_depth > parms_depth)
11690         args = get_innermost_template_args (args, parms_depth);
11691
11692       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
11693                                               args, tf_error, NULL_TREE);
11694       if (specs)
11695         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
11696                                                     specs);
11697
11698       /* Merge parameter declarations.  */
11699       decl_parm = skip_artificial_parms_for (decl,
11700                                              DECL_ARGUMENTS (decl));
11701       pattern_parm
11702         = skip_artificial_parms_for (code_pattern,
11703                                      DECL_ARGUMENTS (code_pattern));
11704       while (decl_parm)
11705         {
11706           tree parm_type;
11707           tree attributes;
11708
11709           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
11710             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
11711           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
11712                               NULL_TREE);
11713           parm_type = type_decays_to (parm_type);
11714           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
11715             TREE_TYPE (decl_parm) = parm_type;
11716           attributes = DECL_ATTRIBUTES (pattern_parm);
11717           if (DECL_ATTRIBUTES (decl_parm) != attributes)
11718             {
11719               DECL_ATTRIBUTES (decl_parm) = attributes;
11720               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
11721             }
11722           decl_parm = TREE_CHAIN (decl_parm);
11723           pattern_parm = TREE_CHAIN (pattern_parm);
11724         }
11725
11726       /* Merge additional specifiers from the CODE_PATTERN.  */
11727       if (DECL_DECLARED_INLINE_P (code_pattern)
11728           && !DECL_DECLARED_INLINE_P (decl))
11729         DECL_DECLARED_INLINE_P (decl) = 1;
11730       if (DECL_INLINE (code_pattern) && !DECL_INLINE (decl))
11731         DECL_INLINE (decl) = 1;
11732     }
11733   else if (TREE_CODE (decl) == VAR_DECL)
11734     DECL_INITIAL (decl) =
11735       tsubst_expr (DECL_INITIAL (code_pattern), args,
11736                    tf_error, DECL_TI_TEMPLATE (decl));
11737   else
11738     gcc_unreachable ();
11739
11740   pop_access_scope (decl);
11741 }
11742
11743 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
11744    substituted to get DECL.  */
11745
11746 tree
11747 template_for_substitution (tree decl)
11748 {
11749   tree tmpl = DECL_TI_TEMPLATE (decl);
11750
11751   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
11752      for the instantiation.  This is not always the most general
11753      template.  Consider, for example:
11754
11755         template <class T>
11756         struct S { template <class U> void f();
11757                    template <> void f<int>(); };
11758
11759      and an instantiation of S<double>::f<int>.  We want TD to be the
11760      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
11761   while (/* An instantiation cannot have a definition, so we need a
11762             more general template.  */
11763          DECL_TEMPLATE_INSTANTIATION (tmpl)
11764            /* We must also deal with friend templates.  Given:
11765
11766                 template <class T> struct S {
11767                   template <class U> friend void f() {};
11768                 };
11769
11770               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
11771               so far as the language is concerned, but that's still
11772               where we get the pattern for the instantiation from.  On
11773               other hand, if the definition comes outside the class, say:
11774
11775                 template <class T> struct S {
11776                   template <class U> friend void f();
11777                 };
11778                 template <class U> friend void f() {}
11779
11780               we don't need to look any further.  That's what the check for
11781               DECL_INITIAL is for.  */
11782           || (TREE_CODE (decl) == FUNCTION_DECL
11783               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
11784               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
11785     {
11786       /* The present template, TD, should not be a definition.  If it
11787          were a definition, we should be using it!  Note that we
11788          cannot restructure the loop to just keep going until we find
11789          a template with a definition, since that might go too far if
11790          a specialization was declared, but not defined.  */
11791       gcc_assert (TREE_CODE (decl) != VAR_DECL
11792                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
11793
11794       /* Fetch the more general template.  */
11795       tmpl = DECL_TI_TEMPLATE (tmpl);
11796     }
11797
11798   return tmpl;
11799 }
11800
11801 /* Produce the definition of D, a _DECL generated from a template.  If
11802    DEFER_OK is nonzero, then we don't have to actually do the
11803    instantiation now; we just have to do it sometime.  Normally it is
11804    an error if this is an explicit instantiation but D is undefined.
11805    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
11806    explicitly instantiated class template.  */
11807
11808 tree
11809 instantiate_decl (tree d, int defer_ok,
11810                   bool expl_inst_class_mem_p)
11811 {
11812   tree tmpl = DECL_TI_TEMPLATE (d);
11813   tree gen_args;
11814   tree args;
11815   tree td;
11816   tree code_pattern;
11817   tree spec;
11818   tree gen_tmpl;
11819   bool pattern_defined;
11820   int need_push;
11821   location_t saved_loc = input_location;
11822   bool external_p;
11823
11824   /* This function should only be used to instantiate templates for
11825      functions and static member variables.  */
11826   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
11827               || TREE_CODE (d) == VAR_DECL);
11828
11829   /* Variables are never deferred; if instantiation is required, they
11830      are instantiated right away.  That allows for better code in the
11831      case that an expression refers to the value of the variable --
11832      if the variable has a constant value the referring expression can
11833      take advantage of that fact.  */
11834   if (TREE_CODE (d) == VAR_DECL)
11835     defer_ok = 0;
11836
11837   /* Don't instantiate cloned functions.  Instead, instantiate the
11838      functions they cloned.  */
11839   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
11840     d = DECL_CLONED_FUNCTION (d);
11841
11842   if (DECL_TEMPLATE_INSTANTIATED (d))
11843     /* D has already been instantiated.  It might seem reasonable to
11844        check whether or not D is an explicit instantiation, and, if so,
11845        stop here.  But when an explicit instantiation is deferred
11846        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
11847        is set, even though we still need to do the instantiation.  */
11848     return d;
11849
11850   /* If we already have a specialization of this declaration, then
11851      there's no reason to instantiate it.  Note that
11852      retrieve_specialization gives us both instantiations and
11853      specializations, so we must explicitly check
11854      DECL_TEMPLATE_SPECIALIZATION.  */
11855   gen_tmpl = most_general_template (tmpl);
11856   gen_args = DECL_TI_ARGS (d);
11857   spec = retrieve_specialization (gen_tmpl, gen_args,
11858                                   /*class_specializations_p=*/false);
11859   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
11860     return spec;
11861
11862   /* This needs to happen before any tsubsting.  */
11863   if (! push_tinst_level (d))
11864     return d;
11865
11866   timevar_push (TV_PARSE);
11867
11868   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
11869      for the instantiation.  */
11870   td = template_for_substitution (d);
11871   code_pattern = DECL_TEMPLATE_RESULT (td);
11872
11873   /* We should never be trying to instantiate a member of a class
11874      template or partial specialization.  */
11875   gcc_assert (d != code_pattern);
11876
11877   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
11878       || DECL_TEMPLATE_SPECIALIZATION (td))
11879     /* In the case of a friend template whose definition is provided
11880        outside the class, we may have too many arguments.  Drop the
11881        ones we don't need.  The same is true for specializations.  */
11882     args = get_innermost_template_args
11883       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
11884   else
11885     args = gen_args;
11886
11887   if (TREE_CODE (d) == FUNCTION_DECL)
11888     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
11889   else
11890     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
11891
11892   /* We may be in the middle of deferred access check.  Disable it now.  */
11893   push_deferring_access_checks (dk_no_deferred);
11894
11895   /* Unless an explicit instantiation directive has already determined
11896      the linkage of D, remember that a definition is available for
11897      this entity.  */
11898   if (pattern_defined
11899       && !DECL_INTERFACE_KNOWN (d)
11900       && !DECL_NOT_REALLY_EXTERN (d))
11901     mark_definable (d);
11902
11903   input_location = DECL_SOURCE_LOCATION (d);
11904
11905   /* If D is a member of an explicitly instantiated class template,
11906      and no definition is available, treat it like an implicit
11907      instantiation.  */
11908   if (!pattern_defined && expl_inst_class_mem_p
11909       && DECL_EXPLICIT_INSTANTIATION (d))
11910     {
11911       DECL_NOT_REALLY_EXTERN (d) = 0;
11912       DECL_INTERFACE_KNOWN (d) = 0;
11913       SET_DECL_IMPLICIT_INSTANTIATION (d);
11914     }
11915
11916   if (!defer_ok)
11917     {
11918       /* Recheck the substitutions to obtain any warning messages
11919          about ignoring cv qualifiers.  */
11920       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
11921       tree type = TREE_TYPE (gen);
11922
11923       /* Make sure that we can see identifiers, and compute access
11924          correctly.  D is already the target FUNCTION_DECL with the
11925          right context.  */
11926       push_access_scope (d);
11927
11928       if (TREE_CODE (gen) == FUNCTION_DECL)
11929         {
11930           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
11931           tsubst (TYPE_RAISES_EXCEPTIONS (type), gen_args,
11932                   tf_warning_or_error, d);
11933           /* Don't simply tsubst the function type, as that will give
11934              duplicate warnings about poor parameter qualifications.
11935              The function arguments are the same as the decl_arguments
11936              without the top level cv qualifiers.  */
11937           type = TREE_TYPE (type);
11938         }
11939       tsubst (type, gen_args, tf_warning_or_error, d);
11940
11941       pop_access_scope (d);
11942     }
11943
11944   /* Check to see whether we know that this template will be
11945      instantiated in some other file, as with "extern template"
11946      extension.  */
11947   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
11948   /* In general, we do not instantiate such templates...  */
11949   if (external_p
11950       /* ... but we instantiate inline functions so that we can inline
11951          them and ... */
11952       && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d))
11953       /* ... we instantiate static data members whose values are
11954          needed in integral constant expressions.  */
11955       && ! (TREE_CODE (d) == VAR_DECL
11956             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
11957     goto out;
11958   /* Defer all other templates, unless we have been explicitly
11959      forbidden from doing so.  */
11960   if (/* If there is no definition, we cannot instantiate the
11961          template.  */
11962       ! pattern_defined
11963       /* If it's OK to postpone instantiation, do so.  */
11964       || defer_ok
11965       /* If this is a static data member that will be defined
11966          elsewhere, we don't want to instantiate the entire data
11967          member, but we do want to instantiate the initializer so that
11968          we can substitute that elsewhere.  */
11969       || (external_p && TREE_CODE (d) == VAR_DECL))
11970     {
11971       /* The definition of the static data member is now required so
11972          we must substitute the initializer.  */
11973       if (TREE_CODE (d) == VAR_DECL
11974           && !DECL_INITIAL (d)
11975           && DECL_INITIAL (code_pattern))
11976         {
11977           tree ns;
11978           tree init;
11979
11980           ns = decl_namespace_context (d);
11981           push_nested_namespace (ns);
11982           push_nested_class (DECL_CONTEXT (d));
11983           init = tsubst_expr (DECL_INITIAL (code_pattern),
11984                               args,
11985                               tf_warning_or_error, NULL_TREE);
11986           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
11987                           /*asmspec_tree=*/NULL_TREE,
11988                           LOOKUP_ONLYCONVERTING);
11989           pop_nested_class ();
11990           pop_nested_namespace (ns);
11991         }
11992
11993       /* We restore the source position here because it's used by
11994          add_pending_template.  */
11995       input_location = saved_loc;
11996
11997       if (at_eof && !pattern_defined
11998           && DECL_EXPLICIT_INSTANTIATION (d))
11999         /* [temp.explicit]
12000
12001            The definition of a non-exported function template, a
12002            non-exported member function template, or a non-exported
12003            member function or static data member of a class template
12004            shall be present in every translation unit in which it is
12005            explicitly instantiated.  */
12006         pedwarn
12007           ("explicit instantiation of %qD but no definition available", d);
12008
12009       /* ??? Historically, we have instantiated inline functions, even
12010          when marked as "extern template".  */
12011       if (!(external_p && TREE_CODE (d) == VAR_DECL))
12012         add_pending_template (d);
12013       goto out;
12014     }
12015   /* Tell the repository that D is available in this translation unit
12016      -- and see if it is supposed to be instantiated here.  */
12017   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
12018     {
12019       /* In a PCH file, despite the fact that the repository hasn't
12020          requested instantiation in the PCH it is still possible that
12021          an instantiation will be required in a file that includes the
12022          PCH.  */
12023       if (pch_file)
12024         add_pending_template (d);
12025       /* Instantiate inline functions so that the inliner can do its
12026          job, even though we'll not be emitting a copy of this
12027          function.  */
12028       if (!(TREE_CODE (d) == FUNCTION_DECL
12029             && flag_inline_trees
12030             && DECL_DECLARED_INLINE_P (d)))
12031         goto out;
12032     }
12033
12034   need_push = !cfun || !global_bindings_p ();
12035   if (need_push)
12036     push_to_top_level ();
12037
12038   /* Mark D as instantiated so that recursive calls to
12039      instantiate_decl do not try to instantiate it again.  */
12040   DECL_TEMPLATE_INSTANTIATED (d) = 1;
12041
12042   /* Regenerate the declaration in case the template has been modified
12043      by a subsequent redeclaration.  */
12044   regenerate_decl_from_template (d, td);
12045
12046   /* We already set the file and line above.  Reset them now in case
12047      they changed as a result of calling regenerate_decl_from_template.  */
12048   input_location = DECL_SOURCE_LOCATION (d);
12049
12050   if (TREE_CODE (d) == VAR_DECL)
12051     {
12052       tree init;
12053
12054       /* Clear out DECL_RTL; whatever was there before may not be right
12055          since we've reset the type of the declaration.  */
12056       SET_DECL_RTL (d, NULL_RTX);
12057       DECL_IN_AGGR_P (d) = 0;
12058
12059       /* The initializer is placed in DECL_INITIAL by
12060          regenerate_decl_from_template.  Pull it out so that
12061          finish_decl can process it.  */
12062       init = DECL_INITIAL (d);
12063       DECL_INITIAL (d) = NULL_TREE;
12064       DECL_INITIALIZED_P (d) = 0;
12065
12066       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
12067          initializer.  That function will defer actual emission until
12068          we have a chance to determine linkage.  */
12069       DECL_EXTERNAL (d) = 0;
12070
12071       /* Enter the scope of D so that access-checking works correctly.  */
12072       push_nested_class (DECL_CONTEXT (d));
12073       finish_decl (d, init, NULL_TREE);
12074       pop_nested_class ();
12075     }
12076   else if (TREE_CODE (d) == FUNCTION_DECL)
12077     {
12078       htab_t saved_local_specializations;
12079       tree subst_decl;
12080       tree tmpl_parm;
12081       tree spec_parm;
12082
12083       /* Save away the current list, in case we are instantiating one
12084          template from within the body of another.  */
12085       saved_local_specializations = local_specializations;
12086
12087       /* Set up the list of local specializations.  */
12088       local_specializations = htab_create (37,
12089                                            hash_local_specialization,
12090                                            eq_local_specializations,
12091                                            NULL);
12092
12093       /* Set up context.  */
12094       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
12095
12096       /* Create substitution entries for the parameters.  */
12097       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
12098       tmpl_parm = DECL_ARGUMENTS (subst_decl);
12099       spec_parm = DECL_ARGUMENTS (d);
12100       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
12101         {
12102           register_local_specialization (spec_parm, tmpl_parm);
12103           spec_parm = skip_artificial_parms_for (d, spec_parm);
12104           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
12105         }
12106       while (tmpl_parm)
12107         {
12108           register_local_specialization (spec_parm, tmpl_parm);
12109           tmpl_parm = TREE_CHAIN (tmpl_parm);
12110           spec_parm = TREE_CHAIN (spec_parm);
12111         }
12112       gcc_assert (!spec_parm);
12113
12114       /* Substitute into the body of the function.  */
12115       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
12116                    tf_warning_or_error, tmpl);
12117
12118       /* We don't need the local specializations any more.  */
12119       htab_delete (local_specializations);
12120       local_specializations = saved_local_specializations;
12121
12122       /* Finish the function.  */
12123       d = finish_function (0);
12124       expand_or_defer_fn (d);
12125     }
12126
12127   /* We're not deferring instantiation any more.  */
12128   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
12129
12130   if (need_push)
12131     pop_from_top_level ();
12132
12133 out:
12134   input_location = saved_loc;
12135   pop_deferring_access_checks ();
12136   pop_tinst_level ();
12137
12138   timevar_pop (TV_PARSE);
12139
12140   return d;
12141 }
12142
12143 /* Run through the list of templates that we wish we could
12144    instantiate, and instantiate any we can.  RETRIES is the
12145    number of times we retry pending template instantiation.  */
12146
12147 void
12148 instantiate_pending_templates (int retries)
12149 {
12150   tree *t;
12151   tree last = NULL_TREE;
12152   int reconsider;
12153   location_t saved_loc = input_location;
12154   int saved_in_system_header = in_system_header;
12155
12156   /* Instantiating templates may trigger vtable generation.  This in turn
12157      may require further template instantiations.  We place a limit here
12158      to avoid infinite loop.  */
12159   if (pending_templates && retries >= max_tinst_depth)
12160     {
12161       tree decl = TREE_VALUE (pending_templates);
12162
12163       error ("template instantiation depth exceeds maximum of %d"
12164              " instantiating %q+D, possibly from virtual table generation"
12165              " (use -ftemplate-depth-NN to increase the maximum)",
12166              max_tinst_depth, decl);
12167       if (TREE_CODE (decl) == FUNCTION_DECL)
12168         /* Pretend that we defined it.  */
12169         DECL_INITIAL (decl) = error_mark_node;
12170       return;
12171     }
12172
12173   do
12174     {
12175       reconsider = 0;
12176
12177       t = &pending_templates;
12178       while (*t)
12179         {
12180           tree instantiation = TREE_VALUE (*t);
12181
12182           reopen_tinst_level (TREE_PURPOSE (*t));
12183
12184           if (TYPE_P (instantiation))
12185             {
12186               tree fn;
12187
12188               if (!COMPLETE_TYPE_P (instantiation))
12189                 {
12190                   instantiate_class_template (instantiation);
12191                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
12192                     for (fn = TYPE_METHODS (instantiation);
12193                          fn;
12194                          fn = TREE_CHAIN (fn))
12195                       if (! DECL_ARTIFICIAL (fn))
12196                         instantiate_decl (fn,
12197                                           /*defer_ok=*/0,
12198                                           /*expl_inst_class_mem_p=*/false);
12199                   if (COMPLETE_TYPE_P (instantiation))
12200                     reconsider = 1;
12201                 }
12202
12203               if (COMPLETE_TYPE_P (instantiation))
12204                 /* If INSTANTIATION has been instantiated, then we don't
12205                    need to consider it again in the future.  */
12206                 *t = TREE_CHAIN (*t);
12207               else
12208                 {
12209                   last = *t;
12210                   t = &TREE_CHAIN (*t);
12211                 }
12212             }
12213           else
12214             {
12215               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
12216                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
12217                 {
12218                   instantiation
12219                     = instantiate_decl (instantiation,
12220                                         /*defer_ok=*/0,
12221                                         /*expl_inst_class_mem_p=*/false);
12222                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
12223                     reconsider = 1;
12224                 }
12225
12226               if (DECL_TEMPLATE_SPECIALIZATION (instantiation)
12227                   || DECL_TEMPLATE_INSTANTIATED (instantiation))
12228                 /* If INSTANTIATION has been instantiated, then we don't
12229                    need to consider it again in the future.  */
12230                 *t = TREE_CHAIN (*t);
12231               else
12232                 {
12233                   last = *t;
12234                   t = &TREE_CHAIN (*t);
12235                 }
12236             }
12237           tinst_depth = 0;
12238           current_tinst_level = NULL_TREE;
12239         }
12240       last_pending_template = last;
12241     }
12242   while (reconsider);
12243
12244   input_location = saved_loc;
12245   in_system_header = saved_in_system_header;
12246 }
12247
12248 /* Substitute ARGVEC into T, which is a list of initializers for
12249    either base class or a non-static data member.  The TREE_PURPOSEs
12250    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
12251    instantiate_decl.  */
12252
12253 static tree
12254 tsubst_initializer_list (tree t, tree argvec)
12255 {
12256   tree inits = NULL_TREE;
12257
12258   for (; t; t = TREE_CHAIN (t))
12259     {
12260       tree decl;
12261       tree init;
12262
12263       decl = tsubst_copy (TREE_PURPOSE (t), argvec, tf_warning_or_error,
12264                           NULL_TREE);
12265       decl = expand_member_init (decl);
12266       if (decl && !DECL_P (decl))
12267         in_base_initializer = 1;
12268
12269       init = tsubst_expr (TREE_VALUE (t), argvec, tf_warning_or_error,
12270                           NULL_TREE);
12271       in_base_initializer = 0;
12272
12273       if (decl)
12274         {
12275           init = build_tree_list (decl, init);
12276           TREE_CHAIN (init) = inits;
12277           inits = init;
12278         }
12279     }
12280   return inits;
12281 }
12282
12283 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
12284
12285 static void
12286 set_current_access_from_decl (tree decl)
12287 {
12288   if (TREE_PRIVATE (decl))
12289     current_access_specifier = access_private_node;
12290   else if (TREE_PROTECTED (decl))
12291     current_access_specifier = access_protected_node;
12292   else
12293     current_access_specifier = access_public_node;
12294 }
12295
12296 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
12297    is the instantiation (which should have been created with
12298    start_enum) and ARGS are the template arguments to use.  */
12299
12300 static void
12301 tsubst_enum (tree tag, tree newtag, tree args)
12302 {
12303   tree e;
12304
12305   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
12306     {
12307       tree value;
12308       tree decl;
12309
12310       decl = TREE_VALUE (e);
12311       /* Note that in a template enum, the TREE_VALUE is the
12312          CONST_DECL, not the corresponding INTEGER_CST.  */
12313       value = tsubst_expr (DECL_INITIAL (decl),
12314                            args, tf_warning_or_error, NULL_TREE);
12315
12316       /* Give this enumeration constant the correct access.  */
12317       set_current_access_from_decl (decl);
12318
12319       /* Actually build the enumerator itself.  */
12320       build_enumerator (DECL_NAME (decl), value, newtag);
12321     }
12322
12323   finish_enum (newtag);
12324   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
12325     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
12326 }
12327
12328 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
12329    its type -- but without substituting the innermost set of template
12330    arguments.  So, innermost set of template parameters will appear in
12331    the type.  */
12332
12333 tree
12334 get_mostly_instantiated_function_type (tree decl)
12335 {
12336   tree fn_type;
12337   tree tmpl;
12338   tree targs;
12339   tree tparms;
12340   int parm_depth;
12341
12342   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
12343   targs = DECL_TI_ARGS (decl);
12344   tparms = DECL_TEMPLATE_PARMS (tmpl);
12345   parm_depth = TMPL_PARMS_DEPTH (tparms);
12346
12347   /* There should be as many levels of arguments as there are levels
12348      of parameters.  */
12349   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
12350
12351   fn_type = TREE_TYPE (tmpl);
12352
12353   if (parm_depth == 1)
12354     /* No substitution is necessary.  */
12355     ;
12356   else
12357     {
12358       int i, save_access_control;
12359       tree partial_args;
12360
12361       /* Replace the innermost level of the TARGS with NULL_TREEs to
12362          let tsubst know not to substitute for those parameters.  */
12363       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
12364       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
12365         SET_TMPL_ARGS_LEVEL (partial_args, i,
12366                              TMPL_ARGS_LEVEL (targs, i));
12367       SET_TMPL_ARGS_LEVEL (partial_args,
12368                            TMPL_ARGS_DEPTH (targs),
12369                            make_tree_vec (DECL_NTPARMS (tmpl)));
12370
12371       /* Disable access control as this function is used only during
12372          name-mangling.  */
12373       save_access_control = flag_access_control;
12374       flag_access_control = 0;
12375
12376       ++processing_template_decl;
12377       /* Now, do the (partial) substitution to figure out the
12378          appropriate function type.  */
12379       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
12380       --processing_template_decl;
12381
12382       /* Substitute into the template parameters to obtain the real
12383          innermost set of parameters.  This step is important if the
12384          innermost set of template parameters contains value
12385          parameters whose types depend on outer template parameters.  */
12386       TREE_VEC_LENGTH (partial_args)--;
12387       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
12388
12389       flag_access_control = save_access_control;
12390     }
12391
12392   return fn_type;
12393 }
12394
12395 /* Return truthvalue if we're processing a template different from
12396    the last one involved in diagnostics.  */
12397 int
12398 problematic_instantiation_changed (void)
12399 {
12400   return last_template_error_tick != tinst_level_tick;
12401 }
12402
12403 /* Remember current template involved in diagnostics.  */
12404 void
12405 record_last_problematic_instantiation (void)
12406 {
12407   last_template_error_tick = tinst_level_tick;
12408 }
12409
12410 tree
12411 current_instantiation (void)
12412 {
12413   return current_tinst_level;
12414 }
12415
12416 /* [temp.param] Check that template non-type parm TYPE is of an allowable
12417    type. Return zero for ok, nonzero for disallowed. Issue error and
12418    warning messages under control of COMPLAIN.  */
12419
12420 static int
12421 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
12422 {
12423   if (INTEGRAL_TYPE_P (type))
12424     return 0;
12425   else if (POINTER_TYPE_P (type))
12426     return 0;
12427   else if (TYPE_PTR_TO_MEMBER_P (type))
12428     return 0;
12429   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
12430     return 0;
12431   else if (TREE_CODE (type) == TYPENAME_TYPE)
12432     return 0;
12433
12434   if (complain & tf_error)
12435     error ("%q#T is not a valid type for a template constant parameter", type);
12436   return 1;
12437 }
12438
12439 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
12440    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
12441
12442 static bool
12443 dependent_type_p_r (tree type)
12444 {
12445   tree scope;
12446
12447   /* [temp.dep.type]
12448
12449      A type is dependent if it is:
12450
12451      -- a template parameter. Template template parameters are types
12452         for us (since TYPE_P holds true for them) so we handle
12453         them here.  */
12454   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
12455       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
12456     return true;
12457   /* -- a qualified-id with a nested-name-specifier which contains a
12458         class-name that names a dependent type or whose unqualified-id
12459         names a dependent type.  */
12460   if (TREE_CODE (type) == TYPENAME_TYPE)
12461     return true;
12462   /* -- a cv-qualified type where the cv-unqualified type is
12463         dependent.  */
12464   type = TYPE_MAIN_VARIANT (type);
12465   /* -- a compound type constructed from any dependent type.  */
12466   if (TYPE_PTR_TO_MEMBER_P (type))
12467     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
12468             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
12469                                            (type)));
12470   else if (TREE_CODE (type) == POINTER_TYPE
12471            || TREE_CODE (type) == REFERENCE_TYPE)
12472     return dependent_type_p (TREE_TYPE (type));
12473   else if (TREE_CODE (type) == FUNCTION_TYPE
12474            || TREE_CODE (type) == METHOD_TYPE)
12475     {
12476       tree arg_type;
12477
12478       if (dependent_type_p (TREE_TYPE (type)))
12479         return true;
12480       for (arg_type = TYPE_ARG_TYPES (type);
12481            arg_type;
12482            arg_type = TREE_CHAIN (arg_type))
12483         if (dependent_type_p (TREE_VALUE (arg_type)))
12484           return true;
12485       return false;
12486     }
12487   /* -- an array type constructed from any dependent type or whose
12488         size is specified by a constant expression that is
12489         value-dependent.  */
12490   if (TREE_CODE (type) == ARRAY_TYPE)
12491     {
12492       if (TYPE_DOMAIN (type)
12493           && ((value_dependent_expression_p
12494                (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))
12495               || (type_dependent_expression_p
12496                   (TYPE_MAX_VALUE (TYPE_DOMAIN (type))))))
12497         return true;
12498       return dependent_type_p (TREE_TYPE (type));
12499     }
12500
12501   /* -- a template-id in which either the template name is a template
12502      parameter ...  */
12503   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
12504     return true;
12505   /* ... or any of the template arguments is a dependent type or
12506         an expression that is type-dependent or value-dependent.  */
12507   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
12508            && (any_dependent_template_arguments_p
12509                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
12510     return true;
12511
12512   /* All TYPEOF_TYPEs are dependent; if the argument of the `typeof'
12513      expression is not type-dependent, then it should already been
12514      have resolved.  */
12515   if (TREE_CODE (type) == TYPEOF_TYPE)
12516     return true;
12517
12518   /* The standard does not specifically mention types that are local
12519      to template functions or local classes, but they should be
12520      considered dependent too.  For example:
12521
12522        template <int I> void f() {
12523          enum E { a = I };
12524          S<sizeof (E)> s;
12525        }
12526
12527      The size of `E' cannot be known until the value of `I' has been
12528      determined.  Therefore, `E' must be considered dependent.  */
12529   scope = TYPE_CONTEXT (type);
12530   if (scope && TYPE_P (scope))
12531     return dependent_type_p (scope);
12532   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
12533     return type_dependent_expression_p (scope);
12534
12535   /* Other types are non-dependent.  */
12536   return false;
12537 }
12538
12539 /* Returns TRUE if TYPE is dependent, in the sense of
12540    [temp.dep.type].  */
12541
12542 bool
12543 dependent_type_p (tree type)
12544 {
12545   /* If there are no template parameters in scope, then there can't be
12546      any dependent types.  */
12547   if (!processing_template_decl)
12548     {
12549       /* If we are not processing a template, then nobody should be
12550          providing us with a dependent type.  */
12551       gcc_assert (type);
12552       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM);
12553       return false;
12554     }
12555
12556   /* If the type is NULL, we have not computed a type for the entity
12557      in question; in that case, the type is dependent.  */
12558   if (!type)
12559     return true;
12560
12561   /* Erroneous types can be considered non-dependent.  */
12562   if (type == error_mark_node)
12563     return false;
12564
12565   /* If we have not already computed the appropriate value for TYPE,
12566      do so now.  */
12567   if (!TYPE_DEPENDENT_P_VALID (type))
12568     {
12569       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
12570       TYPE_DEPENDENT_P_VALID (type) = 1;
12571     }
12572
12573   return TYPE_DEPENDENT_P (type);
12574 }
12575
12576 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
12577
12578 static bool
12579 dependent_scope_ref_p (tree expression, bool criterion (tree))
12580 {
12581   tree scope;
12582   tree name;
12583
12584   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
12585
12586   if (!TYPE_P (TREE_OPERAND (expression, 0)))
12587     return true;
12588
12589   scope = TREE_OPERAND (expression, 0);
12590   name = TREE_OPERAND (expression, 1);
12591
12592   /* [temp.dep.expr]
12593
12594      An id-expression is type-dependent if it contains a
12595      nested-name-specifier that contains a class-name that names a
12596      dependent type.  */
12597   /* The suggested resolution to Core Issue 2 implies that if the
12598      qualifying type is the current class, then we must peek
12599      inside it.  */
12600   if (DECL_P (name)
12601       && currently_open_class (scope)
12602       && !criterion (name))
12603     return false;
12604   if (dependent_type_p (scope))
12605     return true;
12606
12607   return false;
12608 }
12609
12610 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
12611    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
12612    expression.  */
12613
12614 bool
12615 value_dependent_expression_p (tree expression)
12616 {
12617   if (!processing_template_decl)
12618     return false;
12619
12620   /* A name declared with a dependent type.  */
12621   if (DECL_P (expression) && type_dependent_expression_p (expression))
12622     return true;
12623
12624   switch (TREE_CODE (expression))
12625     {
12626     case IDENTIFIER_NODE:
12627       /* A name that has not been looked up -- must be dependent.  */
12628       return true;
12629
12630     case TEMPLATE_PARM_INDEX:
12631       /* A non-type template parm.  */
12632       return true;
12633
12634     case CONST_DECL:
12635       /* A non-type template parm.  */
12636       if (DECL_TEMPLATE_PARM_P (expression))
12637         return true;
12638       return false;
12639
12640     case VAR_DECL:
12641        /* A constant with integral or enumeration type and is initialized
12642           with an expression that is value-dependent.  */
12643       if (DECL_INITIAL (expression)
12644           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
12645           && value_dependent_expression_p (DECL_INITIAL (expression)))
12646         return true;
12647       return false;
12648
12649     case DYNAMIC_CAST_EXPR:
12650     case STATIC_CAST_EXPR:
12651     case CONST_CAST_EXPR:
12652     case REINTERPRET_CAST_EXPR:
12653     case CAST_EXPR:
12654       /* These expressions are value-dependent if the type to which
12655          the cast occurs is dependent or the expression being casted
12656          is value-dependent.  */
12657       {
12658         tree type = TREE_TYPE (expression);
12659
12660         if (dependent_type_p (type))
12661           return true;
12662
12663         /* A functional cast has a list of operands.  */
12664         expression = TREE_OPERAND (expression, 0);
12665         if (!expression)
12666           {
12667             /* If there are no operands, it must be an expression such
12668                as "int()". This should not happen for aggregate types
12669                because it would form non-constant expressions.  */
12670             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
12671
12672             return false;
12673           }
12674
12675         if (TREE_CODE (expression) == TREE_LIST)
12676           {
12677             for (; expression; expression = TREE_CHAIN (expression))
12678               if (value_dependent_expression_p (TREE_VALUE (expression)))
12679                 return true;
12680             return false;
12681           }
12682
12683         return value_dependent_expression_p (expression);
12684       }
12685
12686     case SIZEOF_EXPR:
12687     case ALIGNOF_EXPR:
12688       /* A `sizeof' expression is value-dependent if the operand is
12689          type-dependent.  */
12690       expression = TREE_OPERAND (expression, 0);
12691       if (TYPE_P (expression))
12692         return dependent_type_p (expression);
12693       return type_dependent_expression_p (expression);
12694
12695     case SCOPE_REF:
12696       return dependent_scope_ref_p (expression, value_dependent_expression_p);
12697
12698     case COMPONENT_REF:
12699       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
12700               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
12701
12702     case CALL_EXPR:
12703       /* A CALL_EXPR may appear in a constant expression if it is a
12704          call to a builtin function, e.g., __builtin_constant_p.  All
12705          such calls are value-dependent.  */
12706       return true;
12707
12708     default:
12709       /* A constant expression is value-dependent if any subexpression is
12710          value-dependent.  */
12711       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
12712         {
12713         case tcc_reference:
12714         case tcc_unary:
12715           return (value_dependent_expression_p
12716                   (TREE_OPERAND (expression, 0)));
12717
12718         case tcc_comparison:
12719         case tcc_binary:
12720           return ((value_dependent_expression_p
12721                    (TREE_OPERAND (expression, 0)))
12722                   || (value_dependent_expression_p
12723                       (TREE_OPERAND (expression, 1))));
12724
12725         case tcc_expression:
12726           {
12727             int i;
12728             for (i = 0; i < TREE_CODE_LENGTH (TREE_CODE (expression)); ++i)
12729               /* In some cases, some of the operands may be missing.
12730                  (For example, in the case of PREDECREMENT_EXPR, the
12731                  amount to increment by may be missing.)  That doesn't
12732                  make the expression dependent.  */
12733               if (TREE_OPERAND (expression, i)
12734                   && (value_dependent_expression_p
12735                       (TREE_OPERAND (expression, i))))
12736                 return true;
12737             return false;
12738           }
12739
12740         default:
12741           break;
12742         }
12743     }
12744
12745   /* The expression is not value-dependent.  */
12746   return false;
12747 }
12748
12749 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
12750    [temp.dep.expr].  */
12751
12752 bool
12753 type_dependent_expression_p (tree expression)
12754 {
12755   if (!processing_template_decl)
12756     return false;
12757
12758   if (expression == error_mark_node)
12759     return false;
12760
12761   /* An unresolved name is always dependent.  */
12762   if (TREE_CODE (expression) == IDENTIFIER_NODE)
12763     return true;
12764
12765   /* Some expression forms are never type-dependent.  */
12766   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
12767       || TREE_CODE (expression) == SIZEOF_EXPR
12768       || TREE_CODE (expression) == ALIGNOF_EXPR
12769       || TREE_CODE (expression) == TYPEID_EXPR
12770       || TREE_CODE (expression) == DELETE_EXPR
12771       || TREE_CODE (expression) == VEC_DELETE_EXPR
12772       || TREE_CODE (expression) == THROW_EXPR)
12773     return false;
12774
12775   /* The types of these expressions depends only on the type to which
12776      the cast occurs.  */
12777   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
12778       || TREE_CODE (expression) == STATIC_CAST_EXPR
12779       || TREE_CODE (expression) == CONST_CAST_EXPR
12780       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
12781       || TREE_CODE (expression) == CAST_EXPR)
12782     return dependent_type_p (TREE_TYPE (expression));
12783
12784   /* The types of these expressions depends only on the type created
12785      by the expression.  */
12786   if (TREE_CODE (expression) == NEW_EXPR
12787       || TREE_CODE (expression) == VEC_NEW_EXPR)
12788     {
12789       /* For NEW_EXPR tree nodes created inside a template, either
12790          the object type itself or a TREE_LIST may appear as the
12791          operand 1.  */
12792       tree type = TREE_OPERAND (expression, 1);
12793       if (TREE_CODE (type) == TREE_LIST)
12794         /* This is an array type.  We need to check array dimensions
12795            as well.  */
12796         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
12797                || value_dependent_expression_p
12798                     (TREE_OPERAND (TREE_VALUE (type), 1));
12799       else
12800         return dependent_type_p (type);
12801     }
12802
12803   if (TREE_CODE (expression) == SCOPE_REF
12804       && dependent_scope_ref_p (expression,
12805                                 type_dependent_expression_p))
12806     return true;
12807
12808   if (TREE_CODE (expression) == FUNCTION_DECL
12809       && DECL_LANG_SPECIFIC (expression)
12810       && DECL_TEMPLATE_INFO (expression)
12811       && (any_dependent_template_arguments_p
12812           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
12813     return true;
12814
12815   if (TREE_CODE (expression) == TEMPLATE_DECL
12816       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
12817     return false;
12818
12819   if (TREE_TYPE (expression) == unknown_type_node)
12820     {
12821       if (TREE_CODE (expression) == ADDR_EXPR)
12822         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
12823       if (TREE_CODE (expression) == COMPONENT_REF
12824           || TREE_CODE (expression) == OFFSET_REF)
12825         {
12826           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
12827             return true;
12828           expression = TREE_OPERAND (expression, 1);
12829           if (TREE_CODE (expression) == IDENTIFIER_NODE)
12830             return false;
12831         }
12832       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
12833       if (TREE_CODE (expression) == SCOPE_REF)
12834         return false;
12835
12836       if (TREE_CODE (expression) == BASELINK)
12837         expression = BASELINK_FUNCTIONS (expression);
12838
12839       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
12840         {
12841           if (any_dependent_template_arguments_p
12842               (TREE_OPERAND (expression, 1)))
12843             return true;
12844           expression = TREE_OPERAND (expression, 0);
12845         }
12846       gcc_assert (TREE_CODE (expression) == OVERLOAD
12847                   || TREE_CODE (expression) == FUNCTION_DECL);
12848
12849       while (expression)
12850         {
12851           if (type_dependent_expression_p (OVL_CURRENT (expression)))
12852             return true;
12853           expression = OVL_NEXT (expression);
12854         }
12855       return false;
12856     }
12857
12858   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
12859
12860   return (dependent_type_p (TREE_TYPE (expression)));
12861 }
12862
12863 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
12864    contains a type-dependent expression.  */
12865
12866 bool
12867 any_type_dependent_arguments_p (tree args)
12868 {
12869   while (args)
12870     {
12871       tree arg = TREE_VALUE (args);
12872
12873       if (type_dependent_expression_p (arg))
12874         return true;
12875       args = TREE_CHAIN (args);
12876     }
12877   return false;
12878 }
12879
12880 /* Returns TRUE if the ARG (a template argument) is dependent.  */
12881
12882 static bool
12883 dependent_template_arg_p (tree arg)
12884 {
12885   if (!processing_template_decl)
12886     return false;
12887
12888   if (TREE_CODE (arg) == TEMPLATE_DECL
12889       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
12890     return dependent_template_p (arg);
12891   else if (TYPE_P (arg))
12892     return dependent_type_p (arg);
12893   else
12894     return (type_dependent_expression_p (arg)
12895             || value_dependent_expression_p (arg));
12896 }
12897
12898 /* Returns true if ARGS (a collection of template arguments) contains
12899    any dependent arguments.  */
12900
12901 bool
12902 any_dependent_template_arguments_p (tree args)
12903 {
12904   int i;
12905   int j;
12906
12907   if (!args)
12908     return false;
12909   if (args == error_mark_node)
12910     return true;
12911
12912   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
12913     {
12914       tree level = TMPL_ARGS_LEVEL (args, i + 1);
12915       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
12916         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
12917           return true;
12918     }
12919
12920   return false;
12921 }
12922
12923 /* Returns TRUE if the template TMPL is dependent.  */
12924
12925 bool
12926 dependent_template_p (tree tmpl)
12927 {
12928   if (TREE_CODE (tmpl) == OVERLOAD)
12929     {
12930       while (tmpl)
12931         {
12932           if (dependent_template_p (OVL_FUNCTION (tmpl)))
12933             return true;
12934           tmpl = OVL_CHAIN (tmpl);
12935         }
12936       return false;
12937     }
12938
12939   /* Template template parameters are dependent.  */
12940   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
12941       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
12942     return true;
12943   /* So are names that have not been looked up.  */
12944   if (TREE_CODE (tmpl) == SCOPE_REF
12945       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
12946     return true;
12947   /* So are member templates of dependent classes.  */
12948   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
12949     return dependent_type_p (DECL_CONTEXT (tmpl));
12950   return false;
12951 }
12952
12953 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
12954
12955 bool
12956 dependent_template_id_p (tree tmpl, tree args)
12957 {
12958   return (dependent_template_p (tmpl)
12959           || any_dependent_template_arguments_p (args));
12960 }
12961
12962 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
12963    TYPENAME_TYPE corresponds.  Returns ERROR_MARK_NODE if no such TYPE
12964    can be found.  Note that this function peers inside uninstantiated
12965    templates and therefore should be used only in extremely limited
12966    situations.  ONLY_CURRENT_P restricts this peering to the currently
12967    open classes hierarchy (which is required when comparing types).  */
12968
12969 tree
12970 resolve_typename_type (tree type, bool only_current_p)
12971 {
12972   tree scope;
12973   tree name;
12974   tree decl;
12975   int quals;
12976   tree pushed_scope;
12977
12978   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
12979
12980   scope = TYPE_CONTEXT (type);
12981   name = TYPE_IDENTIFIER (type);
12982
12983   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
12984      it first before we can figure out what NAME refers to.  */
12985   if (TREE_CODE (scope) == TYPENAME_TYPE)
12986     scope = resolve_typename_type (scope, only_current_p);
12987   /* If we don't know what SCOPE refers to, then we cannot resolve the
12988      TYPENAME_TYPE.  */
12989   if (scope == error_mark_node || TREE_CODE (scope) == TYPENAME_TYPE)
12990     return error_mark_node;
12991   /* If the SCOPE is a template type parameter, we have no way of
12992      resolving the name.  */
12993   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
12994     return type;
12995   /* If the SCOPE is not the current instantiation, there's no reason
12996      to look inside it.  */
12997   if (only_current_p && !currently_open_class (scope))
12998     return error_mark_node;
12999   /* If SCOPE is a partial instantiation, it will not have a valid
13000      TYPE_FIELDS list, so use the original template.  */
13001   scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
13002   /* Enter the SCOPE so that name lookup will be resolved as if we
13003      were in the class definition.  In particular, SCOPE will no
13004      longer be considered a dependent type.  */
13005   pushed_scope = push_scope (scope);
13006   /* Look up the declaration.  */
13007   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
13008   /* Obtain the set of qualifiers applied to the TYPE.  */
13009   quals = cp_type_quals (type);
13010   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
13011      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
13012   if (!decl)
13013     type = error_mark_node;
13014   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
13015            && TREE_CODE (decl) == TYPE_DECL)
13016     type = TREE_TYPE (decl);
13017   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
13018            && DECL_CLASS_TEMPLATE_P (decl))
13019     {
13020       tree tmpl;
13021       tree args;
13022       /* Obtain the template and the arguments.  */
13023       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
13024       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
13025       /* Instantiate the template.  */
13026       type = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
13027                                     /*entering_scope=*/0, tf_error | tf_user);
13028     }
13029   else
13030     type = error_mark_node;
13031   /* Qualify the resulting type.  */
13032   if (type != error_mark_node && quals)
13033     type = cp_build_qualified_type (type, quals);
13034   /* Leave the SCOPE.  */
13035   if (pushed_scope)
13036     pop_scope (pushed_scope);
13037
13038   return type;
13039 }
13040
13041 /* EXPR is an expression which is not type-dependent.  Return a proxy
13042    for EXPR that can be used to compute the types of larger
13043    expressions containing EXPR.  */
13044
13045 tree
13046 build_non_dependent_expr (tree expr)
13047 {
13048   tree inner_expr;
13049
13050   /* Preserve null pointer constants so that the type of things like
13051      "p == 0" where "p" is a pointer can be determined.  */
13052   if (null_ptr_cst_p (expr))
13053     return expr;
13054   /* Preserve OVERLOADs; the functions must be available to resolve
13055      types.  */
13056   inner_expr = expr;
13057   if (TREE_CODE (inner_expr) == ADDR_EXPR)
13058     inner_expr = TREE_OPERAND (inner_expr, 0);
13059   if (TREE_CODE (inner_expr) == COMPONENT_REF)
13060     inner_expr = TREE_OPERAND (inner_expr, 1);
13061   if (is_overloaded_fn (inner_expr)
13062       || TREE_CODE (inner_expr) == OFFSET_REF)
13063     return expr;
13064   /* There is no need to return a proxy for a variable.  */
13065   if (TREE_CODE (expr) == VAR_DECL)
13066     return expr;
13067   /* Preserve string constants; conversions from string constants to
13068      "char *" are allowed, even though normally a "const char *"
13069      cannot be used to initialize a "char *".  */
13070   if (TREE_CODE (expr) == STRING_CST)
13071     return expr;
13072   /* Preserve arithmetic constants, as an optimization -- there is no
13073      reason to create a new node.  */
13074   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
13075     return expr;
13076   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
13077      There is at least one place where we want to know that a
13078      particular expression is a throw-expression: when checking a ?:
13079      expression, there are special rules if the second or third
13080      argument is a throw-expression.  */
13081   if (TREE_CODE (expr) == THROW_EXPR)
13082     return expr;
13083
13084   if (TREE_CODE (expr) == COND_EXPR)
13085     return build3 (COND_EXPR,
13086                    TREE_TYPE (expr),
13087                    TREE_OPERAND (expr, 0),
13088                    (TREE_OPERAND (expr, 1)
13089                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
13090                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
13091                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
13092   if (TREE_CODE (expr) == COMPOUND_EXPR
13093       && !COMPOUND_EXPR_OVERLOADED (expr))
13094     return build2 (COMPOUND_EXPR,
13095                    TREE_TYPE (expr),
13096                    TREE_OPERAND (expr, 0),
13097                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
13098
13099   /* If the type is unknown, it can't really be non-dependent */
13100   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
13101
13102   /* Otherwise, build a NON_DEPENDENT_EXPR.
13103
13104      REFERENCE_TYPEs are not stripped for expressions in templates
13105      because doing so would play havoc with mangling.  Consider, for
13106      example:
13107
13108        template <typename T> void f<T& g>() { g(); }
13109
13110      In the body of "f", the expression for "g" will have
13111      REFERENCE_TYPE, even though the standard says that it should
13112      not.  The reason is that we must preserve the syntactic form of
13113      the expression so that mangling (say) "f<g>" inside the body of
13114      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
13115      stripped here.  */
13116   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
13117 }
13118
13119 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
13120    Return a new TREE_LIST with the various arguments replaced with
13121    equivalent non-dependent expressions.  */
13122
13123 tree
13124 build_non_dependent_args (tree args)
13125 {
13126   tree a;
13127   tree new_args;
13128
13129   new_args = NULL_TREE;
13130   for (a = args; a; a = TREE_CHAIN (a))
13131     new_args = tree_cons (NULL_TREE,
13132                           build_non_dependent_expr (TREE_VALUE (a)),
13133                           new_args);
13134   return nreverse (new_args);
13135 }
13136
13137 #include "gt-cp-pt.h"