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