1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992-2013 Free Software Foundation, Inc.
3    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4    Rewritten by Jason Merrill (jason@cygnus.com).
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12 
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21 
22 /* Known bugs or deficiencies include:
23 
24      all methods must be provided in header files; can't use a source
25      file that contains only the method templates and "just win".  */
26 
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "tm.h"
31 #include "tree.h"
32 #include "intl.h"
33 #include "pointer-set.h"
34 #include "flags.h"
35 #include "cp-tree.h"
36 #include "c-family/c-common.h"
37 #include "c-family/c-objc.h"
38 #include "cp-objcp-common.h"
39 #include "tree-inline.h"
40 #include "decl.h"
41 #include "toplev.h"
42 #include "timevar.h"
43 #include "tree-iterator.h"
44 
45 /* The type of functions taking a tree, and some additional data, and
46    returning an int.  */
47 typedef int (*tree_fn_t) (tree, void*);
48 
49 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
50    instantiations have been deferred, either because their definitions
51    were not yet available, or because we were putting off doing the work.  */
52 struct GTY ((chain_next ("%h.next"))) pending_template {
53   struct pending_template *next;
54   struct tinst_level *tinst;
55 };
56 
57 static GTY(()) struct pending_template *pending_templates;
58 static GTY(()) struct pending_template *last_pending_template;
59 
60 int processing_template_parmlist;
61 static int template_header_count;
62 
63 static GTY(()) tree saved_trees;
64 static vec<int> inline_parm_levels;
65 
66 static GTY(()) struct tinst_level *current_tinst_level;
67 
68 static GTY(()) tree saved_access_scope;
69 
70 /* Live only within one (recursive) call to tsubst_expr.  We use
71    this to pass the statement expression node from the STMT_EXPR
72    to the EXPR_STMT that is its result.  */
73 static tree cur_stmt_expr;
74 
75 /* A map from local variable declarations in the body of the template
76    presently being instantiated to the corresponding instantiated
77    local variables.  */
78 static struct pointer_map_t *local_specializations;
79 
80 /* True if we've recursed into fn_type_unification too many times.  */
81 static bool excessive_deduction_depth;
82 
83 typedef struct GTY(()) spec_entry
84 {
85   tree tmpl;
86   tree args;
87   tree spec;
88 } spec_entry;
89 
90 static GTY ((param_is (spec_entry)))
91   htab_t decl_specializations;
92 
93 static GTY ((param_is (spec_entry)))
94   htab_t type_specializations;
95 
96 /* Contains canonical template parameter types. The vector is indexed by
97    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
98    TREE_LIST, whose TREE_VALUEs contain the canonical template
99    parameters of various types and levels.  */
100 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
101 
102 #define UNIFY_ALLOW_NONE 0
103 #define UNIFY_ALLOW_MORE_CV_QUAL 1
104 #define UNIFY_ALLOW_LESS_CV_QUAL 2
105 #define UNIFY_ALLOW_DERIVED 4
106 #define UNIFY_ALLOW_INTEGER 8
107 #define UNIFY_ALLOW_OUTER_LEVEL 16
108 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
109 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
110 
111 enum template_base_result {
112   tbr_incomplete_type,
113   tbr_ambiguous_baseclass,
114   tbr_success
115 };
116 
117 static void push_access_scope (tree);
118 static void pop_access_scope (tree);
119 static bool resolve_overloaded_unification (tree, tree, tree, tree,
120 					    unification_kind_t, int,
121 					    bool);
122 static int try_one_overload (tree, tree, tree, tree, tree,
123 			     unification_kind_t, int, bool, bool);
124 static int unify (tree, tree, tree, tree, int, bool);
125 static void add_pending_template (tree);
126 static tree reopen_tinst_level (struct tinst_level *);
127 static tree tsubst_initializer_list (tree, tree);
128 static tree get_class_bindings (tree, tree, tree, tree);
129 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
130 				   bool, bool);
131 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
132 					      bool, bool);
133 static void tsubst_enum	(tree, tree, tree);
134 static tree add_to_template_args (tree, tree);
135 static tree add_outermost_template_args (tree, tree);
136 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
137 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
138 					     tree);
139 static int type_unification_real (tree, tree, tree, const tree *,
140 				  unsigned int, int, unification_kind_t, int,
141 				  bool);
142 static void note_template_header (int);
143 static tree convert_nontype_argument_function (tree, tree);
144 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
145 static tree convert_template_argument (tree, tree, tree,
146 				       tsubst_flags_t, int, tree);
147 static int for_each_template_parm (tree, tree_fn_t, void*,
148 				   struct pointer_set_t*, bool);
149 static tree expand_template_argument_pack (tree);
150 static tree build_template_parm_index (int, int, int, tree, tree);
151 static bool inline_needs_template_parms (tree);
152 static void push_inline_template_parms_recursive (tree, int);
153 static tree retrieve_local_specialization (tree);
154 static void register_local_specialization (tree, tree);
155 static hashval_t hash_specialization (const void *p);
156 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
157 static int mark_template_parm (tree, void *);
158 static int template_parm_this_level_p (tree, void *);
159 static tree tsubst_friend_function (tree, tree);
160 static tree tsubst_friend_class (tree, tree);
161 static int can_complete_type_without_circularity (tree);
162 static tree get_bindings (tree, tree, tree, bool);
163 static int template_decl_level (tree);
164 static int check_cv_quals_for_unify (int, tree, tree);
165 static void template_parm_level_and_index (tree, int*, int*);
166 static int unify_pack_expansion (tree, tree, tree,
167 				 tree, unification_kind_t, bool, bool);
168 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
169 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
170 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
171 static void regenerate_decl_from_template (tree, tree);
172 static tree most_specialized_class (tree, tree, tsubst_flags_t);
173 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
174 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
175 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
176 static bool check_specialization_scope (void);
177 static tree process_partial_specialization (tree);
178 static void set_current_access_from_decl (tree);
179 static enum template_base_result get_template_base (tree, tree, tree, tree,
180 						    bool , tree *);
181 static tree try_class_unification (tree, tree, tree, tree, bool);
182 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
183 					   tree, tree);
184 static bool template_template_parm_bindings_ok_p (tree, tree);
185 static int template_args_equal (tree, tree);
186 static void tsubst_default_arguments (tree);
187 static tree for_each_template_parm_r (tree *, int *, void *);
188 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
189 static void copy_default_args_to_explicit_spec (tree);
190 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
191 static bool dependent_template_arg_p (tree);
192 static bool any_template_arguments_need_structural_equality_p (tree);
193 static bool dependent_type_p_r (tree);
194 static tree tsubst_expr	(tree, tree, tsubst_flags_t, tree, bool);
195 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
196 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
197 static tree tsubst_decl (tree, tree, tsubst_flags_t);
198 static void perform_typedefs_access_check (tree tmpl, tree targs);
199 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
200 							location_t);
201 static tree listify (tree);
202 static tree listify_autos (tree, tree);
203 static tree template_parm_to_arg (tree t);
204 static tree current_template_args (void);
205 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
206 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
207 
208 /* Make the current scope suitable for access checking when we are
209    processing T.  T can be FUNCTION_DECL for instantiated function
210    template, VAR_DECL for static member variable, or TYPE_DECL for
211    alias template (needed by instantiate_decl).  */
212 
213 static void
push_access_scope(tree t)214 push_access_scope (tree t)
215 {
216   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
217 	      || TREE_CODE (t) == TYPE_DECL
218 	      || TREE_CODE (t) == VAR_DECL);
219 
220   if (DECL_FRIEND_CONTEXT (t))
221     push_nested_class (DECL_FRIEND_CONTEXT (t));
222   else if (DECL_CLASS_SCOPE_P (t))
223     push_nested_class (DECL_CONTEXT (t));
224   else
225     push_to_top_level ();
226 
227   if (TREE_CODE (t) == FUNCTION_DECL)
228     {
229       saved_access_scope = tree_cons
230 	(NULL_TREE, current_function_decl, saved_access_scope);
231       current_function_decl = t;
232     }
233 }
234 
235 /* Restore the scope set up by push_access_scope.  T is the node we
236    are processing.  */
237 
238 static void
pop_access_scope(tree t)239 pop_access_scope (tree t)
240 {
241   if (TREE_CODE (t) == FUNCTION_DECL)
242     {
243       current_function_decl = TREE_VALUE (saved_access_scope);
244       saved_access_scope = TREE_CHAIN (saved_access_scope);
245     }
246 
247   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
248     pop_nested_class ();
249   else
250     pop_from_top_level ();
251 }
252 
253 /* Do any processing required when DECL (a member template
254    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
255    to DECL, unless it is a specialization, in which case the DECL
256    itself is returned.  */
257 
258 tree
finish_member_template_decl(tree decl)259 finish_member_template_decl (tree decl)
260 {
261   if (decl == error_mark_node)
262     return error_mark_node;
263 
264   gcc_assert (DECL_P (decl));
265 
266   if (TREE_CODE (decl) == TYPE_DECL)
267     {
268       tree type;
269 
270       type = TREE_TYPE (decl);
271       if (type == error_mark_node)
272 	return error_mark_node;
273       if (MAYBE_CLASS_TYPE_P (type)
274 	  && CLASSTYPE_TEMPLATE_INFO (type)
275 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
276 	{
277 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
278 	  check_member_template (tmpl);
279 	  return tmpl;
280 	}
281       return NULL_TREE;
282     }
283   else if (TREE_CODE (decl) == FIELD_DECL)
284     error ("data member %qD cannot be a member template", decl);
285   else if (DECL_TEMPLATE_INFO (decl))
286     {
287       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
288 	{
289 	  check_member_template (DECL_TI_TEMPLATE (decl));
290 	  return DECL_TI_TEMPLATE (decl);
291 	}
292       else
293 	return decl;
294     }
295   else
296     error ("invalid member template declaration %qD", decl);
297 
298   return error_mark_node;
299 }
300 
301 /* Create a template info node.  */
302 
303 tree
build_template_info(tree template_decl,tree template_args)304 build_template_info (tree template_decl, tree template_args)
305 {
306   tree result = make_node (TEMPLATE_INFO);
307   TI_TEMPLATE (result) = template_decl;
308   TI_ARGS (result) = template_args;
309   return result;
310 }
311 
312 /* Return the template info node corresponding to T, whatever T is.  */
313 
314 tree
get_template_info(const_tree t)315 get_template_info (const_tree t)
316 {
317   tree tinfo = NULL_TREE;
318 
319   if (!t || t == error_mark_node)
320     return NULL;
321 
322   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
323     tinfo = DECL_TEMPLATE_INFO (t);
324 
325   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
326     t = TREE_TYPE (t);
327 
328   if (TAGGED_TYPE_P (t))
329     tinfo = TYPE_TEMPLATE_INFO (t);
330   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
331     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
332 
333   return tinfo;
334 }
335 
336 /* Returns the template nesting level of the indicated class TYPE.
337 
338    For example, in:
339      template <class T>
340      struct A
341      {
342        template <class U>
343        struct B {};
344      };
345 
346    A<T>::B<U> has depth two, while A<T> has depth one.
347    Both A<T>::B<int> and A<int>::B<U> have depth one, if
348    they are instantiations, not specializations.
349 
350    This function is guaranteed to return 0 if passed NULL_TREE so
351    that, for example, `template_class_depth (current_class_type)' is
352    always safe.  */
353 
354 int
template_class_depth(tree type)355 template_class_depth (tree type)
356 {
357   int depth;
358 
359   for (depth = 0;
360        type && TREE_CODE (type) != NAMESPACE_DECL;
361        type = (TREE_CODE (type) == FUNCTION_DECL)
362 	 ? CP_DECL_CONTEXT (type) : CP_TYPE_CONTEXT (type))
363     {
364       tree tinfo = get_template_info (type);
365 
366       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
367 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
368 	++depth;
369     }
370 
371   return depth;
372 }
373 
374 /* Subroutine of maybe_begin_member_template_processing.
375    Returns true if processing DECL needs us to push template parms.  */
376 
377 static bool
inline_needs_template_parms(tree decl)378 inline_needs_template_parms (tree decl)
379 {
380   if (! DECL_TEMPLATE_INFO (decl))
381     return false;
382 
383   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
384 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
385 }
386 
387 /* Subroutine of maybe_begin_member_template_processing.
388    Push the template parms in PARMS, starting from LEVELS steps into the
389    chain, and ending at the beginning, since template parms are listed
390    innermost first.  */
391 
392 static void
push_inline_template_parms_recursive(tree parmlist,int levels)393 push_inline_template_parms_recursive (tree parmlist, int levels)
394 {
395   tree parms = TREE_VALUE (parmlist);
396   int i;
397 
398   if (levels > 1)
399     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
400 
401   ++processing_template_decl;
402   current_template_parms
403     = tree_cons (size_int (processing_template_decl),
404 		 parms, current_template_parms);
405   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
406 
407   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
408 	       NULL);
409   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
410     {
411       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
412 
413       if (parm == error_mark_node)
414 	continue;
415 
416       gcc_assert (DECL_P (parm));
417 
418       switch (TREE_CODE (parm))
419 	{
420 	case TYPE_DECL:
421 	case TEMPLATE_DECL:
422 	  pushdecl (parm);
423 	  break;
424 
425 	case PARM_DECL:
426 	  {
427 	    /* Make a CONST_DECL as is done in process_template_parm.
428 	       It is ugly that we recreate this here; the original
429 	       version built in process_template_parm is no longer
430 	       available.  */
431 	    tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
432 				    CONST_DECL, DECL_NAME (parm),
433 				    TREE_TYPE (parm));
434 	    DECL_ARTIFICIAL (decl) = 1;
435 	    TREE_CONSTANT (decl) = 1;
436 	    TREE_READONLY (decl) = 1;
437 	    DECL_INITIAL (decl) = DECL_INITIAL (parm);
438 	    SET_DECL_TEMPLATE_PARM_P (decl);
439 	    pushdecl (decl);
440 	  }
441 	  break;
442 
443 	default:
444 	  gcc_unreachable ();
445 	}
446     }
447 }
448 
449 /* Restore the template parameter context for a member template or
450    a friend template defined in a class definition.  */
451 
452 void
maybe_begin_member_template_processing(tree decl)453 maybe_begin_member_template_processing (tree decl)
454 {
455   tree parms;
456   int levels = 0;
457 
458   if (inline_needs_template_parms (decl))
459     {
460       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
461       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
462 
463       if (DECL_TEMPLATE_SPECIALIZATION (decl))
464 	{
465 	  --levels;
466 	  parms = TREE_CHAIN (parms);
467 	}
468 
469       push_inline_template_parms_recursive (parms, levels);
470     }
471 
472   /* Remember how many levels of template parameters we pushed so that
473      we can pop them later.  */
474   inline_parm_levels.safe_push (levels);
475 }
476 
477 /* Undo the effects of maybe_begin_member_template_processing.  */
478 
479 void
maybe_end_member_template_processing(void)480 maybe_end_member_template_processing (void)
481 {
482   int i;
483   int last;
484 
485   if (inline_parm_levels.length () == 0)
486     return;
487 
488   last = inline_parm_levels.pop ();
489   for (i = 0; i < last; ++i)
490     {
491       --processing_template_decl;
492       current_template_parms = TREE_CHAIN (current_template_parms);
493       poplevel (0, 0, 0);
494     }
495 }
496 
497 /* Return a new template argument vector which contains all of ARGS,
498    but has as its innermost set of arguments the EXTRA_ARGS.  */
499 
500 static tree
add_to_template_args(tree args,tree extra_args)501 add_to_template_args (tree args, tree extra_args)
502 {
503   tree new_args;
504   int extra_depth;
505   int i;
506   int j;
507 
508   if (args == NULL_TREE || extra_args == error_mark_node)
509     return extra_args;
510 
511   extra_depth = TMPL_ARGS_DEPTH (extra_args);
512   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
513 
514   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
515     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
516 
517   for (j = 1; j <= extra_depth; ++j, ++i)
518     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
519 
520   return new_args;
521 }
522 
523 /* Like add_to_template_args, but only the outermost ARGS are added to
524    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
525    (EXTRA_ARGS) levels are added.  This function is used to combine
526    the template arguments from a partial instantiation with the
527    template arguments used to attain the full instantiation from the
528    partial instantiation.  */
529 
530 static tree
add_outermost_template_args(tree args,tree extra_args)531 add_outermost_template_args (tree args, tree extra_args)
532 {
533   tree new_args;
534 
535   /* If there are more levels of EXTRA_ARGS than there are ARGS,
536      something very fishy is going on.  */
537   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
538 
539   /* If *all* the new arguments will be the EXTRA_ARGS, just return
540      them.  */
541   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
542     return extra_args;
543 
544   /* For the moment, we make ARGS look like it contains fewer levels.  */
545   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
546 
547   new_args = add_to_template_args (args, extra_args);
548 
549   /* Now, we restore ARGS to its full dimensions.  */
550   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
551 
552   return new_args;
553 }
554 
555 /* Return the N levels of innermost template arguments from the ARGS.  */
556 
557 tree
get_innermost_template_args(tree args,int n)558 get_innermost_template_args (tree args, int n)
559 {
560   tree new_args;
561   int extra_levels;
562   int i;
563 
564   gcc_assert (n >= 0);
565 
566   /* If N is 1, just return the innermost set of template arguments.  */
567   if (n == 1)
568     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
569 
570   /* If we're not removing anything, just return the arguments we were
571      given.  */
572   extra_levels = TMPL_ARGS_DEPTH (args) - n;
573   gcc_assert (extra_levels >= 0);
574   if (extra_levels == 0)
575     return args;
576 
577   /* Make a new set of arguments, not containing the outer arguments.  */
578   new_args = make_tree_vec (n);
579   for (i = 1; i <= n; ++i)
580     SET_TMPL_ARGS_LEVEL (new_args, i,
581 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
582 
583   return new_args;
584 }
585 
586 /* The inverse of get_innermost_template_args: Return all but the innermost
587    EXTRA_LEVELS levels of template arguments from the ARGS.  */
588 
589 static tree
strip_innermost_template_args(tree args,int extra_levels)590 strip_innermost_template_args (tree args, int extra_levels)
591 {
592   tree new_args;
593   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
594   int i;
595 
596   gcc_assert (n >= 0);
597 
598   /* If N is 1, just return the outermost set of template arguments.  */
599   if (n == 1)
600     return TMPL_ARGS_LEVEL (args, 1);
601 
602   /* If we're not removing anything, just return the arguments we were
603      given.  */
604   gcc_assert (extra_levels >= 0);
605   if (extra_levels == 0)
606     return args;
607 
608   /* Make a new set of arguments, not containing the inner arguments.  */
609   new_args = make_tree_vec (n);
610   for (i = 1; i <= n; ++i)
611     SET_TMPL_ARGS_LEVEL (new_args, i,
612 			 TMPL_ARGS_LEVEL (args, i));
613 
614   return new_args;
615 }
616 
617 /* We've got a template header coming up; push to a new level for storing
618    the parms.  */
619 
620 void
begin_template_parm_list(void)621 begin_template_parm_list (void)
622 {
623   /* We use a non-tag-transparent scope here, which causes pushtag to
624      put tags in this scope, rather than in the enclosing class or
625      namespace scope.  This is the right thing, since we want
626      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
627      global template class, push_template_decl handles putting the
628      TEMPLATE_DECL into top-level scope.  For a nested template class,
629      e.g.:
630 
631        template <class T> struct S1 {
632 	 template <class T> struct S2 {};
633        };
634 
635      pushtag contains special code to call pushdecl_with_scope on the
636      TEMPLATE_DECL for S2.  */
637   begin_scope (sk_template_parms, NULL);
638   ++processing_template_decl;
639   ++processing_template_parmlist;
640   note_template_header (0);
641 }
642 
643 /* This routine is called when a specialization is declared.  If it is
644    invalid to declare a specialization here, an error is reported and
645    false is returned, otherwise this routine will return true.  */
646 
647 static bool
check_specialization_scope(void)648 check_specialization_scope (void)
649 {
650   tree scope = current_scope ();
651 
652   /* [temp.expl.spec]
653 
654      An explicit specialization shall be declared in the namespace of
655      which the template is a member, or, for member templates, in the
656      namespace of which the enclosing class or enclosing class
657      template is a member.  An explicit specialization of a member
658      function, member class or static data member of a class template
659      shall be declared in the namespace of which the class template
660      is a member.  */
661   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
662     {
663       error ("explicit specialization in non-namespace scope %qD", scope);
664       return false;
665     }
666 
667   /* [temp.expl.spec]
668 
669      In an explicit specialization declaration for a member of a class
670      template or a member template that appears in namespace scope,
671      the member template and some of its enclosing class templates may
672      remain unspecialized, except that the declaration shall not
673      explicitly specialize a class member template if its enclosing
674      class templates are not explicitly specialized as well.  */
675   if (current_template_parms)
676     {
677       error ("enclosing class templates are not explicitly specialized");
678       return false;
679     }
680 
681   return true;
682 }
683 
684 /* We've just seen template <>.  */
685 
686 bool
begin_specialization(void)687 begin_specialization (void)
688 {
689   begin_scope (sk_template_spec, NULL);
690   note_template_header (1);
691   return check_specialization_scope ();
692 }
693 
694 /* Called at then end of processing a declaration preceded by
695    template<>.  */
696 
697 void
end_specialization(void)698 end_specialization (void)
699 {
700   finish_scope ();
701   reset_specialization ();
702 }
703 
704 /* Any template <>'s that we have seen thus far are not referring to a
705    function specialization.  */
706 
707 void
reset_specialization(void)708 reset_specialization (void)
709 {
710   processing_specialization = 0;
711   template_header_count = 0;
712 }
713 
714 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
715    it was of the form template <>.  */
716 
717 static void
note_template_header(int specialization)718 note_template_header (int specialization)
719 {
720   processing_specialization = specialization;
721   template_header_count++;
722 }
723 
724 /* We're beginning an explicit instantiation.  */
725 
726 void
begin_explicit_instantiation(void)727 begin_explicit_instantiation (void)
728 {
729   gcc_assert (!processing_explicit_instantiation);
730   processing_explicit_instantiation = true;
731 }
732 
733 
734 void
end_explicit_instantiation(void)735 end_explicit_instantiation (void)
736 {
737   gcc_assert (processing_explicit_instantiation);
738   processing_explicit_instantiation = false;
739 }
740 
741 /* An explicit specialization or partial specialization of TMPL is being
742    declared.  Check that the namespace in which the specialization is
743    occurring is permissible.  Returns false iff it is invalid to
744    specialize TMPL in the current namespace.  */
745 
746 static bool
check_specialization_namespace(tree tmpl)747 check_specialization_namespace (tree tmpl)
748 {
749   tree tpl_ns = decl_namespace_context (tmpl);
750 
751   /* [tmpl.expl.spec]
752 
753      An explicit specialization shall be declared in the namespace of
754      which the template is a member, or, for member templates, in the
755      namespace of which the enclosing class or enclosing class
756      template is a member.  An explicit specialization of a member
757      function, member class or static data member of a class template
758      shall be declared in the namespace of which the class template is
759      a member.  */
760   if (current_scope() != DECL_CONTEXT (tmpl)
761       && !at_namespace_scope_p ())
762     {
763       error ("specialization of %qD must appear at namespace scope", tmpl);
764       return false;
765     }
766   if (is_associated_namespace (current_namespace, tpl_ns))
767     /* Same or super-using namespace.  */
768     return true;
769   else
770     {
771       permerror (input_location, "specialization of %qD in different namespace", tmpl);
772       permerror (input_location, "  from definition of %q+#D", tmpl);
773       return false;
774     }
775 }
776 
777 /* SPEC is an explicit instantiation.  Check that it is valid to
778    perform this explicit instantiation in the current namespace.  */
779 
780 static void
check_explicit_instantiation_namespace(tree spec)781 check_explicit_instantiation_namespace (tree spec)
782 {
783   tree ns;
784 
785   /* DR 275: An explicit instantiation shall appear in an enclosing
786      namespace of its template.  */
787   ns = decl_namespace_context (spec);
788   if (!is_ancestor (current_namespace, ns))
789     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
790 	       "(which does not enclose namespace %qD)",
791 	       spec, current_namespace, ns);
792 }
793 
794 /* The TYPE is being declared.  If it is a template type, that means it
795    is a partial specialization.  Do appropriate error-checking.  */
796 
797 tree
maybe_process_partial_specialization(tree type)798 maybe_process_partial_specialization (tree type)
799 {
800   tree context;
801 
802   if (type == error_mark_node)
803     return error_mark_node;
804 
805   /* A lambda that appears in specialization context is not itself a
806      specialization.  */
807   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
808     return type;
809 
810   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
811     {
812       error ("name of class shadows template template parameter %qD",
813 	     TYPE_NAME (type));
814       return error_mark_node;
815     }
816 
817   context = TYPE_CONTEXT (type);
818 
819   if (TYPE_ALIAS_P (type))
820     {
821       if (TYPE_TEMPLATE_INFO (type)
822 	  && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (type)))
823 	error ("specialization of alias template %qD",
824 	       TYPE_TI_TEMPLATE (type));
825       else
826 	error ("explicit specialization of non-template %qT", type);
827       return error_mark_node;
828     }
829   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
830     {
831       /* This is for ordinary explicit specialization and partial
832 	 specialization of a template class such as:
833 
834 	   template <> class C<int>;
835 
836 	 or:
837 
838 	   template <class T> class C<T*>;
839 
840 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
841 
842       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
843 	  && !COMPLETE_TYPE_P (type))
844 	{
845 	  check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
846 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
847 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
848 	  if (processing_template_decl)
849 	    {
850 	      if (push_template_decl (TYPE_MAIN_DECL (type))
851 		  == error_mark_node)
852 		return error_mark_node;
853 	    }
854 	}
855       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
856 	error ("specialization of %qT after instantiation", type);
857       else if (errorcount && !processing_specialization
858 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
859 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
860 	/* Trying to define a specialization either without a template<> header
861 	   or in an inappropriate place.  We've already given an error, so just
862 	   bail now so we don't actually define the specialization.  */
863 	return error_mark_node;
864     }
865   else if (CLASS_TYPE_P (type)
866 	   && !CLASSTYPE_USE_TEMPLATE (type)
867 	   && CLASSTYPE_TEMPLATE_INFO (type)
868 	   && context && CLASS_TYPE_P (context)
869 	   && CLASSTYPE_TEMPLATE_INFO (context))
870     {
871       /* This is for an explicit specialization of member class
872 	 template according to [temp.expl.spec/18]:
873 
874 	   template <> template <class U> class C<int>::D;
875 
876 	 The context `C<int>' must be an implicit instantiation.
877 	 Otherwise this is just a member class template declared
878 	 earlier like:
879 
880 	   template <> class C<int> { template <class U> class D; };
881 	   template <> template <class U> class C<int>::D;
882 
883 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
884 	 while in the second case, `C<int>::D' is a primary template
885 	 and `C<T>::D' may not exist.  */
886 
887       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
888 	  && !COMPLETE_TYPE_P (type))
889 	{
890 	  tree t;
891 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
892 
893 	  if (current_namespace
894 	      != decl_namespace_context (tmpl))
895 	    {
896 	      permerror (input_location, "specializing %q#T in different namespace", type);
897 	      permerror (input_location, "  from definition of %q+#D", tmpl);
898 	    }
899 
900 	  /* Check for invalid specialization after instantiation:
901 
902 	       template <> template <> class C<int>::D<int>;
903 	       template <> template <class U> class C<int>::D;  */
904 
905 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
906 	       t; t = TREE_CHAIN (t))
907 	    {
908 	      tree inst = TREE_VALUE (t);
909 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
910 		{
911 		  /* We already have a full specialization of this partial
912 		     instantiation.  Reassign it to the new member
913 		     specialization template.  */
914 		  spec_entry elt;
915 		  spec_entry *entry;
916 		  void **slot;
917 
918 		  elt.tmpl = most_general_template (tmpl);
919 		  elt.args = CLASSTYPE_TI_ARGS (inst);
920 		  elt.spec = inst;
921 
922 		  htab_remove_elt (type_specializations, &elt);
923 
924 		  elt.tmpl = tmpl;
925 		  elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
926 
927 		  slot = htab_find_slot (type_specializations, &elt, INSERT);
928 		  entry = ggc_alloc_spec_entry ();
929 		  *entry = elt;
930 		  *slot = entry;
931 		}
932 	      else if (COMPLETE_OR_OPEN_TYPE_P (inst))
933 		/* But if we've had an implicit instantiation, that's a
934 		   problem ([temp.expl.spec]/6).  */
935 		error ("specialization %qT after instantiation %qT",
936 		       type, inst);
937 	    }
938 
939 	  /* Mark TYPE as a specialization.  And as a result, we only
940 	     have one level of template argument for the innermost
941 	     class template.  */
942 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
943 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
944 	  CLASSTYPE_TI_ARGS (type)
945 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
946 	}
947     }
948   else if (processing_specialization)
949     {
950        /* Someday C++0x may allow for enum template specialization.  */
951       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
952 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
953 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
954 		 "of %qD not allowed by ISO C++", type);
955       else
956 	{
957 	  error ("explicit specialization of non-template %qT", type);
958 	  return error_mark_node;
959 	}
960     }
961 
962   return type;
963 }
964 
965 /* Returns nonzero if we can optimize the retrieval of specializations
966    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
967    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
968 
969 static inline bool
optimize_specialization_lookup_p(tree tmpl)970 optimize_specialization_lookup_p (tree tmpl)
971 {
972   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
973 	  && DECL_CLASS_SCOPE_P (tmpl)
974 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
975 	     parameter.  */
976 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
977 	  /* The optimized lookup depends on the fact that the
978 	     template arguments for the member function template apply
979 	     purely to the containing class, which is not true if the
980 	     containing class is an explicit or partial
981 	     specialization.  */
982 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
983 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
984 	  && !DECL_CONV_FN_P (tmpl)
985 	  /* It is possible to have a template that is not a member
986 	     template and is not a member of a template class:
987 
988 	     template <typename T>
989 	     struct S { friend A::f(); };
990 
991 	     Here, the friend function is a template, but the context does
992 	     not have template information.  The optimized lookup relies
993 	     on having ARGS be the template arguments for both the class
994 	     and the function template.  */
995 	  && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
996 }
997 
998 /* Retrieve the specialization (in the sense of [temp.spec] - a
999    specialization is either an instantiation or an explicit
1000    specialization) of TMPL for the given template ARGS.  If there is
1001    no such specialization, return NULL_TREE.  The ARGS are a vector of
1002    arguments, or a vector of vectors of arguments, in the case of
1003    templates with more than one level of parameters.
1004 
1005    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1006    then we search for a partial specialization matching ARGS.  This
1007    parameter is ignored if TMPL is not a class template.  */
1008 
1009 static tree
retrieve_specialization(tree tmpl,tree args,hashval_t hash)1010 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1011 {
1012   if (args == error_mark_node)
1013     return NULL_TREE;
1014 
1015   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1016 
1017   /* There should be as many levels of arguments as there are
1018      levels of parameters.  */
1019   gcc_assert (TMPL_ARGS_DEPTH (args)
1020 	      == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
1021 
1022   if (optimize_specialization_lookup_p (tmpl))
1023     {
1024       tree class_template;
1025       tree class_specialization;
1026       vec<tree, va_gc> *methods;
1027       tree fns;
1028       int idx;
1029 
1030       /* The template arguments actually apply to the containing
1031 	 class.  Find the class specialization with those
1032 	 arguments.  */
1033       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1034       class_specialization
1035 	= retrieve_specialization (class_template, args, 0);
1036       if (!class_specialization)
1037 	return NULL_TREE;
1038       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1039 	 for the specialization.  */
1040       idx = class_method_index_for_fn (class_specialization, tmpl);
1041       if (idx == -1)
1042 	return NULL_TREE;
1043       /* Iterate through the methods with the indicated name, looking
1044 	 for the one that has an instance of TMPL.  */
1045       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1046       for (fns = (*methods)[idx]; fns; fns = OVL_NEXT (fns))
1047 	{
1048 	  tree fn = OVL_CURRENT (fns);
1049 	  if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1050 	      /* using-declarations can add base methods to the method vec,
1051 		 and we don't want those here.  */
1052 	      && DECL_CONTEXT (fn) == class_specialization)
1053 	    return fn;
1054 	}
1055       return NULL_TREE;
1056     }
1057   else
1058     {
1059       spec_entry *found;
1060       spec_entry elt;
1061       htab_t specializations;
1062 
1063       elt.tmpl = tmpl;
1064       elt.args = args;
1065       elt.spec = NULL_TREE;
1066 
1067       if (DECL_CLASS_TEMPLATE_P (tmpl))
1068 	specializations = type_specializations;
1069       else
1070 	specializations = decl_specializations;
1071 
1072       if (hash == 0)
1073 	hash = hash_specialization (&elt);
1074       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1075       if (found)
1076 	return found->spec;
1077     }
1078 
1079   return NULL_TREE;
1080 }
1081 
1082 /* Like retrieve_specialization, but for local declarations.  */
1083 
1084 static tree
retrieve_local_specialization(tree tmpl)1085 retrieve_local_specialization (tree tmpl)
1086 {
1087   void **slot;
1088 
1089   if (local_specializations == NULL)
1090     return NULL_TREE;
1091 
1092   slot = pointer_map_contains (local_specializations, tmpl);
1093   return slot ? (tree) *slot : NULL_TREE;
1094 }
1095 
1096 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1097 
1098 int
is_specialization_of(tree decl,tree tmpl)1099 is_specialization_of (tree decl, tree tmpl)
1100 {
1101   tree t;
1102 
1103   if (TREE_CODE (decl) == FUNCTION_DECL)
1104     {
1105       for (t = decl;
1106 	   t != NULL_TREE;
1107 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1108 	if (t == tmpl)
1109 	  return 1;
1110     }
1111   else
1112     {
1113       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1114 
1115       for (t = TREE_TYPE (decl);
1116 	   t != NULL_TREE;
1117 	   t = CLASSTYPE_USE_TEMPLATE (t)
1118 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1119 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1120 	  return 1;
1121     }
1122 
1123   return 0;
1124 }
1125 
1126 /* Returns nonzero iff DECL is a specialization of friend declaration
1127    FRIEND_DECL according to [temp.friend].  */
1128 
1129 bool
is_specialization_of_friend(tree decl,tree friend_decl)1130 is_specialization_of_friend (tree decl, tree friend_decl)
1131 {
1132   bool need_template = true;
1133   int template_depth;
1134 
1135   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1136 	      || TREE_CODE (decl) == TYPE_DECL);
1137 
1138   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1139      of a template class, we want to check if DECL is a specialization
1140      if this.  */
1141   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1142       && DECL_TEMPLATE_INFO (friend_decl)
1143       && !DECL_USE_TEMPLATE (friend_decl))
1144     {
1145       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1146       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1147       need_template = false;
1148     }
1149   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1150 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1151     need_template = false;
1152 
1153   /* There is nothing to do if this is not a template friend.  */
1154   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1155     return false;
1156 
1157   if (is_specialization_of (decl, friend_decl))
1158     return true;
1159 
1160   /* [temp.friend/6]
1161      A member of a class template may be declared to be a friend of a
1162      non-template class.  In this case, the corresponding member of
1163      every specialization of the class template is a friend of the
1164      class granting friendship.
1165 
1166      For example, given a template friend declaration
1167 
1168        template <class T> friend void A<T>::f();
1169 
1170      the member function below is considered a friend
1171 
1172        template <> struct A<int> {
1173 	 void f();
1174        };
1175 
1176      For this type of template friend, TEMPLATE_DEPTH below will be
1177      nonzero.  To determine if DECL is a friend of FRIEND, we first
1178      check if the enclosing class is a specialization of another.  */
1179 
1180   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1181   if (template_depth
1182       && DECL_CLASS_SCOPE_P (decl)
1183       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1184 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1185     {
1186       /* Next, we check the members themselves.  In order to handle
1187 	 a few tricky cases, such as when FRIEND_DECL's are
1188 
1189 	   template <class T> friend void A<T>::g(T t);
1190 	   template <class T> template <T t> friend void A<T>::h();
1191 
1192 	 and DECL's are
1193 
1194 	   void A<int>::g(int);
1195 	   template <int> void A<int>::h();
1196 
1197 	 we need to figure out ARGS, the template arguments from
1198 	 the context of DECL.  This is required for template substitution
1199 	 of `T' in the function parameter of `g' and template parameter
1200 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1201 
1202       tree context = DECL_CONTEXT (decl);
1203       tree args = NULL_TREE;
1204       int current_depth = 0;
1205 
1206       while (current_depth < template_depth)
1207 	{
1208 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1209 	    {
1210 	      if (current_depth == 0)
1211 		args = TYPE_TI_ARGS (context);
1212 	      else
1213 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1214 	      current_depth++;
1215 	    }
1216 	  context = TYPE_CONTEXT (context);
1217 	}
1218 
1219       if (TREE_CODE (decl) == FUNCTION_DECL)
1220 	{
1221 	  bool is_template;
1222 	  tree friend_type;
1223 	  tree decl_type;
1224 	  tree friend_args_type;
1225 	  tree decl_args_type;
1226 
1227 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1228 	     non-templates.  */
1229 	  is_template = DECL_TEMPLATE_INFO (decl)
1230 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1231 	  if (need_template ^ is_template)
1232 	    return false;
1233 	  else if (is_template)
1234 	    {
1235 	      /* If both are templates, check template parameter list.  */
1236 	      tree friend_parms
1237 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1238 					 args, tf_none);
1239 	      if (!comp_template_parms
1240 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1241 		      friend_parms))
1242 		return false;
1243 
1244 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1245 	    }
1246 	  else
1247 	    decl_type = TREE_TYPE (decl);
1248 
1249 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1250 					      tf_none, NULL_TREE);
1251 	  if (friend_type == error_mark_node)
1252 	    return false;
1253 
1254 	  /* Check if return types match.  */
1255 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1256 	    return false;
1257 
1258 	  /* Check if function parameter types match, ignoring the
1259 	     `this' parameter.  */
1260 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1261 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1262 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1263 	    friend_args_type = TREE_CHAIN (friend_args_type);
1264 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1265 	    decl_args_type = TREE_CHAIN (decl_args_type);
1266 
1267 	  return compparms (decl_args_type, friend_args_type);
1268 	}
1269       else
1270 	{
1271 	  /* DECL is a TYPE_DECL */
1272 	  bool is_template;
1273 	  tree decl_type = TREE_TYPE (decl);
1274 
1275 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1276 	     non-templates.  */
1277 	  is_template
1278 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1279 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1280 
1281 	  if (need_template ^ is_template)
1282 	    return false;
1283 	  else if (is_template)
1284 	    {
1285 	      tree friend_parms;
1286 	      /* If both are templates, check the name of the two
1287 		 TEMPLATE_DECL's first because is_friend didn't.  */
1288 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1289 		  != DECL_NAME (friend_decl))
1290 		return false;
1291 
1292 	      /* Now check template parameter list.  */
1293 	      friend_parms
1294 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1295 					 args, tf_none);
1296 	      return comp_template_parms
1297 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1298 		 friend_parms);
1299 	    }
1300 	  else
1301 	    return (DECL_NAME (decl)
1302 		    == DECL_NAME (friend_decl));
1303 	}
1304     }
1305   return false;
1306 }
1307 
1308 /* Register the specialization SPEC as a specialization of TMPL with
1309    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1310    is actually just a friend declaration.  Returns SPEC, or an
1311    equivalent prior declaration, if available.  */
1312 
1313 static tree
register_specialization(tree spec,tree tmpl,tree args,bool is_friend,hashval_t hash)1314 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1315 			 hashval_t hash)
1316 {
1317   tree fn;
1318   void **slot = NULL;
1319   spec_entry elt;
1320 
1321   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1322 
1323   if (TREE_CODE (spec) == FUNCTION_DECL
1324       && uses_template_parms (DECL_TI_ARGS (spec)))
1325     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1326        register it; we want the corresponding TEMPLATE_DECL instead.
1327        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1328        the more obvious `uses_template_parms (spec)' to avoid problems
1329        with default function arguments.  In particular, given
1330        something like this:
1331 
1332 	  template <class T> void f(T t1, T t = T())
1333 
1334        the default argument expression is not substituted for in an
1335        instantiation unless and until it is actually needed.  */
1336     return spec;
1337 
1338   if (optimize_specialization_lookup_p (tmpl))
1339     /* We don't put these specializations in the hash table, but we might
1340        want to give an error about a mismatch.  */
1341     fn = retrieve_specialization (tmpl, args, 0);
1342   else
1343     {
1344       elt.tmpl = tmpl;
1345       elt.args = args;
1346       elt.spec = spec;
1347 
1348       if (hash == 0)
1349 	hash = hash_specialization (&elt);
1350 
1351       slot =
1352 	htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1353       if (*slot)
1354 	fn = ((spec_entry *) *slot)->spec;
1355       else
1356 	fn = NULL_TREE;
1357     }
1358 
1359   /* We can sometimes try to re-register a specialization that we've
1360      already got.  In particular, regenerate_decl_from_template calls
1361      duplicate_decls which will update the specialization list.  But,
1362      we'll still get called again here anyhow.  It's more convenient
1363      to simply allow this than to try to prevent it.  */
1364   if (fn == spec)
1365     return spec;
1366   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1367     {
1368       if (DECL_TEMPLATE_INSTANTIATION (fn))
1369 	{
1370 	  if (DECL_ODR_USED (fn)
1371 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1372 	    {
1373 	      error ("specialization of %qD after instantiation",
1374 		     fn);
1375 	      return error_mark_node;
1376 	    }
1377 	  else
1378 	    {
1379 	      tree clone;
1380 	      /* This situation should occur only if the first
1381 		 specialization is an implicit instantiation, the
1382 		 second is an explicit specialization, and the
1383 		 implicit instantiation has not yet been used.  That
1384 		 situation can occur if we have implicitly
1385 		 instantiated a member function and then specialized
1386 		 it later.
1387 
1388 		 We can also wind up here if a friend declaration that
1389 		 looked like an instantiation turns out to be a
1390 		 specialization:
1391 
1392 		   template <class T> void foo(T);
1393 		   class S { friend void foo<>(int) };
1394 		   template <> void foo(int);
1395 
1396 		 We transform the existing DECL in place so that any
1397 		 pointers to it become pointers to the updated
1398 		 declaration.
1399 
1400 		 If there was a definition for the template, but not
1401 		 for the specialization, we want this to look as if
1402 		 there were no definition, and vice versa.  */
1403 	      DECL_INITIAL (fn) = NULL_TREE;
1404 	      duplicate_decls (spec, fn, is_friend);
1405 	      /* The call to duplicate_decls will have applied
1406 		 [temp.expl.spec]:
1407 
1408 		   An explicit specialization of a function template
1409 		   is inline only if it is explicitly declared to be,
1410 		   and independently of whether its function template
1411 		   is.
1412 
1413 		to the primary function; now copy the inline bits to
1414 		the various clones.  */
1415 	      FOR_EACH_CLONE (clone, fn)
1416 		{
1417 		  DECL_DECLARED_INLINE_P (clone)
1418 		    = DECL_DECLARED_INLINE_P (fn);
1419 		  DECL_SOURCE_LOCATION (clone)
1420 		    = DECL_SOURCE_LOCATION (fn);
1421 		}
1422 	      check_specialization_namespace (tmpl);
1423 
1424 	      return fn;
1425 	    }
1426 	}
1427       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1428 	{
1429 	  if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1430 	    /* Dup decl failed, but this is a new definition. Set the
1431 	       line number so any errors match this new
1432 	       definition.  */
1433 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1434 
1435 	  return fn;
1436 	}
1437     }
1438   else if (fn)
1439     return duplicate_decls (spec, fn, is_friend);
1440 
1441   /* A specialization must be declared in the same namespace as the
1442      template it is specializing.  */
1443   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1444       && !check_specialization_namespace (tmpl))
1445     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1446 
1447   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1448     {
1449       spec_entry *entry = ggc_alloc_spec_entry ();
1450       gcc_assert (tmpl && args && spec);
1451       *entry = elt;
1452       *slot = entry;
1453       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1454 	  && PRIMARY_TEMPLATE_P (tmpl)
1455 	  && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1456 	/* TMPL is a forward declaration of a template function; keep a list
1457 	   of all specializations in case we need to reassign them to a friend
1458 	   template later in tsubst_friend_function.  */
1459 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1460 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1461     }
1462 
1463   return spec;
1464 }
1465 
1466 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1467    TMPL and ARGS members, ignores SPEC.  */
1468 
1469 int comparing_specializations;
1470 
1471 static int
eq_specializations(const void * p1,const void * p2)1472 eq_specializations (const void *p1, const void *p2)
1473 {
1474   const spec_entry *e1 = (const spec_entry *)p1;
1475   const spec_entry *e2 = (const spec_entry *)p2;
1476   int equal;
1477 
1478   ++comparing_specializations;
1479   equal = (e1->tmpl == e2->tmpl
1480 	   && comp_template_args (e1->args, e2->args));
1481   --comparing_specializations;
1482 
1483   return equal;
1484 }
1485 
1486 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1487 
1488 static hashval_t
hash_tmpl_and_args(tree tmpl,tree args)1489 hash_tmpl_and_args (tree tmpl, tree args)
1490 {
1491   hashval_t val = DECL_UID (tmpl);
1492   return iterative_hash_template_arg (args, val);
1493 }
1494 
1495 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1496    ignoring SPEC.  */
1497 
1498 static hashval_t
hash_specialization(const void * p)1499 hash_specialization (const void *p)
1500 {
1501   const spec_entry *e = (const spec_entry *)p;
1502   return hash_tmpl_and_args (e->tmpl, e->args);
1503 }
1504 
1505 /* Recursively calculate a hash value for a template argument ARG, for use
1506    in the hash tables of template specializations.  */
1507 
1508 hashval_t
iterative_hash_template_arg(tree arg,hashval_t val)1509 iterative_hash_template_arg (tree arg, hashval_t val)
1510 {
1511   unsigned HOST_WIDE_INT i;
1512   enum tree_code code;
1513   char tclass;
1514 
1515   if (arg == NULL_TREE)
1516     return iterative_hash_object (arg, val);
1517 
1518   if (!TYPE_P (arg))
1519     STRIP_NOPS (arg);
1520 
1521   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1522     /* We can get one of these when re-hashing a previous entry in the middle
1523        of substituting into a pack expansion.  Just look through it.  */
1524     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1525 
1526   code = TREE_CODE (arg);
1527   tclass = TREE_CODE_CLASS (code);
1528 
1529   val = iterative_hash_object (code, val);
1530 
1531   switch (code)
1532     {
1533     case ERROR_MARK:
1534       return val;
1535 
1536     case IDENTIFIER_NODE:
1537       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1538 
1539     case TREE_VEC:
1540       {
1541 	int i, len = TREE_VEC_LENGTH (arg);
1542 	for (i = 0; i < len; ++i)
1543 	  val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1544 	return val;
1545       }
1546 
1547     case TYPE_PACK_EXPANSION:
1548     case EXPR_PACK_EXPANSION:
1549       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1550       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1551 
1552     case TYPE_ARGUMENT_PACK:
1553     case NONTYPE_ARGUMENT_PACK:
1554       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1555 
1556     case TREE_LIST:
1557       for (; arg; arg = TREE_CHAIN (arg))
1558 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1559       return val;
1560 
1561     case OVERLOAD:
1562       for (; arg; arg = OVL_NEXT (arg))
1563 	val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1564       return val;
1565 
1566     case CONSTRUCTOR:
1567       {
1568 	tree field, value;
1569 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1570 	  {
1571 	    val = iterative_hash_template_arg (field, val);
1572 	    val = iterative_hash_template_arg (value, val);
1573 	  }
1574 	return val;
1575       }
1576 
1577     case PARM_DECL:
1578       if (!DECL_ARTIFICIAL (arg))
1579 	{
1580 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1581 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1582 	}
1583       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1584 
1585     case TARGET_EXPR:
1586       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1587 
1588     case PTRMEM_CST:
1589       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1590       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1591 
1592     case TEMPLATE_PARM_INDEX:
1593       val = iterative_hash_template_arg
1594 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1595       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1596       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1597 
1598     case TRAIT_EXPR:
1599       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1600       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1601       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1602 
1603     case BASELINK:
1604       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1605 					 val);
1606       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1607 					  val);
1608 
1609     case MODOP_EXPR:
1610       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1611       code = TREE_CODE (TREE_OPERAND (arg, 1));
1612       val = iterative_hash_object (code, val);
1613       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1614 
1615     case LAMBDA_EXPR:
1616       /* A lambda can't appear in a template arg, but don't crash on
1617 	 erroneous input.  */
1618       gcc_assert (seen_error ());
1619       return val;
1620 
1621     case CAST_EXPR:
1622     case IMPLICIT_CONV_EXPR:
1623     case STATIC_CAST_EXPR:
1624     case REINTERPRET_CAST_EXPR:
1625     case CONST_CAST_EXPR:
1626     case DYNAMIC_CAST_EXPR:
1627     case NEW_EXPR:
1628       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1629       /* Now hash operands as usual.  */
1630       break;
1631 
1632     default:
1633       break;
1634     }
1635 
1636   switch (tclass)
1637     {
1638     case tcc_type:
1639       if (TYPE_CANONICAL (arg))
1640 	return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1641 				      val);
1642       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1643 	return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1644       /* Otherwise just compare the types during lookup.  */
1645       return val;
1646 
1647     case tcc_declaration:
1648     case tcc_constant:
1649       return iterative_hash_expr (arg, val);
1650 
1651     default:
1652       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1653       {
1654 	unsigned n = cp_tree_operand_length (arg);
1655 	for (i = 0; i < n; ++i)
1656 	  val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1657 	return val;
1658       }
1659     }
1660   gcc_unreachable ();
1661   return 0;
1662 }
1663 
1664 /* Unregister the specialization SPEC as a specialization of TMPL.
1665    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1666    if the SPEC was listed as a specialization of TMPL.
1667 
1668    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1669 
1670 bool
reregister_specialization(tree spec,tree tinfo,tree new_spec)1671 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1672 {
1673   spec_entry *entry;
1674   spec_entry elt;
1675 
1676   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1677   elt.args = TI_ARGS (tinfo);
1678   elt.spec = NULL_TREE;
1679 
1680   entry = (spec_entry *) htab_find (decl_specializations, &elt);
1681   if (entry != NULL)
1682     {
1683       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1684       gcc_assert (new_spec != NULL_TREE);
1685       entry->spec = new_spec;
1686       return 1;
1687     }
1688 
1689   return 0;
1690 }
1691 
1692 /* Like register_specialization, but for local declarations.  We are
1693    registering SPEC, an instantiation of TMPL.  */
1694 
1695 static void
register_local_specialization(tree spec,tree tmpl)1696 register_local_specialization (tree spec, tree tmpl)
1697 {
1698   void **slot;
1699 
1700   slot = pointer_map_insert (local_specializations, tmpl);
1701   *slot = spec;
1702 }
1703 
1704 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1705    specialized class.  */
1706 
1707 bool
explicit_class_specialization_p(tree type)1708 explicit_class_specialization_p (tree type)
1709 {
1710   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1711     return false;
1712   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1713 }
1714 
1715 /* Print the list of functions at FNS, going through all the overloads
1716    for each element of the list.  Alternatively, FNS can not be a
1717    TREE_LIST, in which case it will be printed together with all the
1718    overloads.
1719 
1720    MORE and *STR should respectively be FALSE and NULL when the function
1721    is called from the outside.  They are used internally on recursive
1722    calls.  print_candidates manages the two parameters and leaves NULL
1723    in *STR when it ends.  */
1724 
1725 static void
print_candidates_1(tree fns,bool more,const char ** str)1726 print_candidates_1 (tree fns, bool more, const char **str)
1727 {
1728   tree fn, fn2;
1729   char *spaces = NULL;
1730 
1731   for (fn = fns; fn; fn = OVL_NEXT (fn))
1732     if (TREE_CODE (fn) == TREE_LIST)
1733       {
1734         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1735           print_candidates_1 (TREE_VALUE (fn2),
1736                               TREE_CHAIN (fn2) || more, str);
1737       }
1738     else
1739       {
1740 	tree cand = OVL_CURRENT (fn);
1741         if (!*str)
1742           {
1743             /* Pick the prefix string.  */
1744             if (!more && !OVL_NEXT (fns))
1745               {
1746                 inform (DECL_SOURCE_LOCATION (cand),
1747 			"candidate is: %#D", cand);
1748                 continue;
1749               }
1750 
1751             *str = _("candidates are:");
1752             spaces = get_spaces (*str);
1753           }
1754         inform (DECL_SOURCE_LOCATION (cand), "%s %#D", *str, cand);
1755         *str = spaces ? spaces : *str;
1756       }
1757 
1758   if (!more)
1759     {
1760       free (spaces);
1761       *str = NULL;
1762     }
1763 }
1764 
1765 /* Print the list of candidate FNS in an error message.  FNS can also
1766    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1767 
1768 void
print_candidates(tree fns)1769 print_candidates (tree fns)
1770 {
1771   const char *str = NULL;
1772   print_candidates_1 (fns, false, &str);
1773   gcc_assert (str == NULL);
1774 }
1775 
1776 /* Returns the template (one of the functions given by TEMPLATE_ID)
1777    which can be specialized to match the indicated DECL with the
1778    explicit template args given in TEMPLATE_ID.  The DECL may be
1779    NULL_TREE if none is available.  In that case, the functions in
1780    TEMPLATE_ID are non-members.
1781 
1782    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1783    specialization of a member template.
1784 
1785    The TEMPLATE_COUNT is the number of references to qualifying
1786    template classes that appeared in the name of the function. See
1787    check_explicit_specialization for a more accurate description.
1788 
1789    TSK indicates what kind of template declaration (if any) is being
1790    declared.  TSK_TEMPLATE indicates that the declaration given by
1791    DECL, though a FUNCTION_DECL, has template parameters, and is
1792    therefore a template function.
1793 
1794    The template args (those explicitly specified and those deduced)
1795    are output in a newly created vector *TARGS_OUT.
1796 
1797    If it is impossible to determine the result, an error message is
1798    issued.  The error_mark_node is returned to indicate failure.  */
1799 
1800 static tree
determine_specialization(tree template_id,tree decl,tree * targs_out,int need_member_template,int template_count,tmpl_spec_kind tsk)1801 determine_specialization (tree template_id,
1802 			  tree decl,
1803 			  tree* targs_out,
1804 			  int need_member_template,
1805 			  int template_count,
1806 			  tmpl_spec_kind tsk)
1807 {
1808   tree fns;
1809   tree targs;
1810   tree explicit_targs;
1811   tree candidates = NULL_TREE;
1812   /* A TREE_LIST of templates of which DECL may be a specialization.
1813      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1814      corresponding TREE_PURPOSE is the set of template arguments that,
1815      when used to instantiate the template, would produce a function
1816      with the signature of DECL.  */
1817   tree templates = NULL_TREE;
1818   int header_count;
1819   cp_binding_level *b;
1820 
1821   *targs_out = NULL_TREE;
1822 
1823   if (template_id == error_mark_node || decl == error_mark_node)
1824     return error_mark_node;
1825 
1826   /* We shouldn't be specializing a member template of an
1827      unspecialized class template; we already gave an error in
1828      check_specialization_scope, now avoid crashing.  */
1829   if (template_count && DECL_CLASS_SCOPE_P (decl)
1830       && template_class_depth (DECL_CONTEXT (decl)) > 0)
1831     {
1832       gcc_assert (errorcount);
1833       return error_mark_node;
1834     }
1835 
1836   fns = TREE_OPERAND (template_id, 0);
1837   explicit_targs = TREE_OPERAND (template_id, 1);
1838 
1839   if (fns == error_mark_node)
1840     return error_mark_node;
1841 
1842   /* Check for baselinks.  */
1843   if (BASELINK_P (fns))
1844     fns = BASELINK_FUNCTIONS (fns);
1845 
1846   if (!is_overloaded_fn (fns))
1847     {
1848       error ("%qD is not a function template", fns);
1849       return error_mark_node;
1850     }
1851 
1852   /* Count the number of template headers specified for this
1853      specialization.  */
1854   header_count = 0;
1855   for (b = current_binding_level;
1856        b->kind == sk_template_parms;
1857        b = b->level_chain)
1858     ++header_count;
1859 
1860   for (; fns; fns = OVL_NEXT (fns))
1861     {
1862       tree fn = OVL_CURRENT (fns);
1863 
1864       if (TREE_CODE (fn) == TEMPLATE_DECL)
1865 	{
1866 	  tree decl_arg_types;
1867 	  tree fn_arg_types;
1868 	  tree insttype;
1869 
1870 	  /* In case of explicit specialization, we need to check if
1871 	     the number of template headers appearing in the specialization
1872 	     is correct. This is usually done in check_explicit_specialization,
1873 	     but the check done there cannot be exhaustive when specializing
1874 	     member functions. Consider the following code:
1875 
1876 	     template <> void A<int>::f(int);
1877 	     template <> template <> void A<int>::f(int);
1878 
1879 	     Assuming that A<int> is not itself an explicit specialization
1880 	     already, the first line specializes "f" which is a non-template
1881 	     member function, whilst the second line specializes "f" which
1882 	     is a template member function. So both lines are syntactically
1883 	     correct, and check_explicit_specialization does not reject
1884 	     them.
1885 
1886 	     Here, we can do better, as we are matching the specialization
1887 	     against the declarations. We count the number of template
1888 	     headers, and we check if they match TEMPLATE_COUNT + 1
1889 	     (TEMPLATE_COUNT is the number of qualifying template classes,
1890 	     plus there must be another header for the member template
1891 	     itself).
1892 
1893 	     Notice that if header_count is zero, this is not a
1894 	     specialization but rather a template instantiation, so there
1895 	     is no check we can perform here.  */
1896 	  if (header_count && header_count != template_count + 1)
1897 	    continue;
1898 
1899 	  /* Check that the number of template arguments at the
1900 	     innermost level for DECL is the same as for FN.  */
1901 	  if (current_binding_level->kind == sk_template_parms
1902 	      && !current_binding_level->explicit_spec_p
1903 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1904 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1905 				      (current_template_parms))))
1906 	    continue;
1907 
1908 	  /* DECL might be a specialization of FN.  */
1909 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1910 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1911 
1912 	  /* For a non-static member function, we need to make sure
1913 	     that the const qualification is the same.  Since
1914 	     get_bindings does not try to merge the "this" parameter,
1915 	     we must do the comparison explicitly.  */
1916 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1917 	      && !same_type_p (TREE_VALUE (fn_arg_types),
1918 			       TREE_VALUE (decl_arg_types)))
1919 	    continue;
1920 
1921 	  /* Skip the "this" parameter and, for constructors of
1922 	     classes with virtual bases, the VTT parameter.  A
1923 	     full specialization of a constructor will have a VTT
1924 	     parameter, but a template never will.  */
1925 	  decl_arg_types
1926 	    = skip_artificial_parms_for (decl, decl_arg_types);
1927 	  fn_arg_types
1928 	    = skip_artificial_parms_for (fn, fn_arg_types);
1929 
1930 	  /* Function templates cannot be specializations; there are
1931 	     no partial specializations of functions.  Therefore, if
1932 	     the type of DECL does not match FN, there is no
1933 	     match.  */
1934 	  if (tsk == tsk_template)
1935 	    {
1936 	      if (compparms (fn_arg_types, decl_arg_types))
1937 		candidates = tree_cons (NULL_TREE, fn, candidates);
1938 	      continue;
1939 	    }
1940 
1941 	  /* See whether this function might be a specialization of this
1942 	     template.  Suppress access control because we might be trying
1943 	     to make this specialization a friend, and we have already done
1944 	     access control for the declaration of the specialization.  */
1945 	  push_deferring_access_checks (dk_no_check);
1946 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1947 	  pop_deferring_access_checks ();
1948 
1949 	  if (!targs)
1950 	    /* We cannot deduce template arguments that when used to
1951 	       specialize TMPL will produce DECL.  */
1952 	    continue;
1953 
1954 	  /* Make sure that the deduced arguments actually work.  */
1955 	  insttype = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
1956 	  if (insttype == error_mark_node)
1957 	    continue;
1958 	  fn_arg_types
1959 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
1960 	  if (!compparms (fn_arg_types, decl_arg_types))
1961 	    continue;
1962 
1963 	  /* Save this template, and the arguments deduced.  */
1964 	  templates = tree_cons (targs, fn, templates);
1965 	}
1966       else if (need_member_template)
1967 	/* FN is an ordinary member function, and we need a
1968 	   specialization of a member template.  */
1969 	;
1970       else if (TREE_CODE (fn) != FUNCTION_DECL)
1971 	/* We can get IDENTIFIER_NODEs here in certain erroneous
1972 	   cases.  */
1973 	;
1974       else if (!DECL_FUNCTION_MEMBER_P (fn))
1975 	/* This is just an ordinary non-member function.  Nothing can
1976 	   be a specialization of that.  */
1977 	;
1978       else if (DECL_ARTIFICIAL (fn))
1979 	/* Cannot specialize functions that are created implicitly.  */
1980 	;
1981       else
1982 	{
1983 	  tree decl_arg_types;
1984 
1985 	  /* This is an ordinary member function.  However, since
1986 	     we're here, we can assume it's enclosing class is a
1987 	     template class.  For example,
1988 
1989 	       template <typename T> struct S { void f(); };
1990 	       template <> void S<int>::f() {}
1991 
1992 	     Here, S<int>::f is a non-template, but S<int> is a
1993 	     template class.  If FN has the same type as DECL, we
1994 	     might be in business.  */
1995 
1996 	  if (!DECL_TEMPLATE_INFO (fn))
1997 	    /* Its enclosing class is an explicit specialization
1998 	       of a template class.  This is not a candidate.  */
1999 	    continue;
2000 
2001 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2002 			    TREE_TYPE (TREE_TYPE (fn))))
2003 	    /* The return types differ.  */
2004 	    continue;
2005 
2006 	  /* Adjust the type of DECL in case FN is a static member.  */
2007 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2008 	  if (DECL_STATIC_FUNCTION_P (fn)
2009 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2010 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2011 
2012 	  if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2013 			 decl_arg_types))
2014 	    /* They match!  */
2015 	    candidates = tree_cons (NULL_TREE, fn, candidates);
2016 	}
2017     }
2018 
2019   if (templates && TREE_CHAIN (templates))
2020     {
2021       /* We have:
2022 
2023 	   [temp.expl.spec]
2024 
2025 	   It is possible for a specialization with a given function
2026 	   signature to be instantiated from more than one function
2027 	   template.  In such cases, explicit specification of the
2028 	   template arguments must be used to uniquely identify the
2029 	   function template specialization being specialized.
2030 
2031 	 Note that here, there's no suggestion that we're supposed to
2032 	 determine which of the candidate templates is most
2033 	 specialized.  However, we, also have:
2034 
2035 	   [temp.func.order]
2036 
2037 	   Partial ordering of overloaded function template
2038 	   declarations is used in the following contexts to select
2039 	   the function template to which a function template
2040 	   specialization refers:
2041 
2042 	   -- when an explicit specialization refers to a function
2043 	      template.
2044 
2045 	 So, we do use the partial ordering rules, at least for now.
2046 	 This extension can only serve to make invalid programs valid,
2047 	 so it's safe.  And, there is strong anecdotal evidence that
2048 	 the committee intended the partial ordering rules to apply;
2049 	 the EDG front end has that behavior, and John Spicer claims
2050 	 that the committee simply forgot to delete the wording in
2051 	 [temp.expl.spec].  */
2052       tree tmpl = most_specialized_instantiation (templates);
2053       if (tmpl != error_mark_node)
2054 	{
2055 	  templates = tmpl;
2056 	  TREE_CHAIN (templates) = NULL_TREE;
2057 	}
2058     }
2059 
2060   if (templates == NULL_TREE && candidates == NULL_TREE)
2061     {
2062       error ("template-id %qD for %q+D does not match any template "
2063 	     "declaration", template_id, decl);
2064       if (header_count && header_count != template_count + 1)
2065 	inform (input_location, "saw %d %<template<>%>, need %d for "
2066 		"specializing a member function template",
2067 		header_count, template_count + 1);
2068       return error_mark_node;
2069     }
2070   else if ((templates && TREE_CHAIN (templates))
2071 	   || (candidates && TREE_CHAIN (candidates))
2072 	   || (templates && candidates))
2073     {
2074       error ("ambiguous template specialization %qD for %q+D",
2075 	     template_id, decl);
2076       candidates = chainon (candidates, templates);
2077       print_candidates (candidates);
2078       return error_mark_node;
2079     }
2080 
2081   /* We have one, and exactly one, match.  */
2082   if (candidates)
2083     {
2084       tree fn = TREE_VALUE (candidates);
2085       *targs_out = copy_node (DECL_TI_ARGS (fn));
2086       /* DECL is a re-declaration or partial instantiation of a template
2087 	 function.  */
2088       if (TREE_CODE (fn) == TEMPLATE_DECL)
2089 	return fn;
2090       /* It was a specialization of an ordinary member function in a
2091 	 template class.  */
2092       return DECL_TI_TEMPLATE (fn);
2093     }
2094 
2095   /* It was a specialization of a template.  */
2096   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2097   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2098     {
2099       *targs_out = copy_node (targs);
2100       SET_TMPL_ARGS_LEVEL (*targs_out,
2101 			   TMPL_ARGS_DEPTH (*targs_out),
2102 			   TREE_PURPOSE (templates));
2103     }
2104   else
2105     *targs_out = TREE_PURPOSE (templates);
2106   return TREE_VALUE (templates);
2107 }
2108 
2109 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2110    but with the default argument values filled in from those in the
2111    TMPL_TYPES.  */
2112 
2113 static tree
copy_default_args_to_explicit_spec_1(tree spec_types,tree tmpl_types)2114 copy_default_args_to_explicit_spec_1 (tree spec_types,
2115 				      tree tmpl_types)
2116 {
2117   tree new_spec_types;
2118 
2119   if (!spec_types)
2120     return NULL_TREE;
2121 
2122   if (spec_types == void_list_node)
2123     return void_list_node;
2124 
2125   /* Substitute into the rest of the list.  */
2126   new_spec_types =
2127     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2128 					  TREE_CHAIN (tmpl_types));
2129 
2130   /* Add the default argument for this parameter.  */
2131   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2132 			 TREE_VALUE (spec_types),
2133 			 new_spec_types);
2134 }
2135 
2136 /* DECL is an explicit specialization.  Replicate default arguments
2137    from the template it specializes.  (That way, code like:
2138 
2139      template <class T> void f(T = 3);
2140      template <> void f(double);
2141      void g () { f (); }
2142 
2143    works, as required.)  An alternative approach would be to look up
2144    the correct default arguments at the call-site, but this approach
2145    is consistent with how implicit instantiations are handled.  */
2146 
2147 static void
copy_default_args_to_explicit_spec(tree decl)2148 copy_default_args_to_explicit_spec (tree decl)
2149 {
2150   tree tmpl;
2151   tree spec_types;
2152   tree tmpl_types;
2153   tree new_spec_types;
2154   tree old_type;
2155   tree new_type;
2156   tree t;
2157   tree object_type = NULL_TREE;
2158   tree in_charge = NULL_TREE;
2159   tree vtt = NULL_TREE;
2160 
2161   /* See if there's anything we need to do.  */
2162   tmpl = DECL_TI_TEMPLATE (decl);
2163   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2164   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2165     if (TREE_PURPOSE (t))
2166       break;
2167   if (!t)
2168     return;
2169 
2170   old_type = TREE_TYPE (decl);
2171   spec_types = TYPE_ARG_TYPES (old_type);
2172 
2173   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2174     {
2175       /* Remove the this pointer, but remember the object's type for
2176 	 CV quals.  */
2177       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2178       spec_types = TREE_CHAIN (spec_types);
2179       tmpl_types = TREE_CHAIN (tmpl_types);
2180 
2181       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2182 	{
2183 	  /* DECL may contain more parameters than TMPL due to the extra
2184 	     in-charge parameter in constructors and destructors.  */
2185 	  in_charge = spec_types;
2186 	  spec_types = TREE_CHAIN (spec_types);
2187 	}
2188       if (DECL_HAS_VTT_PARM_P (decl))
2189 	{
2190 	  vtt = spec_types;
2191 	  spec_types = TREE_CHAIN (spec_types);
2192 	}
2193     }
2194 
2195   /* Compute the merged default arguments.  */
2196   new_spec_types =
2197     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2198 
2199   /* Compute the new FUNCTION_TYPE.  */
2200   if (object_type)
2201     {
2202       if (vtt)
2203 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2204 					 TREE_VALUE (vtt),
2205 					 new_spec_types);
2206 
2207       if (in_charge)
2208 	/* Put the in-charge parameter back.  */
2209 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2210 					 TREE_VALUE (in_charge),
2211 					 new_spec_types);
2212 
2213       new_type = build_method_type_directly (object_type,
2214 					     TREE_TYPE (old_type),
2215 					     new_spec_types);
2216     }
2217   else
2218     new_type = build_function_type (TREE_TYPE (old_type),
2219 				    new_spec_types);
2220   new_type = cp_build_type_attribute_variant (new_type,
2221 					      TYPE_ATTRIBUTES (old_type));
2222   new_type = build_exception_variant (new_type,
2223 				      TYPE_RAISES_EXCEPTIONS (old_type));
2224   TREE_TYPE (decl) = new_type;
2225 }
2226 
2227 /* Return the number of template headers we expect to see for a definition
2228    or specialization of CTYPE or one of its non-template members.  */
2229 
2230 int
num_template_headers_for_class(tree ctype)2231 num_template_headers_for_class (tree ctype)
2232 {
2233   int num_templates = 0;
2234 
2235   while (ctype && CLASS_TYPE_P (ctype))
2236     {
2237       /* You're supposed to have one `template <...>' for every
2238 	 template class, but you don't need one for a full
2239 	 specialization.  For example:
2240 
2241 	 template <class T> struct S{};
2242 	 template <> struct S<int> { void f(); };
2243 	 void S<int>::f () {}
2244 
2245 	 is correct; there shouldn't be a `template <>' for the
2246 	 definition of `S<int>::f'.  */
2247       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2248 	/* If CTYPE does not have template information of any
2249 	   kind,  then it is not a template, nor is it nested
2250 	   within a template.  */
2251 	break;
2252       if (explicit_class_specialization_p (ctype))
2253 	break;
2254       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2255 	++num_templates;
2256 
2257       ctype = TYPE_CONTEXT (ctype);
2258     }
2259 
2260   return num_templates;
2261 }
2262 
2263 /* Do a simple sanity check on the template headers that precede the
2264    variable declaration DECL.  */
2265 
2266 void
check_template_variable(tree decl)2267 check_template_variable (tree decl)
2268 {
2269   tree ctx = CP_DECL_CONTEXT (decl);
2270   int wanted = num_template_headers_for_class (ctx);
2271   if (!TYPE_P (ctx) || !CLASSTYPE_TEMPLATE_INFO (ctx))
2272     permerror (DECL_SOURCE_LOCATION (decl),
2273 	       "%qD is not a static data member of a class template", decl);
2274   else if (template_header_count > wanted)
2275     {
2276       pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2277 	       "too many template headers for %D (should be %d)",
2278 	       decl, wanted);
2279       if (CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2280 	inform (DECL_SOURCE_LOCATION (decl),
2281 		"members of an explicitly specialized class are defined "
2282 		"without a template header");
2283     }
2284 }
2285 
2286 /* Check to see if the function just declared, as indicated in
2287    DECLARATOR, and in DECL, is a specialization of a function
2288    template.  We may also discover that the declaration is an explicit
2289    instantiation at this point.
2290 
2291    Returns DECL, or an equivalent declaration that should be used
2292    instead if all goes well.  Issues an error message if something is
2293    amiss.  Returns error_mark_node if the error is not easily
2294    recoverable.
2295 
2296    FLAGS is a bitmask consisting of the following flags:
2297 
2298    2: The function has a definition.
2299    4: The function is a friend.
2300 
2301    The TEMPLATE_COUNT is the number of references to qualifying
2302    template classes that appeared in the name of the function.  For
2303    example, in
2304 
2305      template <class T> struct S { void f(); };
2306      void S<int>::f();
2307 
2308    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2309    classes are not counted in the TEMPLATE_COUNT, so that in
2310 
2311      template <class T> struct S {};
2312      template <> struct S<int> { void f(); }
2313      template <> void S<int>::f();
2314 
2315    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2316    invalid; there should be no template <>.)
2317 
2318    If the function is a specialization, it is marked as such via
2319    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2320    is set up correctly, and it is added to the list of specializations
2321    for that template.  */
2322 
2323 tree
check_explicit_specialization(tree declarator,tree decl,int template_count,int flags)2324 check_explicit_specialization (tree declarator,
2325 			       tree decl,
2326 			       int template_count,
2327 			       int flags)
2328 {
2329   int have_def = flags & 2;
2330   int is_friend = flags & 4;
2331   int specialization = 0;
2332   int explicit_instantiation = 0;
2333   int member_specialization = 0;
2334   tree ctype = DECL_CLASS_CONTEXT (decl);
2335   tree dname = DECL_NAME (decl);
2336   tmpl_spec_kind tsk;
2337 
2338   if (is_friend)
2339     {
2340       if (!processing_specialization)
2341 	tsk = tsk_none;
2342       else
2343 	tsk = tsk_excessive_parms;
2344     }
2345   else
2346     tsk = current_tmpl_spec_kind (template_count);
2347 
2348   switch (tsk)
2349     {
2350     case tsk_none:
2351       if (processing_specialization)
2352 	{
2353 	  specialization = 1;
2354 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2355 	}
2356       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2357 	{
2358 	  if (is_friend)
2359 	    /* This could be something like:
2360 
2361 	       template <class T> void f(T);
2362 	       class S { friend void f<>(int); }  */
2363 	    specialization = 1;
2364 	  else
2365 	    {
2366 	      /* This case handles bogus declarations like template <>
2367 		 template <class T> void f<int>(); */
2368 
2369 	      error ("template-id %qD in declaration of primary template",
2370 		     declarator);
2371 	      return decl;
2372 	    }
2373 	}
2374       break;
2375 
2376     case tsk_invalid_member_spec:
2377       /* The error has already been reported in
2378 	 check_specialization_scope.  */
2379       return error_mark_node;
2380 
2381     case tsk_invalid_expl_inst:
2382       error ("template parameter list used in explicit instantiation");
2383 
2384       /* Fall through.  */
2385 
2386     case tsk_expl_inst:
2387       if (have_def)
2388 	error ("definition provided for explicit instantiation");
2389 
2390       explicit_instantiation = 1;
2391       break;
2392 
2393     case tsk_excessive_parms:
2394     case tsk_insufficient_parms:
2395       if (tsk == tsk_excessive_parms)
2396 	error ("too many template parameter lists in declaration of %qD",
2397 	       decl);
2398       else if (template_header_count)
2399 	error("too few template parameter lists in declaration of %qD", decl);
2400       else
2401 	error("explicit specialization of %qD must be introduced by "
2402 	      "%<template <>%>", decl);
2403 
2404       /* Fall through.  */
2405     case tsk_expl_spec:
2406       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2407       if (ctype)
2408 	member_specialization = 1;
2409       else
2410 	specialization = 1;
2411       break;
2412 
2413     case tsk_template:
2414       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2415 	{
2416 	  /* This case handles bogus declarations like template <>
2417 	     template <class T> void f<int>(); */
2418 
2419 	  if (uses_template_parms (declarator))
2420 	    error ("function template partial specialization %qD "
2421 		   "is not allowed", declarator);
2422 	  else
2423 	    error ("template-id %qD in declaration of primary template",
2424 		   declarator);
2425 	  return decl;
2426 	}
2427 
2428       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2429 	/* This is a specialization of a member template, without
2430 	   specialization the containing class.  Something like:
2431 
2432 	     template <class T> struct S {
2433 	       template <class U> void f (U);
2434 	     };
2435 	     template <> template <class U> void S<int>::f(U) {}
2436 
2437 	   That's a specialization -- but of the entire template.  */
2438 	specialization = 1;
2439       break;
2440 
2441     default:
2442       gcc_unreachable ();
2443     }
2444 
2445   if (specialization || member_specialization)
2446     {
2447       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2448       for (; t; t = TREE_CHAIN (t))
2449 	if (TREE_PURPOSE (t))
2450 	  {
2451 	    permerror (input_location,
2452 		       "default argument specified in explicit specialization");
2453 	    break;
2454 	  }
2455     }
2456 
2457   if (specialization || member_specialization || explicit_instantiation)
2458     {
2459       tree tmpl = NULL_TREE;
2460       tree targs = NULL_TREE;
2461 
2462       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2463       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2464 	{
2465 	  tree fns;
2466 
2467 	  gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2468 	  if (ctype)
2469 	    fns = dname;
2470 	  else
2471 	    {
2472 	      /* If there is no class context, the explicit instantiation
2473 		 must be at namespace scope.  */
2474 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2475 
2476 	      /* Find the namespace binding, using the declaration
2477 		 context.  */
2478 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2479 					   false, true);
2480 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
2481 		{
2482 		  error ("%qD is not a template function", dname);
2483 		  fns = error_mark_node;
2484 		}
2485 	      else
2486 		{
2487 		  tree fn = OVL_CURRENT (fns);
2488 		  if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2489 						CP_DECL_CONTEXT (fn)))
2490 		    error ("%qD is not declared in %qD",
2491 			   decl, current_namespace);
2492 		}
2493 	    }
2494 
2495 	  declarator = lookup_template_function (fns, NULL_TREE);
2496 	}
2497 
2498       if (declarator == error_mark_node)
2499 	return error_mark_node;
2500 
2501       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2502 	{
2503 	  if (!explicit_instantiation)
2504 	    /* A specialization in class scope.  This is invalid,
2505 	       but the error will already have been flagged by
2506 	       check_specialization_scope.  */
2507 	    return error_mark_node;
2508 	  else
2509 	    {
2510 	      /* It's not valid to write an explicit instantiation in
2511 		 class scope, e.g.:
2512 
2513 		   class C { template void f(); }
2514 
2515 		   This case is caught by the parser.  However, on
2516 		   something like:
2517 
2518 		   template class C { void f(); };
2519 
2520 		   (which is invalid) we can get here.  The error will be
2521 		   issued later.  */
2522 	      ;
2523 	    }
2524 
2525 	  return decl;
2526 	}
2527       else if (ctype != NULL_TREE
2528 	       && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2529 		   IDENTIFIER_NODE))
2530 	{
2531 	  /* Find the list of functions in ctype that have the same
2532 	     name as the declared function.  */
2533 	  tree name = TREE_OPERAND (declarator, 0);
2534 	  tree fns = NULL_TREE;
2535 	  int idx;
2536 
2537 	  if (constructor_name_p (name, ctype))
2538 	    {
2539 	      int is_constructor = DECL_CONSTRUCTOR_P (decl);
2540 
2541 	      if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2542 		  : !CLASSTYPE_DESTRUCTORS (ctype))
2543 		{
2544 		  /* From [temp.expl.spec]:
2545 
2546 		     If such an explicit specialization for the member
2547 		     of a class template names an implicitly-declared
2548 		     special member function (clause _special_), the
2549 		     program is ill-formed.
2550 
2551 		     Similar language is found in [temp.explicit].  */
2552 		  error ("specialization of implicitly-declared special member function");
2553 		  return error_mark_node;
2554 		}
2555 
2556 	      name = is_constructor ? ctor_identifier : dtor_identifier;
2557 	    }
2558 
2559 	  if (!DECL_CONV_FN_P (decl))
2560 	    {
2561 	      idx = lookup_fnfields_1 (ctype, name);
2562 	      if (idx >= 0)
2563 		fns = (*CLASSTYPE_METHOD_VEC (ctype))[idx];
2564 	    }
2565 	  else
2566 	    {
2567 	      vec<tree, va_gc> *methods;
2568 	      tree ovl;
2569 
2570 	      /* For a type-conversion operator, we cannot do a
2571 		 name-based lookup.  We might be looking for `operator
2572 		 int' which will be a specialization of `operator T'.
2573 		 So, we find *all* the conversion operators, and then
2574 		 select from them.  */
2575 	      fns = NULL_TREE;
2576 
2577 	      methods = CLASSTYPE_METHOD_VEC (ctype);
2578 	      if (methods)
2579 		for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2580 		     methods->iterate (idx, &ovl);
2581 		     ++idx)
2582 		  {
2583 		    if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2584 		      /* There are no more conversion functions.  */
2585 		      break;
2586 
2587 		    /* Glue all these conversion functions together
2588 		       with those we already have.  */
2589 		    for (; ovl; ovl = OVL_NEXT (ovl))
2590 		      fns = ovl_cons (OVL_CURRENT (ovl), fns);
2591 		  }
2592 	    }
2593 
2594 	  if (fns == NULL_TREE)
2595 	    {
2596 	      error ("no member function %qD declared in %qT", name, ctype);
2597 	      return error_mark_node;
2598 	    }
2599 	  else
2600 	    TREE_OPERAND (declarator, 0) = fns;
2601 	}
2602 
2603       /* Figure out what exactly is being specialized at this point.
2604 	 Note that for an explicit instantiation, even one for a
2605 	 member function, we cannot tell apriori whether the
2606 	 instantiation is for a member template, or just a member
2607 	 function of a template class.  Even if a member template is
2608 	 being instantiated, the member template arguments may be
2609 	 elided if they can be deduced from the rest of the
2610 	 declaration.  */
2611       tmpl = determine_specialization (declarator, decl,
2612 				       &targs,
2613 				       member_specialization,
2614 				       template_count,
2615 				       tsk);
2616 
2617       if (!tmpl || tmpl == error_mark_node)
2618 	/* We couldn't figure out what this declaration was
2619 	   specializing.  */
2620 	return error_mark_node;
2621       else
2622 	{
2623 	  tree gen_tmpl = most_general_template (tmpl);
2624 
2625 	  if (explicit_instantiation)
2626 	    {
2627 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2628 		 is done by do_decl_instantiation later.  */
2629 
2630 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
2631 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2632 
2633 	      if (arg_depth > parm_depth)
2634 		{
2635 		  /* If TMPL is not the most general template (for
2636 		     example, if TMPL is a friend template that is
2637 		     injected into namespace scope), then there will
2638 		     be too many levels of TARGS.  Remove some of them
2639 		     here.  */
2640 		  int i;
2641 		  tree new_targs;
2642 
2643 		  new_targs = make_tree_vec (parm_depth);
2644 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2645 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2646 		      = TREE_VEC_ELT (targs, i);
2647 		  targs = new_targs;
2648 		}
2649 
2650 	      return instantiate_template (tmpl, targs, tf_error);
2651 	    }
2652 
2653 	  /* If we thought that the DECL was a member function, but it
2654 	     turns out to be specializing a static member function,
2655 	     make DECL a static member function as well.  */
2656 	  if (DECL_STATIC_FUNCTION_P (tmpl)
2657 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2658 	    revert_static_member_fn (decl);
2659 
2660 	  /* If this is a specialization of a member template of a
2661 	     template class, we want to return the TEMPLATE_DECL, not
2662 	     the specialization of it.  */
2663 	  if (tsk == tsk_template)
2664 	    {
2665 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
2666 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2667 	      DECL_INITIAL (result) = NULL_TREE;
2668 	      if (have_def)
2669 		{
2670 		  tree parm;
2671 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2672 		  DECL_SOURCE_LOCATION (result)
2673 		    = DECL_SOURCE_LOCATION (decl);
2674 		  /* We want to use the argument list specified in the
2675 		     definition, not in the original declaration.  */
2676 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2677 		  for (parm = DECL_ARGUMENTS (result); parm;
2678 		       parm = DECL_CHAIN (parm))
2679 		    DECL_CONTEXT (parm) = result;
2680 		}
2681 	      return register_specialization (tmpl, gen_tmpl, targs,
2682 					      is_friend, 0);
2683 	    }
2684 
2685 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2686 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2687 
2688 	  /* Inherit default function arguments from the template
2689 	     DECL is specializing.  */
2690 	  copy_default_args_to_explicit_spec (decl);
2691 
2692 	  /* This specialization has the same protection as the
2693 	     template it specializes.  */
2694 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2695 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2696 
2697           /* 7.1.1-1 [dcl.stc]
2698 
2699              A storage-class-specifier shall not be specified in an
2700              explicit specialization...
2701 
2702              The parser rejects these, so unless action is taken here,
2703              explicit function specializations will always appear with
2704              global linkage.
2705 
2706              The action recommended by the C++ CWG in response to C++
2707              defect report 605 is to make the storage class and linkage
2708              of the explicit specialization match the templated function:
2709 
2710              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2711            */
2712           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2713             {
2714               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2715               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2716 
2717               /* This specialization has the same linkage and visibility as
2718                  the function template it specializes.  */
2719               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2720 	      if (! TREE_PUBLIC (decl))
2721 		{
2722 		  DECL_INTERFACE_KNOWN (decl) = 1;
2723 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
2724 		}
2725               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2726               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2727                 {
2728                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2729                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2730                 }
2731             }
2732 
2733 	  /* If DECL is a friend declaration, declared using an
2734 	     unqualified name, the namespace associated with DECL may
2735 	     have been set incorrectly.  For example, in:
2736 
2737 	       template <typename T> void f(T);
2738 	       namespace N {
2739 		 struct S { friend void f<int>(int); }
2740 	       }
2741 
2742 	     we will have set the DECL_CONTEXT for the friend
2743 	     declaration to N, rather than to the global namespace.  */
2744 	  if (DECL_NAMESPACE_SCOPE_P (decl))
2745 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2746 
2747 	  if (is_friend && !have_def)
2748 	    /* This is not really a declaration of a specialization.
2749 	       It's just the name of an instantiation.  But, it's not
2750 	       a request for an instantiation, either.  */
2751 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
2752 	  else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2753 	    /* This is indeed a specialization.  In case of constructors
2754 	       and destructors, we need in-charge and not-in-charge
2755 	       versions in V3 ABI.  */
2756 	    clone_function_decl (decl, /*update_method_vec_p=*/0);
2757 
2758 	  /* Register this specialization so that we can find it
2759 	     again.  */
2760 	  decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2761 	}
2762     }
2763 
2764   return decl;
2765 }
2766 
2767 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2768    parameters.  These are represented in the same format used for
2769    DECL_TEMPLATE_PARMS.  */
2770 
2771 int
comp_template_parms(const_tree parms1,const_tree parms2)2772 comp_template_parms (const_tree parms1, const_tree parms2)
2773 {
2774   const_tree p1;
2775   const_tree p2;
2776 
2777   if (parms1 == parms2)
2778     return 1;
2779 
2780   for (p1 = parms1, p2 = parms2;
2781        p1 != NULL_TREE && p2 != NULL_TREE;
2782        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2783     {
2784       tree t1 = TREE_VALUE (p1);
2785       tree t2 = TREE_VALUE (p2);
2786       int i;
2787 
2788       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2789       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2790 
2791       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2792 	return 0;
2793 
2794       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2795 	{
2796           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2797           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2798 
2799           /* If either of the template parameters are invalid, assume
2800              they match for the sake of error recovery. */
2801           if (parm1 == error_mark_node || parm2 == error_mark_node)
2802             return 1;
2803 
2804 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
2805 	    return 0;
2806 
2807 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2808               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2809                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2810 	    continue;
2811 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2812 	    return 0;
2813 	}
2814     }
2815 
2816   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2817     /* One set of parameters has more parameters lists than the
2818        other.  */
2819     return 0;
2820 
2821   return 1;
2822 }
2823 
2824 /* Determine whether PARM is a parameter pack.  */
2825 
2826 bool
template_parameter_pack_p(const_tree parm)2827 template_parameter_pack_p (const_tree parm)
2828 {
2829   /* Determine if we have a non-type template parameter pack.  */
2830   if (TREE_CODE (parm) == PARM_DECL)
2831     return (DECL_TEMPLATE_PARM_P (parm)
2832             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2833   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
2834     return TEMPLATE_PARM_PARAMETER_PACK (parm);
2835 
2836   /* If this is a list of template parameters, we could get a
2837      TYPE_DECL or a TEMPLATE_DECL.  */
2838   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2839     parm = TREE_TYPE (parm);
2840 
2841   /* Otherwise it must be a type template parameter.  */
2842   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2843 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2844 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2845 }
2846 
2847 /* Determine if T is a function parameter pack.  */
2848 
2849 bool
function_parameter_pack_p(const_tree t)2850 function_parameter_pack_p (const_tree t)
2851 {
2852   if (t && TREE_CODE (t) == PARM_DECL)
2853     return FUNCTION_PARAMETER_PACK_P (t);
2854   return false;
2855 }
2856 
2857 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2858    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2859 
2860 tree
get_function_template_decl(const_tree primary_func_tmpl_inst)2861 get_function_template_decl (const_tree primary_func_tmpl_inst)
2862 {
2863   if (! primary_func_tmpl_inst
2864       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2865       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2866     return NULL;
2867 
2868   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2869 }
2870 
2871 /* Return true iff the function parameter PARAM_DECL was expanded
2872    from the function parameter pack PACK.  */
2873 
2874 bool
function_parameter_expanded_from_pack_p(tree param_decl,tree pack)2875 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2876 {
2877   if (DECL_ARTIFICIAL (param_decl)
2878       || !function_parameter_pack_p (pack))
2879     return false;
2880 
2881   /* The parameter pack and its pack arguments have the same
2882      DECL_PARM_INDEX.  */
2883   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2884 }
2885 
2886 /* Determine whether ARGS describes a variadic template args list,
2887    i.e., one that is terminated by a template argument pack.  */
2888 
2889 static bool
template_args_variadic_p(tree args)2890 template_args_variadic_p (tree args)
2891 {
2892   int nargs;
2893   tree last_parm;
2894 
2895   if (args == NULL_TREE)
2896     return false;
2897 
2898   args = INNERMOST_TEMPLATE_ARGS (args);
2899   nargs = TREE_VEC_LENGTH (args);
2900 
2901   if (nargs == 0)
2902     return false;
2903 
2904   last_parm = TREE_VEC_ELT (args, nargs - 1);
2905 
2906   return ARGUMENT_PACK_P (last_parm);
2907 }
2908 
2909 /* Generate a new name for the parameter pack name NAME (an
2910    IDENTIFIER_NODE) that incorporates its */
2911 
2912 static tree
make_ith_pack_parameter_name(tree name,int i)2913 make_ith_pack_parameter_name (tree name, int i)
2914 {
2915   /* Munge the name to include the parameter index.  */
2916 #define NUMBUF_LEN 128
2917   char numbuf[NUMBUF_LEN];
2918   char* newname;
2919   int newname_len;
2920 
2921   if (name == NULL_TREE)
2922     return name;
2923   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2924   newname_len = IDENTIFIER_LENGTH (name)
2925 	        + strlen (numbuf) + 2;
2926   newname = (char*)alloca (newname_len);
2927   snprintf (newname, newname_len,
2928 	    "%s#%i", IDENTIFIER_POINTER (name), i);
2929   return get_identifier (newname);
2930 }
2931 
2932 /* Return true if T is a primary function, class or alias template
2933    instantiation.  */
2934 
2935 bool
primary_template_instantiation_p(const_tree t)2936 primary_template_instantiation_p (const_tree t)
2937 {
2938   if (!t)
2939     return false;
2940 
2941   if (TREE_CODE (t) == FUNCTION_DECL)
2942     return DECL_LANG_SPECIFIC (t)
2943 	   && DECL_TEMPLATE_INSTANTIATION (t)
2944 	   && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2945   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
2946     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2947 	   && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2948   else if (alias_template_specialization_p (t))
2949     return true;
2950   return false;
2951 }
2952 
2953 /* Return true if PARM is a template template parameter.  */
2954 
2955 bool
template_template_parameter_p(const_tree parm)2956 template_template_parameter_p (const_tree parm)
2957 {
2958   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2959 }
2960 
2961 /* Return true iff PARM is a DECL representing a type template
2962    parameter.  */
2963 
2964 bool
template_type_parameter_p(const_tree parm)2965 template_type_parameter_p (const_tree parm)
2966 {
2967   return (parm
2968 	  && (TREE_CODE (parm) == TYPE_DECL
2969 	      || TREE_CODE (parm) == TEMPLATE_DECL)
2970 	  && DECL_TEMPLATE_PARM_P (parm));
2971 }
2972 
2973 /* Return the template parameters of T if T is a
2974    primary template instantiation, NULL otherwise.  */
2975 
2976 tree
get_primary_template_innermost_parameters(const_tree t)2977 get_primary_template_innermost_parameters (const_tree t)
2978 {
2979   tree parms = NULL, template_info = NULL;
2980 
2981   if ((template_info = get_template_info (t))
2982       && primary_template_instantiation_p (t))
2983     parms = INNERMOST_TEMPLATE_PARMS
2984 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2985 
2986   return parms;
2987 }
2988 
2989 /* Return the template parameters of the LEVELth level from the full list
2990    of template parameters PARMS.  */
2991 
2992 tree
get_template_parms_at_level(tree parms,int level)2993 get_template_parms_at_level (tree parms, int level)
2994 {
2995   tree p;
2996   if (!parms
2997       || TREE_CODE (parms) != TREE_LIST
2998       || level > TMPL_PARMS_DEPTH (parms))
2999     return NULL_TREE;
3000 
3001   for (p = parms; p; p = TREE_CHAIN (p))
3002     if (TMPL_PARMS_DEPTH (p) == level)
3003       return p;
3004 
3005   return NULL_TREE;
3006 }
3007 
3008 /* Returns the template arguments of T if T is a template instantiation,
3009    NULL otherwise.  */
3010 
3011 tree
get_template_innermost_arguments(const_tree t)3012 get_template_innermost_arguments (const_tree t)
3013 {
3014   tree args = NULL, template_info = NULL;
3015 
3016   if ((template_info = get_template_info (t))
3017       && TI_ARGS (template_info))
3018     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3019 
3020   return args;
3021 }
3022 
3023 /* Return the argument pack elements of T if T is a template argument pack,
3024    NULL otherwise.  */
3025 
3026 tree
get_template_argument_pack_elems(const_tree t)3027 get_template_argument_pack_elems (const_tree t)
3028 {
3029   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3030       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3031     return NULL;
3032 
3033   return ARGUMENT_PACK_ARGS (t);
3034 }
3035 
3036 /* Structure used to track the progress of find_parameter_packs_r.  */
3037 struct find_parameter_pack_data
3038 {
3039   /* TREE_LIST that will contain all of the parameter packs found by
3040      the traversal.  */
3041   tree* parameter_packs;
3042 
3043   /* Set of AST nodes that have been visited by the traversal.  */
3044   struct pointer_set_t *visited;
3045 };
3046 
3047 /* Identifies all of the argument packs that occur in a template
3048    argument and appends them to the TREE_LIST inside DATA, which is a
3049    find_parameter_pack_data structure. This is a subroutine of
3050    make_pack_expansion and uses_parameter_packs.  */
3051 static tree
find_parameter_packs_r(tree * tp,int * walk_subtrees,void * data)3052 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3053 {
3054   tree t = *tp;
3055   struct find_parameter_pack_data* ppd =
3056     (struct find_parameter_pack_data*)data;
3057   bool parameter_pack_p = false;
3058 
3059   /* Handle type aliases/typedefs.  */
3060   if (TYPE_P (t)
3061       && TYPE_NAME (t)
3062       && TREE_CODE (TYPE_NAME (t)) == TYPE_DECL
3063       && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3064     {
3065       if (TYPE_TEMPLATE_INFO (t))
3066 	cp_walk_tree (&TYPE_TI_ARGS (t),
3067 		      &find_parameter_packs_r,
3068 		      ppd, ppd->visited);
3069       *walk_subtrees = 0;
3070       return NULL_TREE;
3071     }
3072 
3073   /* Identify whether this is a parameter pack or not.  */
3074   switch (TREE_CODE (t))
3075     {
3076     case TEMPLATE_PARM_INDEX:
3077       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3078         parameter_pack_p = true;
3079       break;
3080 
3081     case TEMPLATE_TYPE_PARM:
3082       t = TYPE_MAIN_VARIANT (t);
3083     case TEMPLATE_TEMPLATE_PARM:
3084       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3085         parameter_pack_p = true;
3086       break;
3087 
3088     case PARM_DECL:
3089       if (FUNCTION_PARAMETER_PACK_P (t))
3090         {
3091           /* We don't want to walk into the type of a PARM_DECL,
3092              because we don't want to see the type parameter pack.  */
3093           *walk_subtrees = 0;
3094 	  parameter_pack_p = true;
3095         }
3096       break;
3097 
3098     case BASES:
3099       parameter_pack_p = true;
3100       break;
3101     default:
3102       /* Not a parameter pack.  */
3103       break;
3104     }
3105 
3106   if (parameter_pack_p)
3107     {
3108       /* Add this parameter pack to the list.  */
3109       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3110     }
3111 
3112   if (TYPE_P (t))
3113     cp_walk_tree (&TYPE_CONTEXT (t),
3114 		  &find_parameter_packs_r, ppd, ppd->visited);
3115 
3116   /* This switch statement will return immediately if we don't find a
3117      parameter pack.  */
3118   switch (TREE_CODE (t))
3119     {
3120     case TEMPLATE_PARM_INDEX:
3121       return NULL_TREE;
3122 
3123     case BOUND_TEMPLATE_TEMPLATE_PARM:
3124       /* Check the template itself.  */
3125       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3126 		    &find_parameter_packs_r, ppd, ppd->visited);
3127       /* Check the template arguments.  */
3128       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
3129 		    ppd->visited);
3130       *walk_subtrees = 0;
3131       return NULL_TREE;
3132 
3133     case TEMPLATE_TYPE_PARM:
3134     case TEMPLATE_TEMPLATE_PARM:
3135       return NULL_TREE;
3136 
3137     case PARM_DECL:
3138       return NULL_TREE;
3139 
3140     case RECORD_TYPE:
3141       if (TYPE_PTRMEMFUNC_P (t))
3142 	return NULL_TREE;
3143       /* Fall through.  */
3144 
3145     case UNION_TYPE:
3146     case ENUMERAL_TYPE:
3147       if (TYPE_TEMPLATE_INFO (t))
3148 	cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3149 		      &find_parameter_packs_r, ppd, ppd->visited);
3150 
3151       *walk_subtrees = 0;
3152       return NULL_TREE;
3153 
3154     case CONSTRUCTOR:
3155     case TEMPLATE_DECL:
3156       cp_walk_tree (&TREE_TYPE (t),
3157 		    &find_parameter_packs_r, ppd, ppd->visited);
3158       return NULL_TREE;
3159 
3160     case TYPENAME_TYPE:
3161       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3162                    ppd, ppd->visited);
3163       *walk_subtrees = 0;
3164       return NULL_TREE;
3165 
3166     case TYPE_PACK_EXPANSION:
3167     case EXPR_PACK_EXPANSION:
3168       *walk_subtrees = 0;
3169       return NULL_TREE;
3170 
3171     case INTEGER_TYPE:
3172       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3173 		    ppd, ppd->visited);
3174       *walk_subtrees = 0;
3175       return NULL_TREE;
3176 
3177     case IDENTIFIER_NODE:
3178       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3179 		    ppd->visited);
3180       *walk_subtrees = 0;
3181       return NULL_TREE;
3182 
3183     default:
3184       return NULL_TREE;
3185     }
3186 
3187   return NULL_TREE;
3188 }
3189 
3190 /* Determines if the expression or type T uses any parameter packs.  */
3191 bool
uses_parameter_packs(tree t)3192 uses_parameter_packs (tree t)
3193 {
3194   tree parameter_packs = NULL_TREE;
3195   struct find_parameter_pack_data ppd;
3196   ppd.parameter_packs = &parameter_packs;
3197   ppd.visited = pointer_set_create ();
3198   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3199   pointer_set_destroy (ppd.visited);
3200   return parameter_packs != NULL_TREE;
3201 }
3202 
3203 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3204    representation a base-class initializer into a parameter pack
3205    expansion. If all goes well, the resulting node will be an
3206    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3207    respectively.  */
3208 tree
make_pack_expansion(tree arg)3209 make_pack_expansion (tree arg)
3210 {
3211   tree result;
3212   tree parameter_packs = NULL_TREE;
3213   bool for_types = false;
3214   struct find_parameter_pack_data ppd;
3215 
3216   if (!arg || arg == error_mark_node)
3217     return arg;
3218 
3219   if (TREE_CODE (arg) == TREE_LIST)
3220     {
3221       /* The only time we will see a TREE_LIST here is for a base
3222          class initializer.  In this case, the TREE_PURPOSE will be a
3223          _TYPE node (representing the base class expansion we're
3224          initializing) and the TREE_VALUE will be a TREE_LIST
3225          containing the initialization arguments.
3226 
3227          The resulting expansion looks somewhat different from most
3228          expansions. Rather than returning just one _EXPANSION, we
3229          return a TREE_LIST whose TREE_PURPOSE is a
3230          TYPE_PACK_EXPANSION containing the bases that will be
3231          initialized.  The TREE_VALUE will be identical to the
3232          original TREE_VALUE, which is a list of arguments that will
3233          be passed to each base.  We do not introduce any new pack
3234          expansion nodes into the TREE_VALUE (although it is possible
3235          that some already exist), because the TREE_PURPOSE and
3236          TREE_VALUE all need to be expanded together with the same
3237          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3238          resulting TREE_PURPOSE will mention the parameter packs in
3239          both the bases and the arguments to the bases.  */
3240       tree purpose;
3241       tree value;
3242       tree parameter_packs = NULL_TREE;
3243 
3244       /* Determine which parameter packs will be used by the base
3245          class expansion.  */
3246       ppd.visited = pointer_set_create ();
3247       ppd.parameter_packs = &parameter_packs;
3248       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3249                     &ppd, ppd.visited);
3250 
3251       if (parameter_packs == NULL_TREE)
3252         {
3253           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3254           pointer_set_destroy (ppd.visited);
3255           return error_mark_node;
3256         }
3257 
3258       if (TREE_VALUE (arg) != void_type_node)
3259         {
3260           /* Collect the sets of parameter packs used in each of the
3261              initialization arguments.  */
3262           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3263             {
3264               /* Determine which parameter packs will be expanded in this
3265                  argument.  */
3266               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
3267                             &ppd, ppd.visited);
3268             }
3269         }
3270 
3271       pointer_set_destroy (ppd.visited);
3272 
3273       /* Create the pack expansion type for the base type.  */
3274       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3275       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3276       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3277 
3278       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3279 	 they will rarely be compared to anything.  */
3280       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3281 
3282       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3283     }
3284 
3285   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3286     for_types = true;
3287 
3288   /* Build the PACK_EXPANSION_* node.  */
3289   result = for_types
3290      ? cxx_make_type (TYPE_PACK_EXPANSION)
3291      : make_node (EXPR_PACK_EXPANSION);
3292   SET_PACK_EXPANSION_PATTERN (result, arg);
3293   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3294     {
3295       /* Propagate type and const-expression information.  */
3296       TREE_TYPE (result) = TREE_TYPE (arg);
3297       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3298     }
3299   else
3300     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3301        they will rarely be compared to anything.  */
3302     SET_TYPE_STRUCTURAL_EQUALITY (result);
3303 
3304   /* Determine which parameter packs will be expanded.  */
3305   ppd.parameter_packs = &parameter_packs;
3306   ppd.visited = pointer_set_create ();
3307   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3308   pointer_set_destroy (ppd.visited);
3309 
3310   /* Make sure we found some parameter packs.  */
3311   if (parameter_packs == NULL_TREE)
3312     {
3313       if (TYPE_P (arg))
3314         error ("expansion pattern %<%T%> contains no argument packs", arg);
3315       else
3316         error ("expansion pattern %<%E%> contains no argument packs", arg);
3317       return error_mark_node;
3318     }
3319   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3320 
3321   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
3322 
3323   return result;
3324 }
3325 
3326 /* Checks T for any "bare" parameter packs, which have not yet been
3327    expanded, and issues an error if any are found. This operation can
3328    only be done on full expressions or types (e.g., an expression
3329    statement, "if" condition, etc.), because we could have expressions like:
3330 
3331      foo(f(g(h(args)))...)
3332 
3333    where "args" is a parameter pack. check_for_bare_parameter_packs
3334    should not be called for the subexpressions args, h(args),
3335    g(h(args)), or f(g(h(args))), because we would produce erroneous
3336    error messages.
3337 
3338    Returns TRUE and emits an error if there were bare parameter packs,
3339    returns FALSE otherwise.  */
3340 bool
check_for_bare_parameter_packs(tree t)3341 check_for_bare_parameter_packs (tree t)
3342 {
3343   tree parameter_packs = NULL_TREE;
3344   struct find_parameter_pack_data ppd;
3345 
3346   if (!processing_template_decl || !t || t == error_mark_node)
3347     return false;
3348 
3349   if (TREE_CODE (t) == TYPE_DECL)
3350     t = TREE_TYPE (t);
3351 
3352   ppd.parameter_packs = &parameter_packs;
3353   ppd.visited = pointer_set_create ();
3354   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3355   pointer_set_destroy (ppd.visited);
3356 
3357   if (parameter_packs)
3358     {
3359       error ("parameter packs not expanded with %<...%>:");
3360       while (parameter_packs)
3361         {
3362           tree pack = TREE_VALUE (parameter_packs);
3363           tree name = NULL_TREE;
3364 
3365           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3366               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3367             name = TYPE_NAME (pack);
3368           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3369             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3370           else
3371             name = DECL_NAME (pack);
3372 
3373 	  if (name)
3374 	    inform (input_location, "        %qD", name);
3375 	  else
3376 	    inform (input_location, "        <anonymous>");
3377 
3378           parameter_packs = TREE_CHAIN (parameter_packs);
3379         }
3380 
3381       return true;
3382     }
3383 
3384   return false;
3385 }
3386 
3387 /* Expand any parameter packs that occur in the template arguments in
3388    ARGS.  */
3389 tree
expand_template_argument_pack(tree args)3390 expand_template_argument_pack (tree args)
3391 {
3392   tree result_args = NULL_TREE;
3393   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3394   int num_result_args = -1;
3395   int non_default_args_count = -1;
3396 
3397   /* First, determine if we need to expand anything, and the number of
3398      slots we'll need.  */
3399   for (in_arg = 0; in_arg < nargs; ++in_arg)
3400     {
3401       tree arg = TREE_VEC_ELT (args, in_arg);
3402       if (arg == NULL_TREE)
3403 	return args;
3404       if (ARGUMENT_PACK_P (arg))
3405         {
3406           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3407           if (num_result_args < 0)
3408             num_result_args = in_arg + num_packed;
3409           else
3410             num_result_args += num_packed;
3411         }
3412       else
3413         {
3414           if (num_result_args >= 0)
3415             num_result_args++;
3416         }
3417     }
3418 
3419   /* If no expansion is necessary, we're done.  */
3420   if (num_result_args < 0)
3421     return args;
3422 
3423   /* Expand arguments.  */
3424   result_args = make_tree_vec (num_result_args);
3425   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3426     non_default_args_count =
3427       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3428   for (in_arg = 0; in_arg < nargs; ++in_arg)
3429     {
3430       tree arg = TREE_VEC_ELT (args, in_arg);
3431       if (ARGUMENT_PACK_P (arg))
3432         {
3433           tree packed = ARGUMENT_PACK_ARGS (arg);
3434           int i, num_packed = TREE_VEC_LENGTH (packed);
3435           for (i = 0; i < num_packed; ++i, ++out_arg)
3436             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3437 	  if (non_default_args_count > 0)
3438 	    non_default_args_count += num_packed;
3439         }
3440       else
3441         {
3442           TREE_VEC_ELT (result_args, out_arg) = arg;
3443           ++out_arg;
3444         }
3445     }
3446   if (non_default_args_count >= 0)
3447     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3448   return result_args;
3449 }
3450 
3451 /* Checks if DECL shadows a template parameter.
3452 
3453    [temp.local]: A template-parameter shall not be redeclared within its
3454    scope (including nested scopes).
3455 
3456    Emits an error and returns TRUE if the DECL shadows a parameter,
3457    returns FALSE otherwise.  */
3458 
3459 bool
check_template_shadow(tree decl)3460 check_template_shadow (tree decl)
3461 {
3462   tree olddecl;
3463 
3464   /* If we're not in a template, we can't possibly shadow a template
3465      parameter.  */
3466   if (!current_template_parms)
3467     return true;
3468 
3469   /* Figure out what we're shadowing.  */
3470   if (TREE_CODE (decl) == OVERLOAD)
3471     decl = OVL_CURRENT (decl);
3472   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3473 
3474   /* If there's no previous binding for this name, we're not shadowing
3475      anything, let alone a template parameter.  */
3476   if (!olddecl)
3477     return true;
3478 
3479   /* If we're not shadowing a template parameter, we're done.  Note
3480      that OLDDECL might be an OVERLOAD (or perhaps even an
3481      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3482      node.  */
3483   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3484     return true;
3485 
3486   /* We check for decl != olddecl to avoid bogus errors for using a
3487      name inside a class.  We check TPFI to avoid duplicate errors for
3488      inline member templates.  */
3489   if (decl == olddecl
3490       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3491     return true;
3492 
3493   error ("declaration of %q+#D", decl);
3494   error (" shadows template parm %q+#D", olddecl);
3495   return false;
3496 }
3497 
3498 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3499    ORIG_LEVEL, DECL, and TYPE.  */
3500 
3501 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)3502 build_template_parm_index (int index,
3503 			   int level,
3504 			   int orig_level,
3505 			   tree decl,
3506 			   tree type)
3507 {
3508   tree t = make_node (TEMPLATE_PARM_INDEX);
3509   TEMPLATE_PARM_IDX (t) = index;
3510   TEMPLATE_PARM_LEVEL (t) = level;
3511   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3512   TEMPLATE_PARM_DECL (t) = decl;
3513   TREE_TYPE (t) = type;
3514   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3515   TREE_READONLY (t) = TREE_READONLY (decl);
3516 
3517   return t;
3518 }
3519 
3520 /* Find the canonical type parameter for the given template type
3521    parameter.  Returns the canonical type parameter, which may be TYPE
3522    if no such parameter existed.  */
3523 
3524 static tree
canonical_type_parameter(tree type)3525 canonical_type_parameter (tree type)
3526 {
3527   tree list;
3528   int idx = TEMPLATE_TYPE_IDX (type);
3529   if (!canonical_template_parms)
3530     vec_alloc (canonical_template_parms, idx+1);
3531 
3532   while (canonical_template_parms->length () <= (unsigned)idx)
3533     vec_safe_push (canonical_template_parms, NULL_TREE);
3534 
3535   list = (*canonical_template_parms)[idx];
3536   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3537     list = TREE_CHAIN (list);
3538 
3539   if (list)
3540     return TREE_VALUE (list);
3541   else
3542     {
3543       (*canonical_template_parms)[idx]
3544 		= tree_cons (NULL_TREE, type,
3545 			     (*canonical_template_parms)[idx]);
3546       return type;
3547     }
3548 }
3549 
3550 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3551    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3552    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3553    new one is created.  */
3554 
3555 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)3556 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3557 			    tsubst_flags_t complain)
3558 {
3559   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3560       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3561 	  != TEMPLATE_PARM_LEVEL (index) - levels)
3562       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3563     {
3564       tree orig_decl = TEMPLATE_PARM_DECL (index);
3565       tree decl, t;
3566 
3567       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3568 			 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3569       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3570       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3571       DECL_ARTIFICIAL (decl) = 1;
3572       SET_DECL_TEMPLATE_PARM_P (decl);
3573 
3574       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3575 				     TEMPLATE_PARM_LEVEL (index) - levels,
3576 				     TEMPLATE_PARM_ORIG_LEVEL (index),
3577 				     decl, type);
3578       TEMPLATE_PARM_DESCENDANTS (index) = t;
3579       TEMPLATE_PARM_PARAMETER_PACK (t)
3580 	= TEMPLATE_PARM_PARAMETER_PACK (index);
3581 
3582 	/* Template template parameters need this.  */
3583       if (TREE_CODE (decl) == TEMPLATE_DECL)
3584 	DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3585 	  (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3586 	   args, complain);
3587     }
3588 
3589   return TEMPLATE_PARM_DESCENDANTS (index);
3590 }
3591 
3592 /* Process information from new template parameter PARM and append it
3593    to the LIST being built.  This new parameter is a non-type
3594    parameter iff IS_NON_TYPE is true. This new parameter is a
3595    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3596    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3597    parameter list PARM belongs to. This is used used to create a
3598    proper canonical type for the type of PARM that is to be created,
3599    iff PARM is a type.  If the size is not known, this parameter shall
3600    be set to 0.  */
3601 
3602 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)3603 process_template_parm (tree list, location_t parm_loc, tree parm,
3604 		       bool is_non_type, bool is_parameter_pack)
3605 {
3606   tree decl = 0;
3607   tree defval;
3608   tree err_parm_list;
3609   int idx = 0;
3610 
3611   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3612   defval = TREE_PURPOSE (parm);
3613 
3614   if (list)
3615     {
3616       tree p = tree_last (list);
3617 
3618       if (p && TREE_VALUE (p) != error_mark_node)
3619         {
3620           p = TREE_VALUE (p);
3621           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3622             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3623           else
3624             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3625         }
3626 
3627       ++idx;
3628     }
3629   else
3630     idx = 0;
3631 
3632   if (is_non_type)
3633     {
3634       parm = TREE_VALUE (parm);
3635 
3636       SET_DECL_TEMPLATE_PARM_P (parm);
3637 
3638       if (TREE_TYPE (parm) == error_mark_node)
3639         {
3640           err_parm_list = build_tree_list (defval, parm);
3641           TREE_VALUE (err_parm_list) = error_mark_node;
3642 	   return chainon (list, err_parm_list);
3643         }
3644       else
3645       {
3646 	/* [temp.param]
3647 
3648 	   The top-level cv-qualifiers on the template-parameter are
3649 	   ignored when determining its type.  */
3650 	TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3651 	if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3652           {
3653             err_parm_list = build_tree_list (defval, parm);
3654             TREE_VALUE (err_parm_list) = error_mark_node;
3655 	     return chainon (list, err_parm_list);
3656           }
3657 
3658         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3659 	  {
3660 	    /* This template parameter is not a parameter pack, but it
3661 	       should be. Complain about "bare" parameter packs.  */
3662 	    check_for_bare_parameter_packs (TREE_TYPE (parm));
3663 
3664 	    /* Recover by calling this a parameter pack.  */
3665 	    is_parameter_pack = true;
3666 	  }
3667       }
3668 
3669       /* A template parameter is not modifiable.  */
3670       TREE_CONSTANT (parm) = 1;
3671       TREE_READONLY (parm) = 1;
3672       decl = build_decl (parm_loc,
3673 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3674       TREE_CONSTANT (decl) = 1;
3675       TREE_READONLY (decl) = 1;
3676       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3677 	= build_template_parm_index (idx, processing_template_decl,
3678 				     processing_template_decl,
3679 				     decl, TREE_TYPE (parm));
3680 
3681       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
3682 	= is_parameter_pack;
3683     }
3684   else
3685     {
3686       tree t;
3687       parm = TREE_VALUE (TREE_VALUE (parm));
3688 
3689       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3690 	{
3691 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3692 	  /* This is for distinguishing between real templates and template
3693 	     template parameters */
3694 	  TREE_TYPE (parm) = t;
3695 	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3696 	  decl = parm;
3697 	}
3698       else
3699 	{
3700 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
3701 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3702 	  decl = build_decl (parm_loc,
3703 			     TYPE_DECL, parm, t);
3704 	}
3705 
3706       TYPE_NAME (t) = decl;
3707       TYPE_STUB_DECL (t) = decl;
3708       parm = decl;
3709       TEMPLATE_TYPE_PARM_INDEX (t)
3710 	= build_template_parm_index (idx, processing_template_decl,
3711 				     processing_template_decl,
3712 				     decl, TREE_TYPE (parm));
3713       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3714       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3715     }
3716   DECL_ARTIFICIAL (decl) = 1;
3717   SET_DECL_TEMPLATE_PARM_P (decl);
3718   pushdecl (decl);
3719   parm = build_tree_list (defval, parm);
3720   return chainon (list, parm);
3721 }
3722 
3723 /* The end of a template parameter list has been reached.  Process the
3724    tree list into a parameter vector, converting each parameter into a more
3725    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
3726    as PARM_DECLs.  */
3727 
3728 tree
end_template_parm_list(tree parms)3729 end_template_parm_list (tree parms)
3730 {
3731   int nparms;
3732   tree parm, next;
3733   tree saved_parmlist = make_tree_vec (list_length (parms));
3734 
3735   current_template_parms
3736     = tree_cons (size_int (processing_template_decl),
3737 		 saved_parmlist, current_template_parms);
3738 
3739   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3740     {
3741       next = TREE_CHAIN (parm);
3742       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3743       TREE_CHAIN (parm) = NULL_TREE;
3744     }
3745 
3746   --processing_template_parmlist;
3747 
3748   return saved_parmlist;
3749 }
3750 
3751 /* end_template_decl is called after a template declaration is seen.  */
3752 
3753 void
end_template_decl(void)3754 end_template_decl (void)
3755 {
3756   reset_specialization ();
3757 
3758   if (! processing_template_decl)
3759     return;
3760 
3761   /* This matches the pushlevel in begin_template_parm_list.  */
3762   finish_scope ();
3763 
3764   --processing_template_decl;
3765   current_template_parms = TREE_CHAIN (current_template_parms);
3766 }
3767 
3768 /* Takes a TREE_LIST representing a template parameter and convert it
3769    into an argument suitable to be passed to the type substitution
3770    functions.  Note that If the TREE_LIST contains an error_mark
3771    node, the returned argument is error_mark_node.  */
3772 
3773 static tree
template_parm_to_arg(tree t)3774 template_parm_to_arg (tree t)
3775 {
3776 
3777   if (t == NULL_TREE
3778       || TREE_CODE (t) != TREE_LIST)
3779     return t;
3780 
3781   if (error_operand_p (TREE_VALUE (t)))
3782     return error_mark_node;
3783 
3784   t = TREE_VALUE (t);
3785 
3786   if (TREE_CODE (t) == TYPE_DECL
3787       || TREE_CODE (t) == TEMPLATE_DECL)
3788     {
3789       t = TREE_TYPE (t);
3790 
3791       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3792 	{
3793 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
3794 	     with a single element, which expands T.  */
3795 	  tree vec = make_tree_vec (1);
3796 #ifdef ENABLE_CHECKING
3797 	  SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3798 	    (vec, TREE_VEC_LENGTH (vec));
3799 #endif
3800 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3801 
3802 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
3803 	  SET_ARGUMENT_PACK_ARGS (t, vec);
3804 	}
3805     }
3806   else
3807     {
3808       t = DECL_INITIAL (t);
3809 
3810       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3811 	{
3812 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3813 	     with a single element, which expands T.  */
3814 	  tree vec = make_tree_vec (1);
3815 	  tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3816 #ifdef ENABLE_CHECKING
3817 	  SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3818 	    (vec, TREE_VEC_LENGTH (vec));
3819 #endif
3820 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3821 
3822 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
3823 	  SET_ARGUMENT_PACK_ARGS (t, vec);
3824 	  TREE_TYPE (t) = type;
3825 	}
3826     }
3827   return t;
3828 }
3829 
3830 /* Given a set of template parameters, return them as a set of template
3831    arguments.  The template parameters are represented as a TREE_VEC, in
3832    the form documented in cp-tree.h for template arguments.  */
3833 
3834 static tree
template_parms_to_args(tree parms)3835 template_parms_to_args (tree parms)
3836 {
3837   tree header;
3838   tree args = NULL_TREE;
3839   int length = TMPL_PARMS_DEPTH (parms);
3840   int l = length;
3841 
3842   /* If there is only one level of template parameters, we do not
3843      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3844      TREE_VEC containing the arguments.  */
3845   if (length > 1)
3846     args = make_tree_vec (length);
3847 
3848   for (header = parms; header; header = TREE_CHAIN (header))
3849     {
3850       tree a = copy_node (TREE_VALUE (header));
3851       int i;
3852 
3853       TREE_TYPE (a) = NULL_TREE;
3854       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3855 	TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
3856 
3857 #ifdef ENABLE_CHECKING
3858       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3859 #endif
3860 
3861       if (length > 1)
3862 	TREE_VEC_ELT (args, --l) = a;
3863       else
3864 	args = a;
3865     }
3866 
3867     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
3868       /* This can happen for template parms of a template template
3869 	 parameter, e.g:
3870 
3871 	 template<template<class T, class U> class TT> struct S;
3872 
3873 	 Consider the level of the parms of TT; T and U both have
3874 	 level 2; TT has no template parm of level 1. So in this case
3875 	 the first element of full_template_args is NULL_TREE. If we
3876 	 leave it like this TMPL_ARG_DEPTH on args returns 1 instead
3877 	 of 2. This will make tsubst wrongly consider that T and U
3878 	 have level 1. Instead, let's create a dummy vector as the
3879 	 first element of full_template_args so that TMPL_ARG_DEPTH
3880 	 returns the correct depth for args.  */
3881       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
3882   return args;
3883 }
3884 
3885 /* Within the declaration of a template, return the currently active
3886    template parameters as an argument TREE_VEC.  */
3887 
3888 static tree
current_template_args(void)3889 current_template_args (void)
3890 {
3891   return template_parms_to_args (current_template_parms);
3892 }
3893 
3894 /* Update the declared TYPE by doing any lookups which were thought to be
3895    dependent, but are not now that we know the SCOPE of the declarator.  */
3896 
3897 tree
maybe_update_decl_type(tree orig_type,tree scope)3898 maybe_update_decl_type (tree orig_type, tree scope)
3899 {
3900   tree type = orig_type;
3901 
3902   if (type == NULL_TREE)
3903     return type;
3904 
3905   if (TREE_CODE (orig_type) == TYPE_DECL)
3906     type = TREE_TYPE (type);
3907 
3908   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3909       && dependent_type_p (type)
3910       /* Don't bother building up the args in this case.  */
3911       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3912     {
3913       /* tsubst in the args corresponding to the template parameters,
3914 	 including auto if present.  Most things will be unchanged, but
3915 	 make_typename_type and tsubst_qualified_id will resolve
3916 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3917       tree args = current_template_args ();
3918       tree auto_node = type_uses_auto (type);
3919       tree pushed;
3920       if (auto_node)
3921 	{
3922 	  tree auto_vec = make_tree_vec (1);
3923 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
3924 	  args = add_to_template_args (args, auto_vec);
3925 	}
3926       pushed = push_scope (scope);
3927       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3928       if (pushed)
3929 	pop_scope (scope);
3930     }
3931 
3932   if (type == error_mark_node)
3933     return orig_type;
3934 
3935   if (TREE_CODE (orig_type) == TYPE_DECL)
3936     {
3937       if (same_type_p (type, TREE_TYPE (orig_type)))
3938 	type = orig_type;
3939       else
3940 	type = TYPE_NAME (type);
3941     }
3942   return type;
3943 }
3944 
3945 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3946    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3947    a member template.  Used by push_template_decl below.  */
3948 
3949 static tree
build_template_decl(tree decl,tree parms,bool member_template_p)3950 build_template_decl (tree decl, tree parms, bool member_template_p)
3951 {
3952   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3953   DECL_TEMPLATE_PARMS (tmpl) = parms;
3954   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3955   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3956   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3957 
3958   return tmpl;
3959 }
3960 
3961 struct template_parm_data
3962 {
3963   /* The level of the template parameters we are currently
3964      processing.  */
3965   int level;
3966 
3967   /* The index of the specialization argument we are currently
3968      processing.  */
3969   int current_arg;
3970 
3971   /* An array whose size is the number of template parameters.  The
3972      elements are nonzero if the parameter has been used in any one
3973      of the arguments processed so far.  */
3974   int* parms;
3975 
3976   /* An array whose size is the number of template arguments.  The
3977      elements are nonzero if the argument makes use of template
3978      parameters of this level.  */
3979   int* arg_uses_template_parms;
3980 };
3981 
3982 /* Subroutine of push_template_decl used to see if each template
3983    parameter in a partial specialization is used in the explicit
3984    argument list.  If T is of the LEVEL given in DATA (which is
3985    treated as a template_parm_data*), then DATA->PARMS is marked
3986    appropriately.  */
3987 
3988 static int
mark_template_parm(tree t,void * data)3989 mark_template_parm (tree t, void* data)
3990 {
3991   int level;
3992   int idx;
3993   struct template_parm_data* tpd = (struct template_parm_data*) data;
3994 
3995   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3996     {
3997       level = TEMPLATE_PARM_LEVEL (t);
3998       idx = TEMPLATE_PARM_IDX (t);
3999     }
4000   else
4001     {
4002       level = TEMPLATE_TYPE_LEVEL (t);
4003       idx = TEMPLATE_TYPE_IDX (t);
4004     }
4005 
4006   if (level == tpd->level)
4007     {
4008       tpd->parms[idx] = 1;
4009       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4010     }
4011 
4012   /* Return zero so that for_each_template_parm will continue the
4013      traversal of the tree; we want to mark *every* template parm.  */
4014   return 0;
4015 }
4016 
4017 /* Process the partial specialization DECL.  */
4018 
4019 static tree
process_partial_specialization(tree decl)4020 process_partial_specialization (tree decl)
4021 {
4022   tree type = TREE_TYPE (decl);
4023   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4024   tree specargs = CLASSTYPE_TI_ARGS (type);
4025   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4026   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4027   tree inner_parms;
4028   tree inst;
4029   int nargs = TREE_VEC_LENGTH (inner_args);
4030   int ntparms;
4031   int  i;
4032   bool did_error_intro = false;
4033   struct template_parm_data tpd;
4034   struct template_parm_data tpd2;
4035 
4036   gcc_assert (current_template_parms);
4037 
4038   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4039   ntparms = TREE_VEC_LENGTH (inner_parms);
4040 
4041   /* We check that each of the template parameters given in the
4042      partial specialization is used in the argument list to the
4043      specialization.  For example:
4044 
4045        template <class T> struct S;
4046        template <class T> struct S<T*>;
4047 
4048      The second declaration is OK because `T*' uses the template
4049      parameter T, whereas
4050 
4051        template <class T> struct S<int>;
4052 
4053      is no good.  Even trickier is:
4054 
4055        template <class T>
4056        struct S1
4057        {
4058 	  template <class U>
4059 	  struct S2;
4060 	  template <class U>
4061 	  struct S2<T>;
4062        };
4063 
4064      The S2<T> declaration is actually invalid; it is a
4065      full-specialization.  Of course,
4066 
4067 	  template <class U>
4068 	  struct S2<T (*)(U)>;
4069 
4070      or some such would have been OK.  */
4071   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4072   tpd.parms = XALLOCAVEC (int, ntparms);
4073   memset (tpd.parms, 0, sizeof (int) * ntparms);
4074 
4075   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4076   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4077   for (i = 0; i < nargs; ++i)
4078     {
4079       tpd.current_arg = i;
4080       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4081 			      &mark_template_parm,
4082 			      &tpd,
4083 			      NULL,
4084 			      /*include_nondeduced_p=*/false);
4085     }
4086   for (i = 0; i < ntparms; ++i)
4087     if (tpd.parms[i] == 0)
4088       {
4089 	/* One of the template parms was not used in the
4090 	   specialization.  */
4091 	if (!did_error_intro)
4092 	  {
4093 	    error ("template parameters not used in partial specialization:");
4094 	    did_error_intro = true;
4095 	  }
4096 
4097 	error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4098       }
4099 
4100   if (did_error_intro)
4101     return error_mark_node;
4102 
4103   /* [temp.class.spec]
4104 
4105      The argument list of the specialization shall not be identical to
4106      the implicit argument list of the primary template.  */
4107   if (comp_template_args
4108       (inner_args,
4109        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4110 						   (maintmpl)))))
4111     error ("partial specialization %qT does not specialize any template arguments", type);
4112 
4113   /* A partial specialization that replaces multiple parameters of the
4114      primary template with a pack expansion is less specialized for those
4115      parameters.  */
4116   if (nargs < DECL_NTPARMS (maintmpl))
4117     {
4118       error ("partial specialization is not more specialized than the "
4119 	     "primary template because it replaces multiple parameters "
4120 	     "with a pack expansion");
4121       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4122       return decl;
4123     }
4124 
4125   /* [temp.class.spec]
4126 
4127      A partially specialized non-type argument expression shall not
4128      involve template parameters of the partial specialization except
4129      when the argument expression is a simple identifier.
4130 
4131      The type of a template parameter corresponding to a specialized
4132      non-type argument shall not be dependent on a parameter of the
4133      specialization.
4134 
4135      Also, we verify that pack expansions only occur at the
4136      end of the argument list.  */
4137   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4138   tpd2.parms = 0;
4139   for (i = 0; i < nargs; ++i)
4140     {
4141       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4142       tree arg = TREE_VEC_ELT (inner_args, i);
4143       tree packed_args = NULL_TREE;
4144       int j, len = 1;
4145 
4146       if (ARGUMENT_PACK_P (arg))
4147         {
4148           /* Extract the arguments from the argument pack. We'll be
4149              iterating over these in the following loop.  */
4150           packed_args = ARGUMENT_PACK_ARGS (arg);
4151           len = TREE_VEC_LENGTH (packed_args);
4152         }
4153 
4154       for (j = 0; j < len; j++)
4155         {
4156           if (packed_args)
4157             /* Get the Jth argument in the parameter pack.  */
4158             arg = TREE_VEC_ELT (packed_args, j);
4159 
4160           if (PACK_EXPANSION_P (arg))
4161             {
4162               /* Pack expansions must come at the end of the
4163                  argument list.  */
4164               if ((packed_args && j < len - 1)
4165                   || (!packed_args && i < nargs - 1))
4166                 {
4167                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4168                     error ("parameter pack argument %qE must be at the "
4169 			   "end of the template argument list", arg);
4170                   else
4171                     error ("parameter pack argument %qT must be at the "
4172 			   "end of the template argument list", arg);
4173                 }
4174             }
4175 
4176           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4177             /* We only care about the pattern.  */
4178             arg = PACK_EXPANSION_PATTERN (arg);
4179 
4180           if (/* These first two lines are the `non-type' bit.  */
4181               !TYPE_P (arg)
4182               && TREE_CODE (arg) != TEMPLATE_DECL
4183               /* This next line is the `argument expression is not just a
4184                  simple identifier' condition and also the `specialized
4185                  non-type argument' bit.  */
4186               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4187             {
4188               if ((!packed_args && tpd.arg_uses_template_parms[i])
4189                   || (packed_args && uses_template_parms (arg)))
4190                 error ("template argument %qE involves template parameter(s)",
4191                        arg);
4192               else
4193                 {
4194                   /* Look at the corresponding template parameter,
4195                      marking which template parameters its type depends
4196                      upon.  */
4197                   tree type = TREE_TYPE (parm);
4198 
4199                   if (!tpd2.parms)
4200                     {
4201                       /* We haven't yet initialized TPD2.  Do so now.  */
4202                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4203                       /* The number of parameters here is the number in the
4204                          main template, which, as checked in the assertion
4205                          above, is NARGS.  */
4206                       tpd2.parms = XALLOCAVEC (int, nargs);
4207                       tpd2.level =
4208                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4209                     }
4210 
4211                   /* Mark the template parameters.  But this time, we're
4212                      looking for the template parameters of the main
4213                      template, not in the specialization.  */
4214                   tpd2.current_arg = i;
4215                   tpd2.arg_uses_template_parms[i] = 0;
4216                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4217                   for_each_template_parm (type,
4218                                           &mark_template_parm,
4219                                           &tpd2,
4220                                           NULL,
4221 					  /*include_nondeduced_p=*/false);
4222 
4223                   if (tpd2.arg_uses_template_parms [i])
4224                     {
4225                       /* The type depended on some template parameters.
4226                          If they are fully specialized in the
4227                          specialization, that's OK.  */
4228                       int j;
4229                       int count = 0;
4230                       for (j = 0; j < nargs; ++j)
4231                         if (tpd2.parms[j] != 0
4232                             && tpd.arg_uses_template_parms [j])
4233                           ++count;
4234                       if (count != 0)
4235                         error_n (input_location, count,
4236                                  "type %qT of template argument %qE depends "
4237                                  "on a template parameter",
4238                                  "type %qT of template argument %qE depends "
4239                                  "on template parameters",
4240                                  type,
4241                                  arg);
4242                     }
4243                 }
4244             }
4245         }
4246     }
4247 
4248   /* We should only get here once.  */
4249   gcc_assert (!COMPLETE_TYPE_P (type));
4250 
4251   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4252     = tree_cons (specargs, inner_parms,
4253                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4254   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4255 
4256   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4257        inst = TREE_CHAIN (inst))
4258     {
4259       tree inst_type = TREE_VALUE (inst);
4260       if (COMPLETE_TYPE_P (inst_type)
4261 	  && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4262 	{
4263 	  tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4264 	  if (spec && TREE_TYPE (spec) == type)
4265 	    permerror (input_location,
4266 		       "partial specialization of %qT after instantiation "
4267 		       "of %qT", type, inst_type);
4268 	}
4269     }
4270 
4271   return decl;
4272 }
4273 
4274 /* Check that a template declaration's use of default arguments and
4275    parameter packs is not invalid.  Here, PARMS are the template
4276    parameters.  IS_PRIMARY is true if DECL is the thing declared by
4277    a primary template.  IS_PARTIAL is true if DECL is a partial
4278    specialization.
4279 
4280    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4281    declaration (but not a definition); 1 indicates a declaration, 2
4282    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4283    emitted for extraneous default arguments.
4284 
4285    Returns TRUE if there were no errors found, FALSE otherwise. */
4286 
4287 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)4288 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
4289                          bool is_partial, int is_friend_decl)
4290 {
4291   const char *msg;
4292   int last_level_to_check;
4293   tree parm_level;
4294   bool no_errors = true;
4295 
4296   /* [temp.param]
4297 
4298      A default template-argument shall not be specified in a
4299      function template declaration or a function template definition, nor
4300      in the template-parameter-list of the definition of a member of a
4301      class template.  */
4302 
4303   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4304     /* You can't have a function template declaration in a local
4305        scope, nor you can you define a member of a class template in a
4306        local scope.  */
4307     return true;
4308 
4309   if (TREE_CODE (decl) == TYPE_DECL
4310       && TREE_TYPE (decl)
4311       && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4312     /* A lambda doesn't have an explicit declaration; don't complain
4313        about the parms of the enclosing class.  */
4314     return true;
4315 
4316   if (current_class_type
4317       && !TYPE_BEING_DEFINED (current_class_type)
4318       && DECL_LANG_SPECIFIC (decl)
4319       && DECL_DECLARES_FUNCTION_P (decl)
4320       /* If this is either a friend defined in the scope of the class
4321 	 or a member function.  */
4322       && (DECL_FUNCTION_MEMBER_P (decl)
4323 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4324 	  : DECL_FRIEND_CONTEXT (decl)
4325 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4326 	  : false)
4327       /* And, if it was a member function, it really was defined in
4328 	 the scope of the class.  */
4329       && (!DECL_FUNCTION_MEMBER_P (decl)
4330 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
4331     /* We already checked these parameters when the template was
4332        declared, so there's no need to do it again now.  This function
4333        was defined in class scope, but we're processing it's body now
4334        that the class is complete.  */
4335     return true;
4336 
4337   /* Core issue 226 (C++0x only): the following only applies to class
4338      templates.  */
4339   if (is_primary
4340       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
4341     {
4342       /* [temp.param]
4343 
4344          If a template-parameter has a default template-argument, all
4345          subsequent template-parameters shall have a default
4346          template-argument supplied.  */
4347       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4348         {
4349           tree inner_parms = TREE_VALUE (parm_level);
4350           int ntparms = TREE_VEC_LENGTH (inner_parms);
4351           int seen_def_arg_p = 0;
4352           int i;
4353 
4354           for (i = 0; i < ntparms; ++i)
4355             {
4356               tree parm = TREE_VEC_ELT (inner_parms, i);
4357 
4358               if (parm == error_mark_node)
4359                 continue;
4360 
4361               if (TREE_PURPOSE (parm))
4362                 seen_def_arg_p = 1;
4363               else if (seen_def_arg_p
4364 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
4365                 {
4366                   error ("no default argument for %qD", TREE_VALUE (parm));
4367                   /* For better subsequent error-recovery, we indicate that
4368                      there should have been a default argument.  */
4369                   TREE_PURPOSE (parm) = error_mark_node;
4370                   no_errors = false;
4371                 }
4372 	      else if (!is_partial
4373 		       && !is_friend_decl
4374 		       /* Don't complain about an enclosing partial
4375 			  specialization.  */
4376 		       && parm_level == parms
4377 		       && TREE_CODE (decl) == TYPE_DECL
4378 		       && i < ntparms - 1
4379 		       && template_parameter_pack_p (TREE_VALUE (parm)))
4380 		{
4381 		  /* A primary class template can only have one
4382 		     parameter pack, at the end of the template
4383 		     parameter list.  */
4384 
4385 		  if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4386 		    error ("parameter pack %qE must be at the end of the"
4387 			   " template parameter list", TREE_VALUE (parm));
4388 		  else
4389 		    error ("parameter pack %qT must be at the end of the"
4390 			   " template parameter list",
4391 			   TREE_TYPE (TREE_VALUE (parm)));
4392 
4393 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
4394 		    = error_mark_node;
4395 		  no_errors = false;
4396 		}
4397             }
4398         }
4399     }
4400 
4401   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4402       || is_partial
4403       || !is_primary
4404       || is_friend_decl)
4405     /* For an ordinary class template, default template arguments are
4406        allowed at the innermost level, e.g.:
4407 	 template <class T = int>
4408 	 struct S {};
4409        but, in a partial specialization, they're not allowed even
4410        there, as we have in [temp.class.spec]:
4411 
4412 	 The template parameter list of a specialization shall not
4413 	 contain default template argument values.
4414 
4415        So, for a partial specialization, or for a function template
4416        (in C++98/C++03), we look at all of them.  */
4417     ;
4418   else
4419     /* But, for a primary class template that is not a partial
4420        specialization we look at all template parameters except the
4421        innermost ones.  */
4422     parms = TREE_CHAIN (parms);
4423 
4424   /* Figure out what error message to issue.  */
4425   if (is_friend_decl == 2)
4426     msg = G_("default template arguments may not be used in function template "
4427 	     "friend re-declaration");
4428   else if (is_friend_decl)
4429     msg = G_("default template arguments may not be used in function template "
4430 	     "friend declarations");
4431   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4432     msg = G_("default template arguments may not be used in function templates "
4433 	     "without -std=c++11 or -std=gnu++11");
4434   else if (is_partial)
4435     msg = G_("default template arguments may not be used in "
4436 	     "partial specializations");
4437   else
4438     msg = G_("default argument for template parameter for class enclosing %qD");
4439 
4440   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4441     /* If we're inside a class definition, there's no need to
4442        examine the parameters to the class itself.  On the one
4443        hand, they will be checked when the class is defined, and,
4444        on the other, default arguments are valid in things like:
4445 	 template <class T = double>
4446 	 struct S { template <class U> void f(U); };
4447        Here the default argument for `S' has no bearing on the
4448        declaration of `f'.  */
4449     last_level_to_check = template_class_depth (current_class_type) + 1;
4450   else
4451     /* Check everything.  */
4452     last_level_to_check = 0;
4453 
4454   for (parm_level = parms;
4455        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4456        parm_level = TREE_CHAIN (parm_level))
4457     {
4458       tree inner_parms = TREE_VALUE (parm_level);
4459       int i;
4460       int ntparms;
4461 
4462       ntparms = TREE_VEC_LENGTH (inner_parms);
4463       for (i = 0; i < ntparms; ++i)
4464         {
4465           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4466             continue;
4467 
4468 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4469 	    {
4470 	      if (msg)
4471 	        {
4472                   no_errors = false;
4473                   if (is_friend_decl == 2)
4474                     return no_errors;
4475 
4476 		  error (msg, decl);
4477 		  msg = 0;
4478 	        }
4479 
4480 	      /* Clear out the default argument so that we are not
4481 	         confused later.  */
4482 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4483 	    }
4484         }
4485 
4486       /* At this point, if we're still interested in issuing messages,
4487 	 they must apply to classes surrounding the object declared.  */
4488       if (msg)
4489 	msg = G_("default argument for template parameter for class "
4490 		 "enclosing %qD");
4491     }
4492 
4493   return no_errors;
4494 }
4495 
4496 /* Worker for push_template_decl_real, called via
4497    for_each_template_parm.  DATA is really an int, indicating the
4498    level of the parameters we are interested in.  If T is a template
4499    parameter of that level, return nonzero.  */
4500 
4501 static int
template_parm_this_level_p(tree t,void * data)4502 template_parm_this_level_p (tree t, void* data)
4503 {
4504   int this_level = *(int *)data;
4505   int level;
4506 
4507   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4508     level = TEMPLATE_PARM_LEVEL (t);
4509   else
4510     level = TEMPLATE_TYPE_LEVEL (t);
4511   return level == this_level;
4512 }
4513 
4514 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4515    parameters given by current_template_args, or reuses a
4516    previously existing one, if appropriate.  Returns the DECL, or an
4517    equivalent one, if it is replaced via a call to duplicate_decls.
4518 
4519    If IS_FRIEND is true, DECL is a friend declaration.  */
4520 
4521 tree
push_template_decl_real(tree decl,bool is_friend)4522 push_template_decl_real (tree decl, bool is_friend)
4523 {
4524   tree tmpl;
4525   tree args;
4526   tree info;
4527   tree ctx;
4528   bool is_primary;
4529   bool is_partial;
4530   int new_template_p = 0;
4531   /* True if the template is a member template, in the sense of
4532      [temp.mem].  */
4533   bool member_template_p = false;
4534 
4535   if (decl == error_mark_node || !current_template_parms)
4536     return error_mark_node;
4537 
4538   /* See if this is a partial specialization.  */
4539   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4540 		&& TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4541 		&& CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4542 
4543   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4544     is_friend = true;
4545 
4546   if (is_friend)
4547     /* For a friend, we want the context of the friend function, not
4548        the type of which it is a friend.  */
4549     ctx = CP_DECL_CONTEXT (decl);
4550   else if (CP_DECL_CONTEXT (decl)
4551 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4552     /* In the case of a virtual function, we want the class in which
4553        it is defined.  */
4554     ctx = CP_DECL_CONTEXT (decl);
4555   else
4556     /* Otherwise, if we're currently defining some class, the DECL
4557        is assumed to be a member of the class.  */
4558     ctx = current_scope ();
4559 
4560   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4561     ctx = NULL_TREE;
4562 
4563   if (!DECL_CONTEXT (decl))
4564     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4565 
4566   /* See if this is a primary template.  */
4567   if (is_friend && ctx)
4568     /* A friend template that specifies a class context, i.e.
4569          template <typename T> friend void A<T>::f();
4570        is not primary.  */
4571     is_primary = false;
4572   else
4573     is_primary = template_parm_scope_p ();
4574 
4575   if (is_primary)
4576     {
4577       if (DECL_CLASS_SCOPE_P (decl))
4578 	member_template_p = true;
4579       if (TREE_CODE (decl) == TYPE_DECL
4580 	  && ANON_AGGRNAME_P (DECL_NAME (decl)))
4581 	{
4582 	  error ("template class without a name");
4583 	  return error_mark_node;
4584 	}
4585       else if (TREE_CODE (decl) == FUNCTION_DECL)
4586 	{
4587 	  if (DECL_DESTRUCTOR_P (decl))
4588 	    {
4589 	      /* [temp.mem]
4590 
4591 		 A destructor shall not be a member template.  */
4592 	      error ("destructor %qD declared as member template", decl);
4593 	      return error_mark_node;
4594 	    }
4595 	  if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4596 	      && (!prototype_p (TREE_TYPE (decl))
4597 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4598 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4599 		  || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4600 		      == void_list_node)))
4601 	    {
4602 	      /* [basic.stc.dynamic.allocation]
4603 
4604 		 An allocation function can be a function
4605 		 template. ... Template allocation functions shall
4606 		 have two or more parameters.  */
4607 	      error ("invalid template declaration of %qD", decl);
4608 	      return error_mark_node;
4609 	    }
4610 	}
4611       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4612 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
4613 	/* OK */;
4614       else if (TREE_CODE (decl) == TYPE_DECL
4615 	       && TYPE_DECL_ALIAS_P (decl))
4616 	/* alias-declaration */
4617 	gcc_assert (!DECL_ARTIFICIAL (decl));
4618       else
4619 	{
4620 	  error ("template declaration of %q#D", decl);
4621 	  return error_mark_node;
4622 	}
4623     }
4624 
4625   /* Check to see that the rules regarding the use of default
4626      arguments are not being violated.  */
4627   check_default_tmpl_args (decl, current_template_parms,
4628 			   is_primary, is_partial, /*is_friend_decl=*/0);
4629 
4630   /* Ensure that there are no parameter packs in the type of this
4631      declaration that have not been expanded.  */
4632   if (TREE_CODE (decl) == FUNCTION_DECL)
4633     {
4634       /* Check each of the arguments individually to see if there are
4635          any bare parameter packs.  */
4636       tree type = TREE_TYPE (decl);
4637       tree arg = DECL_ARGUMENTS (decl);
4638       tree argtype = TYPE_ARG_TYPES (type);
4639 
4640       while (arg && argtype)
4641         {
4642           if (!FUNCTION_PARAMETER_PACK_P (arg)
4643               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4644             {
4645             /* This is a PARM_DECL that contains unexpanded parameter
4646                packs. We have already complained about this in the
4647                check_for_bare_parameter_packs call, so just replace
4648                these types with ERROR_MARK_NODE.  */
4649               TREE_TYPE (arg) = error_mark_node;
4650               TREE_VALUE (argtype) = error_mark_node;
4651             }
4652 
4653           arg = DECL_CHAIN (arg);
4654           argtype = TREE_CHAIN (argtype);
4655         }
4656 
4657       /* Check for bare parameter packs in the return type and the
4658          exception specifiers.  */
4659       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4660 	/* Errors were already issued, set return type to int
4661 	   as the frontend doesn't expect error_mark_node as
4662 	   the return type.  */
4663 	TREE_TYPE (type) = integer_type_node;
4664       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4665 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4666     }
4667   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
4668 					    && TYPE_DECL_ALIAS_P (decl))
4669 					   ? DECL_ORIGINAL_TYPE (decl)
4670 					   : TREE_TYPE (decl)))
4671     {
4672       TREE_TYPE (decl) = error_mark_node;
4673       return error_mark_node;
4674     }
4675 
4676   if (is_partial)
4677     return process_partial_specialization (decl);
4678 
4679   args = current_template_args ();
4680 
4681   if (!ctx
4682       || TREE_CODE (ctx) == FUNCTION_DECL
4683       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4684       || (TREE_CODE (decl) == TYPE_DECL
4685 	  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4686       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4687     {
4688       if (DECL_LANG_SPECIFIC (decl)
4689 	  && DECL_TEMPLATE_INFO (decl)
4690 	  && DECL_TI_TEMPLATE (decl))
4691 	tmpl = DECL_TI_TEMPLATE (decl);
4692       /* If DECL is a TYPE_DECL for a class-template, then there won't
4693 	 be DECL_LANG_SPECIFIC.  The information equivalent to
4694 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4695       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4696 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4697 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4698 	{
4699 	  /* Since a template declaration already existed for this
4700 	     class-type, we must be redeclaring it here.  Make sure
4701 	     that the redeclaration is valid.  */
4702 	  redeclare_class_template (TREE_TYPE (decl),
4703 				    current_template_parms);
4704 	  /* We don't need to create a new TEMPLATE_DECL; just use the
4705 	     one we already had.  */
4706 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4707 	}
4708       else
4709 	{
4710 	  tmpl = build_template_decl (decl, current_template_parms,
4711 				      member_template_p);
4712 	  new_template_p = 1;
4713 
4714 	  if (DECL_LANG_SPECIFIC (decl)
4715 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
4716 	    {
4717 	      /* A specialization of a member template of a template
4718 		 class.  */
4719 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4720 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4721 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4722 	    }
4723 	}
4724     }
4725   else
4726     {
4727       tree a, t, current, parms;
4728       int i;
4729       tree tinfo = get_template_info (decl);
4730 
4731       if (!tinfo)
4732 	{
4733 	  error ("template definition of non-template %q#D", decl);
4734 	  return error_mark_node;
4735 	}
4736 
4737       tmpl = TI_TEMPLATE (tinfo);
4738 
4739       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4740 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4741 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
4742 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
4743 	{
4744 	  tree new_tmpl;
4745 
4746 	  /* The declaration is a specialization of a member
4747 	     template, declared outside the class.  Therefore, the
4748 	     innermost template arguments will be NULL, so we
4749 	     replace them with the arguments determined by the
4750 	     earlier call to check_explicit_specialization.  */
4751 	  args = DECL_TI_ARGS (decl);
4752 
4753 	  new_tmpl
4754 	    = build_template_decl (decl, current_template_parms,
4755 				   member_template_p);
4756 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4757 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4758 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
4759 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4760 	  DECL_TEMPLATE_INFO (new_tmpl)
4761 	    = build_template_info (tmpl, args);
4762 
4763 	  register_specialization (new_tmpl,
4764 				   most_general_template (tmpl),
4765 				   args,
4766 				   is_friend, 0);
4767 	  return decl;
4768 	}
4769 
4770       /* Make sure the template headers we got make sense.  */
4771 
4772       parms = DECL_TEMPLATE_PARMS (tmpl);
4773       i = TMPL_PARMS_DEPTH (parms);
4774       if (TMPL_ARGS_DEPTH (args) != i)
4775 	{
4776 	  error ("expected %d levels of template parms for %q#D, got %d",
4777 		 i, decl, TMPL_ARGS_DEPTH (args));
4778 	}
4779       else
4780 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4781 	  {
4782 	    a = TMPL_ARGS_LEVEL (args, i);
4783 	    t = INNERMOST_TEMPLATE_PARMS (parms);
4784 
4785 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4786 	      {
4787 		if (current == decl)
4788 		  error ("got %d template parameters for %q#D",
4789 			 TREE_VEC_LENGTH (a), decl);
4790 		else
4791 		  error ("got %d template parameters for %q#T",
4792 			 TREE_VEC_LENGTH (a), current);
4793 		error ("  but %d required", TREE_VEC_LENGTH (t));
4794 		/* Avoid crash in import_export_decl.  */
4795 		DECL_INTERFACE_KNOWN (decl) = 1;
4796 		return error_mark_node;
4797 	      }
4798 
4799 	    if (current == decl)
4800 	      current = ctx;
4801 	    else if (current == NULL_TREE)
4802 	      /* Can happen in erroneous input.  */
4803 	      break;
4804 	    else
4805 	      current = (TYPE_P (current)
4806 			 ? TYPE_CONTEXT (current)
4807 			 : DECL_CONTEXT (current));
4808 	  }
4809 
4810       /* Check that the parms are used in the appropriate qualifying scopes
4811 	 in the declarator.  */
4812       if (!comp_template_args
4813 	  (TI_ARGS (tinfo),
4814 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4815 	{
4816 	  error ("\
4817 template arguments to %qD do not match original template %qD",
4818 		 decl, DECL_TEMPLATE_RESULT (tmpl));
4819 	  if (!uses_template_parms (TI_ARGS (tinfo)))
4820 	    inform (input_location, "use template<> for an explicit specialization");
4821 	  /* Avoid crash in import_export_decl.  */
4822 	  DECL_INTERFACE_KNOWN (decl) = 1;
4823 	  return error_mark_node;
4824 	}
4825     }
4826 
4827   DECL_TEMPLATE_RESULT (tmpl) = decl;
4828   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4829 
4830   /* Push template declarations for global functions and types.  Note
4831      that we do not try to push a global template friend declared in a
4832      template class; such a thing may well depend on the template
4833      parameters of the class.  */
4834   if (new_template_p && !ctx
4835       && !(is_friend && template_class_depth (current_class_type) > 0))
4836     {
4837       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4838       if (tmpl == error_mark_node)
4839 	return error_mark_node;
4840 
4841       /* Hide template friend classes that haven't been declared yet.  */
4842       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4843 	{
4844 	  DECL_ANTICIPATED (tmpl) = 1;
4845 	  DECL_FRIEND_P (tmpl) = 1;
4846 	}
4847     }
4848 
4849   if (is_primary)
4850     {
4851       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4852       int i;
4853 
4854       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4855       if (DECL_CONV_FN_P (tmpl))
4856 	{
4857 	  int depth = TMPL_PARMS_DEPTH (parms);
4858 
4859 	  /* It is a conversion operator. See if the type converted to
4860 	     depends on innermost template operands.  */
4861 
4862 	  if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4863 					 depth))
4864 	    DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4865 	}
4866 
4867       /* Give template template parms a DECL_CONTEXT of the template
4868 	 for which they are a parameter.  */
4869       parms = INNERMOST_TEMPLATE_PARMS (parms);
4870       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4871 	{
4872 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4873 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
4874 	    DECL_CONTEXT (parm) = tmpl;
4875 	}
4876     }
4877 
4878   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4879      back to its most general template.  If TMPL is a specialization,
4880      ARGS may only have the innermost set of arguments.  Add the missing
4881      argument levels if necessary.  */
4882   if (DECL_TEMPLATE_INFO (tmpl))
4883     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4884 
4885   info = build_template_info (tmpl, args);
4886 
4887   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4888     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4889   else
4890     {
4891       if (is_primary && !DECL_LANG_SPECIFIC (decl))
4892 	retrofit_lang_decl (decl);
4893       if (DECL_LANG_SPECIFIC (decl))
4894 	DECL_TEMPLATE_INFO (decl) = info;
4895     }
4896 
4897   return DECL_TEMPLATE_RESULT (tmpl);
4898 }
4899 
4900 tree
push_template_decl(tree decl)4901 push_template_decl (tree decl)
4902 {
4903   return push_template_decl_real (decl, false);
4904 }
4905 
4906 /* FN is an inheriting constructor that inherits from the constructor
4907    template INHERITED; turn FN into a constructor template with a matching
4908    template header.  */
4909 
4910 tree
add_inherited_template_parms(tree fn,tree inherited)4911 add_inherited_template_parms (tree fn, tree inherited)
4912 {
4913   tree inner_parms
4914     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
4915   inner_parms = copy_node (inner_parms);
4916   tree parms
4917     = tree_cons (size_int (processing_template_decl + 1),
4918 		 inner_parms, current_template_parms);
4919   tree tmpl = build_template_decl (fn, parms, /*member*/true);
4920   tree args = template_parms_to_args (parms);
4921   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
4922   TREE_TYPE (tmpl) = TREE_TYPE (fn);
4923   DECL_TEMPLATE_RESULT (tmpl) = fn;
4924   DECL_ARTIFICIAL (tmpl) = true;
4925   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4926   return tmpl;
4927 }
4928 
4929 /* Called when a class template TYPE is redeclared with the indicated
4930    template PARMS, e.g.:
4931 
4932      template <class T> struct S;
4933      template <class T> struct S {};  */
4934 
4935 bool
redeclare_class_template(tree type,tree parms)4936 redeclare_class_template (tree type, tree parms)
4937 {
4938   tree tmpl;
4939   tree tmpl_parms;
4940   int i;
4941 
4942   if (!TYPE_TEMPLATE_INFO (type))
4943     {
4944       error ("%qT is not a template type", type);
4945       return false;
4946     }
4947 
4948   tmpl = TYPE_TI_TEMPLATE (type);
4949   if (!PRIMARY_TEMPLATE_P (tmpl))
4950     /* The type is nested in some template class.  Nothing to worry
4951        about here; there are no new template parameters for the nested
4952        type.  */
4953     return true;
4954 
4955   if (!parms)
4956     {
4957       error ("template specifiers not specified in declaration of %qD",
4958 	     tmpl);
4959       return false;
4960     }
4961 
4962   parms = INNERMOST_TEMPLATE_PARMS (parms);
4963   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4964 
4965   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4966     {
4967       error_n (input_location, TREE_VEC_LENGTH (parms),
4968                "redeclared with %d template parameter",
4969                "redeclared with %d template parameters",
4970                TREE_VEC_LENGTH (parms));
4971       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4972                 "previous declaration %q+D used %d template parameter",
4973                 "previous declaration %q+D used %d template parameters",
4974                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4975       return false;
4976     }
4977 
4978   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4979     {
4980       tree tmpl_parm;
4981       tree parm;
4982       tree tmpl_default;
4983       tree parm_default;
4984 
4985       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4986           || TREE_VEC_ELT (parms, i) == error_mark_node)
4987         continue;
4988 
4989       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4990       if (tmpl_parm == error_mark_node)
4991 	return false;
4992 
4993       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4994       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4995       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4996 
4997       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4998 	 TEMPLATE_DECL.  */
4999       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5000 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
5001 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5002 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
5003 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5004 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5005 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
5006 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5007 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5008 	{
5009 	  error ("template parameter %q+#D", tmpl_parm);
5010 	  error ("redeclared here as %q#D", parm);
5011 	  return false;
5012 	}
5013 
5014       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5015 	{
5016 	  /* We have in [temp.param]:
5017 
5018 	     A template-parameter may not be given default arguments
5019 	     by two different declarations in the same scope.  */
5020 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
5021 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
5022 		  "original definition appeared here");
5023 	  return false;
5024 	}
5025 
5026       if (parm_default != NULL_TREE)
5027 	/* Update the previous template parameters (which are the ones
5028 	   that will really count) with the new default value.  */
5029 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5030       else if (tmpl_default != NULL_TREE)
5031 	/* Update the new parameters, too; they'll be used as the
5032 	   parameters for any members.  */
5033 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5034     }
5035 
5036     return true;
5037 }
5038 
5039 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5040    (possibly simplified) expression.  */
5041 
5042 tree
fold_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)5043 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5044 {
5045   if (expr == NULL_TREE)
5046     return NULL_TREE;
5047 
5048   /* If we're in a template, but EXPR isn't value dependent, simplify
5049      it.  We're supposed to treat:
5050 
5051        template <typename T> void f(T[1 + 1]);
5052        template <typename T> void f(T[2]);
5053 
5054      as two declarations of the same function, for example.  */
5055   if (processing_template_decl
5056       && !type_dependent_expression_p (expr)
5057       && potential_constant_expression (expr)
5058       && !value_dependent_expression_p (expr))
5059     {
5060       HOST_WIDE_INT saved_processing_template_decl;
5061 
5062       saved_processing_template_decl = processing_template_decl;
5063       processing_template_decl = 0;
5064       expr = tsubst_copy_and_build (expr,
5065 				    /*args=*/NULL_TREE,
5066 				    complain,
5067 				    /*in_decl=*/NULL_TREE,
5068 				    /*function_p=*/false,
5069 				    /*integral_constant_expression_p=*/true);
5070       processing_template_decl = saved_processing_template_decl;
5071     }
5072   return expr;
5073 }
5074 
5075 tree
fold_non_dependent_expr(tree expr)5076 fold_non_dependent_expr (tree expr)
5077 {
5078   return fold_non_dependent_expr_sfinae (expr, tf_error);
5079 }
5080 
5081 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
5082    template declaration, or a TYPE_DECL for an alias declaration.  */
5083 
5084 bool
alias_type_or_template_p(tree t)5085 alias_type_or_template_p (tree t)
5086 {
5087   if (t == NULL_TREE)
5088     return false;
5089   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
5090 	  || (TYPE_P (t)
5091 	      && TYPE_NAME (t)
5092 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
5093 	  || DECL_ALIAS_TEMPLATE_P (t));
5094 }
5095 
5096 /* Return TRUE iff is a specialization of an alias template.  */
5097 
5098 bool
alias_template_specialization_p(const_tree t)5099 alias_template_specialization_p (const_tree t)
5100 {
5101   if (t == NULL_TREE)
5102     return false;
5103 
5104   return (TYPE_P (t)
5105 	  && TYPE_TEMPLATE_INFO (t)
5106 	  && PRIMARY_TEMPLATE_P (TYPE_TI_TEMPLATE (t))
5107 	  && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (t)));
5108 }
5109 
5110 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5111    must be a function or a pointer-to-function type, as specified
5112    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5113    and check that the resulting function has external linkage.  */
5114 
5115 static tree
convert_nontype_argument_function(tree type,tree expr)5116 convert_nontype_argument_function (tree type, tree expr)
5117 {
5118   tree fns = expr;
5119   tree fn, fn_no_ptr;
5120   linkage_kind linkage;
5121 
5122   fn = instantiate_type (type, fns, tf_none);
5123   if (fn == error_mark_node)
5124     return error_mark_node;
5125 
5126   fn_no_ptr = fn;
5127   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5128     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5129   if (BASELINK_P (fn_no_ptr))
5130     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5131 
5132   /* [temp.arg.nontype]/1
5133 
5134      A template-argument for a non-type, non-template template-parameter
5135      shall be one of:
5136      [...]
5137      -- the address of an object or function with external [C++11: or
5138         internal] linkage.  */
5139 
5140   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
5141     {
5142       error ("%qE is not a valid template argument for type %qT", expr, type);
5143       if (TREE_CODE (type) == POINTER_TYPE)
5144 	error ("it must be the address of a function with external linkage");
5145       else
5146 	error ("it must be the name of a function with external linkage");
5147       return NULL_TREE;
5148     }
5149 
5150   linkage = decl_linkage (fn_no_ptr);
5151   if (cxx_dialect >= cxx0x ? linkage == lk_none : linkage != lk_external)
5152     {
5153       if (cxx_dialect >= cxx0x)
5154 	error ("%qE is not a valid template argument for type %qT "
5155 	       "because %qD has no linkage",
5156 	       expr, type, fn_no_ptr);
5157       else
5158 	error ("%qE is not a valid template argument for type %qT "
5159 	       "because %qD does not have external linkage",
5160 	       expr, type, fn_no_ptr);
5161       return NULL_TREE;
5162     }
5163 
5164   return fn;
5165 }
5166 
5167 /* Subroutine of convert_nontype_argument.
5168    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5169    Emit an error otherwise.  */
5170 
5171 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)5172 check_valid_ptrmem_cst_expr (tree type, tree expr,
5173 			     tsubst_flags_t complain)
5174 {
5175   STRIP_NOPS (expr);
5176   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5177     return true;
5178   if (cxx_dialect >= cxx0x && null_member_pointer_value_p (expr))
5179     return true;
5180   if (complain & tf_error)
5181     {
5182       error ("%qE is not a valid template argument for type %qT",
5183 	     expr, type);
5184       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5185     }
5186   return false;
5187 }
5188 
5189 /* Returns TRUE iff the address of OP is value-dependent.
5190 
5191    14.6.2.4 [temp.dep.temp]:
5192    A non-integral non-type template-argument is dependent if its type is
5193    dependent or it has either of the following forms
5194      qualified-id
5195      & qualified-id
5196    and contains a nested-name-specifier which specifies a class-name that
5197    names a dependent type.
5198 
5199    We generalize this to just say that the address of a member of a
5200    dependent class is value-dependent; the above doesn't cover the
5201    address of a static data member named with an unqualified-id.  */
5202 
5203 static bool
has_value_dependent_address(tree op)5204 has_value_dependent_address (tree op)
5205 {
5206   /* We could use get_inner_reference here, but there's no need;
5207      this is only relevant for template non-type arguments, which
5208      can only be expressed as &id-expression.  */
5209   if (DECL_P (op))
5210     {
5211       tree ctx = CP_DECL_CONTEXT (op);
5212       if (TYPE_P (ctx) && dependent_type_p (ctx))
5213 	return true;
5214     }
5215 
5216   return false;
5217 }
5218 
5219 /* The next set of functions are used for providing helpful explanatory
5220    diagnostics for failed overload resolution.  Their messages should be
5221    indented by two spaces for consistency with the messages in
5222    call.c  */
5223 
5224 static int
unify_success(bool)5225 unify_success (bool /*explain_p*/)
5226 {
5227   return 0;
5228 }
5229 
5230 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)5231 unify_parameter_deduction_failure (bool explain_p, tree parm)
5232 {
5233   if (explain_p)
5234     inform (input_location,
5235 	    "  couldn't deduce template parameter %qD", parm);
5236   return 1;
5237 }
5238 
5239 static int
unify_invalid(bool)5240 unify_invalid (bool /*explain_p*/)
5241 {
5242   return 1;
5243 }
5244 
5245 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)5246 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
5247 {
5248   if (explain_p)
5249     inform (input_location,
5250 	    "  types %qT and %qT have incompatible cv-qualifiers",
5251 	    parm, arg);
5252   return 1;
5253 }
5254 
5255 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)5256 unify_type_mismatch (bool explain_p, tree parm, tree arg)
5257 {
5258   if (explain_p)
5259     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
5260   return 1;
5261 }
5262 
5263 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)5264 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
5265 {
5266   if (explain_p)
5267     inform (input_location,
5268 	    "  template parameter %qD is not a parameter pack, but "
5269 	    "argument %qD is",
5270 	    parm, arg);
5271   return 1;
5272 }
5273 
5274 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)5275 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
5276 {
5277   if (explain_p)
5278     inform (input_location,
5279 	    "  template argument %qE does not match "
5280 	    "pointer-to-member constant %qE",
5281 	    arg, parm);
5282   return 1;
5283 }
5284 
5285 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)5286 unify_expression_unequal (bool explain_p, tree parm, tree arg)
5287 {
5288   if (explain_p)
5289     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
5290   return 1;
5291 }
5292 
5293 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)5294 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
5295 {
5296   if (explain_p)
5297     inform (input_location,
5298 	    "  inconsistent parameter pack deduction with %qT and %qT",
5299 	    old_arg, new_arg);
5300   return 1;
5301 }
5302 
5303 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)5304 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
5305 {
5306   if (explain_p)
5307     {
5308       if (TYPE_P (parm))
5309 	inform (input_location,
5310 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
5311 		parm, first, second);
5312       else
5313 	inform (input_location,
5314 		"  deduced conflicting values for non-type parameter "
5315 		"%qE (%qE and %qE)", parm, first, second);
5316     }
5317   return 1;
5318 }
5319 
5320 static int
unify_vla_arg(bool explain_p,tree arg)5321 unify_vla_arg (bool explain_p, tree arg)
5322 {
5323   if (explain_p)
5324     inform (input_location,
5325 	    "  variable-sized array type %qT is not "
5326 	    "a valid template argument",
5327 	    arg);
5328   return 1;
5329 }
5330 
5331 static int
unify_method_type_error(bool explain_p,tree arg)5332 unify_method_type_error (bool explain_p, tree arg)
5333 {
5334   if (explain_p)
5335     inform (input_location,
5336 	    "  member function type %qT is not a valid template argument",
5337 	    arg);
5338   return 1;
5339 }
5340 
5341 static int
unify_arity(bool explain_p,int have,int wanted)5342 unify_arity (bool explain_p, int have, int wanted)
5343 {
5344   if (explain_p)
5345     inform_n (input_location, wanted,
5346 	      "  candidate expects %d argument, %d provided",
5347 	      "  candidate expects %d arguments, %d provided",
5348 	      wanted, have);
5349   return 1;
5350 }
5351 
5352 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)5353 unify_too_many_arguments (bool explain_p, int have, int wanted)
5354 {
5355   return unify_arity (explain_p, have, wanted);
5356 }
5357 
5358 static int
unify_too_few_arguments(bool explain_p,int have,int wanted)5359 unify_too_few_arguments (bool explain_p, int have, int wanted)
5360 {
5361   return unify_arity (explain_p, have, wanted);
5362 }
5363 
5364 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)5365 unify_arg_conversion (bool explain_p, tree to_type,
5366 		      tree from_type, tree arg)
5367 {
5368   if (explain_p)
5369     inform (input_location, "  cannot convert %qE (type %qT) to type %qT",
5370 	    arg, from_type, to_type);
5371   return 1;
5372 }
5373 
5374 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)5375 unify_no_common_base (bool explain_p, enum template_base_result r,
5376 		      tree parm, tree arg)
5377 {
5378   if (explain_p)
5379     switch (r)
5380       {
5381       case tbr_ambiguous_baseclass:
5382 	inform (input_location, "  %qT is an ambiguous base class of %qT",
5383 		arg, parm);
5384 	break;
5385       default:
5386 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
5387 	break;
5388       }
5389   return 1;
5390 }
5391 
5392 static int
unify_inconsistent_template_template_parameters(bool explain_p)5393 unify_inconsistent_template_template_parameters (bool explain_p)
5394 {
5395   if (explain_p)
5396     inform (input_location,
5397 	    "  template parameters of a template template argument are "
5398 	    "inconsistent with other deduced template arguments");
5399   return 1;
5400 }
5401 
5402 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)5403 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
5404 {
5405   if (explain_p)
5406     inform (input_location,
5407 	    "  can't deduce a template for %qT from non-template type %qT",
5408 	    parm, arg);
5409   return 1;
5410 }
5411 
5412 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)5413 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
5414 {
5415   if (explain_p)
5416     inform (input_location,
5417 	    "  template argument %qE does not match %qD", arg, parm);
5418   return 1;
5419 }
5420 
5421 static int
unify_overload_resolution_failure(bool explain_p,tree arg)5422 unify_overload_resolution_failure (bool explain_p, tree arg)
5423 {
5424   if (explain_p)
5425     inform (input_location,
5426 	    "  could not resolve address from overloaded function %qE",
5427 	    arg);
5428   return 1;
5429 }
5430 
5431 /* Attempt to convert the non-type template parameter EXPR to the
5432    indicated TYPE.  If the conversion is successful, return the
5433    converted value.  If the conversion is unsuccessful, return
5434    NULL_TREE if we issued an error message, or error_mark_node if we
5435    did not.  We issue error messages for out-and-out bad template
5436    parameters, but not simply because the conversion failed, since we
5437    might be just trying to do argument deduction.  Both TYPE and EXPR
5438    must be non-dependent.
5439 
5440    The conversion follows the special rules described in
5441    [temp.arg.nontype], and it is much more strict than an implicit
5442    conversion.
5443 
5444    This function is called twice for each template argument (see
5445    lookup_template_class for a more accurate description of this
5446    problem). This means that we need to handle expressions which
5447    are not valid in a C++ source, but can be created from the
5448    first call (for instance, casts to perform conversions). These
5449    hacks can go away after we fix the double coercion problem.  */
5450 
5451 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)5452 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5453 {
5454   tree expr_type;
5455 
5456   /* Detect immediately string literals as invalid non-type argument.
5457      This special-case is not needed for correctness (we would easily
5458      catch this later), but only to provide better diagnostic for this
5459      common user mistake. As suggested by DR 100, we do not mention
5460      linkage issues in the diagnostic as this is not the point.  */
5461   /* FIXME we're making this OK.  */
5462   if (TREE_CODE (expr) == STRING_CST)
5463     {
5464       if (complain & tf_error)
5465 	error ("%qE is not a valid template argument for type %qT "
5466 	       "because string literals can never be used in this context",
5467 	       expr, type);
5468       return NULL_TREE;
5469     }
5470 
5471   /* Add the ADDR_EXPR now for the benefit of
5472      value_dependent_expression_p.  */
5473   if (TYPE_PTROBV_P (type)
5474       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
5475     {
5476       expr = decay_conversion (expr, complain);
5477       if (expr == error_mark_node)
5478 	return error_mark_node;
5479     }
5480 
5481   /* If we are in a template, EXPR may be non-dependent, but still
5482      have a syntactic, rather than semantic, form.  For example, EXPR
5483      might be a SCOPE_REF, rather than the VAR_DECL to which the
5484      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5485      so that access checking can be performed when the template is
5486      instantiated -- but here we need the resolved form so that we can
5487      convert the argument.  */
5488   if (TYPE_REF_OBJ_P (type)
5489       && has_value_dependent_address (expr))
5490     /* If we want the address and it's value-dependent, don't fold.  */;
5491   else if (!type_unknown_p (expr))
5492     expr = fold_non_dependent_expr_sfinae (expr, complain);
5493   if (error_operand_p (expr))
5494     return error_mark_node;
5495   expr_type = TREE_TYPE (expr);
5496   if (TREE_CODE (type) == REFERENCE_TYPE)
5497     expr = mark_lvalue_use (expr);
5498   else
5499     expr = mark_rvalue_use (expr);
5500 
5501   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
5502      to a non-type argument of "nullptr".  */
5503   if (expr == nullptr_node && TYPE_PTR_OR_PTRMEM_P (type))
5504     expr = convert (type, expr);
5505 
5506   /* In C++11, integral or enumeration non-type template arguments can be
5507      arbitrary constant expressions.  Pointer and pointer to
5508      member arguments can be general constant expressions that evaluate
5509      to a null value, but otherwise still need to be of a specific form.  */
5510   if (cxx_dialect >= cxx0x)
5511     {
5512       if (TREE_CODE (expr) == PTRMEM_CST)
5513 	/* A PTRMEM_CST is already constant, and a valid template
5514 	   argument for a parameter of pointer to member type, we just want
5515 	   to leave it in that form rather than lower it to a
5516 	   CONSTRUCTOR.  */;
5517       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5518 	expr = maybe_constant_value (expr);
5519       else if (TYPE_PTR_OR_PTRMEM_P (type))
5520 	{
5521 	  tree folded = maybe_constant_value (expr);
5522 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
5523 	      : null_member_pointer_value_p (folded))
5524 	    expr = folded;
5525 	}
5526     }
5527 
5528   /* HACK: Due to double coercion, we can get a
5529      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5530      which is the tree that we built on the first call (see
5531      below when coercing to reference to object or to reference to
5532      function). We just strip everything and get to the arg.
5533      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5534      for examples.  */
5535   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5536     {
5537       tree probe_type, probe = expr;
5538       if (REFERENCE_REF_P (probe))
5539 	probe = TREE_OPERAND (probe, 0);
5540       probe_type = TREE_TYPE (probe);
5541       if (TREE_CODE (probe) == NOP_EXPR)
5542 	{
5543 	  /* ??? Maybe we could use convert_from_reference here, but we
5544 	     would need to relax its constraints because the NOP_EXPR
5545 	     could actually change the type to something more cv-qualified,
5546 	     and this is not folded by convert_from_reference.  */
5547 	  tree addr = TREE_OPERAND (probe, 0);
5548 	  if (TREE_CODE (probe_type) == REFERENCE_TYPE
5549 	      && TREE_CODE (addr) == ADDR_EXPR
5550 	      && TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE
5551 	      && (same_type_ignoring_top_level_qualifiers_p
5552 		  (TREE_TYPE (probe_type),
5553 		   TREE_TYPE (TREE_TYPE (addr)))))
5554 	    {
5555 	      expr = TREE_OPERAND (addr, 0);
5556 	      expr_type = TREE_TYPE (expr);
5557 	    }
5558 	}
5559     }
5560 
5561   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5562      parameter is a pointer to object, through decay and
5563      qualification conversion. Let's strip everything.  */
5564   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
5565     {
5566       STRIP_NOPS (expr);
5567       gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5568       gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5569       /* Skip the ADDR_EXPR only if it is part of the decay for
5570 	 an array. Otherwise, it is part of the original argument
5571 	 in the source code.  */
5572       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5573 	expr = TREE_OPERAND (expr, 0);
5574       expr_type = TREE_TYPE (expr);
5575     }
5576 
5577   /* [temp.arg.nontype]/5, bullet 1
5578 
5579      For a non-type template-parameter of integral or enumeration type,
5580      integral promotions (_conv.prom_) and integral conversions
5581      (_conv.integral_) are applied.  */
5582   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5583     {
5584       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5585       t = maybe_constant_value (t);
5586       if (t != error_mark_node)
5587 	expr = t;
5588 
5589       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5590 	return error_mark_node;
5591 
5592       /* Notice that there are constant expressions like '4 % 0' which
5593 	 do not fold into integer constants.  */
5594       if (TREE_CODE (expr) != INTEGER_CST)
5595 	{
5596 	  if (complain & tf_error)
5597 	    {
5598 	      int errs = errorcount, warns = warningcount;
5599 	      if (processing_template_decl
5600 		  && !require_potential_constant_expression (expr))
5601 		return NULL_TREE;
5602 	      expr = cxx_constant_value (expr);
5603 	      if (errorcount > errs || warningcount > warns)
5604 		inform (EXPR_LOC_OR_HERE (expr),
5605 			"in template argument for type %qT ", type);
5606 	      if (expr == error_mark_node)
5607 		return NULL_TREE;
5608 	      /* else cxx_constant_value complained but gave us
5609 		 a real constant, so go ahead.  */
5610 	      gcc_assert (TREE_CODE (expr) == INTEGER_CST);
5611 	    }
5612 	  else
5613 	    return NULL_TREE;
5614 	}
5615     }
5616   /* [temp.arg.nontype]/5, bullet 2
5617 
5618      For a non-type template-parameter of type pointer to object,
5619      qualification conversions (_conv.qual_) and the array-to-pointer
5620      conversion (_conv.array_) are applied.  */
5621   else if (TYPE_PTROBV_P (type))
5622     {
5623       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5624 
5625 	 A template-argument for a non-type, non-template template-parameter
5626 	 shall be one of: [...]
5627 
5628 	 -- the name of a non-type template-parameter;
5629 	 -- the address of an object or function with external linkage, [...]
5630 	    expressed as "& id-expression" where the & is optional if the name
5631 	    refers to a function or array, or if the corresponding
5632 	    template-parameter is a reference.
5633 
5634 	Here, we do not care about functions, as they are invalid anyway
5635 	for a parameter of type pointer-to-object.  */
5636 
5637       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5638 	/* Non-type template parameters are OK.  */
5639 	;
5640       else if (cxx_dialect >= cxx0x && integer_zerop (expr))
5641 	/* Null pointer values are OK in C++11.  */;
5642       else if (TREE_CODE (expr) != ADDR_EXPR
5643 	       && TREE_CODE (expr_type) != ARRAY_TYPE)
5644 	{
5645 	  if (TREE_CODE (expr) == VAR_DECL)
5646 	    {
5647 	      error ("%qD is not a valid template argument "
5648 		     "because %qD is a variable, not the address of "
5649 		     "a variable",
5650 		     expr, expr);
5651 	      return NULL_TREE;
5652 	    }
5653 	  /* Other values, like integer constants, might be valid
5654 	     non-type arguments of some other type.  */
5655 	  return error_mark_node;
5656 	}
5657       else
5658 	{
5659 	  tree decl;
5660 
5661 	  decl = ((TREE_CODE (expr) == ADDR_EXPR)
5662 		  ? TREE_OPERAND (expr, 0) : expr);
5663 	  if (TREE_CODE (decl) != VAR_DECL)
5664 	    {
5665 	      error ("%qE is not a valid template argument of type %qT "
5666 		     "because %qE is not a variable",
5667 		     expr, type, decl);
5668 	      return NULL_TREE;
5669 	    }
5670 	  else if (cxx_dialect < cxx0x && !DECL_EXTERNAL_LINKAGE_P (decl))
5671 	    {
5672 	      error ("%qE is not a valid template argument of type %qT "
5673 		     "because %qD does not have external linkage",
5674 		     expr, type, decl);
5675 	      return NULL_TREE;
5676 	    }
5677 	  else if (cxx_dialect >= cxx0x && decl_linkage (decl) == lk_none)
5678 	    {
5679 	      error ("%qE is not a valid template argument of type %qT "
5680 		     "because %qD has no linkage",
5681 		     expr, type, decl);
5682 	      return NULL_TREE;
5683 	    }
5684 	}
5685 
5686       expr = decay_conversion (expr, complain);
5687       if (expr == error_mark_node)
5688 	return error_mark_node;
5689 
5690       expr = perform_qualification_conversions (type, expr);
5691       if (expr == error_mark_node)
5692 	return error_mark_node;
5693     }
5694   /* [temp.arg.nontype]/5, bullet 3
5695 
5696      For a non-type template-parameter of type reference to object, no
5697      conversions apply. The type referred to by the reference may be more
5698      cv-qualified than the (otherwise identical) type of the
5699      template-argument. The template-parameter is bound directly to the
5700      template-argument, which must be an lvalue.  */
5701   else if (TYPE_REF_OBJ_P (type))
5702     {
5703       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5704 						      expr_type))
5705 	return error_mark_node;
5706 
5707       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5708 	{
5709 	  error ("%qE is not a valid template argument for type %qT "
5710 		 "because of conflicts in cv-qualification", expr, type);
5711 	  return NULL_TREE;
5712 	}
5713 
5714       if (!real_lvalue_p (expr))
5715 	{
5716 	  error ("%qE is not a valid template argument for type %qT "
5717 		 "because it is not an lvalue", expr, type);
5718 	  return NULL_TREE;
5719 	}
5720 
5721       /* [temp.arg.nontype]/1
5722 
5723 	 A template-argument for a non-type, non-template template-parameter
5724 	 shall be one of: [...]
5725 
5726 	 -- the address of an object or function with external linkage.  */
5727       if (TREE_CODE (expr) == INDIRECT_REF
5728 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5729 	{
5730 	  expr = TREE_OPERAND (expr, 0);
5731 	  if (DECL_P (expr))
5732 	    {
5733 	      error ("%q#D is not a valid template argument for type %qT "
5734 		     "because a reference variable does not have a constant "
5735 		     "address", expr, type);
5736 	      return NULL_TREE;
5737 	    }
5738 	}
5739 
5740       if (!DECL_P (expr))
5741 	{
5742 	  error ("%qE is not a valid template argument for type %qT "
5743 		 "because it is not an object with external linkage",
5744 		 expr, type);
5745 	  return NULL_TREE;
5746 	}
5747 
5748       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5749 	{
5750 	  error ("%qE is not a valid template argument for type %qT "
5751 		 "because object %qD has not external linkage",
5752 		 expr, type, expr);
5753 	  return NULL_TREE;
5754 	}
5755 
5756       expr = build_nop (type, build_address (expr));
5757     }
5758   /* [temp.arg.nontype]/5, bullet 4
5759 
5760      For a non-type template-parameter of type pointer to function, only
5761      the function-to-pointer conversion (_conv.func_) is applied. If the
5762      template-argument represents a set of overloaded functions (or a
5763      pointer to such), the matching function is selected from the set
5764      (_over.over_).  */
5765   else if (TYPE_PTRFN_P (type))
5766     {
5767       /* If the argument is a template-id, we might not have enough
5768 	 context information to decay the pointer.  */
5769       if (!type_unknown_p (expr_type))
5770 	{
5771 	  expr = decay_conversion (expr, complain);
5772 	  if (expr == error_mark_node)
5773 	    return error_mark_node;
5774 	}
5775 
5776       if (cxx_dialect >= cxx0x && integer_zerop (expr))
5777 	/* Null pointer values are OK in C++11.  */
5778 	return perform_qualification_conversions (type, expr);
5779 
5780       expr = convert_nontype_argument_function (type, expr);
5781       if (!expr || expr == error_mark_node)
5782 	return expr;
5783     }
5784   /* [temp.arg.nontype]/5, bullet 5
5785 
5786      For a non-type template-parameter of type reference to function, no
5787      conversions apply. If the template-argument represents a set of
5788      overloaded functions, the matching function is selected from the set
5789      (_over.over_).  */
5790   else if (TYPE_REFFN_P (type))
5791     {
5792       if (TREE_CODE (expr) == ADDR_EXPR)
5793 	{
5794 	  error ("%qE is not a valid template argument for type %qT "
5795 		 "because it is a pointer", expr, type);
5796 	  inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5797 	  return NULL_TREE;
5798 	}
5799 
5800       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5801       if (!expr || expr == error_mark_node)
5802 	return expr;
5803 
5804       expr = build_nop (type, build_address (expr));
5805     }
5806   /* [temp.arg.nontype]/5, bullet 6
5807 
5808      For a non-type template-parameter of type pointer to member function,
5809      no conversions apply. If the template-argument represents a set of
5810      overloaded member functions, the matching member function is selected
5811      from the set (_over.over_).  */
5812   else if (TYPE_PTRMEMFUNC_P (type))
5813     {
5814       expr = instantiate_type (type, expr, tf_none);
5815       if (expr == error_mark_node)
5816 	return error_mark_node;
5817 
5818       /* [temp.arg.nontype] bullet 1 says the pointer to member
5819          expression must be a pointer-to-member constant.  */
5820       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5821 	return error_mark_node;
5822 
5823       /* There is no way to disable standard conversions in
5824 	 resolve_address_of_overloaded_function (called by
5825 	 instantiate_type). It is possible that the call succeeded by
5826 	 converting &B::I to &D::I (where B is a base of D), so we need
5827 	 to reject this conversion here.
5828 
5829 	 Actually, even if there was a way to disable standard conversions,
5830 	 it would still be better to reject them here so that we can
5831 	 provide a superior diagnostic.  */
5832       if (!same_type_p (TREE_TYPE (expr), type))
5833 	{
5834 	  error ("%qE is not a valid template argument for type %qT "
5835 		 "because it is of type %qT", expr, type,
5836 		 TREE_TYPE (expr));
5837 	  /* If we are just one standard conversion off, explain.  */
5838 	  if (can_convert (type, TREE_TYPE (expr), complain))
5839 	    inform (input_location,
5840 		    "standard conversions are not allowed in this context");
5841 	  return NULL_TREE;
5842 	}
5843     }
5844   /* [temp.arg.nontype]/5, bullet 7
5845 
5846      For a non-type template-parameter of type pointer to data member,
5847      qualification conversions (_conv.qual_) are applied.  */
5848   else if (TYPE_PTRDATAMEM_P (type))
5849     {
5850       /* [temp.arg.nontype] bullet 1 says the pointer to member
5851          expression must be a pointer-to-member constant.  */
5852       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5853 	return error_mark_node;
5854 
5855       expr = perform_qualification_conversions (type, expr);
5856       if (expr == error_mark_node)
5857 	return expr;
5858     }
5859   else if (NULLPTR_TYPE_P (type))
5860     {
5861       if (expr != nullptr_node)
5862 	{
5863 	  error ("%qE is not a valid template argument for type %qT "
5864 		 "because it is of type %qT", expr, type, TREE_TYPE (expr));
5865 	  return NULL_TREE;
5866 	}
5867       return expr;
5868     }
5869   /* A template non-type parameter must be one of the above.  */
5870   else
5871     gcc_unreachable ();
5872 
5873   /* Sanity check: did we actually convert the argument to the
5874      right type?  */
5875   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5876 	      (type, TREE_TYPE (expr)));
5877   return expr;
5878 }
5879 
5880 /* Subroutine of coerce_template_template_parms, which returns 1 if
5881    PARM_PARM and ARG_PARM match using the rule for the template
5882    parameters of template template parameters. Both PARM and ARG are
5883    template parameters; the rest of the arguments are the same as for
5884    coerce_template_template_parms.
5885  */
5886 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)5887 coerce_template_template_parm (tree parm,
5888                               tree arg,
5889                               tsubst_flags_t complain,
5890                               tree in_decl,
5891                               tree outer_args)
5892 {
5893   if (arg == NULL_TREE || arg == error_mark_node
5894       || parm == NULL_TREE || parm == error_mark_node)
5895     return 0;
5896 
5897   if (TREE_CODE (arg) != TREE_CODE (parm))
5898     return 0;
5899 
5900   switch (TREE_CODE (parm))
5901     {
5902     case TEMPLATE_DECL:
5903       /* We encounter instantiations of templates like
5904 	 template <template <template <class> class> class TT>
5905 	 class C;  */
5906       {
5907 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5908 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5909 
5910 	if (!coerce_template_template_parms
5911 	    (parmparm, argparm, complain, in_decl, outer_args))
5912 	  return 0;
5913       }
5914       /* Fall through.  */
5915 
5916     case TYPE_DECL:
5917       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5918 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5919 	/* Argument is a parameter pack but parameter is not.  */
5920 	return 0;
5921       break;
5922 
5923     case PARM_DECL:
5924       /* The tsubst call is used to handle cases such as
5925 
5926            template <int> class C {};
5927 	   template <class T, template <T> class TT> class D {};
5928 	   D<int, C> d;
5929 
5930 	 i.e. the parameter list of TT depends on earlier parameters.  */
5931       if (!uses_template_parms (TREE_TYPE (arg))
5932 	  && !same_type_p
5933 	        (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5934 		 TREE_TYPE (arg)))
5935 	return 0;
5936 
5937       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5938 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5939 	/* Argument is a parameter pack but parameter is not.  */
5940 	return 0;
5941 
5942       break;
5943 
5944     default:
5945       gcc_unreachable ();
5946     }
5947 
5948   return 1;
5949 }
5950 
5951 
5952 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5953    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5954    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5955    or PARM_DECL.
5956 
5957    Consider the example:
5958      template <class T> class A;
5959      template<template <class U> class TT> class B;
5960 
5961    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5962    the parameters to A, and OUTER_ARGS contains A.  */
5963 
5964 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)5965 coerce_template_template_parms (tree parm_parms,
5966 				tree arg_parms,
5967 				tsubst_flags_t complain,
5968 				tree in_decl,
5969 				tree outer_args)
5970 {
5971   int nparms, nargs, i;
5972   tree parm, arg;
5973   int variadic_p = 0;
5974 
5975   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5976   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5977 
5978   nparms = TREE_VEC_LENGTH (parm_parms);
5979   nargs = TREE_VEC_LENGTH (arg_parms);
5980 
5981   /* Determine whether we have a parameter pack at the end of the
5982      template template parameter's template parameter list.  */
5983   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5984     {
5985       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5986 
5987       if (parm == error_mark_node)
5988 	return 0;
5989 
5990       switch (TREE_CODE (parm))
5991         {
5992         case TEMPLATE_DECL:
5993         case TYPE_DECL:
5994           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5995             variadic_p = 1;
5996           break;
5997 
5998         case PARM_DECL:
5999           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6000             variadic_p = 1;
6001           break;
6002 
6003         default:
6004           gcc_unreachable ();
6005         }
6006     }
6007 
6008   if (nargs != nparms
6009       && !(variadic_p && nargs >= nparms - 1))
6010     return 0;
6011 
6012   /* Check all of the template parameters except the parameter pack at
6013      the end (if any).  */
6014   for (i = 0; i < nparms - variadic_p; ++i)
6015     {
6016       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6017           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6018         continue;
6019 
6020       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6021       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6022 
6023       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6024                                           outer_args))
6025 	return 0;
6026 
6027     }
6028 
6029   if (variadic_p)
6030     {
6031       /* Check each of the template parameters in the template
6032 	 argument against the template parameter pack at the end of
6033 	 the template template parameter.  */
6034       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6035 	return 0;
6036 
6037       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6038 
6039       for (; i < nargs; ++i)
6040         {
6041           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6042             continue;
6043 
6044           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6045 
6046           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6047                                               outer_args))
6048             return 0;
6049         }
6050     }
6051 
6052   return 1;
6053 }
6054 
6055 /* Verifies that the deduced template arguments (in TARGS) for the
6056    template template parameters (in TPARMS) represent valid bindings,
6057    by comparing the template parameter list of each template argument
6058    to the template parameter list of its corresponding template
6059    template parameter, in accordance with DR150. This
6060    routine can only be called after all template arguments have been
6061    deduced. It will return TRUE if all of the template template
6062    parameter bindings are okay, FALSE otherwise.  */
6063 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)6064 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6065 {
6066   int i, ntparms = TREE_VEC_LENGTH (tparms);
6067   bool ret = true;
6068 
6069   /* We're dealing with template parms in this process.  */
6070   ++processing_template_decl;
6071 
6072   targs = INNERMOST_TEMPLATE_ARGS (targs);
6073 
6074   for (i = 0; i < ntparms; ++i)
6075     {
6076       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6077       tree targ = TREE_VEC_ELT (targs, i);
6078 
6079       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6080 	{
6081 	  tree packed_args = NULL_TREE;
6082 	  int idx, len = 1;
6083 
6084 	  if (ARGUMENT_PACK_P (targ))
6085 	    {
6086 	      /* Look inside the argument pack.  */
6087 	      packed_args = ARGUMENT_PACK_ARGS (targ);
6088 	      len = TREE_VEC_LENGTH (packed_args);
6089 	    }
6090 
6091 	  for (idx = 0; idx < len; ++idx)
6092 	    {
6093 	      tree targ_parms = NULL_TREE;
6094 
6095 	      if (packed_args)
6096 		/* Extract the next argument from the argument
6097 		   pack.  */
6098 		targ = TREE_VEC_ELT (packed_args, idx);
6099 
6100 	      if (PACK_EXPANSION_P (targ))
6101 		/* Look at the pattern of the pack expansion.  */
6102 		targ = PACK_EXPANSION_PATTERN (targ);
6103 
6104 	      /* Extract the template parameters from the template
6105 		 argument.  */
6106 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
6107 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6108 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6109 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6110 
6111 	      /* Verify that we can coerce the template template
6112 		 parameters from the template argument to the template
6113 		 parameter.  This requires an exact match.  */
6114 	      if (targ_parms
6115 		  && !coerce_template_template_parms
6116 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6117 			targ_parms,
6118 			tf_none,
6119 			tparm,
6120 			targs))
6121 		{
6122 		  ret = false;
6123 		  goto out;
6124 		}
6125 	    }
6126 	}
6127     }
6128 
6129  out:
6130 
6131   --processing_template_decl;
6132   return ret;
6133 }
6134 
6135 /* Since type attributes aren't mangled, we need to strip them from
6136    template type arguments.  */
6137 
6138 static tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)6139 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6140 {
6141   tree mv;
6142   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6143     return arg;
6144   mv = TYPE_MAIN_VARIANT (arg);
6145   arg = strip_typedefs (arg);
6146   if (TYPE_ALIGN (arg) != TYPE_ALIGN (mv)
6147       || TYPE_ATTRIBUTES (arg) != TYPE_ATTRIBUTES (mv))
6148     {
6149       if (complain & tf_warning)
6150 	warning (0, "ignoring attributes on template argument %qT", arg);
6151       arg = build_aligned_type (arg, TYPE_ALIGN (mv));
6152       arg = cp_build_type_attribute_variant (arg, TYPE_ATTRIBUTES (mv));
6153     }
6154   return arg;
6155 }
6156 
6157 /* Convert the indicated template ARG as necessary to match the
6158    indicated template PARM.  Returns the converted ARG, or
6159    error_mark_node if the conversion was unsuccessful.  Error and
6160    warning messages are issued under control of COMPLAIN.  This
6161    conversion is for the Ith parameter in the parameter list.  ARGS is
6162    the full set of template arguments deduced so far.  */
6163 
6164 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)6165 convert_template_argument (tree parm,
6166 			   tree arg,
6167 			   tree args,
6168 			   tsubst_flags_t complain,
6169 			   int i,
6170 			   tree in_decl)
6171 {
6172   tree orig_arg;
6173   tree val;
6174   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
6175 
6176   if (TREE_CODE (arg) == TREE_LIST
6177       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
6178     {
6179       /* The template argument was the name of some
6180 	 member function.  That's usually
6181 	 invalid, but static members are OK.  In any
6182 	 case, grab the underlying fields/functions
6183 	 and issue an error later if required.  */
6184       orig_arg = TREE_VALUE (arg);
6185       TREE_TYPE (arg) = unknown_type_node;
6186     }
6187 
6188   orig_arg = arg;
6189 
6190   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
6191   requires_type = (TREE_CODE (parm) == TYPE_DECL
6192 		   || requires_tmpl_type);
6193 
6194   /* When determining whether an argument pack expansion is a template,
6195      look at the pattern.  */
6196   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
6197     arg = PACK_EXPANSION_PATTERN (arg);
6198 
6199   /* Deal with an injected-class-name used as a template template arg.  */
6200   if (requires_tmpl_type && CLASS_TYPE_P (arg))
6201     {
6202       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
6203       if (TREE_CODE (t) == TEMPLATE_DECL)
6204 	{
6205 	  if (cxx_dialect >= cxx0x)
6206 	    /* OK under DR 1004.  */;
6207 	  else if (complain & tf_warning_or_error)
6208 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
6209 		     " used as template template argument", TYPE_NAME (arg));
6210 	  else if (flag_pedantic_errors)
6211 	    t = arg;
6212 
6213 	  arg = t;
6214 	}
6215     }
6216 
6217   is_tmpl_type =
6218     ((TREE_CODE (arg) == TEMPLATE_DECL
6219       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
6220      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
6221      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6222      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
6223 
6224   if (is_tmpl_type
6225       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
6226 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
6227     arg = TYPE_STUB_DECL (arg);
6228 
6229   is_type = TYPE_P (arg) || is_tmpl_type;
6230 
6231   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
6232       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
6233     {
6234       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
6235 	{
6236 	  if (complain & tf_error)
6237 	    error ("invalid use of destructor %qE as a type", orig_arg);
6238 	  return error_mark_node;
6239 	}
6240 
6241       permerror (input_location,
6242 		 "to refer to a type member of a template parameter, "
6243 		 "use %<typename %E%>", orig_arg);
6244 
6245       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
6246 				     TREE_OPERAND (arg, 1),
6247 				     typename_type,
6248 				     complain);
6249       arg = orig_arg;
6250       is_type = 1;
6251     }
6252   if (is_type != requires_type)
6253     {
6254       if (in_decl)
6255 	{
6256 	  if (complain & tf_error)
6257 	    {
6258 	      error ("type/value mismatch at argument %d in template "
6259 		     "parameter list for %qD",
6260 		     i + 1, in_decl);
6261 	      if (is_type)
6262 		error ("  expected a constant of type %qT, got %qT",
6263 		       TREE_TYPE (parm),
6264 		       (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6265 	      else if (requires_tmpl_type)
6266 		error ("  expected a class template, got %qE", orig_arg);
6267 	      else
6268 		error ("  expected a type, got %qE", orig_arg);
6269 	    }
6270 	}
6271       return error_mark_node;
6272     }
6273   if (is_tmpl_type ^ requires_tmpl_type)
6274     {
6275       if (in_decl && (complain & tf_error))
6276 	{
6277 	  error ("type/value mismatch at argument %d in template "
6278 		 "parameter list for %qD",
6279 		 i + 1, in_decl);
6280 	  if (is_tmpl_type)
6281 	    error ("  expected a type, got %qT", DECL_NAME (arg));
6282 	  else
6283 	    error ("  expected a class template, got %qT", orig_arg);
6284 	}
6285       return error_mark_node;
6286     }
6287 
6288   if (is_type)
6289     {
6290       if (requires_tmpl_type)
6291 	{
6292 	  if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6293 	    val = orig_arg;
6294 	  else if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6295 	    /* The number of argument required is not known yet.
6296 	       Just accept it for now.  */
6297 	    val = TREE_TYPE (arg);
6298 	  else
6299 	    {
6300 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6301 	      tree argparm;
6302 
6303               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6304 
6305 	      if (coerce_template_template_parms (parmparm, argparm,
6306 						  complain, in_decl,
6307 						  args))
6308 		{
6309 		  val = arg;
6310 
6311 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
6312 		     TEMPLATE_DECL.  */
6313 		  if (val != error_mark_node)
6314                     {
6315                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6316                         val = TREE_TYPE (val);
6317 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6318 			val = make_pack_expansion (val);
6319                     }
6320 		}
6321 	      else
6322 		{
6323 		  if (in_decl && (complain & tf_error))
6324 		    {
6325 		      error ("type/value mismatch at argument %d in "
6326 			     "template parameter list for %qD",
6327 			     i + 1, in_decl);
6328 		      error ("  expected a template of type %qD, got %qT",
6329 			     parm, orig_arg);
6330 		    }
6331 
6332 		  val = error_mark_node;
6333 		}
6334 	    }
6335 	}
6336       else
6337 	val = orig_arg;
6338       /* We only form one instance of each template specialization.
6339 	 Therefore, if we use a non-canonical variant (i.e., a
6340 	 typedef), any future messages referring to the type will use
6341 	 the typedef, which is confusing if those future uses do not
6342 	 themselves also use the typedef.  */
6343       if (TYPE_P (val))
6344 	val = canonicalize_type_argument (val, complain);
6345     }
6346   else
6347     {
6348       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6349 
6350       if (invalid_nontype_parm_type_p (t, complain))
6351 	return error_mark_node;
6352 
6353       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6354 	{
6355 	  if (same_type_p (t, TREE_TYPE (orig_arg)))
6356 	    val = orig_arg;
6357 	  else
6358 	    {
6359 	      /* Not sure if this is reachable, but it doesn't hurt
6360 		 to be robust.  */
6361 	      error ("type mismatch in nontype parameter pack");
6362 	      val = error_mark_node;
6363 	    }
6364 	}
6365       else if (!dependent_template_arg_p (orig_arg)
6366 	       && !uses_template_parms (t))
6367 	/* We used to call digest_init here.  However, digest_init
6368 	   will report errors, which we don't want when complain
6369 	   is zero.  More importantly, digest_init will try too
6370 	   hard to convert things: for example, `0' should not be
6371 	   converted to pointer type at this point according to
6372 	   the standard.  Accepting this is not merely an
6373 	   extension, since deciding whether or not these
6374 	   conversions can occur is part of determining which
6375 	   function template to call, or whether a given explicit
6376 	   argument specification is valid.  */
6377 	val = convert_nontype_argument (t, orig_arg, complain);
6378       else
6379 	val = strip_typedefs_expr (orig_arg);
6380 
6381       if (val == NULL_TREE)
6382 	val = error_mark_node;
6383       else if (val == error_mark_node && (complain & tf_error))
6384 	error ("could not convert template argument %qE to %qT",  orig_arg, t);
6385 
6386       if (TREE_CODE (val) == SCOPE_REF)
6387 	{
6388 	  /* Strip typedefs from the SCOPE_REF.  */
6389 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
6390 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
6391 						   complain);
6392 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6393 				      QUALIFIED_NAME_IS_TEMPLATE (val));
6394 	}
6395     }
6396 
6397   return val;
6398 }
6399 
6400 /* Coerces the remaining template arguments in INNER_ARGS (from
6401    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6402    Returns the coerced argument pack. PARM_IDX is the position of this
6403    parameter in the template parameter list. ARGS is the original
6404    template argument list.  */
6405 static tree
coerce_template_parameter_pack(tree parms,int parm_idx,tree args,tree inner_args,int arg_idx,tree new_args,int * lost,tree in_decl,tsubst_flags_t complain)6406 coerce_template_parameter_pack (tree parms,
6407                                 int parm_idx,
6408                                 tree args,
6409                                 tree inner_args,
6410                                 int arg_idx,
6411                                 tree new_args,
6412                                 int* lost,
6413                                 tree in_decl,
6414                                 tsubst_flags_t complain)
6415 {
6416   tree parm = TREE_VEC_ELT (parms, parm_idx);
6417   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6418   tree packed_args;
6419   tree argument_pack;
6420   tree packed_types = NULL_TREE;
6421 
6422   if (arg_idx > nargs)
6423     arg_idx = nargs;
6424 
6425   packed_args = make_tree_vec (nargs - arg_idx);
6426 
6427   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6428       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6429     {
6430       /* When the template parameter is a non-type template
6431          parameter pack whose type uses parameter packs, we need
6432          to look at each of the template arguments
6433          separately. Build a vector of the types for these
6434          non-type template parameters in PACKED_TYPES.  */
6435       tree expansion
6436         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6437       packed_types = tsubst_pack_expansion (expansion, args,
6438                                             complain, in_decl);
6439 
6440       if (packed_types == error_mark_node)
6441         return error_mark_node;
6442 
6443       /* Check that we have the right number of arguments.  */
6444       if (arg_idx < nargs
6445           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6446           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6447         {
6448           int needed_parms
6449             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6450           error ("wrong number of template arguments (%d, should be %d)",
6451                  nargs, needed_parms);
6452           return error_mark_node;
6453         }
6454 
6455       /* If we aren't able to check the actual arguments now
6456          (because they haven't been expanded yet), we can at least
6457          verify that all of the types used for the non-type
6458          template parameter pack are, in fact, valid for non-type
6459          template parameters.  */
6460       if (arg_idx < nargs
6461           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6462         {
6463           int j, len = TREE_VEC_LENGTH (packed_types);
6464           for (j = 0; j < len; ++j)
6465             {
6466               tree t = TREE_VEC_ELT (packed_types, j);
6467               if (invalid_nontype_parm_type_p (t, complain))
6468                 return error_mark_node;
6469             }
6470         }
6471     }
6472 
6473   /* Convert the remaining arguments, which will be a part of the
6474      parameter pack "parm".  */
6475   for (; arg_idx < nargs; ++arg_idx)
6476     {
6477       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6478       tree actual_parm = TREE_VALUE (parm);
6479 
6480       if (packed_types && !PACK_EXPANSION_P (arg))
6481         {
6482           /* When we have a vector of types (corresponding to the
6483              non-type template parameter pack that uses parameter
6484              packs in its type, as mention above), and the
6485              argument is not an expansion (which expands to a
6486              currently unknown number of arguments), clone the
6487              parm and give it the next type in PACKED_TYPES.  */
6488           actual_parm = copy_node (actual_parm);
6489           TREE_TYPE (actual_parm) =
6490             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6491         }
6492 
6493       if (arg == error_mark_node)
6494 	{
6495 	  if (complain & tf_error)
6496 	    error ("template argument %d is invalid", arg_idx + 1);
6497 	}
6498       else
6499 	arg = convert_template_argument (actual_parm,
6500 					 arg, new_args, complain, parm_idx,
6501 					 in_decl);
6502       if (arg == error_mark_node)
6503         (*lost)++;
6504       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg;
6505     }
6506 
6507   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6508       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6509     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6510   else
6511     {
6512       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6513       TREE_TYPE (argument_pack)
6514         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6515       TREE_CONSTANT (argument_pack) = 1;
6516     }
6517 
6518   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6519 #ifdef ENABLE_CHECKING
6520   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6521 				       TREE_VEC_LENGTH (packed_args));
6522 #endif
6523   return argument_pack;
6524 }
6525 
6526 /* Returns true if the template argument vector ARGS contains
6527    any pack expansions, false otherwise.  */
6528 
6529 static bool
any_pack_expanson_args_p(tree args)6530 any_pack_expanson_args_p (tree args)
6531 {
6532   int i;
6533   if (args)
6534     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
6535       if (PACK_EXPANSION_P (TREE_VEC_ELT (args, i)))
6536 	return true;
6537   return false;
6538 }
6539 
6540 /* Convert all template arguments to their appropriate types, and
6541    return a vector containing the innermost resulting template
6542    arguments.  If any error occurs, return error_mark_node. Error and
6543    warning messages are issued under control of COMPLAIN.
6544 
6545    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6546    for arguments not specified in ARGS.  Otherwise, if
6547    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6548    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6549    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6550    ARGS.  */
6551 
6552 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)6553 coerce_template_parms (tree parms,
6554 		       tree args,
6555 		       tree in_decl,
6556 		       tsubst_flags_t complain,
6557 		       bool require_all_args,
6558 		       bool use_default_args)
6559 {
6560   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6561   tree inner_args;
6562   tree new_args;
6563   tree new_inner_args;
6564   int saved_unevaluated_operand;
6565   int saved_inhibit_evaluation_warnings;
6566 
6567   /* When used as a boolean value, indicates whether this is a
6568      variadic template parameter list. Since it's an int, we can also
6569      subtract it from nparms to get the number of non-variadic
6570      parameters.  */
6571   int variadic_p = 0;
6572   int post_variadic_parms = 0;
6573 
6574   if (args == error_mark_node)
6575     return error_mark_node;
6576 
6577   nparms = TREE_VEC_LENGTH (parms);
6578 
6579   /* Determine if there are any parameter packs.  */
6580   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6581     {
6582       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6583       if (variadic_p)
6584 	++post_variadic_parms;
6585       if (template_parameter_pack_p (tparm))
6586 	++variadic_p;
6587     }
6588 
6589   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6590   /* If there are no parameters that follow a parameter pack, we need to
6591      expand any argument packs so that we can deduce a parameter pack from
6592      some non-packed args followed by an argument pack, as in variadic85.C.
6593      If there are such parameters, we need to leave argument packs intact
6594      so the arguments are assigned properly.  This can happen when dealing
6595      with a nested class inside a partial specialization of a class
6596      template, as in variadic92.C, or when deducing a template parameter pack
6597      from a sub-declarator, as in variadic114.C.  */
6598   if (!post_variadic_parms)
6599     inner_args = expand_template_argument_pack (inner_args);
6600 
6601   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6602   if ((nargs > nparms && !variadic_p)
6603       || (nargs < nparms - variadic_p
6604 	  && require_all_args
6605 	  && !any_pack_expanson_args_p (inner_args)
6606 	  && (!use_default_args
6607 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6608                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6609     {
6610       if (complain & tf_error)
6611 	{
6612           if (variadic_p)
6613             {
6614               nparms -= variadic_p;
6615 	      error ("wrong number of template arguments "
6616 		     "(%d, should be %d or more)", nargs, nparms);
6617             }
6618 	  else
6619 	     error ("wrong number of template arguments "
6620 		    "(%d, should be %d)", nargs, nparms);
6621 
6622 	  if (in_decl)
6623 	    error ("provided for %q+D", in_decl);
6624 	}
6625 
6626       return error_mark_node;
6627     }
6628 
6629   /* We need to evaluate the template arguments, even though this
6630      template-id may be nested within a "sizeof".  */
6631   saved_unevaluated_operand = cp_unevaluated_operand;
6632   cp_unevaluated_operand = 0;
6633   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6634   c_inhibit_evaluation_warnings = 0;
6635   new_inner_args = make_tree_vec (nparms);
6636   new_args = add_outermost_template_args (args, new_inner_args);
6637   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6638     {
6639       tree arg;
6640       tree parm;
6641 
6642       /* Get the Ith template parameter.  */
6643       parm = TREE_VEC_ELT (parms, parm_idx);
6644 
6645       if (parm == error_mark_node)
6646       {
6647         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6648         continue;
6649       }
6650 
6651       /* Calculate the next argument.  */
6652       if (arg_idx < nargs)
6653 	arg = TREE_VEC_ELT (inner_args, arg_idx);
6654       else
6655 	arg = NULL_TREE;
6656 
6657       if (template_parameter_pack_p (TREE_VALUE (parm))
6658 	  && !(arg && ARGUMENT_PACK_P (arg)))
6659         {
6660 	  /* All remaining arguments will be placed in the
6661 	     template parameter pack PARM.  */
6662 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
6663 						inner_args, arg_idx,
6664 						new_args, &lost,
6665 						in_decl, complain);
6666 
6667           /* Store this argument.  */
6668           if (arg == error_mark_node)
6669             lost++;
6670           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6671 
6672 	  /* We are done with all of the arguments.  */
6673 	  arg_idx = nargs;
6674 
6675           continue;
6676         }
6677       else if (arg)
6678 	{
6679           if (PACK_EXPANSION_P (arg))
6680             {
6681               /* We don't know how many args we have yet, just
6682                  use the unconverted ones for now.  */
6683               new_inner_args = inner_args;
6684               break;
6685             }
6686         }
6687       else if (require_all_args)
6688 	{
6689 	  /* There must be a default arg in this case.  */
6690 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6691 				     complain, in_decl);
6692 	  /* The position of the first default template argument,
6693 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6694 	     Record that.  */
6695 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6696 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6697 	}
6698       else
6699 	break;
6700 
6701       if (arg == error_mark_node)
6702 	{
6703 	  if (complain & tf_error)
6704 	    error ("template argument %d is invalid", arg_idx + 1);
6705 	}
6706       else if (!arg)
6707         /* This only occurs if there was an error in the template
6708            parameter list itself (which we would already have
6709            reported) that we are trying to recover from, e.g., a class
6710            template with a parameter list such as
6711            template<typename..., typename>.  */
6712 	++lost;
6713       else
6714 	arg = convert_template_argument (TREE_VALUE (parm),
6715 					 arg, new_args, complain,
6716                                          parm_idx, in_decl);
6717 
6718       if (arg == error_mark_node)
6719 	lost++;
6720       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6721     }
6722   cp_unevaluated_operand = saved_unevaluated_operand;
6723   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6724 
6725   if (lost)
6726     return error_mark_node;
6727 
6728 #ifdef ENABLE_CHECKING
6729   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6730     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6731 					 TREE_VEC_LENGTH (new_inner_args));
6732 #endif
6733 
6734   return new_inner_args;
6735 }
6736 
6737 /* Like coerce_template_parms.  If PARMS represents all template
6738    parameters levels, this function returns a vector of vectors
6739    representing all the resulting argument levels.  Note that in this
6740    case, only the innermost arguments are coerced because the
6741    outermost ones are supposed to have been coerced already.
6742 
6743    Otherwise, if PARMS represents only (the innermost) vector of
6744    parameters, this function returns a vector containing just the
6745    innermost resulting arguments.  */
6746 
6747 static tree
coerce_innermost_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)6748 coerce_innermost_template_parms (tree parms,
6749 				  tree args,
6750 				  tree in_decl,
6751 				  tsubst_flags_t complain,
6752 				  bool require_all_args,
6753 				  bool use_default_args)
6754 {
6755   int parms_depth = TMPL_PARMS_DEPTH (parms);
6756   int args_depth = TMPL_ARGS_DEPTH (args);
6757   tree coerced_args;
6758 
6759   if (parms_depth > 1)
6760     {
6761       coerced_args = make_tree_vec (parms_depth);
6762       tree level;
6763       int cur_depth;
6764 
6765       for (level = parms, cur_depth = parms_depth;
6766 	   parms_depth > 0 && level != NULL_TREE;
6767 	   level = TREE_CHAIN (level), --cur_depth)
6768 	{
6769 	  tree l;
6770 	  if (cur_depth == args_depth)
6771 	    l = coerce_template_parms (TREE_VALUE (level),
6772 				       args, in_decl, complain,
6773 				       require_all_args,
6774 				       use_default_args);
6775 	  else
6776 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
6777 
6778 	  if (l == error_mark_node)
6779 	    return error_mark_node;
6780 
6781 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
6782 	}
6783     }
6784   else
6785     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
6786 					  args, in_decl, complain,
6787 					  require_all_args,
6788 					  use_default_args);
6789   return coerced_args;
6790 }
6791 
6792 /* Returns 1 if template args OT and NT are equivalent.  */
6793 
6794 static int
template_args_equal(tree ot,tree nt)6795 template_args_equal (tree ot, tree nt)
6796 {
6797   if (nt == ot)
6798     return 1;
6799   if (nt == NULL_TREE || ot == NULL_TREE)
6800     return false;
6801 
6802   if (TREE_CODE (nt) == TREE_VEC)
6803     /* For member templates */
6804     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6805   else if (PACK_EXPANSION_P (ot))
6806     return (PACK_EXPANSION_P (nt)
6807 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6808 				    PACK_EXPANSION_PATTERN (nt))
6809 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
6810 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
6811   else if (ARGUMENT_PACK_P (ot))
6812     {
6813       int i, len;
6814       tree opack, npack;
6815 
6816       if (!ARGUMENT_PACK_P (nt))
6817 	return 0;
6818 
6819       opack = ARGUMENT_PACK_ARGS (ot);
6820       npack = ARGUMENT_PACK_ARGS (nt);
6821       len = TREE_VEC_LENGTH (opack);
6822       if (TREE_VEC_LENGTH (npack) != len)
6823 	return 0;
6824       for (i = 0; i < len; ++i)
6825 	if (!template_args_equal (TREE_VEC_ELT (opack, i),
6826 				  TREE_VEC_ELT (npack, i)))
6827 	  return 0;
6828       return 1;
6829     }
6830   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6831     {
6832       /* We get here probably because we are in the middle of substituting
6833          into the pattern of a pack expansion. In that case the
6834 	 ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6835 	 interested in. So we want to use the initial pack argument for
6836 	 the comparison.  */
6837       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6838       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6839 	nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6840       return template_args_equal (ot, nt);
6841     }
6842   else if (TYPE_P (nt))
6843     return TYPE_P (ot) && same_type_p (ot, nt);
6844   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6845     return 0;
6846   else
6847     return cp_tree_equal (ot, nt);
6848 }
6849 
6850 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
6851    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
6852    NEWARG_PTR with the offending arguments if they are non-NULL.  */
6853 
6854 static int
comp_template_args_with_info(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr)6855 comp_template_args_with_info (tree oldargs, tree newargs,
6856 			      tree *oldarg_ptr, tree *newarg_ptr)
6857 {
6858   int i;
6859 
6860   if (oldargs == newargs)
6861     return 1;
6862 
6863   if (!oldargs || !newargs)
6864     return 0;
6865 
6866   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6867     return 0;
6868 
6869   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6870     {
6871       tree nt = TREE_VEC_ELT (newargs, i);
6872       tree ot = TREE_VEC_ELT (oldargs, i);
6873 
6874       if (! template_args_equal (ot, nt))
6875 	{
6876 	  if (oldarg_ptr != NULL)
6877 	    *oldarg_ptr = ot;
6878 	  if (newarg_ptr != NULL)
6879 	    *newarg_ptr = nt;
6880 	  return 0;
6881 	}
6882     }
6883   return 1;
6884 }
6885 
6886 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6887    of template arguments.  Returns 0 otherwise.  */
6888 
6889 int
comp_template_args(tree oldargs,tree newargs)6890 comp_template_args (tree oldargs, tree newargs)
6891 {
6892   return comp_template_args_with_info (oldargs, newargs, NULL, NULL);
6893 }
6894 
6895 static void
add_pending_template(tree d)6896 add_pending_template (tree d)
6897 {
6898   tree ti = (TYPE_P (d)
6899 	     ? CLASSTYPE_TEMPLATE_INFO (d)
6900 	     : DECL_TEMPLATE_INFO (d));
6901   struct pending_template *pt;
6902   int level;
6903 
6904   if (TI_PENDING_TEMPLATE_FLAG (ti))
6905     return;
6906 
6907   /* We are called both from instantiate_decl, where we've already had a
6908      tinst_level pushed, and instantiate_template, where we haven't.
6909      Compensate.  */
6910   level = !current_tinst_level || current_tinst_level->decl != d;
6911 
6912   if (level)
6913     push_tinst_level (d);
6914 
6915   pt = ggc_alloc_pending_template ();
6916   pt->next = NULL;
6917   pt->tinst = current_tinst_level;
6918   if (last_pending_template)
6919     last_pending_template->next = pt;
6920   else
6921     pending_templates = pt;
6922 
6923   last_pending_template = pt;
6924 
6925   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6926 
6927   if (level)
6928     pop_tinst_level ();
6929 }
6930 
6931 
6932 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6933    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6934    documentation for TEMPLATE_ID_EXPR.  */
6935 
6936 tree
lookup_template_function(tree fns,tree arglist)6937 lookup_template_function (tree fns, tree arglist)
6938 {
6939   tree type;
6940 
6941   if (fns == error_mark_node || arglist == error_mark_node)
6942     return error_mark_node;
6943 
6944   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6945 
6946   if (!is_overloaded_fn (fns) && TREE_CODE (fns) != IDENTIFIER_NODE)
6947     {
6948       error ("%q#D is not a function template", fns);
6949       return error_mark_node;
6950     }
6951 
6952   if (BASELINK_P (fns))
6953     {
6954       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6955 					 unknown_type_node,
6956 					 BASELINK_FUNCTIONS (fns),
6957 					 arglist);
6958       return fns;
6959     }
6960 
6961   type = TREE_TYPE (fns);
6962   if (TREE_CODE (fns) == OVERLOAD || !type)
6963     type = unknown_type_node;
6964 
6965   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6966 }
6967 
6968 /* Within the scope of a template class S<T>, the name S gets bound
6969    (in build_self_reference) to a TYPE_DECL for the class, not a
6970    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6971    or one of its enclosing classes, and that type is a template,
6972    return the associated TEMPLATE_DECL.  Otherwise, the original
6973    DECL is returned.
6974 
6975    Also handle the case when DECL is a TREE_LIST of ambiguous
6976    injected-class-names from different bases.  */
6977 
6978 tree
maybe_get_template_decl_from_type_decl(tree decl)6979 maybe_get_template_decl_from_type_decl (tree decl)
6980 {
6981   if (decl == NULL_TREE)
6982     return decl;
6983 
6984   /* DR 176: A lookup that finds an injected-class-name (10.2
6985      [class.member.lookup]) can result in an ambiguity in certain cases
6986      (for example, if it is found in more than one base class). If all of
6987      the injected-class-names that are found refer to specializations of
6988      the same class template, and if the name is followed by a
6989      template-argument-list, the reference refers to the class template
6990      itself and not a specialization thereof, and is not ambiguous.  */
6991   if (TREE_CODE (decl) == TREE_LIST)
6992     {
6993       tree t, tmpl = NULL_TREE;
6994       for (t = decl; t; t = TREE_CHAIN (t))
6995 	{
6996 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6997 	  if (!tmpl)
6998 	    tmpl = elt;
6999 	  else if (tmpl != elt)
7000 	    break;
7001 	}
7002       if (tmpl && t == NULL_TREE)
7003 	return tmpl;
7004       else
7005 	return decl;
7006     }
7007 
7008   return (decl != NULL_TREE
7009 	  && DECL_SELF_REFERENCE_P (decl)
7010 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
7011     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
7012 }
7013 
7014 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
7015    parameters, find the desired type.
7016 
7017    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
7018 
7019    IN_DECL, if non-NULL, is the template declaration we are trying to
7020    instantiate.
7021 
7022    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
7023    the class we are looking up.
7024 
7025    Issue error and warning messages under control of COMPLAIN.
7026 
7027    If the template class is really a local class in a template
7028    function, then the FUNCTION_CONTEXT is the function in which it is
7029    being instantiated.
7030 
7031    ??? Note that this function is currently called *twice* for each
7032    template-id: the first time from the parser, while creating the
7033    incomplete type (finish_template_type), and the second type during the
7034    real instantiation (instantiate_template_class). This is surely something
7035    that we want to avoid. It also causes some problems with argument
7036    coercion (see convert_nontype_argument for more information on this).  */
7037 
7038 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)7039 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
7040 			 int entering_scope, tsubst_flags_t complain)
7041 {
7042   tree templ = NULL_TREE, parmlist;
7043   tree t;
7044   void **slot;
7045   spec_entry *entry;
7046   spec_entry elt;
7047   hashval_t hash;
7048 
7049   if (TREE_CODE (d1) == IDENTIFIER_NODE)
7050     {
7051       tree value = innermost_non_namespace_value (d1);
7052       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
7053 	templ = value;
7054       else
7055 	{
7056 	  if (context)
7057 	    push_decl_namespace (context);
7058 	  templ = lookup_name (d1);
7059 	  templ = maybe_get_template_decl_from_type_decl (templ);
7060 	  if (context)
7061 	    pop_decl_namespace ();
7062 	}
7063       if (templ)
7064 	context = DECL_CONTEXT (templ);
7065     }
7066   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
7067     {
7068       tree type = TREE_TYPE (d1);
7069 
7070       /* If we are declaring a constructor, say A<T>::A<T>, we will get
7071 	 an implicit typename for the second A.  Deal with it.  */
7072       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
7073 	type = TREE_TYPE (type);
7074 
7075       if (CLASSTYPE_TEMPLATE_INFO (type))
7076 	{
7077 	  templ = CLASSTYPE_TI_TEMPLATE (type);
7078 	  d1 = DECL_NAME (templ);
7079 	}
7080     }
7081   else if (TREE_CODE (d1) == ENUMERAL_TYPE
7082 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
7083     {
7084       templ = TYPE_TI_TEMPLATE (d1);
7085       d1 = DECL_NAME (templ);
7086     }
7087   else if (TREE_CODE (d1) == TEMPLATE_DECL
7088            && DECL_TEMPLATE_RESULT (d1)
7089 	   && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
7090     {
7091       templ = d1;
7092       d1 = DECL_NAME (templ);
7093       context = DECL_CONTEXT (templ);
7094     }
7095   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
7096     {
7097       templ = d1;
7098       d1 = DECL_NAME (templ);
7099     }
7100 
7101   /* Issue an error message if we didn't find a template.  */
7102   if (! templ)
7103     {
7104       if (complain & tf_error)
7105 	error ("%qT is not a template", d1);
7106       return error_mark_node;
7107     }
7108 
7109   if (TREE_CODE (templ) != TEMPLATE_DECL
7110 	 /* Make sure it's a user visible template, if it was named by
7111 	    the user.  */
7112       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
7113 	  && !PRIMARY_TEMPLATE_P (templ)))
7114     {
7115       if (complain & tf_error)
7116 	{
7117 	  error ("non-template type %qT used as a template", d1);
7118 	  if (in_decl)
7119 	    error ("for template declaration %q+D", in_decl);
7120 	}
7121       return error_mark_node;
7122     }
7123 
7124   complain &= ~tf_user;
7125 
7126   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
7127     {
7128       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
7129 	 template arguments */
7130 
7131       tree parm;
7132       tree arglist2;
7133       tree outer;
7134 
7135       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7136 
7137       /* Consider an example where a template template parameter declared as
7138 
7139 	   template <class T, class U = std::allocator<T> > class TT
7140 
7141 	 The template parameter level of T and U are one level larger than
7142 	 of TT.  To proper process the default argument of U, say when an
7143 	 instantiation `TT<int>' is seen, we need to build the full
7144 	 arguments containing {int} as the innermost level.  Outer levels,
7145 	 available when not appearing as default template argument, can be
7146 	 obtained from the arguments of the enclosing template.
7147 
7148 	 Suppose that TT is later substituted with std::vector.  The above
7149 	 instantiation is `TT<int, std::allocator<T> >' with TT at
7150 	 level 1, and T at level 2, while the template arguments at level 1
7151 	 becomes {std::vector} and the inner level 2 is {int}.  */
7152 
7153       outer = DECL_CONTEXT (templ);
7154       if (outer)
7155 	outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7156       else if (current_template_parms)
7157 	/* This is an argument of the current template, so we haven't set
7158 	   DECL_CONTEXT yet.  */
7159 	outer = current_template_args ();
7160 
7161       if (outer)
7162 	arglist = add_to_template_args (outer, arglist);
7163 
7164       arglist2 = coerce_template_parms (parmlist, arglist, templ,
7165 					complain,
7166 					/*require_all_args=*/true,
7167 					/*use_default_args=*/true);
7168       if (arglist2 == error_mark_node
7169 	  || (!uses_template_parms (arglist2)
7170 	      && check_instantiated_args (templ, arglist2, complain)))
7171 	return error_mark_node;
7172 
7173       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
7174       return parm;
7175     }
7176   else
7177     {
7178       tree template_type = TREE_TYPE (templ);
7179       tree gen_tmpl;
7180       tree type_decl;
7181       tree found = NULL_TREE;
7182       int arg_depth;
7183       int parm_depth;
7184       int is_dependent_type;
7185       int use_partial_inst_tmpl = false;
7186 
7187       if (template_type == error_mark_node)
7188 	/* An error occured while building the template TEMPL, and a
7189 	   diagnostic has most certainly been emitted for that
7190 	   already.  Let's propagate that error.  */
7191 	return error_mark_node;
7192 
7193       gen_tmpl = most_general_template (templ);
7194       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
7195       parm_depth = TMPL_PARMS_DEPTH (parmlist);
7196       arg_depth = TMPL_ARGS_DEPTH (arglist);
7197 
7198       if (arg_depth == 1 && parm_depth > 1)
7199 	{
7200 	  /* We've been given an incomplete set of template arguments.
7201 	     For example, given:
7202 
7203 	       template <class T> struct S1 {
7204 		 template <class U> struct S2 {};
7205 		 template <class U> struct S2<U*> {};
7206 		};
7207 
7208 	     we will be called with an ARGLIST of `U*', but the
7209 	     TEMPLATE will be `template <class T> template
7210 	     <class U> struct S1<T>::S2'.  We must fill in the missing
7211 	     arguments.  */
7212 	  arglist
7213 	    = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
7214 					   arglist);
7215 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
7216 	}
7217 
7218       /* Now we should have enough arguments.  */
7219       gcc_assert (parm_depth == arg_depth);
7220 
7221       /* From here on, we're only interested in the most general
7222 	 template.  */
7223 
7224       /* Calculate the BOUND_ARGS.  These will be the args that are
7225 	 actually tsubst'd into the definition to create the
7226 	 instantiation.  */
7227       if (parm_depth > 1)
7228 	{
7229 	  /* We have multiple levels of arguments to coerce, at once.  */
7230 	  int i;
7231 	  int saved_depth = TMPL_ARGS_DEPTH (arglist);
7232 
7233 	  tree bound_args = make_tree_vec (parm_depth);
7234 
7235 	  for (i = saved_depth,
7236 		 t = DECL_TEMPLATE_PARMS (gen_tmpl);
7237 	       i > 0 && t != NULL_TREE;
7238 	       --i, t = TREE_CHAIN (t))
7239 	    {
7240 	      tree a;
7241 	      if (i == saved_depth)
7242 		a = coerce_template_parms (TREE_VALUE (t),
7243 					   arglist, gen_tmpl,
7244 					   complain,
7245 					   /*require_all_args=*/true,
7246 					   /*use_default_args=*/true);
7247 	      else
7248 		/* Outer levels should have already been coerced.  */
7249 		a = TMPL_ARGS_LEVEL (arglist, i);
7250 
7251 	      /* Don't process further if one of the levels fails.  */
7252 	      if (a == error_mark_node)
7253 		{
7254 		  /* Restore the ARGLIST to its full size.  */
7255 		  TREE_VEC_LENGTH (arglist) = saved_depth;
7256 		  return error_mark_node;
7257 		}
7258 
7259 	      SET_TMPL_ARGS_LEVEL (bound_args, i, a);
7260 
7261 	      /* We temporarily reduce the length of the ARGLIST so
7262 		 that coerce_template_parms will see only the arguments
7263 		 corresponding to the template parameters it is
7264 		 examining.  */
7265 	      TREE_VEC_LENGTH (arglist)--;
7266 	    }
7267 
7268 	  /* Restore the ARGLIST to its full size.  */
7269 	  TREE_VEC_LENGTH (arglist) = saved_depth;
7270 
7271 	  arglist = bound_args;
7272 	}
7273       else
7274 	arglist
7275 	  = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
7276 				   INNERMOST_TEMPLATE_ARGS (arglist),
7277 				   gen_tmpl,
7278 				   complain,
7279 				   /*require_all_args=*/true,
7280 				   /*use_default_args=*/true);
7281 
7282       if (arglist == error_mark_node)
7283 	/* We were unable to bind the arguments.  */
7284 	return error_mark_node;
7285 
7286       /* In the scope of a template class, explicit references to the
7287 	 template class refer to the type of the template, not any
7288 	 instantiation of it.  For example, in:
7289 
7290 	   template <class T> class C { void f(C<T>); }
7291 
7292 	 the `C<T>' is just the same as `C'.  Outside of the
7293 	 class, however, such a reference is an instantiation.  */
7294       if ((entering_scope
7295 	   || !PRIMARY_TEMPLATE_P (gen_tmpl)
7296 	   || currently_open_class (template_type))
7297 	  /* comp_template_args is expensive, check it last.  */
7298 	  && comp_template_args (TYPE_TI_ARGS (template_type),
7299 				 arglist))
7300 	return template_type;
7301 
7302       /* If we already have this specialization, return it.  */
7303       elt.tmpl = gen_tmpl;
7304       elt.args = arglist;
7305       hash = hash_specialization (&elt);
7306       entry = (spec_entry *) htab_find_with_hash (type_specializations,
7307 						  &elt, hash);
7308 
7309       if (entry)
7310 	return entry->spec;
7311 
7312       is_dependent_type = uses_template_parms (arglist);
7313 
7314       /* If the deduced arguments are invalid, then the binding
7315 	 failed.  */
7316       if (!is_dependent_type
7317 	  && check_instantiated_args (gen_tmpl,
7318 				      INNERMOST_TEMPLATE_ARGS (arglist),
7319 				      complain))
7320 	return error_mark_node;
7321 
7322       if (!is_dependent_type
7323 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
7324 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
7325 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
7326 	{
7327 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
7328 				      DECL_NAME (gen_tmpl),
7329 				      /*tag_scope=*/ts_global);
7330 	  return found;
7331 	}
7332 
7333       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
7334 			complain, in_decl);
7335       if (context == error_mark_node)
7336 	return error_mark_node;
7337 
7338       if (!context)
7339 	context = global_namespace;
7340 
7341       /* Create the type.  */
7342       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
7343 	{
7344 	  if (!is_dependent_type)
7345 	    {
7346 	      set_current_access_from_decl (TYPE_NAME (template_type));
7347 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
7348 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
7349 				      arglist, complain, in_decl),
7350 			      SCOPED_ENUM_P (template_type), NULL);
7351 	    }
7352 	  else
7353             {
7354               /* We don't want to call start_enum for this type, since
7355                  the values for the enumeration constants may involve
7356                  template parameters.  And, no one should be interested
7357                  in the enumeration constants for such a type.  */
7358               t = cxx_make_type (ENUMERAL_TYPE);
7359               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
7360             }
7361           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
7362 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
7363 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
7364 	}
7365       else if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
7366 	{
7367 	  /* The user referred to a specialization of an alias
7368 	    template represented by GEN_TMPL.
7369 
7370 	    [temp.alias]/2 says:
7371 
7372 	        When a template-id refers to the specialization of an
7373 		alias template, it is equivalent to the associated
7374 		type obtained by substitution of its
7375 		template-arguments for the template-parameters in the
7376 		type-id of the alias template.  */
7377 
7378 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
7379 	  /* Note that the call above (by indirectly calling
7380 	     register_specialization in tsubst_decl) registers the
7381 	     TYPE_DECL representing the specialization of the alias
7382 	     template.  So next time someone substitutes ARGLIST for
7383 	     the template parms into the alias template (GEN_TMPL),
7384 	     she'll get that TYPE_DECL back.  */
7385 
7386 	  if (t == error_mark_node)
7387 	    return t;
7388 	}
7389       else if (CLASS_TYPE_P (template_type))
7390 	{
7391 	  t = make_class_type (TREE_CODE (template_type));
7392 	  CLASSTYPE_DECLARED_CLASS (t)
7393 	    = CLASSTYPE_DECLARED_CLASS (template_type);
7394 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7395 	  TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7396 
7397 	  /* A local class.  Make sure the decl gets registered properly.  */
7398 	  if (context == current_function_decl)
7399 	    pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7400 
7401 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7402 	    /* This instantiation is another name for the primary
7403 	       template type. Set the TYPE_CANONICAL field
7404 	       appropriately. */
7405 	    TYPE_CANONICAL (t) = template_type;
7406 	  else if (any_template_arguments_need_structural_equality_p (arglist))
7407 	    /* Some of the template arguments require structural
7408 	       equality testing, so this template class requires
7409 	       structural equality testing. */
7410 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
7411 	}
7412       else
7413 	gcc_unreachable ();
7414 
7415       /* If we called start_enum or pushtag above, this information
7416 	 will already be set up.  */
7417       if (!TYPE_NAME (t))
7418 	{
7419 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7420 
7421 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7422 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7423 	  DECL_SOURCE_LOCATION (type_decl)
7424 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7425 	}
7426       else
7427 	type_decl = TYPE_NAME (t);
7428 
7429       if (CLASS_TYPE_P (template_type))
7430 	{
7431 	  TREE_PRIVATE (type_decl)
7432 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
7433 	  TREE_PROTECTED (type_decl)
7434 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
7435 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7436 	    {
7437 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7438 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7439 	    }
7440 	}
7441 
7442       /* Let's consider the explicit specialization of a member
7443          of a class template specialization that is implicitely instantiated,
7444 	 e.g.:
7445 	     template<class T>
7446 	     struct S
7447 	     {
7448 	       template<class U> struct M {}; //#0
7449 	     };
7450 
7451 	     template<>
7452 	     template<>
7453 	     struct S<int>::M<char> //#1
7454 	     {
7455 	       int i;
7456 	     };
7457 	[temp.expl.spec]/4 says this is valid.
7458 
7459 	In this case, when we write:
7460 	S<int>::M<char> m;
7461 
7462 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7463 	the one of #0.
7464 
7465 	When we encounter #1, we want to store the partial instantiation
7466 	of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7467 
7468 	For all cases other than this "explicit specialization of member of a
7469 	class template", we just want to store the most general template into
7470 	the CLASSTYPE_TI_TEMPLATE of M.
7471 
7472 	This case of "explicit specialization of member of a class template"
7473 	only happens when:
7474 	1/ the enclosing class is an instantiation of, and therefore not
7475 	the same as, the context of the most general template, and
7476 	2/ we aren't looking at the partial instantiation itself, i.e.
7477 	the innermost arguments are not the same as the innermost parms of
7478 	the most general template.
7479 
7480 	So it's only when 1/ and 2/ happens that we want to use the partial
7481 	instantiation of the member template in lieu of its most general
7482 	template.  */
7483 
7484       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7485 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7486 	  /* the enclosing class must be an instantiation...  */
7487 	  && CLASS_TYPE_P (context)
7488 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7489 	{
7490 	  tree partial_inst_args;
7491 	  TREE_VEC_LENGTH (arglist)--;
7492 	  ++processing_template_decl;
7493 	  partial_inst_args =
7494 	    tsubst (INNERMOST_TEMPLATE_ARGS
7495 			(TYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7496 		    arglist, complain, NULL_TREE);
7497 	  --processing_template_decl;
7498 	  TREE_VEC_LENGTH (arglist)++;
7499 	  use_partial_inst_tmpl =
7500 	    /*...and we must not be looking at the partial instantiation
7501 	     itself. */
7502 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7503 				 partial_inst_args);
7504 	}
7505 
7506       if (!use_partial_inst_tmpl)
7507 	/* This case is easy; there are no member templates involved.  */
7508 	found = gen_tmpl;
7509       else
7510 	{
7511 	  /* This is a full instantiation of a member template.  Find
7512 	     the partial instantiation of which this is an instance.  */
7513 
7514 	  /* Temporarily reduce by one the number of levels in the ARGLIST
7515 	     so as to avoid comparing the last set of arguments.  */
7516 	  TREE_VEC_LENGTH (arglist)--;
7517 	  found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7518 	  TREE_VEC_LENGTH (arglist)++;
7519 	  /* FOUND is either a proper class type, or an alias
7520 	     template specialization.  In the later case, it's a
7521 	     TYPE_DECL, resulting from the substituting of arguments
7522 	     for parameters in the TYPE_DECL of the alias template
7523 	     done earlier.  So be careful while getting the template
7524 	     of FOUND.  */
7525 	  found = TREE_CODE (found) == TYPE_DECL
7526 	    ? TYPE_TI_TEMPLATE (TREE_TYPE (found))
7527 	    : CLASSTYPE_TI_TEMPLATE (found);
7528 	}
7529 
7530       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7531 
7532       elt.spec = t;
7533       slot = htab_find_slot_with_hash (type_specializations,
7534 				       &elt, hash, INSERT);
7535       entry = ggc_alloc_spec_entry ();
7536       *entry = elt;
7537       *slot = entry;
7538 
7539       /* Note this use of the partial instantiation so we can check it
7540 	 later in maybe_process_partial_specialization.  */
7541       DECL_TEMPLATE_INSTANTIATIONS (templ)
7542 	= tree_cons (arglist, t,
7543 		     DECL_TEMPLATE_INSTANTIATIONS (templ));
7544 
7545       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type)
7546 	/* Now that the type has been registered on the instantiations
7547 	   list, we set up the enumerators.  Because the enumeration
7548 	   constants may involve the enumeration type itself, we make
7549 	   sure to register the type first, and then create the
7550 	   constants.  That way, doing tsubst_expr for the enumeration
7551 	   constants won't result in recursive calls here; we'll find
7552 	   the instantiation and exit above.  */
7553 	tsubst_enum (template_type, t, arglist);
7554 
7555       if (CLASS_TYPE_P (template_type) && is_dependent_type)
7556 	/* If the type makes use of template parameters, the
7557 	   code that generates debugging information will crash.  */
7558 	DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7559 
7560       /* Possibly limit visibility based on template args.  */
7561       TREE_PUBLIC (type_decl) = 1;
7562       determine_visibility (type_decl);
7563 
7564       return t;
7565     }
7566 }
7567 
7568 /* Wrapper for lookup_template_class_1.  */
7569 
7570 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)7571 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
7572                        int entering_scope, tsubst_flags_t complain)
7573 {
7574   tree ret;
7575   timevar_push (TV_TEMPLATE_INST);
7576   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
7577                                  entering_scope, complain);
7578   timevar_pop (TV_TEMPLATE_INST);
7579   return ret;
7580 }
7581 
7582 struct pair_fn_data
7583 {
7584   tree_fn_t fn;
7585   void *data;
7586   /* True when we should also visit template parameters that occur in
7587      non-deduced contexts.  */
7588   bool include_nondeduced_p;
7589   struct pointer_set_t *visited;
7590 };
7591 
7592 /* Called from for_each_template_parm via walk_tree.  */
7593 
7594 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)7595 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7596 {
7597   tree t = *tp;
7598   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7599   tree_fn_t fn = pfd->fn;
7600   void *data = pfd->data;
7601 
7602   if (TYPE_P (t)
7603       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7604       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7605 				 pfd->include_nondeduced_p))
7606     return error_mark_node;
7607 
7608   switch (TREE_CODE (t))
7609     {
7610     case RECORD_TYPE:
7611       if (TYPE_PTRMEMFUNC_P (t))
7612 	break;
7613       /* Fall through.  */
7614 
7615     case UNION_TYPE:
7616     case ENUMERAL_TYPE:
7617       if (!TYPE_TEMPLATE_INFO (t))
7618 	*walk_subtrees = 0;
7619       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7620 				       fn, data, pfd->visited,
7621 				       pfd->include_nondeduced_p))
7622 	return error_mark_node;
7623       break;
7624 
7625     case INTEGER_TYPE:
7626       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7627 				  fn, data, pfd->visited,
7628 				  pfd->include_nondeduced_p)
7629 	  || for_each_template_parm (TYPE_MAX_VALUE (t),
7630 				     fn, data, pfd->visited,
7631 				     pfd->include_nondeduced_p))
7632 	return error_mark_node;
7633       break;
7634 
7635     case METHOD_TYPE:
7636       /* Since we're not going to walk subtrees, we have to do this
7637 	 explicitly here.  */
7638       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7639 				  pfd->visited, pfd->include_nondeduced_p))
7640 	return error_mark_node;
7641       /* Fall through.  */
7642 
7643     case FUNCTION_TYPE:
7644       /* Check the return type.  */
7645       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7646 				  pfd->include_nondeduced_p))
7647 	return error_mark_node;
7648 
7649       /* Check the parameter types.  Since default arguments are not
7650 	 instantiated until they are needed, the TYPE_ARG_TYPES may
7651 	 contain expressions that involve template parameters.  But,
7652 	 no-one should be looking at them yet.  And, once they're
7653 	 instantiated, they don't contain template parameters, so
7654 	 there's no point in looking at them then, either.  */
7655       {
7656 	tree parm;
7657 
7658 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7659 	  if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7660 				      pfd->visited, pfd->include_nondeduced_p))
7661 	    return error_mark_node;
7662 
7663 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
7664 	   want walk_tree walking into them itself.  */
7665 	*walk_subtrees = 0;
7666       }
7667       break;
7668 
7669     case TYPEOF_TYPE:
7670     case UNDERLYING_TYPE:
7671       if (pfd->include_nondeduced_p
7672 	  && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7673 				     pfd->visited,
7674 				     pfd->include_nondeduced_p))
7675 	return error_mark_node;
7676       break;
7677 
7678     case FUNCTION_DECL:
7679     case VAR_DECL:
7680       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7681 	  && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7682 				     pfd->visited, pfd->include_nondeduced_p))
7683 	return error_mark_node;
7684       /* Fall through.  */
7685 
7686     case PARM_DECL:
7687     case CONST_DECL:
7688       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7689 	  && for_each_template_parm (DECL_INITIAL (t), fn, data,
7690 				     pfd->visited, pfd->include_nondeduced_p))
7691 	return error_mark_node;
7692       if (DECL_CONTEXT (t)
7693 	  && pfd->include_nondeduced_p
7694 	  && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7695 				     pfd->visited, pfd->include_nondeduced_p))
7696 	return error_mark_node;
7697       break;
7698 
7699     case BOUND_TEMPLATE_TEMPLATE_PARM:
7700       /* Record template parameters such as `T' inside `TT<T>'.  */
7701       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7702 				  pfd->include_nondeduced_p))
7703 	return error_mark_node;
7704       /* Fall through.  */
7705 
7706     case TEMPLATE_TEMPLATE_PARM:
7707     case TEMPLATE_TYPE_PARM:
7708     case TEMPLATE_PARM_INDEX:
7709       if (fn && (*fn)(t, data))
7710 	return error_mark_node;
7711       else if (!fn)
7712 	return error_mark_node;
7713       break;
7714 
7715     case TEMPLATE_DECL:
7716       /* A template template parameter is encountered.  */
7717       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7718 	  && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7719 				     pfd->include_nondeduced_p))
7720 	return error_mark_node;
7721 
7722       /* Already substituted template template parameter */
7723       *walk_subtrees = 0;
7724       break;
7725 
7726     case TYPENAME_TYPE:
7727       if (!fn
7728 	  || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7729 				     data, pfd->visited,
7730 				     pfd->include_nondeduced_p))
7731 	return error_mark_node;
7732       break;
7733 
7734     case CONSTRUCTOR:
7735       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7736 	  && pfd->include_nondeduced_p
7737 	  && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7738 				     (TREE_TYPE (t)), fn, data,
7739 				     pfd->visited, pfd->include_nondeduced_p))
7740 	return error_mark_node;
7741       break;
7742 
7743     case INDIRECT_REF:
7744     case COMPONENT_REF:
7745       /* If there's no type, then this thing must be some expression
7746 	 involving template parameters.  */
7747       if (!fn && !TREE_TYPE (t))
7748 	return error_mark_node;
7749       break;
7750 
7751     case MODOP_EXPR:
7752     case CAST_EXPR:
7753     case IMPLICIT_CONV_EXPR:
7754     case REINTERPRET_CAST_EXPR:
7755     case CONST_CAST_EXPR:
7756     case STATIC_CAST_EXPR:
7757     case DYNAMIC_CAST_EXPR:
7758     case ARROW_EXPR:
7759     case DOTSTAR_EXPR:
7760     case TYPEID_EXPR:
7761     case PSEUDO_DTOR_EXPR:
7762       if (!fn)
7763 	return error_mark_node;
7764       break;
7765 
7766     default:
7767       break;
7768     }
7769 
7770   /* We didn't find any template parameters we liked.  */
7771   return NULL_TREE;
7772 }
7773 
7774 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7775    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7776    call FN with the parameter and the DATA.
7777    If FN returns nonzero, the iteration is terminated, and
7778    for_each_template_parm returns 1.  Otherwise, the iteration
7779    continues.  If FN never returns a nonzero value, the value
7780    returned by for_each_template_parm is 0.  If FN is NULL, it is
7781    considered to be the function which always returns 1.
7782 
7783    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7784    parameters that occur in non-deduced contexts.  When false, only
7785    visits those template parameters that can be deduced.  */
7786 
7787 static int
for_each_template_parm(tree t,tree_fn_t fn,void * data,struct pointer_set_t * visited,bool include_nondeduced_p)7788 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7789 			struct pointer_set_t *visited,
7790 			bool include_nondeduced_p)
7791 {
7792   struct pair_fn_data pfd;
7793   int result;
7794 
7795   /* Set up.  */
7796   pfd.fn = fn;
7797   pfd.data = data;
7798   pfd.include_nondeduced_p = include_nondeduced_p;
7799 
7800   /* Walk the tree.  (Conceptually, we would like to walk without
7801      duplicates, but for_each_template_parm_r recursively calls
7802      for_each_template_parm, so we would need to reorganize a fair
7803      bit to use walk_tree_without_duplicates, so we keep our own
7804      visited list.)  */
7805   if (visited)
7806     pfd.visited = visited;
7807   else
7808     pfd.visited = pointer_set_create ();
7809   result = cp_walk_tree (&t,
7810 		         for_each_template_parm_r,
7811 		         &pfd,
7812 		         pfd.visited) != NULL_TREE;
7813 
7814   /* Clean up.  */
7815   if (!visited)
7816     {
7817       pointer_set_destroy (pfd.visited);
7818       pfd.visited = 0;
7819     }
7820 
7821   return result;
7822 }
7823 
7824 /* Returns true if T depends on any template parameter.  */
7825 
7826 int
uses_template_parms(tree t)7827 uses_template_parms (tree t)
7828 {
7829   bool dependent_p;
7830   int saved_processing_template_decl;
7831 
7832   saved_processing_template_decl = processing_template_decl;
7833   if (!saved_processing_template_decl)
7834     processing_template_decl = 1;
7835   if (TYPE_P (t))
7836     dependent_p = dependent_type_p (t);
7837   else if (TREE_CODE (t) == TREE_VEC)
7838     dependent_p = any_dependent_template_arguments_p (t);
7839   else if (TREE_CODE (t) == TREE_LIST)
7840     dependent_p = (uses_template_parms (TREE_VALUE (t))
7841 		   || uses_template_parms (TREE_CHAIN (t)));
7842   else if (TREE_CODE (t) == TYPE_DECL)
7843     dependent_p = dependent_type_p (TREE_TYPE (t));
7844   else if (DECL_P (t)
7845 	   || EXPR_P (t)
7846 	   || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7847 	   || TREE_CODE (t) == OVERLOAD
7848 	   || BASELINK_P (t)
7849 	   || TREE_CODE (t) == IDENTIFIER_NODE
7850 	   || TREE_CODE (t) == TRAIT_EXPR
7851 	   || TREE_CODE (t) == CONSTRUCTOR
7852 	   || CONSTANT_CLASS_P (t))
7853     dependent_p = (type_dependent_expression_p (t)
7854 		   || value_dependent_expression_p (t));
7855   else
7856     {
7857       gcc_assert (t == error_mark_node);
7858       dependent_p = false;
7859     }
7860 
7861   processing_template_decl = saved_processing_template_decl;
7862 
7863   return dependent_p;
7864 }
7865 
7866 /* Returns true iff current_function_decl is an incompletely instantiated
7867    template.  Useful instead of processing_template_decl because the latter
7868    is set to 0 during fold_non_dependent_expr.  */
7869 
7870 bool
in_template_function(void)7871 in_template_function (void)
7872 {
7873   tree fn = current_function_decl;
7874   bool ret;
7875   ++processing_template_decl;
7876   ret = (fn && DECL_LANG_SPECIFIC (fn)
7877 	 && DECL_TEMPLATE_INFO (fn)
7878 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
7879   --processing_template_decl;
7880   return ret;
7881 }
7882 
7883 /* Returns true if T depends on any template parameter with level LEVEL.  */
7884 
7885 int
uses_template_parms_level(tree t,int level)7886 uses_template_parms_level (tree t, int level)
7887 {
7888   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7889 				 /*include_nondeduced_p=*/true);
7890 }
7891 
7892 /* Returns TRUE iff INST is an instantiation we don't need to do in an
7893    ill-formed translation unit, i.e. a variable or function that isn't
7894    usable in a constant expression.  */
7895 
7896 static inline bool
neglectable_inst_p(tree d)7897 neglectable_inst_p (tree d)
7898 {
7899   return (DECL_P (d)
7900 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
7901 	       : decl_maybe_constant_var_p (d)));
7902 }
7903 
7904 /* Returns TRUE iff we should refuse to instantiate DECL because it's
7905    neglectable and instantiated from within an erroneous instantiation.  */
7906 
7907 static bool
limit_bad_template_recursion(tree decl)7908 limit_bad_template_recursion (tree decl)
7909 {
7910   struct tinst_level *lev = current_tinst_level;
7911   int errs = errorcount + sorrycount;
7912   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
7913     return false;
7914 
7915   for (; lev; lev = lev->next)
7916     if (neglectable_inst_p (lev->decl))
7917       break;
7918 
7919   return (lev && errs > lev->errors);
7920 }
7921 
7922 static int tinst_depth;
7923 extern int max_tinst_depth;
7924 int depth_reached;
7925 
7926 static GTY(()) struct tinst_level *last_error_tinst_level;
7927 
7928 /* We're starting to instantiate D; record the template instantiation context
7929    for diagnostics and to restore it later.  */
7930 
7931 int
push_tinst_level(tree d)7932 push_tinst_level (tree d)
7933 {
7934   struct tinst_level *new_level;
7935 
7936   if (tinst_depth >= max_tinst_depth)
7937     {
7938       last_error_tinst_level = current_tinst_level;
7939       if (TREE_CODE (d) == TREE_LIST)
7940 	error ("template instantiation depth exceeds maximum of %d (use "
7941 	       "-ftemplate-depth= to increase the maximum) substituting %qS",
7942 	       max_tinst_depth, d);
7943       else
7944 	error ("template instantiation depth exceeds maximum of %d (use "
7945 	       "-ftemplate-depth= to increase the maximum) instantiating %qD",
7946 	       max_tinst_depth, d);
7947 
7948       print_instantiation_context ();
7949 
7950       return 0;
7951     }
7952 
7953   /* If the current instantiation caused problems, don't let it instantiate
7954      anything else.  Do allow deduction substitution and decls usable in
7955      constant expressions.  */
7956   if (limit_bad_template_recursion (d))
7957     return 0;
7958 
7959   new_level = ggc_alloc_tinst_level ();
7960   new_level->decl = d;
7961   new_level->locus = input_location;
7962   new_level->errors = errorcount+sorrycount;
7963   new_level->in_system_header_p = in_system_header;
7964   new_level->next = current_tinst_level;
7965   current_tinst_level = new_level;
7966 
7967   ++tinst_depth;
7968   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
7969     depth_reached = tinst_depth;
7970 
7971   return 1;
7972 }
7973 
7974 /* We're done instantiating this template; return to the instantiation
7975    context.  */
7976 
7977 void
pop_tinst_level(void)7978 pop_tinst_level (void)
7979 {
7980   /* Restore the filename and line number stashed away when we started
7981      this instantiation.  */
7982   input_location = current_tinst_level->locus;
7983   current_tinst_level = current_tinst_level->next;
7984   --tinst_depth;
7985 }
7986 
7987 /* We're instantiating a deferred template; restore the template
7988    instantiation context in which the instantiation was requested, which
7989    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7990 
7991 static tree
reopen_tinst_level(struct tinst_level * level)7992 reopen_tinst_level (struct tinst_level *level)
7993 {
7994   struct tinst_level *t;
7995 
7996   tinst_depth = 0;
7997   for (t = level; t; t = t->next)
7998     ++tinst_depth;
7999 
8000   current_tinst_level = level;
8001   pop_tinst_level ();
8002   if (current_tinst_level)
8003     current_tinst_level->errors = errorcount+sorrycount;
8004   return level->decl;
8005 }
8006 
8007 /* Returns the TINST_LEVEL which gives the original instantiation
8008    context.  */
8009 
8010 struct tinst_level *
outermost_tinst_level(void)8011 outermost_tinst_level (void)
8012 {
8013   struct tinst_level *level = current_tinst_level;
8014   if (level)
8015     while (level->next)
8016       level = level->next;
8017   return level;
8018 }
8019 
8020 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
8021    vector of template arguments, as for tsubst.
8022 
8023    Returns an appropriate tsubst'd friend declaration.  */
8024 
8025 static tree
tsubst_friend_function(tree decl,tree args)8026 tsubst_friend_function (tree decl, tree args)
8027 {
8028   tree new_friend;
8029 
8030   if (TREE_CODE (decl) == FUNCTION_DECL
8031       && DECL_TEMPLATE_INSTANTIATION (decl)
8032       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
8033     /* This was a friend declared with an explicit template
8034        argument list, e.g.:
8035 
8036        friend void f<>(T);
8037 
8038        to indicate that f was a template instantiation, not a new
8039        function declaration.  Now, we have to figure out what
8040        instantiation of what template.  */
8041     {
8042       tree template_id, arglist, fns;
8043       tree new_args;
8044       tree tmpl;
8045       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
8046 
8047       /* Friend functions are looked up in the containing namespace scope.
8048 	 We must enter that scope, to avoid finding member functions of the
8049 	 current class with same name.  */
8050       push_nested_namespace (ns);
8051       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
8052 			 tf_warning_or_error, NULL_TREE,
8053 			 /*integral_constant_expression_p=*/false);
8054       pop_nested_namespace (ns);
8055       arglist = tsubst (DECL_TI_ARGS (decl), args,
8056 			tf_warning_or_error, NULL_TREE);
8057       template_id = lookup_template_function (fns, arglist);
8058 
8059       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8060       tmpl = determine_specialization (template_id, new_friend,
8061 				       &new_args,
8062 				       /*need_member_template=*/0,
8063 				       TREE_VEC_LENGTH (args),
8064 				       tsk_none);
8065       return instantiate_template (tmpl, new_args, tf_error);
8066     }
8067 
8068   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
8069 
8070   /* The NEW_FRIEND will look like an instantiation, to the
8071      compiler, but is not an instantiation from the point of view of
8072      the language.  For example, we might have had:
8073 
8074      template <class T> struct S {
8075        template <class U> friend void f(T, U);
8076      };
8077 
8078      Then, in S<int>, template <class U> void f(int, U) is not an
8079      instantiation of anything.  */
8080   if (new_friend == error_mark_node)
8081     return error_mark_node;
8082 
8083   DECL_USE_TEMPLATE (new_friend) = 0;
8084   if (TREE_CODE (decl) == TEMPLATE_DECL)
8085     {
8086       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
8087       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
8088 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
8089     }
8090 
8091   /* The mangled name for the NEW_FRIEND is incorrect.  The function
8092      is not a template instantiation and should not be mangled like
8093      one.  Therefore, we forget the mangling here; we'll recompute it
8094      later if we need it.  */
8095   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
8096     {
8097       SET_DECL_RTL (new_friend, NULL);
8098       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
8099     }
8100 
8101   if (DECL_NAMESPACE_SCOPE_P (new_friend))
8102     {
8103       tree old_decl;
8104       tree new_friend_template_info;
8105       tree new_friend_result_template_info;
8106       tree ns;
8107       int  new_friend_is_defn;
8108 
8109       /* We must save some information from NEW_FRIEND before calling
8110 	 duplicate decls since that function will free NEW_FRIEND if
8111 	 possible.  */
8112       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
8113       new_friend_is_defn =
8114 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
8115 			   (template_for_substitution (new_friend)))
8116 	     != NULL_TREE);
8117       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
8118 	{
8119 	  /* This declaration is a `primary' template.  */
8120 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
8121 
8122 	  new_friend_result_template_info
8123 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
8124 	}
8125       else
8126 	new_friend_result_template_info = NULL_TREE;
8127 
8128       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
8129       if (new_friend_is_defn)
8130 	DECL_INITIAL (new_friend) = error_mark_node;
8131 
8132       /* Inside pushdecl_namespace_level, we will push into the
8133 	 current namespace. However, the friend function should go
8134 	 into the namespace of the template.  */
8135       ns = decl_namespace_context (new_friend);
8136       push_nested_namespace (ns);
8137       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
8138       pop_nested_namespace (ns);
8139 
8140       if (old_decl == error_mark_node)
8141 	return error_mark_node;
8142 
8143       if (old_decl != new_friend)
8144 	{
8145 	  /* This new friend declaration matched an existing
8146 	     declaration.  For example, given:
8147 
8148 	       template <class T> void f(T);
8149 	       template <class U> class C {
8150 		 template <class T> friend void f(T) {}
8151 	       };
8152 
8153 	     the friend declaration actually provides the definition
8154 	     of `f', once C has been instantiated for some type.  So,
8155 	     old_decl will be the out-of-class template declaration,
8156 	     while new_friend is the in-class definition.
8157 
8158 	     But, if `f' was called before this point, the
8159 	     instantiation of `f' will have DECL_TI_ARGS corresponding
8160 	     to `T' but not to `U', references to which might appear
8161 	     in the definition of `f'.  Previously, the most general
8162 	     template for an instantiation of `f' was the out-of-class
8163 	     version; now it is the in-class version.  Therefore, we
8164 	     run through all specialization of `f', adding to their
8165 	     DECL_TI_ARGS appropriately.  In particular, they need a
8166 	     new set of outer arguments, corresponding to the
8167 	     arguments for this class instantiation.
8168 
8169 	     The same situation can arise with something like this:
8170 
8171 	       friend void f(int);
8172 	       template <class T> class C {
8173 		 friend void f(T) {}
8174 	       };
8175 
8176 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
8177 	     in the class.  */
8178 
8179 	  if (!new_friend_is_defn)
8180 	    /* On the other hand, if the in-class declaration does
8181 	       *not* provide a definition, then we don't want to alter
8182 	       existing definitions.  We can just leave everything
8183 	       alone.  */
8184 	    ;
8185 	  else
8186 	    {
8187 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
8188 	      tree new_args = TI_ARGS (new_friend_template_info);
8189 
8190 	      /* Overwrite whatever template info was there before, if
8191 		 any, with the new template information pertaining to
8192 		 the declaration.  */
8193 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
8194 
8195 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
8196 		{
8197 		  /* We should have called reregister_specialization in
8198 		     duplicate_decls.  */
8199 		  gcc_assert (retrieve_specialization (new_template,
8200 						       new_args, 0)
8201 			      == old_decl);
8202 
8203 		  /* Instantiate it if the global has already been used.  */
8204 		  if (DECL_ODR_USED (old_decl))
8205 		    instantiate_decl (old_decl, /*defer_ok=*/true,
8206 				      /*expl_inst_class_mem_p=*/false);
8207 		}
8208 	      else
8209 		{
8210 		  tree t;
8211 
8212 		  /* Indicate that the old function template is a partial
8213 		     instantiation.  */
8214 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
8215 		    = new_friend_result_template_info;
8216 
8217 		  gcc_assert (new_template
8218 			      == most_general_template (new_template));
8219 		  gcc_assert (new_template != old_decl);
8220 
8221 		  /* Reassign any specializations already in the hash table
8222 		     to the new more general template, and add the
8223 		     additional template args.  */
8224 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
8225 		       t != NULL_TREE;
8226 		       t = TREE_CHAIN (t))
8227 		    {
8228 		      tree spec = TREE_VALUE (t);
8229 		      spec_entry elt;
8230 
8231 		      elt.tmpl = old_decl;
8232 		      elt.args = DECL_TI_ARGS (spec);
8233 		      elt.spec = NULL_TREE;
8234 
8235 		      htab_remove_elt (decl_specializations, &elt);
8236 
8237 		      DECL_TI_ARGS (spec)
8238 			= add_outermost_template_args (new_args,
8239 						       DECL_TI_ARGS (spec));
8240 
8241 		      register_specialization
8242 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
8243 
8244 		    }
8245 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
8246 		}
8247 	    }
8248 
8249 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
8250 	     by duplicate_decls.  */
8251 	  new_friend = old_decl;
8252 	}
8253     }
8254   else
8255     {
8256       tree context = DECL_CONTEXT (new_friend);
8257       bool dependent_p;
8258 
8259       /* In the code
8260 	   template <class T> class C {
8261 	     template <class U> friend void C1<U>::f (); // case 1
8262 	     friend void C2<T>::f ();			 // case 2
8263 	   };
8264 	 we only need to make sure CONTEXT is a complete type for
8265 	 case 2.  To distinguish between the two cases, we note that
8266 	 CONTEXT of case 1 remains dependent type after tsubst while
8267 	 this isn't true for case 2.  */
8268       ++processing_template_decl;
8269       dependent_p = dependent_type_p (context);
8270       --processing_template_decl;
8271 
8272       if (!dependent_p
8273 	  && !complete_type_or_else (context, NULL_TREE))
8274 	return error_mark_node;
8275 
8276       if (COMPLETE_TYPE_P (context))
8277 	{
8278 	  /* Check to see that the declaration is really present, and,
8279 	     possibly obtain an improved declaration.  */
8280 	  tree fn = check_classfn (context,
8281 				   new_friend, NULL_TREE);
8282 
8283 	  if (fn)
8284 	    new_friend = fn;
8285 	}
8286     }
8287 
8288   return new_friend;
8289 }
8290 
8291 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
8292    template arguments, as for tsubst.
8293 
8294    Returns an appropriate tsubst'd friend type or error_mark_node on
8295    failure.  */
8296 
8297 static tree
tsubst_friend_class(tree friend_tmpl,tree args)8298 tsubst_friend_class (tree friend_tmpl, tree args)
8299 {
8300   tree friend_type;
8301   tree tmpl;
8302   tree context;
8303 
8304   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
8305     {
8306       tree t = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
8307       return TREE_TYPE (t);
8308     }
8309 
8310   context = CP_DECL_CONTEXT (friend_tmpl);
8311 
8312   if (context != global_namespace)
8313     {
8314       if (TREE_CODE (context) == NAMESPACE_DECL)
8315 	push_nested_namespace (context);
8316       else
8317 	push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
8318     }
8319 
8320   /* Look for a class template declaration.  We look for hidden names
8321      because two friend declarations of the same template are the
8322      same.  For example, in:
8323 
8324        struct A {
8325          template <typename> friend class F;
8326        };
8327        template <typename> struct B {
8328          template <typename> friend class F;
8329        };
8330 
8331      both F templates are the same.  */
8332   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
8333 			   /*block_p=*/true, 0, LOOKUP_HIDDEN);
8334 
8335   /* But, if we don't find one, it might be because we're in a
8336      situation like this:
8337 
8338        template <class T>
8339        struct S {
8340 	 template <class U>
8341 	 friend struct S;
8342        };
8343 
8344      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
8345      for `S<int>', not the TEMPLATE_DECL.  */
8346   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
8347     {
8348       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
8349       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
8350     }
8351 
8352   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
8353     {
8354       /* The friend template has already been declared.  Just
8355 	 check to see that the declarations match, and install any new
8356 	 default parameters.  We must tsubst the default parameters,
8357 	 of course.  We only need the innermost template parameters
8358 	 because that is all that redeclare_class_template will look
8359 	 at.  */
8360       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
8361 	  > TMPL_ARGS_DEPTH (args))
8362 	{
8363 	  tree parms;
8364           location_t saved_input_location;
8365 	  parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
8366 					 args, tf_warning_or_error);
8367 
8368           saved_input_location = input_location;
8369           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
8370 	  redeclare_class_template (TREE_TYPE (tmpl), parms);
8371           input_location = saved_input_location;
8372 
8373 	}
8374 
8375       friend_type = TREE_TYPE (tmpl);
8376     }
8377   else
8378     {
8379       /* The friend template has not already been declared.  In this
8380 	 case, the instantiation of the template class will cause the
8381 	 injection of this template into the global scope.  */
8382       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
8383       if (tmpl == error_mark_node)
8384 	return error_mark_node;
8385 
8386       /* The new TMPL is not an instantiation of anything, so we
8387 	 forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
8388 	 the new type because that is supposed to be the corresponding
8389 	 template decl, i.e., TMPL.  */
8390       DECL_USE_TEMPLATE (tmpl) = 0;
8391       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
8392       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
8393       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
8394 	= INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
8395 
8396       /* Inject this template into the global scope.  */
8397       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
8398     }
8399 
8400   if (context != global_namespace)
8401     {
8402       if (TREE_CODE (context) == NAMESPACE_DECL)
8403 	pop_nested_namespace (context);
8404       else
8405 	pop_nested_class ();
8406     }
8407 
8408   return friend_type;
8409 }
8410 
8411 /* Returns zero if TYPE cannot be completed later due to circularity.
8412    Otherwise returns one.  */
8413 
8414 static int
can_complete_type_without_circularity(tree type)8415 can_complete_type_without_circularity (tree type)
8416 {
8417   if (type == NULL_TREE || type == error_mark_node)
8418     return 0;
8419   else if (COMPLETE_TYPE_P (type))
8420     return 1;
8421   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
8422     return can_complete_type_without_circularity (TREE_TYPE (type));
8423   else if (CLASS_TYPE_P (type)
8424 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
8425     return 0;
8426   else
8427     return 1;
8428 }
8429 
8430 /* Apply any attributes which had to be deferred until instantiation
8431    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
8432    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
8433 
8434 static void
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)8435 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
8436 				tree args, tsubst_flags_t complain, tree in_decl)
8437 {
8438   tree last_dep = NULL_TREE;
8439   tree t;
8440   tree *p;
8441 
8442   for (t = attributes; t; t = TREE_CHAIN (t))
8443     if (ATTR_IS_DEPENDENT (t))
8444       {
8445 	last_dep = t;
8446 	attributes = copy_list (attributes);
8447 	break;
8448       }
8449 
8450   if (DECL_P (*decl_p))
8451     {
8452       if (TREE_TYPE (*decl_p) == error_mark_node)
8453 	return;
8454       p = &DECL_ATTRIBUTES (*decl_p);
8455     }
8456   else
8457     p = &TYPE_ATTRIBUTES (*decl_p);
8458 
8459   if (last_dep)
8460     {
8461       tree late_attrs = NULL_TREE;
8462       tree *q = &late_attrs;
8463 
8464       for (*p = attributes; *p; )
8465 	{
8466 	  t = *p;
8467 	  if (ATTR_IS_DEPENDENT (t))
8468 	    {
8469 	      *p = TREE_CHAIN (t);
8470 	      TREE_CHAIN (t) = NULL_TREE;
8471 	      /* If the first attribute argument is an identifier, don't
8472 		 pass it through tsubst.  Attributes like mode, format,
8473 		 cleanup and several target specific attributes expect it
8474 		 unmodified.  */
8475 	      if (TREE_VALUE (t)
8476 		  && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8477 		  && TREE_VALUE (TREE_VALUE (t))
8478 		  && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8479 		      == IDENTIFIER_NODE))
8480 		{
8481 		  tree chain
8482 		    = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8483 				   in_decl,
8484 				   /*integral_constant_expression_p=*/false);
8485 		  if (chain != TREE_CHAIN (TREE_VALUE (t)))
8486 		    TREE_VALUE (t)
8487 		      = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8488 				   chain);
8489 		}
8490 	      else
8491 		TREE_VALUE (t)
8492 		  = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8493 				 /*integral_constant_expression_p=*/false);
8494 	      *q = t;
8495 	      q = &TREE_CHAIN (t);
8496 	    }
8497 	  else
8498 	    p = &TREE_CHAIN (t);
8499 	}
8500 
8501       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8502     }
8503 }
8504 
8505 /* Perform (or defer) access check for typedefs that were referenced
8506    from within the template TMPL code.
8507    This is a subroutine of instantiate_decl and instantiate_class_template.
8508    TMPL is the template to consider and TARGS is the list of arguments of
8509    that template.  */
8510 
8511 static void
perform_typedefs_access_check(tree tmpl,tree targs)8512 perform_typedefs_access_check (tree tmpl, tree targs)
8513 {
8514   location_t saved_location;
8515   unsigned i;
8516   qualified_typedef_usage_t *iter;
8517 
8518   if (!tmpl
8519       || (!CLASS_TYPE_P (tmpl)
8520 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
8521     return;
8522 
8523   saved_location = input_location;
8524   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
8525     {
8526       tree type_decl = iter->typedef_decl;
8527       tree type_scope = iter->context;
8528 
8529       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8530 	continue;
8531 
8532       if (uses_template_parms (type_decl))
8533 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8534       if (uses_template_parms (type_scope))
8535 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8536 
8537       /* Make access check error messages point to the location
8538          of the use of the typedef.  */
8539       input_location = iter->locus;
8540       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8541 				     type_decl, type_decl,
8542 				     tf_warning_or_error);
8543     }
8544     input_location = saved_location;
8545 }
8546 
8547 static tree
instantiate_class_template_1(tree type)8548 instantiate_class_template_1 (tree type)
8549 {
8550   tree templ, args, pattern, t, member;
8551   tree typedecl;
8552   tree pbinfo;
8553   tree base_list;
8554   unsigned int saved_maximum_field_alignment;
8555   tree fn_context;
8556 
8557   if (type == error_mark_node)
8558     return error_mark_node;
8559 
8560   if (COMPLETE_OR_OPEN_TYPE_P (type)
8561       || uses_template_parms (type))
8562     return type;
8563 
8564   /* Figure out which template is being instantiated.  */
8565   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8566   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8567 
8568   /* Determine what specialization of the original template to
8569      instantiate.  */
8570   t = most_specialized_class (type, templ, tf_warning_or_error);
8571   if (t == error_mark_node)
8572     {
8573       TYPE_BEING_DEFINED (type) = 1;
8574       return error_mark_node;
8575     }
8576   else if (t)
8577     {
8578       /* This TYPE is actually an instantiation of a partial
8579 	 specialization.  We replace the innermost set of ARGS with
8580 	 the arguments appropriate for substitution.  For example,
8581 	 given:
8582 
8583 	   template <class T> struct S {};
8584 	   template <class T> struct S<T*> {};
8585 
8586 	 and supposing that we are instantiating S<int*>, ARGS will
8587 	 presently be {int*} -- but we need {int}.  */
8588       pattern = TREE_TYPE (t);
8589       args = TREE_PURPOSE (t);
8590     }
8591   else
8592     {
8593       pattern = TREE_TYPE (templ);
8594       args = CLASSTYPE_TI_ARGS (type);
8595     }
8596 
8597   /* If the template we're instantiating is incomplete, then clearly
8598      there's nothing we can do.  */
8599   if (!COMPLETE_TYPE_P (pattern))
8600     return type;
8601 
8602   /* If we've recursively instantiated too many templates, stop.  */
8603   if (! push_tinst_level (type))
8604     return type;
8605 
8606   /* Now we're really doing the instantiation.  Mark the type as in
8607      the process of being defined.  */
8608   TYPE_BEING_DEFINED (type) = 1;
8609 
8610   /* We may be in the middle of deferred access check.  Disable
8611      it now.  */
8612   push_deferring_access_checks (dk_no_deferred);
8613 
8614   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
8615   if (!fn_context)
8616     push_to_top_level ();
8617   /* Use #pragma pack from the template context.  */
8618   saved_maximum_field_alignment = maximum_field_alignment;
8619   maximum_field_alignment = TYPE_PRECISION (pattern);
8620 
8621   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8622 
8623   /* Set the input location to the most specialized template definition.
8624      This is needed if tsubsting causes an error.  */
8625   typedecl = TYPE_MAIN_DECL (pattern);
8626   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8627     DECL_SOURCE_LOCATION (typedecl);
8628 
8629   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8630   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8631   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8632   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8633   if (ANON_AGGR_TYPE_P (pattern))
8634     SET_ANON_AGGR_TYPE_P (type);
8635   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8636     {
8637       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8638       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8639       /* Adjust visibility for template arguments.  */
8640       determine_visibility (TYPE_MAIN_DECL (type));
8641     }
8642   CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
8643 
8644   pbinfo = TYPE_BINFO (pattern);
8645 
8646   /* We should never instantiate a nested class before its enclosing
8647      class; we need to look up the nested class by name before we can
8648      instantiate it, and that lookup should instantiate the enclosing
8649      class.  */
8650   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8651 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8652 
8653   base_list = NULL_TREE;
8654   if (BINFO_N_BASE_BINFOS (pbinfo))
8655     {
8656       tree pbase_binfo;
8657       tree pushed_scope;
8658       int i;
8659 
8660       /* We must enter the scope containing the type, as that is where
8661 	 the accessibility of types named in dependent bases are
8662 	 looked up from.  */
8663       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8664 
8665       /* Substitute into each of the bases to determine the actual
8666 	 basetypes.  */
8667       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8668 	{
8669 	  tree base;
8670 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
8671           tree expanded_bases = NULL_TREE;
8672           int idx, len = 1;
8673 
8674           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8675             {
8676               expanded_bases =
8677 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8678 				       args, tf_error, NULL_TREE);
8679               if (expanded_bases == error_mark_node)
8680                 continue;
8681 
8682               len = TREE_VEC_LENGTH (expanded_bases);
8683             }
8684 
8685           for (idx = 0; idx < len; idx++)
8686             {
8687               if (expanded_bases)
8688                 /* Extract the already-expanded base class.  */
8689                 base = TREE_VEC_ELT (expanded_bases, idx);
8690               else
8691                 /* Substitute to figure out the base class.  */
8692                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
8693                                NULL_TREE);
8694 
8695               if (base == error_mark_node)
8696                 continue;
8697 
8698               base_list = tree_cons (access, base, base_list);
8699               if (BINFO_VIRTUAL_P (pbase_binfo))
8700                 TREE_TYPE (base_list) = integer_type_node;
8701             }
8702 	}
8703 
8704       /* The list is now in reverse order; correct that.  */
8705       base_list = nreverse (base_list);
8706 
8707       if (pushed_scope)
8708 	pop_scope (pushed_scope);
8709     }
8710   /* Now call xref_basetypes to set up all the base-class
8711      information.  */
8712   xref_basetypes (type, base_list);
8713 
8714   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8715 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
8716 				  args, tf_error, NULL_TREE);
8717   fixup_attribute_variants (type);
8718 
8719   /* Now that our base classes are set up, enter the scope of the
8720      class, so that name lookups into base classes, etc. will work
8721      correctly.  This is precisely analogous to what we do in
8722      begin_class_definition when defining an ordinary non-template
8723      class, except we also need to push the enclosing classes.  */
8724   push_nested_class (type);
8725 
8726   /* Now members are processed in the order of declaration.  */
8727   for (member = CLASSTYPE_DECL_LIST (pattern);
8728        member; member = TREE_CHAIN (member))
8729     {
8730       tree t = TREE_VALUE (member);
8731 
8732       if (TREE_PURPOSE (member))
8733 	{
8734 	  if (TYPE_P (t))
8735 	    {
8736 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
8737 
8738 	      tree newtag;
8739 	      bool class_template_p;
8740 
8741 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8742 				  && TYPE_LANG_SPECIFIC (t)
8743 				  && CLASSTYPE_IS_TEMPLATE (t));
8744 	      /* If the member is a class template, then -- even after
8745 		 substitution -- there may be dependent types in the
8746 		 template argument list for the class.  We increment
8747 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8748 		 that function will assume that no types are dependent
8749 		 when outside of a template.  */
8750 	      if (class_template_p)
8751 		++processing_template_decl;
8752 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
8753 	      if (class_template_p)
8754 		--processing_template_decl;
8755 	      if (newtag == error_mark_node)
8756 		continue;
8757 
8758 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8759 		{
8760 		  tree name = TYPE_IDENTIFIER (t);
8761 
8762 		  if (class_template_p)
8763 		    /* Unfortunately, lookup_template_class sets
8764 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8765 		       instantiation (i.e., for the type of a member
8766 		       template class nested within a template class.)
8767 		       This behavior is required for
8768 		       maybe_process_partial_specialization to work
8769 		       correctly, but is not accurate in this case;
8770 		       the TAG is not an instantiation of anything.
8771 		       (The corresponding TEMPLATE_DECL is an
8772 		       instantiation, but the TYPE is not.) */
8773 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8774 
8775 		  /* Now, we call pushtag to put this NEWTAG into the scope of
8776 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8777 		     pushtag calling push_template_decl.  We don't have to do
8778 		     this for enums because it will already have been done in
8779 		     tsubst_enum.  */
8780 		  if (name)
8781 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8782 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
8783 		}
8784 	    }
8785 	  else if (TREE_CODE (t) == FUNCTION_DECL
8786 		   || DECL_FUNCTION_TEMPLATE_P (t))
8787 	    {
8788 	      /* Build new TYPE_METHODS.  */
8789 	      tree r;
8790 
8791 	      if (TREE_CODE (t) == TEMPLATE_DECL)
8792 		++processing_template_decl;
8793 	      r = tsubst (t, args, tf_error, NULL_TREE);
8794 	      if (TREE_CODE (t) == TEMPLATE_DECL)
8795 		--processing_template_decl;
8796 	      set_current_access_from_decl (r);
8797 	      finish_member_declaration (r);
8798 	      /* Instantiate members marked with attribute used.  */
8799 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
8800 		mark_used (r);
8801 	    }
8802 	  else
8803 	    {
8804 	      /* Build new TYPE_FIELDS.  */
8805               if (TREE_CODE (t) == STATIC_ASSERT)
8806                 {
8807                   tree condition;
8808 
8809 		  ++c_inhibit_evaluation_warnings;
8810 		  condition =
8811 		    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
8812 				 tf_warning_or_error, NULL_TREE,
8813 				 /*integral_constant_expression_p=*/true);
8814 		  --c_inhibit_evaluation_warnings;
8815 
8816                   finish_static_assert (condition,
8817                                         STATIC_ASSERT_MESSAGE (t),
8818                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8819                                         /*member_p=*/true);
8820                 }
8821 	      else if (TREE_CODE (t) != CONST_DECL)
8822 		{
8823 		  tree r;
8824 
8825 		  /* The file and line for this declaration, to
8826 		     assist in error message reporting.  Since we
8827 		     called push_tinst_level above, we don't need to
8828 		     restore these.  */
8829 		  input_location = DECL_SOURCE_LOCATION (t);
8830 
8831 		  if (TREE_CODE (t) == TEMPLATE_DECL)
8832 		    ++processing_template_decl;
8833 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8834 		  if (TREE_CODE (t) == TEMPLATE_DECL)
8835 		    --processing_template_decl;
8836 		  if (TREE_CODE (r) == VAR_DECL)
8837 		    {
8838 		      /* In [temp.inst]:
8839 
8840 			   [t]he initialization (and any associated
8841 			   side-effects) of a static data member does
8842 			   not occur unless the static data member is
8843 			   itself used in a way that requires the
8844 			   definition of the static data member to
8845 			   exist.
8846 
8847 			 Therefore, we do not substitute into the
8848 			 initialized for the static data member here.  */
8849 		      finish_static_data_member_decl
8850 			(r,
8851 			 /*init=*/NULL_TREE,
8852 			 /*init_const_expr_p=*/false,
8853 			 /*asmspec_tree=*/NULL_TREE,
8854 			 /*flags=*/0);
8855 		      /* Instantiate members marked with attribute used.  */
8856 		      if (r != error_mark_node && DECL_PRESERVE_P (r))
8857 			mark_used (r);
8858 		    }
8859 		  else if (TREE_CODE (r) == FIELD_DECL)
8860 		    {
8861 		      /* Determine whether R has a valid type and can be
8862 			 completed later.  If R is invalid, then it is
8863 			 replaced by error_mark_node so that it will not be
8864 			 added to TYPE_FIELDS.  */
8865 		      tree rtype = TREE_TYPE (r);
8866 		      if (can_complete_type_without_circularity (rtype))
8867 			complete_type (rtype);
8868 
8869 		      if (!COMPLETE_TYPE_P (rtype))
8870 			{
8871 			  cxx_incomplete_type_error (r, rtype);
8872 			  r = error_mark_node;
8873 			}
8874 		    }
8875 
8876 		  /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8877 		     such a thing will already have been added to the field
8878 		     list by tsubst_enum in finish_member_declaration in the
8879 		     CLASSTYPE_NESTED_UTDS case above.  */
8880 		  if (!(TREE_CODE (r) == TYPE_DECL
8881 			&& TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8882 			&& DECL_ARTIFICIAL (r)))
8883 		    {
8884 		      set_current_access_from_decl (r);
8885 		      finish_member_declaration (r);
8886 		    }
8887 		}
8888 	    }
8889 	}
8890       else
8891 	{
8892 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
8893 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8894 	    {
8895 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8896 
8897 	      tree friend_type = t;
8898 	      bool adjust_processing_template_decl = false;
8899 
8900 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8901 		{
8902 		  /* template <class T> friend class C;  */
8903 		  friend_type = tsubst_friend_class (friend_type, args);
8904 		  adjust_processing_template_decl = true;
8905 		}
8906 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8907 		{
8908 		  /* template <class T> friend class C::D;  */
8909 		  friend_type = tsubst (friend_type, args,
8910 					tf_warning_or_error, NULL_TREE);
8911 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8912 		    friend_type = TREE_TYPE (friend_type);
8913 		  adjust_processing_template_decl = true;
8914 		}
8915 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
8916 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
8917 		{
8918 		  /* This could be either
8919 
8920 		       friend class T::C;
8921 
8922 		     when dependent_type_p is false or
8923 
8924 		       template <class U> friend class T::C;
8925 
8926 		     otherwise.  */
8927 		  friend_type = tsubst (friend_type, args,
8928 					tf_warning_or_error, NULL_TREE);
8929 		  /* Bump processing_template_decl for correct
8930 		     dependent_type_p calculation.  */
8931 		  ++processing_template_decl;
8932 		  if (dependent_type_p (friend_type))
8933 		    adjust_processing_template_decl = true;
8934 		  --processing_template_decl;
8935 		}
8936 	      else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8937 		       && hidden_name_p (TYPE_NAME (friend_type)))
8938 		{
8939 		  /* friend class C;
8940 
8941 		     where C hasn't been declared yet.  Let's lookup name
8942 		     from namespace scope directly, bypassing any name that
8943 		     come from dependent base class.  */
8944 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8945 
8946 		  /* The call to xref_tag_from_type does injection for friend
8947 		     classes.  */
8948 		  push_nested_namespace (ns);
8949 		  friend_type =
8950 		    xref_tag_from_type (friend_type, NULL_TREE,
8951 					/*tag_scope=*/ts_current);
8952 		  pop_nested_namespace (ns);
8953 		}
8954 	      else if (uses_template_parms (friend_type))
8955 		/* friend class C<T>;  */
8956 		friend_type = tsubst (friend_type, args,
8957 				      tf_warning_or_error, NULL_TREE);
8958 	      /* Otherwise it's
8959 
8960 		   friend class C;
8961 
8962 		 where C is already declared or
8963 
8964 		   friend class C<int>;
8965 
8966 		 We don't have to do anything in these cases.  */
8967 
8968 	      if (adjust_processing_template_decl)
8969 		/* Trick make_friend_class into realizing that the friend
8970 		   we're adding is a template, not an ordinary class.  It's
8971 		   important that we use make_friend_class since it will
8972 		   perform some error-checking and output cross-reference
8973 		   information.  */
8974 		++processing_template_decl;
8975 
8976 	      if (friend_type != error_mark_node)
8977 		make_friend_class (type, friend_type, /*complain=*/false);
8978 
8979 	      if (adjust_processing_template_decl)
8980 		--processing_template_decl;
8981 	    }
8982 	  else
8983 	    {
8984 	      /* Build new DECL_FRIENDLIST.  */
8985 	      tree r;
8986 
8987 	      /* The file and line for this declaration, to
8988 		 assist in error message reporting.  Since we
8989 		 called push_tinst_level above, we don't need to
8990 		 restore these.  */
8991 	      input_location = DECL_SOURCE_LOCATION (t);
8992 
8993 	      if (TREE_CODE (t) == TEMPLATE_DECL)
8994 		{
8995 		  ++processing_template_decl;
8996 		  push_deferring_access_checks (dk_no_check);
8997 		}
8998 
8999 	      r = tsubst_friend_function (t, args);
9000 	      add_friend (type, r, /*complain=*/false);
9001 	      if (TREE_CODE (t) == TEMPLATE_DECL)
9002 		{
9003 		  pop_deferring_access_checks ();
9004 		  --processing_template_decl;
9005 		}
9006 	    }
9007 	}
9008     }
9009 
9010   if (tree expr = CLASSTYPE_LAMBDA_EXPR (type))
9011     {
9012       tree decl = lambda_function (type);
9013       if (decl)
9014 	{
9015 	  instantiate_decl (decl, false, false);
9016 
9017 	  /* We need to instantiate the capture list from the template
9018 	     after we've instantiated the closure members, but before we
9019 	     consider adding the conversion op.  Also keep any captures
9020 	     that may have been added during instantiation of the op().  */
9021 	  tree tmpl_expr = CLASSTYPE_LAMBDA_EXPR (pattern);
9022 	  tree tmpl_cap
9023 	    = tsubst_copy_and_build (LAMBDA_EXPR_CAPTURE_LIST (tmpl_expr),
9024 				     args, tf_warning_or_error, NULL_TREE,
9025 				     false, false);
9026 
9027 	  LAMBDA_EXPR_CAPTURE_LIST (expr)
9028 	    = chainon (tmpl_cap, nreverse (LAMBDA_EXPR_CAPTURE_LIST (expr)));
9029 
9030 	  maybe_add_lambda_conv_op (type);
9031 	}
9032       else
9033 	gcc_assert (errorcount);
9034     }
9035 
9036   /* Set the file and line number information to whatever is given for
9037      the class itself.  This puts error messages involving generated
9038      implicit functions at a predictable point, and the same point
9039      that would be used for non-template classes.  */
9040   input_location = DECL_SOURCE_LOCATION (typedecl);
9041 
9042   unreverse_member_declarations (type);
9043   finish_struct_1 (type);
9044   TYPE_BEING_DEFINED (type) = 0;
9045 
9046   /* We don't instantiate default arguments for member functions.  14.7.1:
9047 
9048      The implicit instantiation of a class template specialization causes
9049      the implicit instantiation of the declarations, but not of the
9050      definitions or default arguments, of the class member functions,
9051      member classes, static data members and member templates....  */
9052 
9053   /* Some typedefs referenced from within the template code need to be access
9054      checked at template instantiation time, i.e now. These types were
9055      added to the template at parsing time. Let's get those and perform
9056      the access checks then.  */
9057   perform_typedefs_access_check (pattern, args);
9058   perform_deferred_access_checks (tf_warning_or_error);
9059   pop_nested_class ();
9060   maximum_field_alignment = saved_maximum_field_alignment;
9061   if (!fn_context)
9062     pop_from_top_level ();
9063   pop_deferring_access_checks ();
9064   pop_tinst_level ();
9065 
9066   /* The vtable for a template class can be emitted in any translation
9067      unit in which the class is instantiated.  When there is no key
9068      method, however, finish_struct_1 will already have added TYPE to
9069      the keyed_classes list.  */
9070   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
9071     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
9072 
9073   return type;
9074 }
9075 
9076 /* Wrapper for instantiate_class_template_1.  */
9077 
9078 tree
instantiate_class_template(tree type)9079 instantiate_class_template (tree type)
9080 {
9081   tree ret;
9082   timevar_push (TV_TEMPLATE_INST);
9083   ret = instantiate_class_template_1 (type);
9084   timevar_pop (TV_TEMPLATE_INST);
9085   return ret;
9086 }
9087 
9088 static tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)9089 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9090 {
9091   tree r;
9092 
9093   if (!t)
9094     r = t;
9095   else if (TYPE_P (t))
9096     r = tsubst (t, args, complain, in_decl);
9097   else
9098     {
9099       if (!(complain & tf_warning))
9100 	++c_inhibit_evaluation_warnings;
9101       r = tsubst_expr (t, args, complain, in_decl,
9102 		       /*integral_constant_expression_p=*/true);
9103       if (!(complain & tf_warning))
9104 	--c_inhibit_evaluation_warnings;
9105       /* Preserve the raw-reference nature of T.  */
9106       if (TREE_TYPE (t) && TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE
9107 	  && REFERENCE_REF_P (r))
9108 	r = TREE_OPERAND (r, 0);
9109     }
9110   return r;
9111 }
9112 
9113 /* Given a function parameter pack TMPL_PARM and some function parameters
9114    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
9115    and set *SPEC_P to point at the next point in the list.  */
9116 
9117 static tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)9118 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
9119 {
9120   /* Collect all of the extra "packed" parameters into an
9121      argument pack.  */
9122   tree parmvec;
9123   tree parmtypevec;
9124   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
9125   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
9126   tree spec_parm = *spec_p;
9127   int i, len;
9128 
9129   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
9130     if (tmpl_parm
9131 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
9132       break;
9133 
9134   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
9135   parmvec = make_tree_vec (len);
9136   parmtypevec = make_tree_vec (len);
9137   spec_parm = *spec_p;
9138   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
9139     {
9140       TREE_VEC_ELT (parmvec, i) = spec_parm;
9141       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
9142     }
9143 
9144   /* Build the argument packs.  */
9145   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
9146   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
9147   TREE_TYPE (argpack) = argtypepack;
9148   *spec_p = spec_parm;
9149 
9150   return argpack;
9151 }
9152 
9153 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
9154    NONTYPE_ARGUMENT_PACK.  */
9155 
9156 static tree
make_fnparm_pack(tree spec_parm)9157 make_fnparm_pack (tree spec_parm)
9158 {
9159   return extract_fnparm_pack (NULL_TREE, &spec_parm);
9160 }
9161 
9162 /* Return true iff the Ith element of the argument pack ARG_PACK is a
9163    pack expansion.  */
9164 
9165 static bool
argument_pack_element_is_expansion_p(tree arg_pack,int i)9166 argument_pack_element_is_expansion_p (tree arg_pack, int i)
9167 {
9168   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
9169   if (i >= TREE_VEC_LENGTH (vec))
9170     return false;
9171   return PACK_EXPANSION_P (TREE_VEC_ELT (vec, i));
9172 }
9173 
9174 
9175 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
9176 
9177 static tree
make_argument_pack_select(tree arg_pack,unsigned index)9178 make_argument_pack_select (tree arg_pack, unsigned index)
9179 {
9180   tree aps = make_node (ARGUMENT_PACK_SELECT);
9181 
9182   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
9183   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
9184 
9185   return aps;
9186 }
9187 
9188 /*  This is a subroutine of tsubst_pack_expansion.
9189 
9190     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
9191     mechanism to store the (non complete list of) arguments of the
9192     substitution and return a non substituted pack expansion, in order
9193     to wait for when we have enough arguments to really perform the
9194     substitution.  */
9195 
9196 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)9197 use_pack_expansion_extra_args_p (tree parm_packs,
9198 				 int arg_pack_len,
9199 				 bool has_empty_arg)
9200 {
9201   /* If one pack has an expansion and another pack has a normal
9202      argument or if one pack has an empty argument and an another
9203      one hasn't then tsubst_pack_expansion cannot perform the
9204      substitution and need to fall back on the
9205      PACK_EXPANSION_EXTRA mechanism.  */
9206   if (parm_packs == NULL_TREE)
9207     return false;
9208   else if (has_empty_arg)
9209     return true;
9210 
9211   bool has_expansion_arg = false;
9212   for (int i = 0 ; i < arg_pack_len; ++i)
9213     {
9214       bool has_non_expansion_arg = false;
9215       for (tree parm_pack = parm_packs;
9216 	   parm_pack;
9217 	   parm_pack = TREE_CHAIN (parm_pack))
9218 	{
9219 	  tree arg = TREE_VALUE (parm_pack);
9220 
9221 	  if (argument_pack_element_is_expansion_p (arg, i))
9222 	    has_expansion_arg = true;
9223 	  else
9224 	    has_non_expansion_arg = true;
9225 	}
9226 
9227       if (has_expansion_arg && has_non_expansion_arg)
9228 	return true;
9229     }
9230   return false;
9231 }
9232 
9233 /* [temp.variadic]/6 says that:
9234 
9235        The instantiation of a pack expansion [...]
9236        produces a list E1,E2, ..., En, where N is the number of elements
9237        in the pack expansion parameters.
9238 
9239    This subroutine of tsubst_pack_expansion produces one of these Ei.
9240 
9241    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
9242    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
9243    PATTERN, and each TREE_VALUE is its corresponding argument pack.
9244    INDEX is the index 'i' of the element Ei to produce.  ARGS,
9245    COMPLAIN, and IN_DECL are the same parameters as for the
9246    tsubst_pack_expansion function.
9247 
9248    The function returns the resulting Ei upon successful completion,
9249    or error_mark_node.
9250 
9251    Note that this function possibly modifies the ARGS parameter, so
9252    it's the responsibility of the caller to restore it.  */
9253 
9254 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)9255 gen_elem_of_pack_expansion_instantiation (tree pattern,
9256 					  tree parm_packs,
9257 					  unsigned index,
9258 					  tree args /* This parm gets
9259 						       modified.  */,
9260 					  tsubst_flags_t complain,
9261 					  tree in_decl)
9262 {
9263   tree t;
9264   bool ith_elem_is_expansion = false;
9265 
9266   /* For each parameter pack, change the substitution of the parameter
9267      pack to the ith argument in its argument pack, then expand the
9268      pattern.  */
9269   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
9270     {
9271       tree parm = TREE_PURPOSE (pack);
9272       tree arg_pack = TREE_VALUE (pack);
9273       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
9274 
9275       ith_elem_is_expansion |=
9276 	argument_pack_element_is_expansion_p (arg_pack, index);
9277 
9278       /* Select the Ith argument from the pack.  */
9279       if (TREE_CODE (parm) == PARM_DECL)
9280 	{
9281 	  if (index == 0)
9282 	    {
9283 	      aps = make_argument_pack_select (arg_pack, index);
9284 	      mark_used (parm);
9285 	      register_local_specialization (aps, parm);
9286 	    }
9287 	  else
9288 	    aps = retrieve_local_specialization (parm);
9289 	}
9290       else
9291 	{
9292 	  int idx, level;
9293 	  template_parm_level_and_index (parm, &level, &idx);
9294 
9295 	  if (index == 0)
9296 	    {
9297 	      aps = make_argument_pack_select (arg_pack, index);
9298 	      /* Update the corresponding argument.  */
9299 	      TMPL_ARG (args, level, idx) = aps;
9300 	    }
9301 	  else
9302 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
9303 	    aps = TMPL_ARG (args, level, idx);
9304 	}
9305       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
9306     }
9307 
9308   /* Substitute into the PATTERN with the (possibly altered)
9309      arguments.  */
9310   if (!TYPE_P (pattern))
9311     t = tsubst_expr (pattern, args, complain, in_decl,
9312 		     /*integral_constant_expression_p=*/false);
9313   else
9314     t = tsubst (pattern, args, complain, in_decl);
9315 
9316   /*  If the Ith argument pack element is a pack expansion, then
9317       the Ith element resulting from the substituting is going to
9318       be a pack expansion as well.  */
9319   if (ith_elem_is_expansion)
9320     t = make_pack_expansion (t);
9321 
9322   return t;
9323 }
9324 
9325 /* Substitute ARGS into T, which is an pack expansion
9326    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
9327    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
9328    (if only a partial substitution could be performed) or
9329    ERROR_MARK_NODE if there was an error.  */
9330 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)9331 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
9332 		       tree in_decl)
9333 {
9334   tree pattern;
9335   tree pack, packs = NULL_TREE;
9336   bool unsubstituted_packs = false;
9337   int i, len = -1;
9338   tree result;
9339   struct pointer_map_t *saved_local_specializations = NULL;
9340   bool need_local_specializations = false;
9341   int levels;
9342 
9343   gcc_assert (PACK_EXPANSION_P (t));
9344   pattern = PACK_EXPANSION_PATTERN (t);
9345 
9346   /* Add in any args remembered from an earlier partial instantiation.  */
9347   args = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
9348 
9349   levels = TMPL_ARGS_DEPTH (args);
9350 
9351   /* Determine the argument packs that will instantiate the parameter
9352      packs used in the expansion expression. While we're at it,
9353      compute the number of arguments to be expanded and make sure it
9354      is consistent.  */
9355   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
9356        pack = TREE_CHAIN (pack))
9357     {
9358       tree parm_pack = TREE_VALUE (pack);
9359       tree arg_pack = NULL_TREE;
9360       tree orig_arg = NULL_TREE;
9361       int level = 0;
9362 
9363       if (TREE_CODE (parm_pack) == BASES)
9364        {
9365          if (BASES_DIRECT (parm_pack))
9366            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
9367                                                         args, complain, in_decl, false));
9368          else
9369            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
9370                                                  args, complain, in_decl, false));
9371        }
9372       if (TREE_CODE (parm_pack) == PARM_DECL)
9373 	{
9374 	  if (PACK_EXPANSION_LOCAL_P (t))
9375 	    arg_pack = retrieve_local_specialization (parm_pack);
9376 	  else
9377 	    {
9378 	      /* We can't rely on local_specializations for a parameter
9379 		 name used later in a function declaration (such as in a
9380 		 late-specified return type).  Even if it exists, it might
9381 		 have the wrong value for a recursive call.  Just make a
9382 		 dummy decl, since it's only used for its type.  */
9383 	      arg_pack = tsubst_decl (parm_pack, args, complain);
9384 	      if (arg_pack && FUNCTION_PARAMETER_PACK_P (arg_pack))
9385 		/* Partial instantiation of the parm_pack, we can't build
9386 		   up an argument pack yet.  */
9387 		arg_pack = NULL_TREE;
9388 	      else
9389 		arg_pack = make_fnparm_pack (arg_pack);
9390 	      need_local_specializations = true;
9391 	    }
9392 	}
9393       else
9394         {
9395 	  int idx;
9396           template_parm_level_and_index (parm_pack, &level, &idx);
9397 
9398           if (level <= levels)
9399             arg_pack = TMPL_ARG (args, level, idx);
9400         }
9401 
9402       orig_arg = arg_pack;
9403       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
9404 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
9405 
9406       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
9407 	/* This can only happen if we forget to expand an argument
9408 	   pack somewhere else. Just return an error, silently.  */
9409 	{
9410 	  result = make_tree_vec (1);
9411 	  TREE_VEC_ELT (result, 0) = error_mark_node;
9412 	  return result;
9413 	}
9414 
9415       if (arg_pack)
9416         {
9417           int my_len =
9418             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
9419 
9420 	  /* Don't bother trying to do a partial substitution with
9421 	     incomplete packs; we'll try again after deduction.  */
9422           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
9423             return t;
9424 
9425           if (len < 0)
9426 	    len = my_len;
9427           else if (len != my_len)
9428             {
9429 	      if (!(complain & tf_error))
9430 		/* Fail quietly.  */;
9431               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
9432                 error ("mismatched argument pack lengths while expanding "
9433                        "%<%T%>",
9434                        pattern);
9435               else
9436                 error ("mismatched argument pack lengths while expanding "
9437                        "%<%E%>",
9438                        pattern);
9439               return error_mark_node;
9440             }
9441 
9442           /* Keep track of the parameter packs and their corresponding
9443              argument packs.  */
9444           packs = tree_cons (parm_pack, arg_pack, packs);
9445           TREE_TYPE (packs) = orig_arg;
9446         }
9447       else
9448 	{
9449 	  /* We can't substitute for this parameter pack.  We use a flag as
9450 	     well as the missing_level counter because function parameter
9451 	     packs don't have a level.  */
9452 	  unsubstituted_packs = true;
9453 	}
9454     }
9455 
9456   /* We cannot expand this expansion expression, because we don't have
9457      all of the argument packs we need.  */
9458   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
9459     {
9460       /* We got some full packs, but we can't substitute them in until we
9461 	 have values for all the packs.  So remember these until then.  */
9462 
9463       t = make_pack_expansion (pattern);
9464       PACK_EXPANSION_EXTRA_ARGS (t) = args;
9465       return t;
9466     }
9467   else if (unsubstituted_packs)
9468     {
9469       /* There were no real arguments, we're just replacing a parameter
9470 	 pack with another version of itself. Substitute into the
9471 	 pattern and return a PACK_EXPANSION_*. The caller will need to
9472 	 deal with that.  */
9473       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
9474 	t = tsubst_expr (pattern, args, complain, in_decl,
9475 			 /*integral_constant_expression_p=*/false);
9476       else
9477 	t = tsubst (pattern, args, complain, in_decl);
9478       t = make_pack_expansion (t);
9479       return t;
9480     }
9481 
9482   gcc_assert (len >= 0);
9483 
9484   if (need_local_specializations)
9485     {
9486       /* We're in a late-specified return type, so create our own local
9487 	 specializations map; the current map is either NULL or (in the
9488 	 case of recursive unification) might have bindings that we don't
9489 	 want to use or alter.  */
9490       saved_local_specializations = local_specializations;
9491       local_specializations = pointer_map_create ();
9492     }
9493 
9494   /* For each argument in each argument pack, substitute into the
9495      pattern.  */
9496   result = make_tree_vec (len);
9497   for (i = 0; i < len; ++i)
9498     {
9499       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
9500 						    i,
9501 						    args, complain,
9502 						    in_decl);
9503       TREE_VEC_ELT (result, i) = t;
9504       if (t == error_mark_node)
9505 	{
9506 	  result = error_mark_node;
9507 	  break;
9508 	}
9509     }
9510 
9511   /* Update ARGS to restore the substitution from parameter packs to
9512      their argument packs.  */
9513   for (pack = packs; pack; pack = TREE_CHAIN (pack))
9514     {
9515       tree parm = TREE_PURPOSE (pack);
9516 
9517       if (TREE_CODE (parm) == PARM_DECL)
9518         register_local_specialization (TREE_TYPE (pack), parm);
9519       else
9520         {
9521           int idx, level;
9522 
9523 	  if (TREE_VALUE (pack) == NULL_TREE)
9524 	    continue;
9525 
9526           template_parm_level_and_index (parm, &level, &idx);
9527 
9528           /* Update the corresponding argument.  */
9529           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
9530             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
9531               TREE_TYPE (pack);
9532           else
9533             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
9534         }
9535     }
9536 
9537   if (need_local_specializations)
9538     {
9539       pointer_map_destroy (local_specializations);
9540       local_specializations = saved_local_specializations;
9541     }
9542 
9543   return result;
9544 }
9545 
9546 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
9547    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
9548    parameter packs; all parms generated from a function parameter pack will
9549    have the same DECL_PARM_INDEX.  */
9550 
9551 tree
get_pattern_parm(tree parm,tree tmpl)9552 get_pattern_parm (tree parm, tree tmpl)
9553 {
9554   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
9555   tree patparm;
9556 
9557   if (DECL_ARTIFICIAL (parm))
9558     {
9559       for (patparm = DECL_ARGUMENTS (pattern);
9560 	   patparm; patparm = DECL_CHAIN (patparm))
9561 	if (DECL_ARTIFICIAL (patparm)
9562 	    && DECL_NAME (parm) == DECL_NAME (patparm))
9563 	  break;
9564     }
9565   else
9566     {
9567       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
9568       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
9569       gcc_assert (DECL_PARM_INDEX (patparm)
9570 		  == DECL_PARM_INDEX (parm));
9571     }
9572 
9573   return patparm;
9574 }
9575 
9576 /* Substitute ARGS into the vector or list of template arguments T.  */
9577 
9578 static tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)9579 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9580 {
9581   tree orig_t = t;
9582   int len, need_new = 0, i, expanded_len_adjust = 0, out;
9583   tree *elts;
9584 
9585   if (t == error_mark_node)
9586     return error_mark_node;
9587 
9588   len = TREE_VEC_LENGTH (t);
9589   elts = XALLOCAVEC (tree, len);
9590 
9591   for (i = 0; i < len; i++)
9592     {
9593       tree orig_arg = TREE_VEC_ELT (t, i);
9594       tree new_arg;
9595 
9596       if (TREE_CODE (orig_arg) == TREE_VEC)
9597 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
9598       else if (PACK_EXPANSION_P (orig_arg))
9599         {
9600           /* Substitute into an expansion expression.  */
9601           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
9602 
9603           if (TREE_CODE (new_arg) == TREE_VEC)
9604             /* Add to the expanded length adjustment the number of
9605                expanded arguments. We subtract one from this
9606                measurement, because the argument pack expression
9607                itself is already counted as 1 in
9608                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
9609                the argument pack is empty.  */
9610             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
9611         }
9612       else if (ARGUMENT_PACK_P (orig_arg))
9613         {
9614           /* Substitute into each of the arguments.  */
9615           new_arg = TYPE_P (orig_arg)
9616             ? cxx_make_type (TREE_CODE (orig_arg))
9617             : make_node (TREE_CODE (orig_arg));
9618 
9619           SET_ARGUMENT_PACK_ARGS (
9620             new_arg,
9621             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
9622                                   args, complain, in_decl));
9623 
9624           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
9625             new_arg = error_mark_node;
9626 
9627           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
9628             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
9629                                           complain, in_decl);
9630             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
9631 
9632             if (TREE_TYPE (new_arg) == error_mark_node)
9633               new_arg = error_mark_node;
9634           }
9635         }
9636       else
9637 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
9638 
9639       if (new_arg == error_mark_node)
9640 	return error_mark_node;
9641 
9642       elts[i] = new_arg;
9643       if (new_arg != orig_arg)
9644 	need_new = 1;
9645     }
9646 
9647   if (!need_new)
9648     return t;
9649 
9650   /* Make space for the expanded arguments coming from template
9651      argument packs.  */
9652   t = make_tree_vec (len + expanded_len_adjust);
9653   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9654      arguments for a member template.
9655      In that case each TREE_VEC in ORIG_T represents a level of template
9656      arguments, and ORIG_T won't carry any non defaulted argument count.
9657      It will rather be the nested TREE_VECs that will carry one.
9658      In other words, ORIG_T carries a non defaulted argument count only
9659      if it doesn't contain any nested TREE_VEC.  */
9660   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9661     {
9662       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9663       count += expanded_len_adjust;
9664       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9665     }
9666   for (i = 0, out = 0; i < len; i++)
9667     {
9668       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9669            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9670           && TREE_CODE (elts[i]) == TREE_VEC)
9671         {
9672           int idx;
9673 
9674           /* Now expand the template argument pack "in place".  */
9675           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9676             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9677         }
9678       else
9679         {
9680           TREE_VEC_ELT (t, out) = elts[i];
9681           out++;
9682         }
9683     }
9684 
9685   return t;
9686 }
9687 
9688 /* Return the result of substituting ARGS into the template parameters
9689    given by PARMS.  If there are m levels of ARGS and m + n levels of
9690    PARMS, then the result will contain n levels of PARMS.  For
9691    example, if PARMS is `template <class T> template <class U>
9692    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9693    result will be `template <int*, double, class V>'.  */
9694 
9695 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)9696 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9697 {
9698   tree r = NULL_TREE;
9699   tree* new_parms;
9700 
9701   /* When substituting into a template, we must set
9702      PROCESSING_TEMPLATE_DECL as the template parameters may be
9703      dependent if they are based on one-another, and the dependency
9704      predicates are short-circuit outside of templates.  */
9705   ++processing_template_decl;
9706 
9707   for (new_parms = &r;
9708        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9709        new_parms = &(TREE_CHAIN (*new_parms)),
9710 	 parms = TREE_CHAIN (parms))
9711     {
9712       tree new_vec =
9713 	make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9714       int i;
9715 
9716       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9717 	{
9718           tree tuple;
9719 
9720           if (parms == error_mark_node)
9721             continue;
9722 
9723           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9724 
9725           if (tuple == error_mark_node)
9726             continue;
9727 
9728 	  TREE_VEC_ELT (new_vec, i) =
9729 	    tsubst_template_parm (tuple, args, complain);
9730 	}
9731 
9732       *new_parms =
9733 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9734 			     - TMPL_ARGS_DEPTH (args)),
9735 		   new_vec, NULL_TREE);
9736     }
9737 
9738   --processing_template_decl;
9739 
9740   return r;
9741 }
9742 
9743 /* Return the result of substituting ARGS into one template parameter
9744    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9745    parameter and which TREE_PURPOSE is the default argument of the
9746    template parameter.  */
9747 
9748 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)9749 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9750 {
9751   tree default_value, parm_decl;
9752 
9753   if (args == NULL_TREE
9754       || t == NULL_TREE
9755       || t == error_mark_node)
9756     return t;
9757 
9758   gcc_assert (TREE_CODE (t) == TREE_LIST);
9759 
9760   default_value = TREE_PURPOSE (t);
9761   parm_decl = TREE_VALUE (t);
9762 
9763   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9764   if (TREE_CODE (parm_decl) == PARM_DECL
9765       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9766     parm_decl = error_mark_node;
9767   default_value = tsubst_template_arg (default_value, args,
9768 				       complain, NULL_TREE);
9769 
9770   return build_tree_list (default_value, parm_decl);
9771 }
9772 
9773 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9774    type T.  If T is not an aggregate or enumeration type, it is
9775    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9776    ENTERING_SCOPE is nonzero, T is the context for a template which
9777    we are presently tsubst'ing.  Return the substituted value.  */
9778 
9779 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)9780 tsubst_aggr_type (tree t,
9781 		  tree args,
9782 		  tsubst_flags_t complain,
9783 		  tree in_decl,
9784 		  int entering_scope)
9785 {
9786   if (t == NULL_TREE)
9787     return NULL_TREE;
9788 
9789   switch (TREE_CODE (t))
9790     {
9791     case RECORD_TYPE:
9792       if (TYPE_PTRMEMFUNC_P (t))
9793 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9794 
9795       /* Else fall through.  */
9796     case ENUMERAL_TYPE:
9797     case UNION_TYPE:
9798       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9799 	{
9800 	  tree argvec;
9801 	  tree context;
9802 	  tree r;
9803 	  int saved_unevaluated_operand;
9804 	  int saved_inhibit_evaluation_warnings;
9805 
9806 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
9807 	  saved_unevaluated_operand = cp_unevaluated_operand;
9808 	  cp_unevaluated_operand = 0;
9809 	  saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9810 	  c_inhibit_evaluation_warnings = 0;
9811 
9812 	  /* First, determine the context for the type we are looking
9813 	     up.  */
9814 	  context = TYPE_CONTEXT (t);
9815 	  if (context && TYPE_P (context))
9816 	    {
9817 	      context = tsubst_aggr_type (context, args, complain,
9818 					  in_decl, /*entering_scope=*/1);
9819 	      /* If context is a nested class inside a class template,
9820 	         it may still need to be instantiated (c++/33959).  */
9821 	      context = complete_type (context);
9822 	    }
9823 
9824 	  /* Then, figure out what arguments are appropriate for the
9825 	     type we are trying to find.  For example, given:
9826 
9827 	       template <class T> struct S;
9828 	       template <class T, class U> void f(T, U) { S<U> su; }
9829 
9830 	     and supposing that we are instantiating f<int, double>,
9831 	     then our ARGS will be {int, double}, but, when looking up
9832 	     S we only want {double}.  */
9833 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9834 					 complain, in_decl);
9835 	  if (argvec == error_mark_node)
9836 	    r = error_mark_node;
9837 	  else
9838 	    {
9839 	      r = lookup_template_class (t, argvec, in_decl, context,
9840 					 entering_scope, complain);
9841 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9842 	    }
9843 
9844 	  cp_unevaluated_operand = saved_unevaluated_operand;
9845 	  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9846 
9847 	  return r;
9848 	}
9849       else
9850 	/* This is not a template type, so there's nothing to do.  */
9851 	return t;
9852 
9853     default:
9854       return tsubst (t, args, complain, in_decl);
9855     }
9856 }
9857 
9858 /* Substitute into the default argument ARG (a default argument for
9859    FN), which has the indicated TYPE.  */
9860 
9861 tree
tsubst_default_argument(tree fn,tree type,tree arg)9862 tsubst_default_argument (tree fn, tree type, tree arg)
9863 {
9864   tree saved_class_ptr = NULL_TREE;
9865   tree saved_class_ref = NULL_TREE;
9866   int errs = errorcount + sorrycount;
9867 
9868   /* This can happen in invalid code.  */
9869   if (TREE_CODE (arg) == DEFAULT_ARG)
9870     return arg;
9871 
9872   /* This default argument came from a template.  Instantiate the
9873      default argument here, not in tsubst.  In the case of
9874      something like:
9875 
9876        template <class T>
9877        struct S {
9878 	 static T t();
9879 	 void f(T = t());
9880        };
9881 
9882      we must be careful to do name lookup in the scope of S<T>,
9883      rather than in the current class.  */
9884   push_access_scope (fn);
9885   /* The "this" pointer is not valid in a default argument.  */
9886   if (cfun)
9887     {
9888       saved_class_ptr = current_class_ptr;
9889       cp_function_chain->x_current_class_ptr = NULL_TREE;
9890       saved_class_ref = current_class_ref;
9891       cp_function_chain->x_current_class_ref = NULL_TREE;
9892     }
9893 
9894   push_deferring_access_checks(dk_no_deferred);
9895   /* The default argument expression may cause implicitly defined
9896      member functions to be synthesized, which will result in garbage
9897      collection.  We must treat this situation as if we were within
9898      the body of function so as to avoid collecting live data on the
9899      stack.  */
9900   ++function_depth;
9901   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9902 		     tf_warning_or_error, NULL_TREE,
9903 		     /*integral_constant_expression_p=*/false);
9904   --function_depth;
9905   pop_deferring_access_checks();
9906 
9907   /* Restore the "this" pointer.  */
9908   if (cfun)
9909     {
9910       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9911       cp_function_chain->x_current_class_ref = saved_class_ref;
9912     }
9913 
9914   if (errorcount+sorrycount > errs)
9915     inform (input_location,
9916 	    "  when instantiating default argument for call to %D", fn);
9917 
9918   /* Make sure the default argument is reasonable.  */
9919   arg = check_default_argument (type, arg);
9920 
9921   pop_access_scope (fn);
9922 
9923   return arg;
9924 }
9925 
9926 /* Substitute into all the default arguments for FN.  */
9927 
9928 static void
tsubst_default_arguments(tree fn)9929 tsubst_default_arguments (tree fn)
9930 {
9931   tree arg;
9932   tree tmpl_args;
9933 
9934   tmpl_args = DECL_TI_ARGS (fn);
9935 
9936   /* If this function is not yet instantiated, we certainly don't need
9937      its default arguments.  */
9938   if (uses_template_parms (tmpl_args))
9939     return;
9940   /* Don't do this again for clones.  */
9941   if (DECL_CLONED_FUNCTION_P (fn))
9942     return;
9943 
9944   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9945        arg;
9946        arg = TREE_CHAIN (arg))
9947     if (TREE_PURPOSE (arg))
9948       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9949 						    TREE_VALUE (arg),
9950 						    TREE_PURPOSE (arg));
9951 }
9952 
9953 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9954    result of the substitution.  Issue error and warning messages under
9955    control of COMPLAIN.  */
9956 
9957 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)9958 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9959 {
9960 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9961   location_t saved_loc;
9962   tree r = NULL_TREE;
9963   tree in_decl = t;
9964   hashval_t hash = 0;
9965 
9966   /* Set the filename and linenumber to improve error-reporting.  */
9967   saved_loc = input_location;
9968   input_location = DECL_SOURCE_LOCATION (t);
9969 
9970   switch (TREE_CODE (t))
9971     {
9972     case TEMPLATE_DECL:
9973       {
9974 	/* We can get here when processing a member function template,
9975 	   member class template, or template template parameter.  */
9976 	tree decl = DECL_TEMPLATE_RESULT (t);
9977 	tree spec;
9978 	tree tmpl_args;
9979 	tree full_args;
9980 
9981 	if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9982 	  {
9983 	    /* Template template parameter is treated here.  */
9984 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9985 	    if (new_type == error_mark_node)
9986 	      RETURN (error_mark_node);
9987 	    /* If we get a real template back, return it.  This can happen in
9988 	       the context of most_specialized_class.  */
9989 	    if (TREE_CODE (new_type) == TEMPLATE_DECL)
9990 	      return new_type;
9991 
9992 	    r = copy_decl (t);
9993 	    DECL_CHAIN (r) = NULL_TREE;
9994 	    TREE_TYPE (r) = new_type;
9995 	    DECL_TEMPLATE_RESULT (r)
9996 	      = build_decl (DECL_SOURCE_LOCATION (decl),
9997 			    TYPE_DECL, DECL_NAME (decl), new_type);
9998 	    DECL_TEMPLATE_PARMS (r)
9999 	      = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
10000 				       complain);
10001 	    TYPE_NAME (new_type) = r;
10002 	    break;
10003 	  }
10004 
10005 	/* We might already have an instance of this template.
10006 	   The ARGS are for the surrounding class type, so the
10007 	   full args contain the tsubst'd args for the context,
10008 	   plus the innermost args from the template decl.  */
10009 	tmpl_args = DECL_CLASS_TEMPLATE_P (t)
10010 	  ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
10011 	  : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
10012 	/* Because this is a template, the arguments will still be
10013 	   dependent, even after substitution.  If
10014 	   PROCESSING_TEMPLATE_DECL is not set, the dependency
10015 	   predicates will short-circuit.  */
10016 	++processing_template_decl;
10017 	full_args = tsubst_template_args (tmpl_args, args,
10018 					  complain, in_decl);
10019 	--processing_template_decl;
10020 	if (full_args == error_mark_node)
10021 	  RETURN (error_mark_node);
10022 
10023 	/* If this is a default template template argument,
10024 	   tsubst might not have changed anything.  */
10025 	if (full_args == tmpl_args)
10026 	  RETURN (t);
10027 
10028 	hash = hash_tmpl_and_args (t, full_args);
10029 	spec = retrieve_specialization (t, full_args, hash);
10030 	if (spec != NULL_TREE)
10031 	  {
10032 	    r = spec;
10033 	    break;
10034 	  }
10035 
10036 	/* Make a new template decl.  It will be similar to the
10037 	   original, but will record the current template arguments.
10038 	   We also create a new function declaration, which is just
10039 	   like the old one, but points to this new template, rather
10040 	   than the old one.  */
10041 	r = copy_decl (t);
10042 	gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
10043 	DECL_CHAIN (r) = NULL_TREE;
10044 
10045 	DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10046 
10047 	if (TREE_CODE (decl) == TYPE_DECL
10048 	    && !TYPE_DECL_ALIAS_P (decl))
10049 	  {
10050 	    tree new_type;
10051 	    ++processing_template_decl;
10052 	    new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10053 	    --processing_template_decl;
10054 	    if (new_type == error_mark_node)
10055 	      RETURN (error_mark_node);
10056 
10057 	    TREE_TYPE (r) = new_type;
10058 	    CLASSTYPE_TI_TEMPLATE (new_type) = r;
10059 	    DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
10060 	    DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
10061 	    DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
10062 	  }
10063 	else
10064 	  {
10065 	    tree new_decl;
10066 	    ++processing_template_decl;
10067 	    new_decl = tsubst (decl, args, complain, in_decl);
10068 	    --processing_template_decl;
10069 	    if (new_decl == error_mark_node)
10070 	      RETURN (error_mark_node);
10071 
10072 	    DECL_TEMPLATE_RESULT (r) = new_decl;
10073 	    DECL_TI_TEMPLATE (new_decl) = r;
10074 	    TREE_TYPE (r) = TREE_TYPE (new_decl);
10075 	    DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
10076 	    DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
10077 	  }
10078 
10079 	SET_DECL_IMPLICIT_INSTANTIATION (r);
10080 	DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
10081 	DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
10082 
10083 	/* The template parameters for this new template are all the
10084 	   template parameters for the old template, except the
10085 	   outermost level of parameters.  */
10086 	DECL_TEMPLATE_PARMS (r)
10087 	  = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
10088 				   complain);
10089 
10090 	if (PRIMARY_TEMPLATE_P (t))
10091 	  DECL_PRIMARY_TEMPLATE (r) = r;
10092 
10093 	if (TREE_CODE (decl) != TYPE_DECL)
10094 	  /* Record this non-type partial instantiation.  */
10095 	  register_specialization (r, t,
10096 				   DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
10097 				   false, hash);
10098       }
10099       break;
10100 
10101     case FUNCTION_DECL:
10102       {
10103 	tree ctx;
10104 	tree argvec = NULL_TREE;
10105 	tree *friends;
10106 	tree gen_tmpl;
10107 	tree type;
10108 	int member;
10109 	int args_depth;
10110 	int parms_depth;
10111 
10112 	/* Nobody should be tsubst'ing into non-template functions.  */
10113 	gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
10114 
10115 	if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
10116 	  {
10117 	    tree spec;
10118 	    bool dependent_p;
10119 
10120 	    /* If T is not dependent, just return it.  We have to
10121 	       increment PROCESSING_TEMPLATE_DECL because
10122 	       value_dependent_expression_p assumes that nothing is
10123 	       dependent when PROCESSING_TEMPLATE_DECL is zero.  */
10124 	    ++processing_template_decl;
10125 	    dependent_p = value_dependent_expression_p (t);
10126 	    --processing_template_decl;
10127 	    if (!dependent_p)
10128 	      RETURN (t);
10129 
10130 	    /* Calculate the most general template of which R is a
10131 	       specialization, and the complete set of arguments used to
10132 	       specialize R.  */
10133 	    gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
10134 	    argvec = tsubst_template_args (DECL_TI_ARGS
10135                                           (DECL_TEMPLATE_RESULT
10136                                                  (DECL_TI_TEMPLATE (t))),
10137 					   args, complain, in_decl);
10138 	    if (argvec == error_mark_node)
10139 	      RETURN (error_mark_node);
10140 
10141 	    /* Check to see if we already have this specialization.  */
10142 	    hash = hash_tmpl_and_args (gen_tmpl, argvec);
10143 	    spec = retrieve_specialization (gen_tmpl, argvec, hash);
10144 
10145 	    if (spec)
10146 	      {
10147 		r = spec;
10148 		break;
10149 	      }
10150 
10151 	    /* We can see more levels of arguments than parameters if
10152 	       there was a specialization of a member template, like
10153 	       this:
10154 
10155 		 template <class T> struct S { template <class U> void f(); }
10156 		 template <> template <class U> void S<int>::f(U);
10157 
10158 	       Here, we'll be substituting into the specialization,
10159 	       because that's where we can find the code we actually
10160 	       want to generate, but we'll have enough arguments for
10161 	       the most general template.
10162 
10163 	       We also deal with the peculiar case:
10164 
10165 		 template <class T> struct S {
10166 		   template <class U> friend void f();
10167 		 };
10168 		 template <class U> void f() {}
10169 		 template S<int>;
10170 		 template void f<double>();
10171 
10172 	       Here, the ARGS for the instantiation of will be {int,
10173 	       double}.  But, we only need as many ARGS as there are
10174 	       levels of template parameters in CODE_PATTERN.  We are
10175 	       careful not to get fooled into reducing the ARGS in
10176 	       situations like:
10177 
10178 		 template <class T> struct S { template <class U> void f(U); }
10179 		 template <class T> template <> void S<T>::f(int) {}
10180 
10181 	       which we can spot because the pattern will be a
10182 	       specialization in this case.  */
10183 	    args_depth = TMPL_ARGS_DEPTH (args);
10184 	    parms_depth =
10185 	      TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
10186 	    if (args_depth > parms_depth
10187 		&& !DECL_TEMPLATE_SPECIALIZATION (t))
10188 	      args = get_innermost_template_args (args, parms_depth);
10189 	  }
10190 	else
10191 	  {
10192 	    /* This special case arises when we have something like this:
10193 
10194 		 template <class T> struct S {
10195 		   friend void f<int>(int, double);
10196 		 };
10197 
10198 	       Here, the DECL_TI_TEMPLATE for the friend declaration
10199 	       will be an IDENTIFIER_NODE.  We are being called from
10200 	       tsubst_friend_function, and we want only to create a
10201 	       new decl (R) with appropriate types so that we can call
10202 	       determine_specialization.  */
10203 	    gen_tmpl = NULL_TREE;
10204 	  }
10205 
10206 	if (DECL_CLASS_SCOPE_P (t))
10207 	  {
10208 	    if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
10209 	      member = 2;
10210 	    else
10211 	      member = 1;
10212 	    ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
10213 				    complain, t, /*entering_scope=*/1);
10214 	  }
10215 	else
10216 	  {
10217 	    member = 0;
10218 	    ctx = DECL_CONTEXT (t);
10219 	  }
10220 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10221 	if (type == error_mark_node)
10222 	  RETURN (error_mark_node);
10223 
10224 	/* If we hit excessive deduction depth, the type is bogus even if
10225 	   it isn't error_mark_node, so don't build a decl.  */
10226 	if (excessive_deduction_depth)
10227 	  RETURN (error_mark_node);
10228 
10229 	/* We do NOT check for matching decls pushed separately at this
10230 	   point, as they may not represent instantiations of this
10231 	   template, and in any case are considered separate under the
10232 	   discrete model.  */
10233 	r = copy_decl (t);
10234 	DECL_USE_TEMPLATE (r) = 0;
10235 	TREE_TYPE (r) = type;
10236 	/* Clear out the mangled name and RTL for the instantiation.  */
10237 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10238 	SET_DECL_RTL (r, NULL);
10239 	/* Leave DECL_INITIAL set on deleted instantiations.  */
10240 	if (!DECL_DELETED_FN (r))
10241 	  DECL_INITIAL (r) = NULL_TREE;
10242 	DECL_CONTEXT (r) = ctx;
10243 
10244 	if (member && DECL_CONV_FN_P (r))
10245 	  /* Type-conversion operator.  Reconstruct the name, in
10246 	     case it's the name of one of the template's parameters.  */
10247 	  DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
10248 
10249 	DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
10250 				     complain, t);
10251 	DECL_RESULT (r) = NULL_TREE;
10252 
10253 	TREE_STATIC (r) = 0;
10254 	TREE_PUBLIC (r) = TREE_PUBLIC (t);
10255 	DECL_EXTERNAL (r) = 1;
10256 	/* If this is an instantiation of a function with internal
10257 	   linkage, we already know what object file linkage will be
10258 	   assigned to the instantiation.  */
10259 	DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
10260 	DECL_DEFER_OUTPUT (r) = 0;
10261 	DECL_CHAIN (r) = NULL_TREE;
10262 	DECL_PENDING_INLINE_INFO (r) = 0;
10263 	DECL_PENDING_INLINE_P (r) = 0;
10264 	DECL_SAVED_TREE (r) = NULL_TREE;
10265 	DECL_STRUCT_FUNCTION (r) = NULL;
10266 	TREE_USED (r) = 0;
10267 	/* We'll re-clone as appropriate in instantiate_template.  */
10268 	DECL_CLONED_FUNCTION (r) = NULL_TREE;
10269 
10270 	/* If we aren't complaining now, return on error before we register
10271 	   the specialization so that we'll complain eventually.  */
10272 	if ((complain & tf_error) == 0
10273 	    && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10274 	    && !grok_op_properties (r, /*complain=*/false))
10275 	  RETURN (error_mark_node);
10276 
10277 	/* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
10278 	   this in the special friend case mentioned above where
10279 	   GEN_TMPL is NULL.  */
10280 	if (gen_tmpl)
10281 	  {
10282 	    DECL_TEMPLATE_INFO (r)
10283 	      = build_template_info (gen_tmpl, argvec);
10284 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
10285 	    register_specialization (r, gen_tmpl, argvec, false, hash);
10286 
10287 	    /* We're not supposed to instantiate default arguments
10288 	       until they are called, for a template.  But, for a
10289 	       declaration like:
10290 
10291 		 template <class T> void f ()
10292 		 { extern void g(int i = T()); }
10293 
10294 	       we should do the substitution when the template is
10295 	       instantiated.  We handle the member function case in
10296 	       instantiate_class_template since the default arguments
10297 	       might refer to other members of the class.  */
10298 	    if (!member
10299 		&& !PRIMARY_TEMPLATE_P (gen_tmpl)
10300 		&& !uses_template_parms (argvec))
10301 	      tsubst_default_arguments (r);
10302 	  }
10303 	else
10304 	  DECL_TEMPLATE_INFO (r) = NULL_TREE;
10305 
10306 	/* Copy the list of befriending classes.  */
10307 	for (friends = &DECL_BEFRIENDING_CLASSES (r);
10308 	     *friends;
10309 	     friends = &TREE_CHAIN (*friends))
10310 	  {
10311 	    *friends = copy_node (*friends);
10312 	    TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
10313 					    args, complain,
10314 					    in_decl);
10315 	  }
10316 
10317 	if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
10318 	  {
10319 	    maybe_retrofit_in_chrg (r);
10320 	    if (DECL_CONSTRUCTOR_P (r))
10321 	      grok_ctor_properties (ctx, r);
10322 	    if (DECL_INHERITED_CTOR_BASE (r))
10323 	      deduce_inheriting_ctor (r);
10324 	    /* If this is an instantiation of a member template, clone it.
10325 	       If it isn't, that'll be handled by
10326 	       clone_constructors_and_destructors.  */
10327 	    if (PRIMARY_TEMPLATE_P (gen_tmpl))
10328 	      clone_function_decl (r, /*update_method_vec_p=*/0);
10329 	  }
10330 	else if ((complain & tf_error) != 0
10331 		 && IDENTIFIER_OPNAME_P (DECL_NAME (r))
10332 		 && !grok_op_properties (r, /*complain=*/true))
10333 	  RETURN (error_mark_node);
10334 
10335 	if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
10336 	  SET_DECL_FRIEND_CONTEXT (r,
10337 				   tsubst (DECL_FRIEND_CONTEXT (t),
10338 					    args, complain, in_decl));
10339 
10340 	/* Possibly limit visibility based on template args.  */
10341 	DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10342 	if (DECL_VISIBILITY_SPECIFIED (t))
10343 	  {
10344 	    DECL_VISIBILITY_SPECIFIED (r) = 0;
10345 	    DECL_ATTRIBUTES (r)
10346 	      = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10347 	  }
10348 	determine_visibility (r);
10349 	if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
10350 	    && !processing_template_decl)
10351 	  defaulted_late_check (r);
10352 
10353 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10354 					args, complain, in_decl);
10355       }
10356       break;
10357 
10358     case PARM_DECL:
10359       {
10360 	tree type = NULL_TREE;
10361         int i, len = 1;
10362         tree expanded_types = NULL_TREE;
10363         tree prev_r = NULL_TREE;
10364         tree first_r = NULL_TREE;
10365 
10366         if (FUNCTION_PARAMETER_PACK_P (t))
10367           {
10368             /* If there is a local specialization that isn't a
10369                parameter pack, it means that we're doing a "simple"
10370                substitution from inside tsubst_pack_expansion. Just
10371                return the local specialization (which will be a single
10372                parm).  */
10373             tree spec = retrieve_local_specialization (t);
10374             if (spec
10375                 && TREE_CODE (spec) == PARM_DECL
10376                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
10377               RETURN (spec);
10378 
10379             /* Expand the TYPE_PACK_EXPANSION that provides the types for
10380                the parameters in this function parameter pack.  */
10381             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
10382 						    complain, in_decl);
10383             if (TREE_CODE (expanded_types) == TREE_VEC)
10384               {
10385                 len = TREE_VEC_LENGTH (expanded_types);
10386 
10387                 /* Zero-length parameter packs are boring. Just substitute
10388                    into the chain.  */
10389                 if (len == 0)
10390                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
10391 				  TREE_CHAIN (t)));
10392               }
10393             else
10394               {
10395                 /* All we did was update the type. Make a note of that.  */
10396                 type = expanded_types;
10397                 expanded_types = NULL_TREE;
10398               }
10399           }
10400 
10401         /* Loop through all of the parameter's we'll build. When T is
10402            a function parameter pack, LEN is the number of expanded
10403            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
10404         r = NULL_TREE;
10405         for (i = 0; i < len; ++i)
10406           {
10407             prev_r = r;
10408             r = copy_node (t);
10409             if (DECL_TEMPLATE_PARM_P (t))
10410               SET_DECL_TEMPLATE_PARM_P (r);
10411 
10412             if (expanded_types)
10413               /* We're on the Ith parameter of the function parameter
10414                  pack.  */
10415               {
10416 		/* An argument of a function parameter pack is not a parameter
10417 		   pack.  */
10418 		FUNCTION_PARAMETER_PACK_P (r) = false;
10419 
10420                 /* Get the Ith type.  */
10421                 type = TREE_VEC_ELT (expanded_types, i);
10422 
10423 		/* Rename the parameter to include the index.  */
10424 		DECL_NAME (r)
10425 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
10426               }
10427             else if (!type)
10428               /* We're dealing with a normal parameter.  */
10429               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10430 
10431             type = type_decays_to (type);
10432             TREE_TYPE (r) = type;
10433             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10434 
10435             if (DECL_INITIAL (r))
10436               {
10437                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
10438                   DECL_INITIAL (r) = TREE_TYPE (r);
10439                 else
10440                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
10441                                              complain, in_decl);
10442               }
10443 
10444             DECL_CONTEXT (r) = NULL_TREE;
10445 
10446             if (!DECL_TEMPLATE_PARM_P (r))
10447               DECL_ARG_TYPE (r) = type_passed_as (type);
10448 
10449 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10450 					    args, complain, in_decl);
10451 
10452             /* Keep track of the first new parameter we
10453                generate. That's what will be returned to the
10454                caller.  */
10455             if (!first_r)
10456               first_r = r;
10457 
10458             /* Build a proper chain of parameters when substituting
10459                into a function parameter pack.  */
10460             if (prev_r)
10461               DECL_CHAIN (prev_r) = r;
10462           }
10463 
10464 	/* If cp_unevaluated_operand is set, we're just looking for a
10465 	   single dummy parameter, so don't keep going.  */
10466 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
10467 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
10468 				   complain, DECL_CHAIN (t));
10469 
10470         /* FIRST_R contains the start of the chain we've built.  */
10471         r = first_r;
10472       }
10473       break;
10474 
10475     case FIELD_DECL:
10476       {
10477 	tree type;
10478 
10479 	r = copy_decl (t);
10480 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10481 	if (type == error_mark_node)
10482 	  RETURN (error_mark_node);
10483 	TREE_TYPE (r) = type;
10484 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10485 
10486 	if (DECL_C_BIT_FIELD (r))
10487 	  /* For bit-fields, DECL_INITIAL gives the number of bits.  For
10488 	     non-bit-fields DECL_INITIAL is a non-static data member
10489 	     initializer, which gets deferred instantiation.  */
10490 	  DECL_INITIAL (r)
10491 	    = tsubst_expr (DECL_INITIAL (t), args,
10492 			   complain, in_decl,
10493 			   /*integral_constant_expression_p=*/true);
10494 	else if (DECL_INITIAL (t))
10495 	  {
10496 	    /* Set up DECL_TEMPLATE_INFO so that we can get at the
10497 	       NSDMI in perform_member_init.  Still set DECL_INITIAL
10498 	       so that we know there is one.  */
10499 	    DECL_INITIAL (r) = void_zero_node;
10500 	    gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
10501 	    retrofit_lang_decl (r);
10502 	    DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
10503 	  }
10504 	/* We don't have to set DECL_CONTEXT here; it is set by
10505 	   finish_member_declaration.  */
10506 	DECL_CHAIN (r) = NULL_TREE;
10507 	if (VOID_TYPE_P (type))
10508 	  error ("instantiation of %q+D as type %qT", r, type);
10509 
10510 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
10511 					args, complain, in_decl);
10512       }
10513       break;
10514 
10515     case USING_DECL:
10516       /* We reach here only for member using decls.  We also need to check
10517 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
10518 	 using-declaration that designates a member of the current
10519 	 instantiation (c++/53549).  */
10520       if (DECL_DEPENDENT_P (t)
10521 	  || uses_template_parms (USING_DECL_SCOPE (t)))
10522 	{
10523 	  tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
10524 					 complain, in_decl);
10525 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
10526 	  r = do_class_using_decl (inst_scope, name);
10527 	  if (!r)
10528 	    r = error_mark_node;
10529 	  else
10530 	    {
10531 	      TREE_PROTECTED (r) = TREE_PROTECTED (t);
10532 	      TREE_PRIVATE (r) = TREE_PRIVATE (t);
10533 	    }
10534 	}
10535       else
10536 	{
10537 	  r = copy_node (t);
10538 	  DECL_CHAIN (r) = NULL_TREE;
10539 	}
10540       break;
10541 
10542     case TYPE_DECL:
10543     case VAR_DECL:
10544       {
10545 	tree argvec = NULL_TREE;
10546 	tree gen_tmpl = NULL_TREE;
10547 	tree spec;
10548 	tree tmpl = NULL_TREE;
10549 	tree ctx;
10550 	tree type = NULL_TREE;
10551 	bool local_p;
10552 
10553 	if (TREE_CODE (t) == TYPE_DECL
10554 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
10555 	  {
10556 	    /* If this is the canonical decl, we don't have to
10557 	       mess with instantiations, and often we can't (for
10558 	       typename, template type parms and such).  Note that
10559 	       TYPE_NAME is not correct for the above test if
10560 	       we've copied the type for a typedef.  */
10561 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10562 	    if (type == error_mark_node)
10563 	      RETURN (error_mark_node);
10564 	    r = TYPE_NAME (type);
10565 	    break;
10566 	  }
10567 
10568 	/* Check to see if we already have the specialization we
10569 	   need.  */
10570 	spec = NULL_TREE;
10571 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
10572 	  {
10573 	    /* T is a static data member or namespace-scope entity.
10574 	       We have to substitute into namespace-scope variables
10575 	       (even though such entities are never templates) because
10576 	       of cases like:
10577 
10578 	         template <class T> void f() { extern T t; }
10579 
10580 	       where the entity referenced is not known until
10581 	       instantiation time.  */
10582 	    local_p = false;
10583 	    ctx = DECL_CONTEXT (t);
10584 	    if (DECL_CLASS_SCOPE_P (t))
10585 	      {
10586 		ctx = tsubst_aggr_type (ctx, args,
10587 					complain,
10588 					in_decl, /*entering_scope=*/1);
10589 		/* If CTX is unchanged, then T is in fact the
10590 		   specialization we want.  That situation occurs when
10591 		   referencing a static data member within in its own
10592 		   class.  We can use pointer equality, rather than
10593 		   same_type_p, because DECL_CONTEXT is always
10594 		   canonical...  */
10595 		if (ctx == DECL_CONTEXT (t)
10596 		    && (TREE_CODE (t) != TYPE_DECL
10597 			/* ... unless T is a member template; in which
10598 			   case our caller can be willing to create a
10599 			   specialization of that template represented
10600 			   by T.  */
10601 			|| !(DECL_TI_TEMPLATE (t)
10602 			     && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t)))))
10603 		  spec = t;
10604 	      }
10605 
10606 	    if (!spec)
10607 	      {
10608 		tmpl = DECL_TI_TEMPLATE (t);
10609 		gen_tmpl = most_general_template (tmpl);
10610 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
10611 		if (argvec == error_mark_node)
10612 		  RETURN (error_mark_node);
10613 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
10614 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
10615 	      }
10616 	  }
10617 	else
10618 	  {
10619 	    /* A local variable.  */
10620 	    local_p = true;
10621 	    /* Subsequent calls to pushdecl will fill this in.  */
10622 	    ctx = NULL_TREE;
10623 	    spec = retrieve_local_specialization (t);
10624 	  }
10625 	/* If we already have the specialization we need, there is
10626 	   nothing more to do.  */
10627 	if (spec)
10628 	  {
10629 	    r = spec;
10630 	    break;
10631 	  }
10632 
10633 	if (TREE_CODE (t) == VAR_DECL && DECL_ANON_UNION_VAR_P (t))
10634 	  {
10635 	    /* Just use name lookup to find a member alias for an anonymous
10636 	       union, but then add it to the hash table.  */
10637 	    r = lookup_name (DECL_NAME (t));
10638 	    gcc_assert (DECL_ANON_UNION_VAR_P (r));
10639 	    register_local_specialization (r, t);
10640 	    break;
10641 	  }
10642 
10643 	/* Create a new node for the specialization we need.  */
10644 	r = copy_decl (t);
10645 	if (type == NULL_TREE)
10646 	  {
10647 	    if (is_typedef_decl (t))
10648 	      type = DECL_ORIGINAL_TYPE (t);
10649 	    else
10650 	      type = TREE_TYPE (t);
10651 	    if (TREE_CODE (t) == VAR_DECL
10652 		&& VAR_HAD_UNKNOWN_BOUND (t)
10653 		&& type != error_mark_node)
10654 	      type = strip_array_domain (type);
10655 	    type = tsubst (type, args, complain, in_decl);
10656 	  }
10657 	if (TREE_CODE (r) == VAR_DECL)
10658 	  {
10659 	    /* Even if the original location is out of scope, the
10660 	       newly substituted one is not.  */
10661 	    DECL_DEAD_FOR_LOCAL (r) = 0;
10662 	    DECL_INITIALIZED_P (r) = 0;
10663 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
10664 	    if (type == error_mark_node)
10665 	      RETURN (error_mark_node);
10666 	    if (TREE_CODE (type) == FUNCTION_TYPE)
10667 	      {
10668 		/* It may seem that this case cannot occur, since:
10669 
10670 		     typedef void f();
10671 		     void g() { f x; }
10672 
10673 		   declares a function, not a variable.  However:
10674 
10675 		     typedef void f();
10676 		     template <typename T> void g() { T t; }
10677 		     template void g<f>();
10678 
10679 		   is an attempt to declare a variable with function
10680 		   type.  */
10681 		error ("variable %qD has function type",
10682 		       /* R is not yet sufficiently initialized, so we
10683 			  just use its name.  */
10684 		       DECL_NAME (r));
10685 		RETURN (error_mark_node);
10686 	      }
10687 	    type = complete_type (type);
10688 	    /* Wait until cp_finish_decl to set this again, to handle
10689 	       circular dependency (template/instantiate6.C). */
10690 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
10691 	    type = check_var_type (DECL_NAME (r), type);
10692 
10693 	    if (DECL_HAS_VALUE_EXPR_P (t))
10694 	      {
10695 		tree ve = DECL_VALUE_EXPR (t);
10696 		ve = tsubst_expr (ve, args, complain, in_decl,
10697 				  /*constant_expression_p=*/false);
10698 		if (REFERENCE_REF_P (ve))
10699 		  {
10700 		    gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
10701 		    ve = TREE_OPERAND (ve, 0);
10702 		  }
10703 		SET_DECL_VALUE_EXPR (r, ve);
10704 	      }
10705 	  }
10706 	else if (DECL_SELF_REFERENCE_P (t))
10707 	  SET_DECL_SELF_REFERENCE_P (r);
10708 	TREE_TYPE (r) = type;
10709 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
10710 	DECL_CONTEXT (r) = ctx;
10711 	/* Clear out the mangled name and RTL for the instantiation.  */
10712 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
10713 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10714 	  SET_DECL_RTL (r, NULL);
10715 	/* The initializer must not be expanded until it is required;
10716 	   see [temp.inst].  */
10717 	DECL_INITIAL (r) = NULL_TREE;
10718 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10719 	  SET_DECL_RTL (r, NULL);
10720 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10721 	if (TREE_CODE (r) == VAR_DECL)
10722 	  {
10723 	    /* Possibly limit visibility based on template args.  */
10724 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10725 	    if (DECL_VISIBILITY_SPECIFIED (t))
10726 	      {
10727 		DECL_VISIBILITY_SPECIFIED (r) = 0;
10728 		DECL_ATTRIBUTES (r)
10729 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10730 	      }
10731 	    determine_visibility (r);
10732 	  }
10733 
10734 	if (!local_p)
10735 	  {
10736 	    /* A static data member declaration is always marked
10737 	       external when it is declared in-class, even if an
10738 	       initializer is present.  We mimic the non-template
10739 	       processing here.  */
10740 	    DECL_EXTERNAL (r) = 1;
10741 
10742 	    register_specialization (r, gen_tmpl, argvec, false, hash);
10743 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10744 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
10745 	  }
10746 	else if (cp_unevaluated_operand)
10747 	  {
10748 	    /* We're substituting this var in a decltype outside of its
10749 	       scope, such as for a lambda return type.  Don't add it to
10750 	       local_specializations, do perform auto deduction.  */
10751 	    tree auto_node = type_uses_auto (type);
10752 	    if (auto_node)
10753 	      {
10754 		tree init
10755 		  = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10756 				 /*constant_expression_p=*/false);
10757 		init = resolve_nondeduced_context (init);
10758 		TREE_TYPE (r) = type
10759 		  = do_auto_deduction (type, init, auto_node);
10760 	      }
10761 	  }
10762 	else
10763 	  register_local_specialization (r, t);
10764 
10765 	DECL_CHAIN (r) = NULL_TREE;
10766 
10767 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10768 					/*flags=*/0,
10769 					args, complain, in_decl);
10770 
10771 	/* Preserve a typedef that names a type.  */
10772 	if (is_typedef_decl (r))
10773 	  {
10774 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10775 	    set_underlying_type (r);
10776 	  }
10777 
10778 	layout_decl (r, 0);
10779       }
10780       break;
10781 
10782     default:
10783       gcc_unreachable ();
10784     }
10785 #undef RETURN
10786 
10787  out:
10788   /* Restore the file and line information.  */
10789   input_location = saved_loc;
10790 
10791   return r;
10792 }
10793 
10794 /* Substitute into the ARG_TYPES of a function type.
10795    If END is a TREE_CHAIN, leave it and any following types
10796    un-substituted.  */
10797 
10798 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)10799 tsubst_arg_types (tree arg_types,
10800 		  tree args,
10801 		  tree end,
10802 		  tsubst_flags_t complain,
10803 		  tree in_decl)
10804 {
10805   tree remaining_arg_types;
10806   tree type = NULL_TREE;
10807   int i = 1;
10808   tree expanded_args = NULL_TREE;
10809   tree default_arg;
10810 
10811   if (!arg_types || arg_types == void_list_node || arg_types == end)
10812     return arg_types;
10813 
10814   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10815 					  args, end, complain, in_decl);
10816   if (remaining_arg_types == error_mark_node)
10817     return error_mark_node;
10818 
10819   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10820     {
10821       /* For a pack expansion, perform substitution on the
10822          entire expression. Later on, we'll handle the arguments
10823          one-by-one.  */
10824       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10825                                             args, complain, in_decl);
10826 
10827       if (TREE_CODE (expanded_args) == TREE_VEC)
10828         /* So that we'll spin through the parameters, one by one.  */
10829         i = TREE_VEC_LENGTH (expanded_args);
10830       else
10831         {
10832           /* We only partially substituted into the parameter
10833              pack. Our type is TYPE_PACK_EXPANSION.  */
10834           type = expanded_args;
10835           expanded_args = NULL_TREE;
10836         }
10837     }
10838 
10839   while (i > 0) {
10840     --i;
10841 
10842     if (expanded_args)
10843       type = TREE_VEC_ELT (expanded_args, i);
10844     else if (!type)
10845       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10846 
10847     if (type == error_mark_node)
10848       return error_mark_node;
10849     if (VOID_TYPE_P (type))
10850       {
10851         if (complain & tf_error)
10852           {
10853             error ("invalid parameter type %qT", type);
10854             if (in_decl)
10855               error ("in declaration %q+D", in_decl);
10856           }
10857         return error_mark_node;
10858     }
10859     /* DR 657. */
10860     if (abstract_virtuals_error_sfinae (NULL_TREE, type, complain))
10861       return error_mark_node;
10862 
10863     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10864        top-level qualifiers as required.  */
10865     type = cv_unqualified (type_decays_to (type));
10866 
10867     /* We do not substitute into default arguments here.  The standard
10868        mandates that they be instantiated only when needed, which is
10869        done in build_over_call.  */
10870     default_arg = TREE_PURPOSE (arg_types);
10871 
10872     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10873       {
10874         /* We've instantiated a template before its default arguments
10875            have been parsed.  This can happen for a nested template
10876            class, and is not an error unless we require the default
10877            argument in a call of this function.  */
10878         remaining_arg_types =
10879           tree_cons (default_arg, type, remaining_arg_types);
10880         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
10881       }
10882     else
10883       remaining_arg_types =
10884         hash_tree_cons (default_arg, type, remaining_arg_types);
10885   }
10886 
10887   return remaining_arg_types;
10888 }
10889 
10890 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10891    *not* handle the exception-specification for FNTYPE, because the
10892    initial substitution of explicitly provided template parameters
10893    during argument deduction forbids substitution into the
10894    exception-specification:
10895 
10896      [temp.deduct]
10897 
10898      All references in the function type of the function template to  the
10899      corresponding template parameters are replaced by the specified tem-
10900      plate argument values.  If a substitution in a template parameter or
10901      in  the function type of the function template results in an invalid
10902      type, type deduction fails.  [Note: The equivalent  substitution  in
10903      exception specifications is done only when the function is instanti-
10904      ated, at which point a program is  ill-formed  if  the  substitution
10905      results in an invalid type.]  */
10906 
10907 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)10908 tsubst_function_type (tree t,
10909 		      tree args,
10910 		      tsubst_flags_t complain,
10911 		      tree in_decl)
10912 {
10913   tree return_type;
10914   tree arg_types;
10915   tree fntype;
10916 
10917   /* The TYPE_CONTEXT is not used for function/method types.  */
10918   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10919 
10920   /* Substitute the return type.  */
10921   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10922   if (return_type == error_mark_node)
10923     return error_mark_node;
10924   /* DR 486 clarifies that creation of a function type with an
10925      invalid return type is a deduction failure.  */
10926   if (TREE_CODE (return_type) == ARRAY_TYPE
10927       || TREE_CODE (return_type) == FUNCTION_TYPE)
10928     {
10929       if (complain & tf_error)
10930 	{
10931 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
10932 	    error ("function returning an array");
10933 	  else
10934 	    error ("function returning a function");
10935 	}
10936       return error_mark_node;
10937     }
10938   /* And DR 657. */
10939   if (abstract_virtuals_error_sfinae (NULL_TREE, return_type, complain))
10940     return error_mark_node;
10941 
10942   /* Substitute the argument types.  */
10943   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
10944 				complain, in_decl);
10945   if (arg_types == error_mark_node)
10946     return error_mark_node;
10947 
10948   /* Construct a new type node and return it.  */
10949   if (TREE_CODE (t) == FUNCTION_TYPE)
10950     {
10951       fntype = build_function_type (return_type, arg_types);
10952       fntype = apply_memfn_quals (fntype,
10953 				  type_memfn_quals (t),
10954 				  type_memfn_rqual (t));
10955     }
10956   else
10957     {
10958       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10959       if (! MAYBE_CLASS_TYPE_P (r))
10960 	{
10961 	  /* [temp.deduct]
10962 
10963 	     Type deduction may fail for any of the following
10964 	     reasons:
10965 
10966 	     -- Attempting to create "pointer to member of T" when T
10967 	     is not a class type.  */
10968 	  if (complain & tf_error)
10969 	    error ("creating pointer to member function of non-class type %qT",
10970 		      r);
10971 	  return error_mark_node;
10972 	}
10973 
10974       fntype = build_method_type_directly (r, return_type,
10975 					   TREE_CHAIN (arg_types));
10976       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
10977     }
10978   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10979 
10980   return fntype;
10981 }
10982 
10983 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10984    ARGS into that specification, and return the substituted
10985    specification.  If there is no specification, return NULL_TREE.  */
10986 
10987 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)10988 tsubst_exception_specification (tree fntype,
10989 				tree args,
10990 				tsubst_flags_t complain,
10991 				tree in_decl,
10992 				bool defer_ok)
10993 {
10994   tree specs;
10995   tree new_specs;
10996 
10997   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10998   new_specs = NULL_TREE;
10999   if (specs && TREE_PURPOSE (specs))
11000     {
11001       /* A noexcept-specifier.  */
11002       tree expr = TREE_PURPOSE (specs);
11003       if (TREE_CODE (expr) == INTEGER_CST)
11004 	new_specs = expr;
11005       else if (defer_ok)
11006 	{
11007 	  /* Defer instantiation of noexcept-specifiers to avoid
11008 	     excessive instantiations (c++/49107).  */
11009 	  new_specs = make_node (DEFERRED_NOEXCEPT);
11010 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
11011 	    {
11012 	      /* We already partially instantiated this member template,
11013 		 so combine the new args with the old.  */
11014 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
11015 		= DEFERRED_NOEXCEPT_PATTERN (expr);
11016 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
11017 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
11018 	    }
11019 	  else
11020 	    {
11021 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
11022 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
11023 	    }
11024 	}
11025       else
11026 	new_specs = tsubst_copy_and_build
11027 	  (expr, args, complain, in_decl, /*function_p=*/false,
11028 	   /*integral_constant_expression_p=*/true);
11029       new_specs = build_noexcept_spec (new_specs, complain);
11030     }
11031   else if (specs)
11032     {
11033       if (! TREE_VALUE (specs))
11034 	new_specs = specs;
11035       else
11036 	while (specs)
11037 	  {
11038 	    tree spec;
11039             int i, len = 1;
11040             tree expanded_specs = NULL_TREE;
11041 
11042             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
11043               {
11044                 /* Expand the pack expansion type.  */
11045                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
11046                                                        args, complain,
11047                                                        in_decl);
11048 
11049 		if (expanded_specs == error_mark_node)
11050 		  return error_mark_node;
11051 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
11052 		  len = TREE_VEC_LENGTH (expanded_specs);
11053 		else
11054 		  {
11055 		    /* We're substituting into a member template, so
11056 		       we got a TYPE_PACK_EXPANSION back.  Add that
11057 		       expansion and move on.  */
11058 		    gcc_assert (TREE_CODE (expanded_specs)
11059 				== TYPE_PACK_EXPANSION);
11060 		    new_specs = add_exception_specifier (new_specs,
11061 							 expanded_specs,
11062 							 complain);
11063 		    specs = TREE_CHAIN (specs);
11064 		    continue;
11065 		  }
11066               }
11067 
11068             for (i = 0; i < len; ++i)
11069               {
11070                 if (expanded_specs)
11071                   spec = TREE_VEC_ELT (expanded_specs, i);
11072                 else
11073                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
11074                 if (spec == error_mark_node)
11075                   return spec;
11076                 new_specs = add_exception_specifier (new_specs, spec,
11077                                                      complain);
11078               }
11079 
11080             specs = TREE_CHAIN (specs);
11081 	  }
11082     }
11083   return new_specs;
11084 }
11085 
11086 /* Take the tree structure T and replace template parameters used
11087    therein with the argument vector ARGS.  IN_DECL is an associated
11088    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
11089    Issue error and warning messages under control of COMPLAIN.  Note
11090    that we must be relatively non-tolerant of extensions here, in
11091    order to preserve conformance; if we allow substitutions that
11092    should not be allowed, we may allow argument deductions that should
11093    not succeed, and therefore report ambiguous overload situations
11094    where there are none.  In theory, we could allow the substitution,
11095    but indicate that it should have failed, and allow our caller to
11096    make sure that the right thing happens, but we don't try to do this
11097    yet.
11098 
11099    This function is used for dealing with types, decls and the like;
11100    for expressions, use tsubst_expr or tsubst_copy.  */
11101 
11102 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)11103 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11104 {
11105   enum tree_code code;
11106   tree type, r = NULL_TREE;
11107 
11108   if (t == NULL_TREE || t == error_mark_node
11109       || t == integer_type_node
11110       || t == void_type_node
11111       || t == char_type_node
11112       || t == unknown_type_node
11113       || TREE_CODE (t) == NAMESPACE_DECL
11114       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
11115     return t;
11116 
11117   if (DECL_P (t))
11118     return tsubst_decl (t, args, complain);
11119 
11120   if (args == NULL_TREE)
11121     return t;
11122 
11123   code = TREE_CODE (t);
11124 
11125   if (code == IDENTIFIER_NODE)
11126     type = IDENTIFIER_TYPE_VALUE (t);
11127   else
11128     type = TREE_TYPE (t);
11129 
11130   gcc_assert (type != unknown_type_node);
11131 
11132   /* Reuse typedefs.  We need to do this to handle dependent attributes,
11133      such as attribute aligned.  */
11134   if (TYPE_P (t)
11135       && typedef_variant_p (t))
11136     {
11137       tree decl = TYPE_NAME (t);
11138 
11139       if (alias_template_specialization_p (t))
11140 	{
11141 	  /* DECL represents an alias template and we want to
11142 	     instantiate it.  */
11143 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
11144 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
11145 	  r = instantiate_alias_template (tmpl, gen_args, complain);
11146 	}
11147       else if (DECL_CLASS_SCOPE_P (decl)
11148 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
11149 	       && uses_template_parms (DECL_CONTEXT (decl)))
11150 	{
11151 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
11152 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
11153 	  r = retrieve_specialization (tmpl, gen_args, 0);
11154 	}
11155       else if (DECL_FUNCTION_SCOPE_P (decl)
11156 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
11157 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
11158 	r = retrieve_local_specialization (decl);
11159       else
11160 	/* The typedef is from a non-template context.  */
11161 	return t;
11162 
11163       if (r)
11164 	{
11165 	  r = TREE_TYPE (r);
11166 	  r = cp_build_qualified_type_real
11167 	    (r, cp_type_quals (t) | cp_type_quals (r),
11168 	     complain | tf_ignore_bad_quals);
11169 	  return r;
11170 	}
11171       else
11172 	{
11173 	  /* We don't have an instantiation yet, so drop the typedef.  */
11174 	  int quals = cp_type_quals (t);
11175 	  t = DECL_ORIGINAL_TYPE (decl);
11176 	  t = cp_build_qualified_type_real (t, quals,
11177 					    complain | tf_ignore_bad_quals);
11178 	}
11179     }
11180 
11181   if (type
11182       && code != TYPENAME_TYPE
11183       && code != TEMPLATE_TYPE_PARM
11184       && code != IDENTIFIER_NODE
11185       && code != FUNCTION_TYPE
11186       && code != METHOD_TYPE)
11187     type = tsubst (type, args, complain, in_decl);
11188   if (type == error_mark_node)
11189     return error_mark_node;
11190 
11191   switch (code)
11192     {
11193     case RECORD_TYPE:
11194     case UNION_TYPE:
11195     case ENUMERAL_TYPE:
11196       return tsubst_aggr_type (t, args, complain, in_decl,
11197 			       /*entering_scope=*/0);
11198 
11199     case ERROR_MARK:
11200     case IDENTIFIER_NODE:
11201     case VOID_TYPE:
11202     case REAL_TYPE:
11203     case COMPLEX_TYPE:
11204     case VECTOR_TYPE:
11205     case BOOLEAN_TYPE:
11206     case NULLPTR_TYPE:
11207     case LANG_TYPE:
11208       return t;
11209 
11210     case INTEGER_TYPE:
11211       if (t == integer_type_node)
11212 	return t;
11213 
11214       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
11215 	  && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
11216 	return t;
11217 
11218       {
11219 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
11220 
11221 	max = tsubst_expr (omax, args, complain, in_decl,
11222 			   /*integral_constant_expression_p=*/false);
11223 
11224 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
11225 	   needed.  */
11226 	if (TREE_CODE (max) == NOP_EXPR
11227 	    && TREE_SIDE_EFFECTS (omax)
11228 	    && !TREE_TYPE (max))
11229 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
11230 
11231 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
11232 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
11233 	   constant expression.  */
11234 	if (processing_template_decl
11235 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
11236 	  {
11237 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
11238 	    TREE_SIDE_EFFECTS (max) = 1;
11239 	  }
11240 
11241 	return compute_array_index_type (NULL_TREE, max, complain);
11242       }
11243 
11244     case TEMPLATE_TYPE_PARM:
11245     case TEMPLATE_TEMPLATE_PARM:
11246     case BOUND_TEMPLATE_TEMPLATE_PARM:
11247     case TEMPLATE_PARM_INDEX:
11248       {
11249 	int idx;
11250 	int level;
11251 	int levels;
11252 	tree arg = NULL_TREE;
11253 
11254 	r = NULL_TREE;
11255 
11256 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
11257 	template_parm_level_and_index (t, &level, &idx);
11258 
11259 	levels = TMPL_ARGS_DEPTH (args);
11260 	if (level <= levels)
11261 	  {
11262 	    arg = TMPL_ARG (args, level, idx);
11263 
11264 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
11265 	      {
11266 		/* See through ARGUMENT_PACK_SELECT arguments. */
11267 		arg = ARGUMENT_PACK_SELECT_ARG (arg);
11268 		/* If the selected argument is an expansion E, that most
11269 		   likely means we were called from
11270 		   gen_elem_of_pack_expansion_instantiation during the
11271 		   substituting of pack an argument pack (which Ith
11272 		   element is a pack expansion, where I is
11273 		   ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
11274 		   In this case, the Ith element resulting from this
11275 		   substituting is going to be a pack expansion, which
11276 		   pattern is the pattern of E.  Let's return the
11277 		   pattern of E, and
11278 		   gen_elem_of_pack_expansion_instantiation will
11279 		   build the resulting pack expansion from it.  */
11280 		if (PACK_EXPANSION_P (arg))
11281 		  arg = PACK_EXPANSION_PATTERN (arg);
11282 	      }
11283 	  }
11284 
11285 	if (arg == error_mark_node)
11286 	  return error_mark_node;
11287 	else if (arg != NULL_TREE)
11288 	  {
11289 	    if (ARGUMENT_PACK_P (arg))
11290 	      /* If ARG is an argument pack, we don't actually want to
11291 		 perform a substitution here, because substitutions
11292 		 for argument packs are only done
11293 		 element-by-element. We can get to this point when
11294 		 substituting the type of a non-type template
11295 		 parameter pack, when that type actually contains
11296 		 template parameter packs from an outer template, e.g.,
11297 
11298 	         template<typename... Types> struct A {
11299 		   template<Types... Values> struct B { };
11300                  };  */
11301 	      return t;
11302 
11303 	    if (code == TEMPLATE_TYPE_PARM)
11304 	      {
11305 		int quals;
11306 		gcc_assert (TYPE_P (arg));
11307 
11308 		quals = cp_type_quals (arg) | cp_type_quals (t);
11309 
11310 		return cp_build_qualified_type_real
11311 		  (arg, quals, complain | tf_ignore_bad_quals);
11312 	      }
11313 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11314 	      {
11315 		/* We are processing a type constructed from a
11316 		   template template parameter.  */
11317 		tree argvec = tsubst (TYPE_TI_ARGS (t),
11318 				      args, complain, in_decl);
11319 		if (argvec == error_mark_node)
11320 		  return error_mark_node;
11321 
11322 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
11323 			    || TREE_CODE (arg) == TEMPLATE_DECL
11324 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
11325 
11326 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
11327 		  /* Consider this code:
11328 
11329 			template <template <class> class Template>
11330 			struct Internal {
11331 			template <class Arg> using Bind = Template<Arg>;
11332 			};
11333 
11334 			template <template <class> class Template, class Arg>
11335 			using Instantiate = Template<Arg>; //#0
11336 
11337 			template <template <class> class Template,
11338                                   class Argument>
11339 			using Bind =
11340 			  Instantiate<Internal<Template>::template Bind,
11341 				      Argument>; //#1
11342 
11343 		     When #1 is parsed, the
11344 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
11345 		     parameter `Template' in #0 matches the
11346 		     UNBOUND_CLASS_TEMPLATE representing the argument
11347 		     `Internal<Template>::template Bind'; We then want
11348 		     to assemble the type `Bind<Argument>' that can't
11349 		     be fully created right now, because
11350 		     `Internal<Template>' not being complete, the Bind
11351 		     template cannot be looked up in that context.  So
11352 		     we need to "store" `Bind<Argument>' for later
11353 		     when the context of Bind becomes complete.  Let's
11354 		     store that in a TYPENAME_TYPE.  */
11355 		  return make_typename_type (TYPE_CONTEXT (arg),
11356 					     build_nt (TEMPLATE_ID_EXPR,
11357 						       TYPE_IDENTIFIER (arg),
11358 						       argvec),
11359 					     typename_type,
11360 					     complain);
11361 
11362 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
11363 		   are resolving nested-types in the signature of a
11364 		   member function templates.  Otherwise ARG is a
11365 		   TEMPLATE_DECL and is the real template to be
11366 		   instantiated.  */
11367 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
11368 		  arg = TYPE_NAME (arg);
11369 
11370 		r = lookup_template_class (arg,
11371 					   argvec, in_decl,
11372 					   DECL_CONTEXT (arg),
11373 					    /*entering_scope=*/0,
11374 					   complain);
11375 		return cp_build_qualified_type_real
11376 		  (r, cp_type_quals (t), complain);
11377 	      }
11378 	    else
11379 	      /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
11380 	      return convert_from_reference (unshare_expr (arg));
11381 	  }
11382 
11383 	if (level == 1)
11384 	  /* This can happen during the attempted tsubst'ing in
11385 	     unify.  This means that we don't yet have any information
11386 	     about the template parameter in question.  */
11387 	  return t;
11388 
11389 	/* Early in template argument deduction substitution, we don't
11390 	   want to reduce the level of 'auto', or it will be confused
11391 	   with a normal template parm in subsequent deduction.  */
11392 	if (is_auto (t) && (complain & tf_partial))
11393 	  return t;
11394 
11395 	/* If we get here, we must have been looking at a parm for a
11396 	   more deeply nested template.  Make a new version of this
11397 	   template parameter, but with a lower level.  */
11398 	switch (code)
11399 	  {
11400 	  case TEMPLATE_TYPE_PARM:
11401 	  case TEMPLATE_TEMPLATE_PARM:
11402 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
11403 	    if (cp_type_quals (t))
11404 	      {
11405 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
11406 		r = cp_build_qualified_type_real
11407 		  (r, cp_type_quals (t),
11408 		   complain | (code == TEMPLATE_TYPE_PARM
11409 			       ? tf_ignore_bad_quals : 0));
11410 	      }
11411 	    else
11412 	      {
11413 		r = copy_type (t);
11414 		TEMPLATE_TYPE_PARM_INDEX (r)
11415 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
11416 						r, levels, args, complain);
11417 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
11418 		TYPE_MAIN_VARIANT (r) = r;
11419 		TYPE_POINTER_TO (r) = NULL_TREE;
11420 		TYPE_REFERENCE_TO (r) = NULL_TREE;
11421 
11422 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
11423 		  /* We have reduced the level of the template
11424 		     template parameter, but not the levels of its
11425 		     template parameters, so canonical_type_parameter
11426 		     will not be able to find the canonical template
11427 		     template parameter for this level. Thus, we
11428 		     require structural equality checking to compare
11429 		     TEMPLATE_TEMPLATE_PARMs. */
11430 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
11431 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
11432 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
11433 		else
11434 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
11435 
11436 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
11437 		  {
11438 		    tree argvec = tsubst (TYPE_TI_ARGS (t), args,
11439 					  complain, in_decl);
11440 		    if (argvec == error_mark_node)
11441 		      return error_mark_node;
11442 
11443 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
11444 		      = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
11445 		  }
11446 	      }
11447 	    break;
11448 
11449 	  case TEMPLATE_PARM_INDEX:
11450 	    r = reduce_template_parm_level (t, type, levels, args, complain);
11451 	    break;
11452 
11453 	  default:
11454 	    gcc_unreachable ();
11455 	  }
11456 
11457 	return r;
11458       }
11459 
11460     case TREE_LIST:
11461       {
11462 	tree purpose, value, chain;
11463 
11464 	if (t == void_list_node)
11465 	  return t;
11466 
11467 	purpose = TREE_PURPOSE (t);
11468 	if (purpose)
11469 	  {
11470 	    purpose = tsubst (purpose, args, complain, in_decl);
11471 	    if (purpose == error_mark_node)
11472 	      return error_mark_node;
11473 	  }
11474 	value = TREE_VALUE (t);
11475 	if (value)
11476 	  {
11477 	    value = tsubst (value, args, complain, in_decl);
11478 	    if (value == error_mark_node)
11479 	      return error_mark_node;
11480 	  }
11481 	chain = TREE_CHAIN (t);
11482 	if (chain && chain != void_type_node)
11483 	  {
11484 	    chain = tsubst (chain, args, complain, in_decl);
11485 	    if (chain == error_mark_node)
11486 	      return error_mark_node;
11487 	  }
11488 	if (purpose == TREE_PURPOSE (t)
11489 	    && value == TREE_VALUE (t)
11490 	    && chain == TREE_CHAIN (t))
11491 	  return t;
11492 	return hash_tree_cons (purpose, value, chain);
11493       }
11494 
11495     case TREE_BINFO:
11496       /* We should never be tsubsting a binfo.  */
11497       gcc_unreachable ();
11498 
11499     case TREE_VEC:
11500       /* A vector of template arguments.  */
11501       gcc_assert (!type);
11502       return tsubst_template_args (t, args, complain, in_decl);
11503 
11504     case POINTER_TYPE:
11505     case REFERENCE_TYPE:
11506       {
11507 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
11508 	  return t;
11509 
11510 	/* [temp.deduct]
11511 
11512 	   Type deduction may fail for any of the following
11513 	   reasons:
11514 
11515 	   -- Attempting to create a pointer to reference type.
11516 	   -- Attempting to create a reference to a reference type or
11517 	      a reference to void.
11518 
11519 	  Core issue 106 says that creating a reference to a reference
11520 	  during instantiation is no longer a cause for failure. We
11521 	  only enforce this check in strict C++98 mode.  */
11522 	if ((TREE_CODE (type) == REFERENCE_TYPE
11523 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
11524 	    || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
11525 	  {
11526 	    static location_t last_loc;
11527 
11528 	    /* We keep track of the last time we issued this error
11529 	       message to avoid spewing a ton of messages during a
11530 	       single bad template instantiation.  */
11531 	    if (complain & tf_error
11532 		&& last_loc != input_location)
11533 	      {
11534 		if (TREE_CODE (type) == VOID_TYPE)
11535 		  error ("forming reference to void");
11536                else if (code == POINTER_TYPE)
11537                  error ("forming pointer to reference type %qT", type);
11538                else
11539 		  error ("forming reference to reference type %qT", type);
11540 		last_loc = input_location;
11541 	      }
11542 
11543 	    return error_mark_node;
11544 	  }
11545 	else if (code == POINTER_TYPE)
11546 	  {
11547 	    r = build_pointer_type (type);
11548 	    if (TREE_CODE (type) == METHOD_TYPE)
11549 	      r = build_ptrmemfunc_type (r);
11550 	  }
11551 	else if (TREE_CODE (type) == REFERENCE_TYPE)
11552 	  /* In C++0x, during template argument substitution, when there is an
11553 	     attempt to create a reference to a reference type, reference
11554 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
11555 
11556 	     "If a template-argument for a template-parameter T names a type
11557 	     that is a reference to a type A, an attempt to create the type
11558 	     'lvalue reference to cv T' creates the type 'lvalue reference to
11559 	     A,' while an attempt to create the type type rvalue reference to
11560 	     cv T' creates the type T"
11561 	  */
11562 	  r = cp_build_reference_type
11563 	      (TREE_TYPE (type),
11564 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
11565 	else
11566 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
11567 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11568 
11569 	if (r != error_mark_node)
11570 	  /* Will this ever be needed for TYPE_..._TO values?  */
11571 	  layout_type (r);
11572 
11573 	return r;
11574       }
11575     case OFFSET_TYPE:
11576       {
11577 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
11578 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
11579 	  {
11580 	    /* [temp.deduct]
11581 
11582 	       Type deduction may fail for any of the following
11583 	       reasons:
11584 
11585 	       -- Attempting to create "pointer to member of T" when T
11586 		  is not a class type.  */
11587 	    if (complain & tf_error)
11588 	      error ("creating pointer to member of non-class type %qT", r);
11589 	    return error_mark_node;
11590 	  }
11591 	if (TREE_CODE (type) == REFERENCE_TYPE)
11592 	  {
11593 	    if (complain & tf_error)
11594 	      error ("creating pointer to member reference type %qT", type);
11595 	    return error_mark_node;
11596 	  }
11597 	if (TREE_CODE (type) == VOID_TYPE)
11598 	  {
11599 	    if (complain & tf_error)
11600 	      error ("creating pointer to member of type void");
11601 	    return error_mark_node;
11602 	  }
11603 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
11604 	if (TREE_CODE (type) == FUNCTION_TYPE)
11605 	  {
11606 	    /* The type of the implicit object parameter gets its
11607 	       cv-qualifiers from the FUNCTION_TYPE. */
11608 	    tree memptr;
11609 	    tree method_type
11610 	      = build_memfn_type (type, r, type_memfn_quals (type),
11611 				  type_memfn_rqual (type));
11612 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
11613 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
11614 						 complain);
11615 	  }
11616 	else
11617 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
11618 					       cp_type_quals (t),
11619 					       complain);
11620       }
11621     case FUNCTION_TYPE:
11622     case METHOD_TYPE:
11623       {
11624 	tree fntype;
11625 	tree specs;
11626 	fntype = tsubst_function_type (t, args, complain, in_decl);
11627 	if (fntype == error_mark_node)
11628 	  return error_mark_node;
11629 
11630 	/* Substitute the exception specification.  */
11631 	specs = tsubst_exception_specification (t, args, complain,
11632 						in_decl, /*defer_ok*/true);
11633 	if (specs == error_mark_node)
11634 	  return error_mark_node;
11635 	if (specs)
11636 	  fntype = build_exception_variant (fntype, specs);
11637 	return fntype;
11638       }
11639     case ARRAY_TYPE:
11640       {
11641 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
11642 	if (domain == error_mark_node)
11643 	  return error_mark_node;
11644 
11645 	/* As an optimization, we avoid regenerating the array type if
11646 	   it will obviously be the same as T.  */
11647 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
11648 	  return t;
11649 
11650 	/* These checks should match the ones in grokdeclarator.
11651 
11652 	   [temp.deduct]
11653 
11654 	   The deduction may fail for any of the following reasons:
11655 
11656 	   -- Attempting to create an array with an element type that
11657 	      is void, a function type, or a reference type, or [DR337]
11658 	      an abstract class type.  */
11659 	if (TREE_CODE (type) == VOID_TYPE
11660 	    || TREE_CODE (type) == FUNCTION_TYPE
11661 	    || TREE_CODE (type) == REFERENCE_TYPE)
11662 	  {
11663 	    if (complain & tf_error)
11664 	      error ("creating array of %qT", type);
11665 	    return error_mark_node;
11666 	  }
11667 	if (ABSTRACT_CLASS_TYPE_P (type))
11668 	  {
11669 	    if (complain & tf_error)
11670 	      error ("creating array of %qT, which is an abstract class type",
11671 		     type);
11672 	    return error_mark_node;
11673 	  }
11674 
11675 	r = build_cplus_array_type (type, domain);
11676 
11677 	if (TYPE_USER_ALIGN (t))
11678 	  {
11679 	    TYPE_ALIGN (r) = TYPE_ALIGN (t);
11680 	    TYPE_USER_ALIGN (r) = 1;
11681 	  }
11682 
11683 	return r;
11684       }
11685 
11686     case TYPENAME_TYPE:
11687       {
11688 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11689 				     in_decl, /*entering_scope=*/1);
11690 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
11691 			      complain, in_decl);
11692 
11693 	if (ctx == error_mark_node || f == error_mark_node)
11694 	  return error_mark_node;
11695 
11696 	if (!MAYBE_CLASS_TYPE_P (ctx))
11697 	  {
11698 	    if (complain & tf_error)
11699 	      error ("%qT is not a class, struct, or union type", ctx);
11700 	    return error_mark_node;
11701 	  }
11702 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
11703 	  {
11704 	    /* Normally, make_typename_type does not require that the CTX
11705 	       have complete type in order to allow things like:
11706 
11707 		 template <class T> struct S { typename S<T>::X Y; };
11708 
11709 	       But, such constructs have already been resolved by this
11710 	       point, so here CTX really should have complete type, unless
11711 	       it's a partial instantiation.  */
11712 	    ctx = complete_type (ctx);
11713 	    if (!COMPLETE_TYPE_P (ctx))
11714 	      {
11715 		if (complain & tf_error)
11716 		  cxx_incomplete_type_error (NULL_TREE, ctx);
11717 		return error_mark_node;
11718 	      }
11719 	  }
11720 
11721 	f = make_typename_type (ctx, f, typename_type,
11722 				complain | tf_keep_type_decl);
11723 	if (f == error_mark_node)
11724 	  return f;
11725 	if (TREE_CODE (f) == TYPE_DECL)
11726 	  {
11727 	    complain |= tf_ignore_bad_quals;
11728 	    f = TREE_TYPE (f);
11729 	  }
11730 
11731 	if (TREE_CODE (f) != TYPENAME_TYPE)
11732 	  {
11733 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
11734 	      {
11735 		if (complain & tf_error)
11736 		  error ("%qT resolves to %qT, which is not an enumeration type",
11737 			 t, f);
11738 		else
11739 		  return error_mark_node;
11740 	      }
11741 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
11742 	      {
11743 		if (complain & tf_error)
11744 		  error ("%qT resolves to %qT, which is is not a class type",
11745 			 t, f);
11746 		else
11747 		  return error_mark_node;
11748 	      }
11749 	  }
11750 
11751 	return cp_build_qualified_type_real
11752 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
11753       }
11754 
11755     case UNBOUND_CLASS_TEMPLATE:
11756       {
11757 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
11758 				     in_decl, /*entering_scope=*/1);
11759 	tree name = TYPE_IDENTIFIER (t);
11760 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
11761 
11762 	if (ctx == error_mark_node || name == error_mark_node)
11763 	  return error_mark_node;
11764 
11765 	if (parm_list)
11766 	  parm_list = tsubst_template_parms (parm_list, args, complain);
11767 	return make_unbound_class_template (ctx, name, parm_list, complain);
11768       }
11769 
11770     case TYPEOF_TYPE:
11771       {
11772 	tree type;
11773 
11774 	++cp_unevaluated_operand;
11775 	++c_inhibit_evaluation_warnings;
11776 
11777 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
11778 			    complain, in_decl,
11779 			    /*integral_constant_expression_p=*/false);
11780 
11781 	--cp_unevaluated_operand;
11782 	--c_inhibit_evaluation_warnings;
11783 
11784 	type = finish_typeof (type);
11785 	return cp_build_qualified_type_real (type,
11786 					     cp_type_quals (t)
11787 					     | cp_type_quals (type),
11788 					     complain);
11789       }
11790 
11791     case DECLTYPE_TYPE:
11792       {
11793 	tree type;
11794 
11795 	++cp_unevaluated_operand;
11796 	++c_inhibit_evaluation_warnings;
11797 
11798 	type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
11799 			    complain|tf_decltype, in_decl,
11800 			    /*integral_constant_expression_p=*/false);
11801 
11802 	--cp_unevaluated_operand;
11803 	--c_inhibit_evaluation_warnings;
11804 
11805 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
11806 	  type = lambda_capture_field_type (type);
11807 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
11808 	  type = lambda_proxy_type (type);
11809 	else
11810 	  {
11811 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
11812 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
11813 		&& EXPR_P (type))
11814 	      /* In a template ~id could be either a complement expression
11815 		 or an unqualified-id naming a destructor; if instantiating
11816 		 it produces an expression, it's not an id-expression or
11817 		 member access.  */
11818 	      id = false;
11819 	    type = finish_decltype_type (type, id, complain);
11820 	  }
11821 	return cp_build_qualified_type_real (type,
11822 					     cp_type_quals (t)
11823 					     | cp_type_quals (type),
11824 					     complain);
11825       }
11826 
11827     case UNDERLYING_TYPE:
11828       {
11829 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
11830 			    complain, in_decl);
11831 	return finish_underlying_type (type);
11832       }
11833 
11834     case TYPE_ARGUMENT_PACK:
11835     case NONTYPE_ARGUMENT_PACK:
11836       {
11837         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
11838         tree packed_out =
11839           tsubst_template_args (ARGUMENT_PACK_ARGS (t),
11840                                 args,
11841                                 complain,
11842                                 in_decl);
11843         SET_ARGUMENT_PACK_ARGS (r, packed_out);
11844 
11845         /* For template nontype argument packs, also substitute into
11846            the type.  */
11847         if (code == NONTYPE_ARGUMENT_PACK)
11848           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
11849 
11850         return r;
11851       }
11852       break;
11853 
11854     case INTEGER_CST:
11855     case REAL_CST:
11856     case STRING_CST:
11857     case PLUS_EXPR:
11858     case MINUS_EXPR:
11859     case NEGATE_EXPR:
11860     case NOP_EXPR:
11861     case INDIRECT_REF:
11862     case ADDR_EXPR:
11863     case CALL_EXPR:
11864     case ARRAY_REF:
11865     case SCOPE_REF:
11866       /* We should use one of the expression tsubsts for these codes.  */
11867       gcc_unreachable ();
11868 
11869     default:
11870       sorry ("use of %qs in template", tree_code_name [(int) code]);
11871       return error_mark_node;
11872     }
11873 }
11874 
11875 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11876    type of the expression on the left-hand side of the "." or "->"
11877    operator.  */
11878 
11879 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)11880 tsubst_baselink (tree baselink, tree object_type,
11881 		 tree args, tsubst_flags_t complain, tree in_decl)
11882 {
11883     tree name;
11884     tree qualifying_scope;
11885     tree fns;
11886     tree optype;
11887     tree template_args = 0;
11888     bool template_id_p = false;
11889     bool qualified = BASELINK_QUALIFIED_P (baselink);
11890 
11891     /* A baselink indicates a function from a base class.  Both the
11892        BASELINK_ACCESS_BINFO and the base class referenced may
11893        indicate bases of the template class, rather than the
11894        instantiated class.  In addition, lookups that were not
11895        ambiguous before may be ambiguous now.  Therefore, we perform
11896        the lookup again.  */
11897     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11898     qualifying_scope = tsubst (qualifying_scope, args,
11899 			       complain, in_decl);
11900     fns = BASELINK_FUNCTIONS (baselink);
11901     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11902     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11903       {
11904 	template_id_p = true;
11905 	template_args = TREE_OPERAND (fns, 1);
11906 	fns = TREE_OPERAND (fns, 0);
11907 	if (template_args)
11908 	  template_args = tsubst_template_args (template_args, args,
11909 						complain, in_decl);
11910       }
11911     name = DECL_NAME (get_first_fn (fns));
11912     if (IDENTIFIER_TYPENAME_P (name))
11913       name = mangle_conv_op_name_for_type (optype);
11914     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11915     if (!baselink)
11916       return error_mark_node;
11917 
11918     /* If lookup found a single function, mark it as used at this
11919        point.  (If it lookup found multiple functions the one selected
11920        later by overload resolution will be marked as used at that
11921        point.)  */
11922     if (BASELINK_P (baselink))
11923       fns = BASELINK_FUNCTIONS (baselink);
11924     if (!template_id_p && !really_overloaded_fn (fns))
11925       mark_used (OVL_CURRENT (fns));
11926 
11927     /* Add back the template arguments, if present.  */
11928     if (BASELINK_P (baselink) && template_id_p)
11929       BASELINK_FUNCTIONS (baselink)
11930 	= build_nt (TEMPLATE_ID_EXPR,
11931 		    BASELINK_FUNCTIONS (baselink),
11932 		    template_args);
11933     /* Update the conversion operator type.  */
11934     BASELINK_OPTYPE (baselink) = optype;
11935 
11936     if (!object_type)
11937       object_type = current_class_type;
11938 
11939     if (qualified)
11940       baselink = adjust_result_of_qualified_name_lookup (baselink,
11941 							 qualifying_scope,
11942 							 object_type);
11943     return baselink;
11944 }
11945 
11946 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11947    true if the qualified-id will be a postfix-expression in-and-of
11948    itself; false if more of the postfix-expression follows the
11949    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11950    of "&".  */
11951 
11952 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)11953 tsubst_qualified_id (tree qualified_id, tree args,
11954 		     tsubst_flags_t complain, tree in_decl,
11955 		     bool done, bool address_p)
11956 {
11957   tree expr;
11958   tree scope;
11959   tree name;
11960   bool is_template;
11961   tree template_args;
11962   location_t loc = UNKNOWN_LOCATION;
11963 
11964   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11965 
11966   /* Figure out what name to look up.  */
11967   name = TREE_OPERAND (qualified_id, 1);
11968   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11969     {
11970       is_template = true;
11971       loc = EXPR_LOCATION (name);
11972       template_args = TREE_OPERAND (name, 1);
11973       if (template_args)
11974 	template_args = tsubst_template_args (template_args, args,
11975 					      complain, in_decl);
11976       name = TREE_OPERAND (name, 0);
11977     }
11978   else
11979     {
11980       is_template = false;
11981       template_args = NULL_TREE;
11982     }
11983 
11984   /* Substitute into the qualifying scope.  When there are no ARGS, we
11985      are just trying to simplify a non-dependent expression.  In that
11986      case the qualifying scope may be dependent, and, in any case,
11987      substituting will not help.  */
11988   scope = TREE_OPERAND (qualified_id, 0);
11989   if (args)
11990     {
11991       scope = tsubst (scope, args, complain, in_decl);
11992       expr = tsubst_copy (name, args, complain, in_decl);
11993     }
11994   else
11995     expr = name;
11996 
11997   if (dependent_scope_p (scope))
11998     {
11999       if (is_template)
12000 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
12001       return build_qualified_name (NULL_TREE, scope, expr,
12002 				   QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
12003     }
12004 
12005   if (!BASELINK_P (name) && !DECL_P (expr))
12006     {
12007       if (TREE_CODE (expr) == BIT_NOT_EXPR)
12008 	{
12009 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
12010 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
12011 	    {
12012 	      error ("qualifying type %qT does not match destructor name ~%qT",
12013 		     scope, TREE_OPERAND (expr, 0));
12014 	      expr = error_mark_node;
12015 	    }
12016 	  else
12017 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
12018 					  /*is_type_p=*/0, false);
12019 	}
12020       else
12021 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
12022       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
12023 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
12024 	{
12025 	  if (complain & tf_error)
12026 	    {
12027 	      error ("dependent-name %qE is parsed as a non-type, but "
12028 		     "instantiation yields a type", qualified_id);
12029 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
12030 	    }
12031 	  return error_mark_node;
12032 	}
12033     }
12034 
12035   if (DECL_P (expr))
12036     {
12037       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
12038 					   scope);
12039       /* Remember that there was a reference to this entity.  */
12040       mark_used (expr);
12041     }
12042 
12043   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
12044     {
12045       if (complain & tf_error)
12046 	qualified_name_lookup_error (scope,
12047 				     TREE_OPERAND (qualified_id, 1),
12048 				     expr, input_location);
12049       return error_mark_node;
12050     }
12051 
12052   if (is_template)
12053     expr = lookup_template_function (expr, template_args);
12054 
12055   if (expr == error_mark_node && complain & tf_error)
12056     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
12057 				 expr, input_location);
12058   else if (TYPE_P (scope))
12059     {
12060       expr = (adjust_result_of_qualified_name_lookup
12061 	      (expr, scope, current_nonlambda_class_type ()));
12062       expr = (finish_qualified_id_expr
12063 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
12064 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
12065 	       /*template_arg_p=*/false, complain));
12066     }
12067 
12068   /* Expressions do not generally have reference type.  */
12069   if (TREE_CODE (expr) != SCOPE_REF
12070       /* However, if we're about to form a pointer-to-member, we just
12071 	 want the referenced member referenced.  */
12072       && TREE_CODE (expr) != OFFSET_REF)
12073     expr = convert_from_reference (expr);
12074 
12075   return expr;
12076 }
12077 
12078 /* Like tsubst, but deals with expressions.  This function just replaces
12079    template parms; to finish processing the resultant expression, use
12080    tsubst_copy_and_build or tsubst_expr.  */
12081 
12082 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)12083 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12084 {
12085   enum tree_code code;
12086   tree r;
12087 
12088   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
12089     return t;
12090 
12091   code = TREE_CODE (t);
12092 
12093   switch (code)
12094     {
12095     case PARM_DECL:
12096       r = retrieve_local_specialization (t);
12097 
12098       if (r == NULL_TREE)
12099 	{
12100 	  /* We get here for a use of 'this' in an NSDMI.  */
12101 	  if (DECL_NAME (t) == this_identifier
12102 	      && at_function_scope_p ()
12103 	      && DECL_CONSTRUCTOR_P (current_function_decl))
12104 	    return current_class_ptr;
12105 
12106 	  /* This can happen for a parameter name used later in a function
12107 	     declaration (such as in a late-specified return type).  Just
12108 	     make a dummy decl, since it's only used for its type.  */
12109 	  gcc_assert (cp_unevaluated_operand != 0);
12110 	  r = tsubst_decl (t, args, complain);
12111 	  /* Give it the template pattern as its context; its true context
12112 	     hasn't been instantiated yet and this is good enough for
12113 	     mangling.  */
12114 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
12115 	}
12116 
12117       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
12118 	r = ARGUMENT_PACK_SELECT_ARG (r);
12119       mark_used (r);
12120       return r;
12121 
12122     case CONST_DECL:
12123       {
12124 	tree enum_type;
12125 	tree v;
12126 
12127 	if (DECL_TEMPLATE_PARM_P (t))
12128 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
12129 	/* There is no need to substitute into namespace-scope
12130 	   enumerators.  */
12131 	if (DECL_NAMESPACE_SCOPE_P (t))
12132 	  return t;
12133 	/* If ARGS is NULL, then T is known to be non-dependent.  */
12134 	if (args == NULL_TREE)
12135 	  return integral_constant_value (t);
12136 
12137 	/* Unfortunately, we cannot just call lookup_name here.
12138 	   Consider:
12139 
12140 	     template <int I> int f() {
12141 	     enum E { a = I };
12142 	     struct S { void g() { E e = a; } };
12143 	     };
12144 
12145 	   When we instantiate f<7>::S::g(), say, lookup_name is not
12146 	   clever enough to find f<7>::a.  */
12147 	enum_type
12148 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
12149 			      /*entering_scope=*/0);
12150 
12151 	for (v = TYPE_VALUES (enum_type);
12152 	     v != NULL_TREE;
12153 	     v = TREE_CHAIN (v))
12154 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
12155 	    return TREE_VALUE (v);
12156 
12157 	  /* We didn't find the name.  That should never happen; if
12158 	     name-lookup found it during preliminary parsing, we
12159 	     should find it again here during instantiation.  */
12160 	gcc_unreachable ();
12161       }
12162       return t;
12163 
12164     case FIELD_DECL:
12165       if (DECL_CONTEXT (t))
12166 	{
12167 	  tree ctx;
12168 
12169 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
12170 				  /*entering_scope=*/1);
12171 	  if (ctx != DECL_CONTEXT (t))
12172 	    {
12173 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
12174 	      if (!r)
12175 		{
12176 		  if (complain & tf_error)
12177 		    error ("using invalid field %qD", t);
12178 		  return error_mark_node;
12179 		}
12180 	      return r;
12181 	    }
12182 	}
12183 
12184       return t;
12185 
12186     case VAR_DECL:
12187     case FUNCTION_DECL:
12188       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
12189 	  || local_variable_p (t))
12190 	t = tsubst (t, args, complain, in_decl);
12191       mark_used (t);
12192       return t;
12193 
12194     case NAMESPACE_DECL:
12195       return t;
12196 
12197     case OVERLOAD:
12198       /* An OVERLOAD will always be a non-dependent overload set; an
12199 	 overload set from function scope will just be represented with an
12200 	 IDENTIFIER_NODE, and from class scope with a BASELINK.  */
12201       gcc_assert (!uses_template_parms (t));
12202       return t;
12203 
12204     case BASELINK:
12205       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
12206 
12207     case TEMPLATE_DECL:
12208       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
12209 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
12210 		       args, complain, in_decl);
12211       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
12212 	return tsubst (t, args, complain, in_decl);
12213       else if (DECL_CLASS_SCOPE_P (t)
12214 	       && uses_template_parms (DECL_CONTEXT (t)))
12215 	{
12216 	  /* Template template argument like the following example need
12217 	     special treatment:
12218 
12219 	       template <template <class> class TT> struct C {};
12220 	       template <class T> struct D {
12221 		 template <class U> struct E {};
12222 		 C<E> c;				// #1
12223 	       };
12224 	       D<int> d;				// #2
12225 
12226 	     We are processing the template argument `E' in #1 for
12227 	     the template instantiation #2.  Originally, `E' is a
12228 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
12229 	     have to substitute this with one having context `D<int>'.  */
12230 
12231 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
12232 	  return lookup_field (context, DECL_NAME(t), 0, false);
12233 	}
12234       else
12235 	/* Ordinary template template argument.  */
12236 	return t;
12237 
12238     case CAST_EXPR:
12239     case REINTERPRET_CAST_EXPR:
12240     case CONST_CAST_EXPR:
12241     case STATIC_CAST_EXPR:
12242     case DYNAMIC_CAST_EXPR:
12243     case IMPLICIT_CONV_EXPR:
12244     case CONVERT_EXPR:
12245     case NOP_EXPR:
12246       return build1
12247 	(code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12248 	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
12249 
12250     case SIZEOF_EXPR:
12251       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12252         {
12253 
12254           tree expanded, op = TREE_OPERAND (t, 0);
12255 	  int len = 0;
12256 
12257 	  if (SIZEOF_EXPR_TYPE_P (t))
12258 	    op = TREE_TYPE (op);
12259 
12260 	  ++cp_unevaluated_operand;
12261 	  ++c_inhibit_evaluation_warnings;
12262 	  /* We only want to compute the number of arguments.  */
12263 	  expanded = tsubst_pack_expansion (op, args, complain, in_decl);
12264 	  --cp_unevaluated_operand;
12265 	  --c_inhibit_evaluation_warnings;
12266 
12267 	  if (TREE_CODE (expanded) == TREE_VEC)
12268 	    len = TREE_VEC_LENGTH (expanded);
12269 
12270 	  if (expanded == error_mark_node)
12271 	    return error_mark_node;
12272 	  else if (PACK_EXPANSION_P (expanded)
12273 		   || (TREE_CODE (expanded) == TREE_VEC
12274 		       && len > 0
12275 		       && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
12276 	    {
12277 	      if (TREE_CODE (expanded) == TREE_VEC)
12278 		expanded = TREE_VEC_ELT (expanded, len - 1);
12279 
12280 	      if (TYPE_P (expanded))
12281 		return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
12282 						   complain & tf_error);
12283 	      else
12284 		return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
12285                                                    complain & tf_error);
12286 	    }
12287 	  else
12288 	    return build_int_cst (size_type_node, len);
12289         }
12290       if (SIZEOF_EXPR_TYPE_P (t))
12291 	{
12292 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
12293 		      args, complain, in_decl);
12294 	  r = build1 (NOP_EXPR, r, error_mark_node);
12295 	  r = build1 (SIZEOF_EXPR,
12296 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
12297 	  SIZEOF_EXPR_TYPE_P (r) = 1;
12298 	  return r;
12299 	}
12300       /* Fall through */
12301 
12302     case INDIRECT_REF:
12303     case NEGATE_EXPR:
12304     case TRUTH_NOT_EXPR:
12305     case BIT_NOT_EXPR:
12306     case ADDR_EXPR:
12307     case UNARY_PLUS_EXPR:      /* Unary + */
12308     case ALIGNOF_EXPR:
12309     case AT_ENCODE_EXPR:
12310     case ARROW_EXPR:
12311     case THROW_EXPR:
12312     case TYPEID_EXPR:
12313     case REALPART_EXPR:
12314     case IMAGPART_EXPR:
12315       return build1
12316 	(code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12317 	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
12318 
12319     case COMPONENT_REF:
12320       {
12321 	tree object;
12322 	tree name;
12323 
12324 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
12325 	name = TREE_OPERAND (t, 1);
12326 	if (TREE_CODE (name) == BIT_NOT_EXPR)
12327 	  {
12328 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
12329 				complain, in_decl);
12330 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
12331 	  }
12332 	else if (TREE_CODE (name) == SCOPE_REF
12333 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
12334 	  {
12335 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
12336 				     complain, in_decl);
12337 	    name = TREE_OPERAND (name, 1);
12338 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
12339 				complain, in_decl);
12340 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
12341 	    name = build_qualified_name (/*type=*/NULL_TREE,
12342 					 base, name,
12343 					 /*template_p=*/false);
12344 	  }
12345 	else if (BASELINK_P (name))
12346 	  name = tsubst_baselink (name,
12347 				  non_reference (TREE_TYPE (object)),
12348 				  args, complain,
12349 				  in_decl);
12350 	else
12351 	  name = tsubst_copy (name, args, complain, in_decl);
12352 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
12353       }
12354 
12355     case PLUS_EXPR:
12356     case MINUS_EXPR:
12357     case MULT_EXPR:
12358     case TRUNC_DIV_EXPR:
12359     case CEIL_DIV_EXPR:
12360     case FLOOR_DIV_EXPR:
12361     case ROUND_DIV_EXPR:
12362     case EXACT_DIV_EXPR:
12363     case BIT_AND_EXPR:
12364     case BIT_IOR_EXPR:
12365     case BIT_XOR_EXPR:
12366     case TRUNC_MOD_EXPR:
12367     case FLOOR_MOD_EXPR:
12368     case TRUTH_ANDIF_EXPR:
12369     case TRUTH_ORIF_EXPR:
12370     case TRUTH_AND_EXPR:
12371     case TRUTH_OR_EXPR:
12372     case RSHIFT_EXPR:
12373     case LSHIFT_EXPR:
12374     case RROTATE_EXPR:
12375     case LROTATE_EXPR:
12376     case EQ_EXPR:
12377     case NE_EXPR:
12378     case MAX_EXPR:
12379     case MIN_EXPR:
12380     case LE_EXPR:
12381     case GE_EXPR:
12382     case LT_EXPR:
12383     case GT_EXPR:
12384     case COMPOUND_EXPR:
12385     case DOTSTAR_EXPR:
12386     case MEMBER_REF:
12387     case PREDECREMENT_EXPR:
12388     case PREINCREMENT_EXPR:
12389     case POSTDECREMENT_EXPR:
12390     case POSTINCREMENT_EXPR:
12391       return build_nt
12392 	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12393 	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12394 
12395     case SCOPE_REF:
12396       return build_qualified_name (/*type=*/NULL_TREE,
12397 				   tsubst_copy (TREE_OPERAND (t, 0),
12398 						args, complain, in_decl),
12399 				   tsubst_copy (TREE_OPERAND (t, 1),
12400 						args, complain, in_decl),
12401 				   QUALIFIED_NAME_IS_TEMPLATE (t));
12402 
12403     case ARRAY_REF:
12404       return build_nt
12405 	(ARRAY_REF,
12406 	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12407 	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12408 	 NULL_TREE, NULL_TREE);
12409 
12410     case CALL_EXPR:
12411       {
12412 	int n = VL_EXP_OPERAND_LENGTH (t);
12413 	tree result = build_vl_exp (CALL_EXPR, n);
12414 	int i;
12415 	for (i = 0; i < n; i++)
12416 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
12417 					     complain, in_decl);
12418 	return result;
12419       }
12420 
12421     case COND_EXPR:
12422     case MODOP_EXPR:
12423     case PSEUDO_DTOR_EXPR:
12424       {
12425 	r = build_nt
12426 	  (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12427 	   tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12428 	   tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12429 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12430 	return r;
12431       }
12432 
12433     case NEW_EXPR:
12434       {
12435 	r = build_nt
12436 	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12437 	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
12438 	 tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
12439 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
12440 	return r;
12441       }
12442 
12443     case DELETE_EXPR:
12444       {
12445 	r = build_nt
12446 	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12447 	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12448 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
12449 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
12450 	return r;
12451       }
12452 
12453     case TEMPLATE_ID_EXPR:
12454       {
12455 	/* Substituted template arguments */
12456 	tree fn = TREE_OPERAND (t, 0);
12457 	tree targs = TREE_OPERAND (t, 1);
12458 
12459 	fn = tsubst_copy (fn, args, complain, in_decl);
12460 	if (targs)
12461 	  targs = tsubst_template_args (targs, args, complain, in_decl);
12462 
12463 	return lookup_template_function (fn, targs);
12464       }
12465 
12466     case TREE_LIST:
12467       {
12468 	tree purpose, value, chain;
12469 
12470 	if (t == void_list_node)
12471 	  return t;
12472 
12473 	purpose = TREE_PURPOSE (t);
12474 	if (purpose)
12475 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
12476 	value = TREE_VALUE (t);
12477 	if (value)
12478 	  value = tsubst_copy (value, args, complain, in_decl);
12479 	chain = TREE_CHAIN (t);
12480 	if (chain && chain != void_type_node)
12481 	  chain = tsubst_copy (chain, args, complain, in_decl);
12482 	if (purpose == TREE_PURPOSE (t)
12483 	    && value == TREE_VALUE (t)
12484 	    && chain == TREE_CHAIN (t))
12485 	  return t;
12486 	return tree_cons (purpose, value, chain);
12487       }
12488 
12489     case RECORD_TYPE:
12490     case UNION_TYPE:
12491     case ENUMERAL_TYPE:
12492     case INTEGER_TYPE:
12493     case TEMPLATE_TYPE_PARM:
12494     case TEMPLATE_TEMPLATE_PARM:
12495     case BOUND_TEMPLATE_TEMPLATE_PARM:
12496     case TEMPLATE_PARM_INDEX:
12497     case POINTER_TYPE:
12498     case REFERENCE_TYPE:
12499     case OFFSET_TYPE:
12500     case FUNCTION_TYPE:
12501     case METHOD_TYPE:
12502     case ARRAY_TYPE:
12503     case TYPENAME_TYPE:
12504     case UNBOUND_CLASS_TEMPLATE:
12505     case TYPEOF_TYPE:
12506     case DECLTYPE_TYPE:
12507     case TYPE_DECL:
12508       return tsubst (t, args, complain, in_decl);
12509 
12510     case IDENTIFIER_NODE:
12511       if (IDENTIFIER_TYPENAME_P (t))
12512 	{
12513 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12514 	  return mangle_conv_op_name_for_type (new_type);
12515 	}
12516       else
12517 	return t;
12518 
12519     case CONSTRUCTOR:
12520       /* This is handled by tsubst_copy_and_build.  */
12521       gcc_unreachable ();
12522 
12523     case VA_ARG_EXPR:
12524       return build_x_va_arg (EXPR_LOCATION (t),
12525 			     tsubst_copy (TREE_OPERAND (t, 0), args, complain,
12526 					  in_decl),
12527 			     tsubst (TREE_TYPE (t), args, complain, in_decl));
12528 
12529     case CLEANUP_POINT_EXPR:
12530       /* We shouldn't have built any of these during initial template
12531 	 generation.  Instead, they should be built during instantiation
12532 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
12533       gcc_unreachable ();
12534 
12535     case OFFSET_REF:
12536       r = build2
12537 	(code, tsubst (TREE_TYPE (t), args, complain, in_decl),
12538 	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
12539 	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
12540       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
12541       mark_used (TREE_OPERAND (r, 1));
12542       return r;
12543 
12544     case EXPR_PACK_EXPANSION:
12545       error ("invalid use of pack expansion expression");
12546       return error_mark_node;
12547 
12548     case NONTYPE_ARGUMENT_PACK:
12549       error ("use %<...%> to expand argument pack");
12550       return error_mark_node;
12551 
12552     case INTEGER_CST:
12553     case REAL_CST:
12554     case STRING_CST:
12555     case COMPLEX_CST:
12556       {
12557 	/* Instantiate any typedefs in the type.  */
12558 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12559 	r = fold_convert (type, t);
12560 	gcc_assert (TREE_CODE (r) == code);
12561 	return r;
12562       }
12563 
12564     case PTRMEM_CST:
12565       /* These can sometimes show up in a partial instantiation, but never
12566 	 involve template parms.  */
12567       gcc_assert (!uses_template_parms (t));
12568       return t;
12569 
12570     default:
12571       /* We shouldn't get here, but keep going if !ENABLE_CHECKING.  */
12572       gcc_checking_assert (false);
12573       return t;
12574     }
12575 }
12576 
12577 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
12578 
12579 static tree
tsubst_omp_clauses(tree clauses,tree args,tsubst_flags_t complain,tree in_decl)12580 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
12581 		    tree in_decl)
12582 {
12583   tree new_clauses = NULL, nc, oc;
12584 
12585   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
12586     {
12587       nc = copy_node (oc);
12588       OMP_CLAUSE_CHAIN (nc) = new_clauses;
12589       new_clauses = nc;
12590 
12591       switch (OMP_CLAUSE_CODE (nc))
12592 	{
12593 	case OMP_CLAUSE_LASTPRIVATE:
12594 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
12595 	    {
12596 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
12597 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
12598 			   in_decl, /*integral_constant_expression_p=*/false);
12599 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
12600 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
12601 	    }
12602 	  /* FALLTHRU */
12603 	case OMP_CLAUSE_PRIVATE:
12604 	case OMP_CLAUSE_SHARED:
12605 	case OMP_CLAUSE_FIRSTPRIVATE:
12606 	case OMP_CLAUSE_REDUCTION:
12607 	case OMP_CLAUSE_COPYIN:
12608 	case OMP_CLAUSE_COPYPRIVATE:
12609 	case OMP_CLAUSE_IF:
12610 	case OMP_CLAUSE_NUM_THREADS:
12611 	case OMP_CLAUSE_SCHEDULE:
12612 	case OMP_CLAUSE_COLLAPSE:
12613 	case OMP_CLAUSE_FINAL:
12614 	  OMP_CLAUSE_OPERAND (nc, 0)
12615 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
12616 			   in_decl, /*integral_constant_expression_p=*/false);
12617 	  break;
12618 	case OMP_CLAUSE_NOWAIT:
12619 	case OMP_CLAUSE_ORDERED:
12620 	case OMP_CLAUSE_DEFAULT:
12621 	case OMP_CLAUSE_UNTIED:
12622 	case OMP_CLAUSE_MERGEABLE:
12623 	  break;
12624 	default:
12625 	  gcc_unreachable ();
12626 	}
12627     }
12628 
12629   return finish_omp_clauses (nreverse (new_clauses));
12630 }
12631 
12632 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
12633 
12634 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)12635 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
12636 			  tree in_decl)
12637 {
12638 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
12639 
12640   tree purpose, value, chain;
12641 
12642   if (t == NULL)
12643     return t;
12644 
12645   if (TREE_CODE (t) != TREE_LIST)
12646     return tsubst_copy_and_build (t, args, complain, in_decl,
12647 				  /*function_p=*/false,
12648 				  /*integral_constant_expression_p=*/false);
12649 
12650   if (t == void_list_node)
12651     return t;
12652 
12653   purpose = TREE_PURPOSE (t);
12654   if (purpose)
12655     purpose = RECUR (purpose);
12656   value = TREE_VALUE (t);
12657   if (value)
12658     {
12659       if (TREE_CODE (value) != LABEL_DECL)
12660 	value = RECUR (value);
12661       else
12662 	{
12663 	  value = lookup_label (DECL_NAME (value));
12664 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
12665 	  TREE_USED (value) = 1;
12666 	}
12667     }
12668   chain = TREE_CHAIN (t);
12669   if (chain && chain != void_type_node)
12670     chain = RECUR (chain);
12671   return tree_cons (purpose, value, chain);
12672 #undef RECUR
12673 }
12674 
12675 /* Substitute one OMP_FOR iterator.  */
12676 
12677 static void
tsubst_omp_for_iterator(tree t,int i,tree declv,tree initv,tree condv,tree incrv,tree * clauses,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)12678 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
12679 			 tree condv, tree incrv, tree *clauses,
12680 			 tree args, tsubst_flags_t complain, tree in_decl,
12681 			 bool integral_constant_expression_p)
12682 {
12683 #define RECUR(NODE)				\
12684   tsubst_expr ((NODE), args, complain, in_decl,	\
12685 	       integral_constant_expression_p)
12686   tree decl, init, cond, incr;
12687   bool init_decl;
12688 
12689   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
12690   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
12691   decl = TREE_OPERAND (init, 0);
12692   init = TREE_OPERAND (init, 1);
12693   /* Do this before substituting into decl to handle 'auto'.  */
12694   init_decl = (init && TREE_CODE (init) == DECL_EXPR);
12695   init = RECUR (init);
12696   decl = RECUR (decl);
12697   if (init_decl)
12698     {
12699       gcc_assert (!processing_template_decl);
12700       init = DECL_INITIAL (decl);
12701       DECL_INITIAL (decl) = NULL_TREE;
12702     }
12703 
12704   gcc_assert (!type_dependent_expression_p (decl));
12705 
12706   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
12707     {
12708       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
12709       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12710       if (TREE_CODE (incr) == MODIFY_EXPR)
12711 	incr = build_x_modify_expr (EXPR_LOCATION (incr),
12712 				    RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
12713 				    RECUR (TREE_OPERAND (incr, 1)),
12714 				    complain);
12715       else
12716 	incr = RECUR (incr);
12717       TREE_VEC_ELT (declv, i) = decl;
12718       TREE_VEC_ELT (initv, i) = init;
12719       TREE_VEC_ELT (condv, i) = cond;
12720       TREE_VEC_ELT (incrv, i) = incr;
12721       return;
12722     }
12723 
12724   if (init && !init_decl)
12725     {
12726       tree c;
12727       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
12728 	{
12729 	  if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
12730 	       || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
12731 	      && OMP_CLAUSE_DECL (c) == decl)
12732 	    break;
12733 	  else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
12734 		   && OMP_CLAUSE_DECL (c) == decl)
12735 	    error ("iteration variable %qD should not be firstprivate", decl);
12736 	  else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
12737 		   && OMP_CLAUSE_DECL (c) == decl)
12738 	    error ("iteration variable %qD should not be reduction", decl);
12739 	}
12740       if (c == NULL)
12741 	{
12742 	  c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
12743 	  OMP_CLAUSE_DECL (c) = decl;
12744 	  c = finish_omp_clauses (c);
12745 	  if (c)
12746 	    {
12747 	      OMP_CLAUSE_CHAIN (c) = *clauses;
12748 	      *clauses = c;
12749 	    }
12750 	}
12751     }
12752   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
12753   if (COMPARISON_CLASS_P (cond))
12754     cond = build2 (TREE_CODE (cond), boolean_type_node,
12755 		   RECUR (TREE_OPERAND (cond, 0)),
12756 		   RECUR (TREE_OPERAND (cond, 1)));
12757   else
12758     cond = RECUR (cond);
12759   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
12760   switch (TREE_CODE (incr))
12761     {
12762     case PREINCREMENT_EXPR:
12763     case PREDECREMENT_EXPR:
12764     case POSTINCREMENT_EXPR:
12765     case POSTDECREMENT_EXPR:
12766       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
12767 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
12768       break;
12769     case MODIFY_EXPR:
12770       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12771 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12772 	{
12773 	  tree rhs = TREE_OPERAND (incr, 1);
12774 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12775 			 RECUR (TREE_OPERAND (incr, 0)),
12776 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12777 				 RECUR (TREE_OPERAND (rhs, 0)),
12778 				 RECUR (TREE_OPERAND (rhs, 1))));
12779 	}
12780       else
12781 	incr = RECUR (incr);
12782       break;
12783     case MODOP_EXPR:
12784       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
12785 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
12786 	{
12787 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
12788 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
12789 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
12790 				 TREE_TYPE (decl), lhs,
12791 				 RECUR (TREE_OPERAND (incr, 2))));
12792 	}
12793       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
12794 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
12795 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
12796 	{
12797 	  tree rhs = TREE_OPERAND (incr, 2);
12798 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
12799 			 RECUR (TREE_OPERAND (incr, 0)),
12800 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
12801 				 RECUR (TREE_OPERAND (rhs, 0)),
12802 				 RECUR (TREE_OPERAND (rhs, 1))));
12803 	}
12804       else
12805 	incr = RECUR (incr);
12806       break;
12807     default:
12808       incr = RECUR (incr);
12809       break;
12810     }
12811 
12812   TREE_VEC_ELT (declv, i) = decl;
12813   TREE_VEC_ELT (initv, i) = init;
12814   TREE_VEC_ELT (condv, i) = cond;
12815   TREE_VEC_ELT (incrv, i) = incr;
12816 #undef RECUR
12817 }
12818 
12819 /* Like tsubst_copy for expressions, etc. but also does semantic
12820    processing.  */
12821 
12822 static tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)12823 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
12824 	     bool integral_constant_expression_p)
12825 {
12826 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
12827 #define RECUR(NODE)				\
12828   tsubst_expr ((NODE), args, complain, in_decl,	\
12829 	       integral_constant_expression_p)
12830 
12831   tree stmt, tmp;
12832   tree r;
12833   location_t loc;
12834 
12835   if (t == NULL_TREE || t == error_mark_node)
12836     return t;
12837 
12838   loc = input_location;
12839   if (EXPR_HAS_LOCATION (t))
12840     input_location = EXPR_LOCATION (t);
12841   if (STATEMENT_CODE_P (TREE_CODE (t)))
12842     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
12843 
12844   switch (TREE_CODE (t))
12845     {
12846     case STATEMENT_LIST:
12847       {
12848 	tree_stmt_iterator i;
12849 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
12850 	  RECUR (tsi_stmt (i));
12851 	break;
12852       }
12853 
12854     case CTOR_INITIALIZER:
12855       finish_mem_initializers (tsubst_initializer_list
12856 			       (TREE_OPERAND (t, 0), args));
12857       break;
12858 
12859     case RETURN_EXPR:
12860       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
12861       break;
12862 
12863     case EXPR_STMT:
12864       tmp = RECUR (EXPR_STMT_EXPR (t));
12865       if (EXPR_STMT_STMT_EXPR_RESULT (t))
12866 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
12867       else
12868 	finish_expr_stmt (tmp);
12869       break;
12870 
12871     case USING_STMT:
12872       do_using_directive (USING_STMT_NAMESPACE (t));
12873       break;
12874 
12875     case DECL_EXPR:
12876       {
12877 	tree decl, pattern_decl;
12878 	tree init;
12879 
12880 	pattern_decl = decl = DECL_EXPR_DECL (t);
12881 	if (TREE_CODE (decl) == LABEL_DECL)
12882 	  finish_label_decl (DECL_NAME (decl));
12883 	else if (TREE_CODE (decl) == USING_DECL)
12884 	  {
12885 	    tree scope = USING_DECL_SCOPE (decl);
12886 	    tree name = DECL_NAME (decl);
12887 	    tree decl;
12888 
12889 	    scope = tsubst (scope, args, complain, in_decl);
12890 	    decl = lookup_qualified_name (scope, name,
12891 					  /*is_type_p=*/false,
12892 					  /*complain=*/false);
12893 	    if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
12894 	      qualified_name_lookup_error (scope, name, decl, input_location);
12895 	    else
12896 	      do_local_using_decl (decl, scope, name);
12897 	  }
12898 	else
12899 	  {
12900 	    init = DECL_INITIAL (decl);
12901 	    decl = tsubst (decl, args, complain, in_decl);
12902 	    if (decl != error_mark_node)
12903 	      {
12904 		/* By marking the declaration as instantiated, we avoid
12905 		   trying to instantiate it.  Since instantiate_decl can't
12906 		   handle local variables, and since we've already done
12907 		   all that needs to be done, that's the right thing to
12908 		   do.  */
12909 		if (TREE_CODE (decl) == VAR_DECL)
12910 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12911 		if (TREE_CODE (decl) == VAR_DECL
12912 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12913 		  /* Anonymous aggregates are a special case.  */
12914 		  finish_anon_union (decl);
12915 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
12916 		  {
12917 		    DECL_CONTEXT (decl) = current_function_decl;
12918 		    if (DECL_NAME (decl) == this_identifier)
12919 		      {
12920 			tree lam = DECL_CONTEXT (current_function_decl);
12921 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
12922 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
12923 		      }
12924 		    insert_capture_proxy (decl);
12925 		  }
12926 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
12927 		  /* We already did a pushtag.  */;
12928 		else
12929 		  {
12930 		    int const_init = false;
12931 		    maybe_push_decl (decl);
12932 		    if (TREE_CODE (decl) == VAR_DECL
12933 			&& DECL_PRETTY_FUNCTION_P (decl))
12934 		      {
12935 			/* For __PRETTY_FUNCTION__ we have to adjust the
12936 			   initializer.  */
12937 			const char *const name
12938 			  = cxx_printable_name (current_function_decl, 2);
12939 			init = cp_fname_init (name, &TREE_TYPE (decl));
12940 		      }
12941 		    else
12942 		      {
12943 			tree t = RECUR (init);
12944 
12945 			if (init && !t)
12946 			  {
12947 			    /* If we had an initializer but it
12948 			       instantiated to nothing,
12949 			       value-initialize the object.  This will
12950 			       only occur when the initializer was a
12951 			       pack expansion where the parameter packs
12952 			       used in that expansion were of length
12953 			       zero.  */
12954 			    init = build_value_init (TREE_TYPE (decl),
12955 						     complain);
12956 			    if (TREE_CODE (init) == AGGR_INIT_EXPR)
12957 			      init = get_target_expr_sfinae (init, complain);
12958 			  }
12959 			else
12960 			  init = t;
12961 		      }
12962 
12963 		    if (TREE_CODE (decl) == VAR_DECL)
12964 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12965 				    (pattern_decl));
12966 		    cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12967 		  }
12968 	      }
12969 	  }
12970 
12971 	break;
12972       }
12973 
12974     case FOR_STMT:
12975       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12976       RECUR (FOR_INIT_STMT (t));
12977       finish_for_init_stmt (stmt);
12978       tmp = RECUR (FOR_COND (t));
12979       finish_for_cond (tmp, stmt);
12980       tmp = RECUR (FOR_EXPR (t));
12981       finish_for_expr (tmp, stmt);
12982       RECUR (FOR_BODY (t));
12983       finish_for_stmt (stmt);
12984       break;
12985 
12986     case RANGE_FOR_STMT:
12987       {
12988         tree decl, expr;
12989         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12990         decl = RANGE_FOR_DECL (t);
12991         decl = tsubst (decl, args, complain, in_decl);
12992         maybe_push_decl (decl);
12993         expr = RECUR (RANGE_FOR_EXPR (t));
12994         stmt = cp_convert_range_for (stmt, decl, expr);
12995         RECUR (RANGE_FOR_BODY (t));
12996         finish_for_stmt (stmt);
12997       }
12998       break;
12999 
13000     case WHILE_STMT:
13001       stmt = begin_while_stmt ();
13002       tmp = RECUR (WHILE_COND (t));
13003       finish_while_stmt_cond (tmp, stmt);
13004       RECUR (WHILE_BODY (t));
13005       finish_while_stmt (stmt);
13006       break;
13007 
13008     case DO_STMT:
13009       stmt = begin_do_stmt ();
13010       RECUR (DO_BODY (t));
13011       finish_do_body (stmt);
13012       tmp = RECUR (DO_COND (t));
13013       finish_do_stmt (tmp, stmt);
13014       break;
13015 
13016     case IF_STMT:
13017       stmt = begin_if_stmt ();
13018       tmp = RECUR (IF_COND (t));
13019       finish_if_stmt_cond (tmp, stmt);
13020       RECUR (THEN_CLAUSE (t));
13021       finish_then_clause (stmt);
13022 
13023       if (ELSE_CLAUSE (t))
13024 	{
13025 	  begin_else_clause (stmt);
13026 	  RECUR (ELSE_CLAUSE (t));
13027 	  finish_else_clause (stmt);
13028 	}
13029 
13030       finish_if_stmt (stmt);
13031       break;
13032 
13033     case BIND_EXPR:
13034       if (BIND_EXPR_BODY_BLOCK (t))
13035 	stmt = begin_function_body ();
13036       else
13037 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
13038 				    ? BCS_TRY_BLOCK : 0);
13039 
13040       RECUR (BIND_EXPR_BODY (t));
13041 
13042       if (BIND_EXPR_BODY_BLOCK (t))
13043 	finish_function_body (stmt);
13044       else
13045 	finish_compound_stmt (stmt);
13046       break;
13047 
13048     case BREAK_STMT:
13049       finish_break_stmt ();
13050       break;
13051 
13052     case CONTINUE_STMT:
13053       finish_continue_stmt ();
13054       break;
13055 
13056     case SWITCH_STMT:
13057       stmt = begin_switch_stmt ();
13058       tmp = RECUR (SWITCH_STMT_COND (t));
13059       finish_switch_cond (tmp, stmt);
13060       RECUR (SWITCH_STMT_BODY (t));
13061       finish_switch_stmt (stmt);
13062       break;
13063 
13064     case CASE_LABEL_EXPR:
13065       finish_case_label (EXPR_LOCATION (t),
13066 			 RECUR (CASE_LOW (t)),
13067 			 RECUR (CASE_HIGH (t)));
13068       break;
13069 
13070     case LABEL_EXPR:
13071       {
13072 	tree decl = LABEL_EXPR_LABEL (t);
13073 	tree label;
13074 
13075 	label = finish_label_stmt (DECL_NAME (decl));
13076 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
13077 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
13078       }
13079       break;
13080 
13081     case GOTO_EXPR:
13082       tmp = GOTO_DESTINATION (t);
13083       if (TREE_CODE (tmp) != LABEL_DECL)
13084 	/* Computed goto's must be tsubst'd into.  On the other hand,
13085 	   non-computed gotos must not be; the identifier in question
13086 	   will have no binding.  */
13087 	tmp = RECUR (tmp);
13088       else
13089 	tmp = DECL_NAME (tmp);
13090       finish_goto_stmt (tmp);
13091       break;
13092 
13093     case ASM_EXPR:
13094       tmp = finish_asm_stmt
13095 	(ASM_VOLATILE_P (t),
13096 	 RECUR (ASM_STRING (t)),
13097 	 tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
13098 	 tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
13099 	 tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
13100 	 tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
13101       {
13102 	tree asm_expr = tmp;
13103 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
13104 	  asm_expr = TREE_OPERAND (asm_expr, 0);
13105 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
13106       }
13107       break;
13108 
13109     case TRY_BLOCK:
13110       if (CLEANUP_P (t))
13111 	{
13112 	  stmt = begin_try_block ();
13113 	  RECUR (TRY_STMTS (t));
13114 	  finish_cleanup_try_block (stmt);
13115 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
13116 	}
13117       else
13118 	{
13119 	  tree compound_stmt = NULL_TREE;
13120 
13121 	  if (FN_TRY_BLOCK_P (t))
13122 	    stmt = begin_function_try_block (&compound_stmt);
13123 	  else
13124 	    stmt = begin_try_block ();
13125 
13126 	  RECUR (TRY_STMTS (t));
13127 
13128 	  if (FN_TRY_BLOCK_P (t))
13129 	    finish_function_try_block (stmt);
13130 	  else
13131 	    finish_try_block (stmt);
13132 
13133 	  RECUR (TRY_HANDLERS (t));
13134 	  if (FN_TRY_BLOCK_P (t))
13135 	    finish_function_handler_sequence (stmt, compound_stmt);
13136 	  else
13137 	    finish_handler_sequence (stmt);
13138 	}
13139       break;
13140 
13141     case HANDLER:
13142       {
13143 	tree decl = HANDLER_PARMS (t);
13144 
13145 	if (decl)
13146 	  {
13147 	    decl = tsubst (decl, args, complain, in_decl);
13148 	    /* Prevent instantiate_decl from trying to instantiate
13149 	       this variable.  We've already done all that needs to be
13150 	       done.  */
13151 	    if (decl != error_mark_node)
13152 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
13153 	  }
13154 	stmt = begin_handler ();
13155 	finish_handler_parms (decl, stmt);
13156 	RECUR (HANDLER_BODY (t));
13157 	finish_handler (stmt);
13158       }
13159       break;
13160 
13161     case TAG_DEFN:
13162       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13163       if (CLASS_TYPE_P (tmp))
13164 	{
13165 	  /* Local classes are not independent templates; they are
13166 	     instantiated along with their containing function.  And this
13167 	     way we don't have to deal with pushing out of one local class
13168 	     to instantiate a member of another local class.  */
13169 	  tree fn;
13170 	  /* Closures are handled by the LAMBDA_EXPR.  */
13171 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
13172 	  complete_type (tmp);
13173 	  for (fn = TYPE_METHODS (tmp); fn; fn = DECL_CHAIN (fn))
13174 	    if (!DECL_ARTIFICIAL (fn))
13175 	      instantiate_decl (fn, /*defer_ok*/0, /*expl_inst_class*/false);
13176 	}
13177       break;
13178 
13179     case STATIC_ASSERT:
13180       {
13181 	tree condition;
13182 
13183 	++c_inhibit_evaluation_warnings;
13184         condition =
13185           tsubst_expr (STATIC_ASSERT_CONDITION (t),
13186                        args,
13187                        complain, in_decl,
13188                        /*integral_constant_expression_p=*/true);
13189 	--c_inhibit_evaluation_warnings;
13190 
13191         finish_static_assert (condition,
13192                               STATIC_ASSERT_MESSAGE (t),
13193                               STATIC_ASSERT_SOURCE_LOCATION (t),
13194                               /*member_p=*/false);
13195       }
13196       break;
13197 
13198     case OMP_PARALLEL:
13199       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
13200 				args, complain, in_decl);
13201       stmt = begin_omp_parallel ();
13202       RECUR (OMP_PARALLEL_BODY (t));
13203       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
13204 	= OMP_PARALLEL_COMBINED (t);
13205       break;
13206 
13207     case OMP_TASK:
13208       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
13209 				args, complain, in_decl);
13210       stmt = begin_omp_task ();
13211       RECUR (OMP_TASK_BODY (t));
13212       finish_omp_task (tmp, stmt);
13213       break;
13214 
13215     case OMP_FOR:
13216       {
13217 	tree clauses, body, pre_body;
13218 	tree declv, initv, condv, incrv;
13219 	int i;
13220 
13221 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
13222 				      args, complain, in_decl);
13223 	declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
13224 	initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
13225 	condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
13226 	incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
13227 
13228 	stmt = begin_omp_structured_block ();
13229 
13230 	for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
13231 	  tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
13232 				   &clauses, args, complain, in_decl,
13233 				   integral_constant_expression_p);
13234 
13235 	pre_body = push_stmt_list ();
13236 	RECUR (OMP_FOR_PRE_BODY (t));
13237 	pre_body = pop_stmt_list (pre_body);
13238 
13239 	body = push_stmt_list ();
13240 	RECUR (OMP_FOR_BODY (t));
13241 	body = pop_stmt_list (body);
13242 
13243 	t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
13244 			    body, pre_body, clauses);
13245 
13246 	add_stmt (finish_omp_structured_block (stmt));
13247       }
13248       break;
13249 
13250     case OMP_SECTIONS:
13251     case OMP_SINGLE:
13252       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
13253       stmt = push_stmt_list ();
13254       RECUR (OMP_BODY (t));
13255       stmt = pop_stmt_list (stmt);
13256 
13257       t = copy_node (t);
13258       OMP_BODY (t) = stmt;
13259       OMP_CLAUSES (t) = tmp;
13260       add_stmt (t);
13261       break;
13262 
13263     case OMP_SECTION:
13264     case OMP_CRITICAL:
13265     case OMP_MASTER:
13266     case OMP_ORDERED:
13267       stmt = push_stmt_list ();
13268       RECUR (OMP_BODY (t));
13269       stmt = pop_stmt_list (stmt);
13270 
13271       t = copy_node (t);
13272       OMP_BODY (t) = stmt;
13273       add_stmt (t);
13274       break;
13275 
13276     case OMP_ATOMIC:
13277       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
13278       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
13279 	{
13280 	  tree op1 = TREE_OPERAND (t, 1);
13281 	  tree rhs1 = NULL_TREE;
13282 	  tree lhs, rhs;
13283 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
13284 	    {
13285 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
13286 	      op1 = TREE_OPERAND (op1, 1);
13287 	    }
13288 	  lhs = RECUR (TREE_OPERAND (op1, 0));
13289 	  rhs = RECUR (TREE_OPERAND (op1, 1));
13290 	  finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
13291 			     NULL_TREE, NULL_TREE, rhs1);
13292 	}
13293       else
13294 	{
13295 	  tree op1 = TREE_OPERAND (t, 1);
13296 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
13297 	  tree rhs1 = NULL_TREE;
13298 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
13299 	  enum tree_code opcode = NOP_EXPR;
13300 	  if (code == OMP_ATOMIC_READ)
13301 	    {
13302 	      v = RECUR (TREE_OPERAND (op1, 0));
13303 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
13304 	    }
13305 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
13306 		   || code == OMP_ATOMIC_CAPTURE_NEW)
13307 	    {
13308 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
13309 	      v = RECUR (TREE_OPERAND (op1, 0));
13310 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
13311 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
13312 		{
13313 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
13314 		  op11 = TREE_OPERAND (op11, 1);
13315 		}
13316 	      lhs = RECUR (TREE_OPERAND (op11, 0));
13317 	      rhs = RECUR (TREE_OPERAND (op11, 1));
13318 	      opcode = TREE_CODE (op11);
13319 	    }
13320 	  else
13321 	    {
13322 	      code = OMP_ATOMIC;
13323 	      lhs = RECUR (TREE_OPERAND (op1, 0));
13324 	      rhs = RECUR (TREE_OPERAND (op1, 1));
13325 	    }
13326 	  finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1);
13327 	}
13328       break;
13329 
13330     case TRANSACTION_EXPR:
13331       {
13332 	int flags = 0;
13333 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
13334 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
13335 
13336         if (TRANSACTION_EXPR_IS_STMT (t))
13337           {
13338 	    tree body = TRANSACTION_EXPR_BODY (t);
13339 	    tree noex = NULL_TREE;
13340 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
13341 	      {
13342 		noex = MUST_NOT_THROW_COND (body);
13343 		if (noex == NULL_TREE)
13344 		  noex = boolean_true_node;
13345 		body = TREE_OPERAND (body, 0);
13346 	      }
13347             stmt = begin_transaction_stmt (input_location, NULL, flags);
13348             RECUR (body);
13349             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
13350           }
13351         else
13352           {
13353             stmt = build_transaction_expr (EXPR_LOCATION (t),
13354 					   RECUR (TRANSACTION_EXPR_BODY (t)),
13355 					   flags, NULL_TREE);
13356             RETURN (stmt);
13357           }
13358       }
13359       break;
13360 
13361     case MUST_NOT_THROW_EXPR:
13362       RETURN (build_must_not_throw_expr (RECUR (TREE_OPERAND (t, 0)),
13363 					RECUR (MUST_NOT_THROW_COND (t))));
13364 
13365     case EXPR_PACK_EXPANSION:
13366       error ("invalid use of pack expansion expression");
13367       RETURN (error_mark_node);
13368 
13369     case NONTYPE_ARGUMENT_PACK:
13370       error ("use %<...%> to expand argument pack");
13371       RETURN (error_mark_node);
13372 
13373     case COMPOUND_EXPR:
13374       tmp = RECUR (TREE_OPERAND (t, 0));
13375       if (tmp == NULL_TREE)
13376 	/* If the first operand was a statement, we're done with it.  */
13377 	RETURN (RECUR (TREE_OPERAND (t, 1)));
13378       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
13379 				    RECUR (TREE_OPERAND (t, 1)),
13380 				    complain));
13381 
13382     default:
13383       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
13384 
13385       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
13386 				    /*function_p=*/false,
13387 				    integral_constant_expression_p));
13388     }
13389 
13390   RETURN (NULL_TREE);
13391  out:
13392   input_location = loc;
13393   return r;
13394 #undef RECUR
13395 #undef RETURN
13396 }
13397 
13398 /* T is a postfix-expression that is not being used in a function
13399    call.  Return the substituted version of T.  */
13400 
13401 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)13402 tsubst_non_call_postfix_expression (tree t, tree args,
13403 				    tsubst_flags_t complain,
13404 				    tree in_decl)
13405 {
13406   if (TREE_CODE (t) == SCOPE_REF)
13407     t = tsubst_qualified_id (t, args, complain, in_decl,
13408 			     /*done=*/false, /*address_p=*/false);
13409   else
13410     t = tsubst_copy_and_build (t, args, complain, in_decl,
13411 			       /*function_p=*/false,
13412 			       /*integral_constant_expression_p=*/false);
13413 
13414   return t;
13415 }
13416 
13417 /* Like tsubst but deals with expressions and performs semantic
13418    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
13419 
13420 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)13421 tsubst_copy_and_build (tree t,
13422 		       tree args,
13423 		       tsubst_flags_t complain,
13424 		       tree in_decl,
13425 		       bool function_p,
13426 		       bool integral_constant_expression_p)
13427 {
13428 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
13429 #define RECUR(NODE)						\
13430   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
13431 			 /*function_p=*/false,			\
13432 			 integral_constant_expression_p)
13433 
13434   tree retval, op1;
13435   location_t loc;
13436 
13437   if (t == NULL_TREE || t == error_mark_node)
13438     return t;
13439 
13440   loc = input_location;
13441   if (EXPR_HAS_LOCATION (t))
13442     input_location = EXPR_LOCATION (t);
13443 
13444   /* N3276 decltype magic only applies to calls at the top level or on the
13445      right side of a comma.  */
13446   tsubst_flags_t decltype_flag = (complain & tf_decltype);
13447   complain &= ~tf_decltype;
13448 
13449   switch (TREE_CODE (t))
13450     {
13451     case USING_DECL:
13452       t = DECL_NAME (t);
13453       /* Fall through.  */
13454     case IDENTIFIER_NODE:
13455       {
13456 	tree decl;
13457 	cp_id_kind idk;
13458 	bool non_integral_constant_expression_p;
13459 	const char *error_msg;
13460 
13461 	if (IDENTIFIER_TYPENAME_P (t))
13462 	  {
13463 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13464 	    t = mangle_conv_op_name_for_type (new_type);
13465 	  }
13466 
13467 	/* Look up the name.  */
13468 	decl = lookup_name (t);
13469 
13470 	/* By convention, expressions use ERROR_MARK_NODE to indicate
13471 	   failure, not NULL_TREE.  */
13472 	if (decl == NULL_TREE)
13473 	  decl = error_mark_node;
13474 
13475 	decl = finish_id_expression (t, decl, NULL_TREE,
13476 				     &idk,
13477 				     integral_constant_expression_p,
13478           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx0x),
13479 				     &non_integral_constant_expression_p,
13480 				     /*template_p=*/false,
13481 				     /*done=*/true,
13482 				     /*address_p=*/false,
13483 				     /*template_arg_p=*/false,
13484 				     &error_msg,
13485 				     input_location);
13486 	if (error_msg)
13487 	  error (error_msg);
13488 	if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
13489 	  {
13490 	    if (complain & tf_error)
13491 	      unqualified_name_lookup_error (decl);
13492 	    decl = error_mark_node;
13493 	  }
13494 	RETURN (decl);
13495       }
13496 
13497     case TEMPLATE_ID_EXPR:
13498       {
13499 	tree object;
13500 	tree templ = RECUR (TREE_OPERAND (t, 0));
13501 	tree targs = TREE_OPERAND (t, 1);
13502 
13503 	if (targs)
13504 	  targs = tsubst_template_args (targs, args, complain, in_decl);
13505 
13506 	if (TREE_CODE (templ) == COMPONENT_REF)
13507 	  {
13508 	    object = TREE_OPERAND (templ, 0);
13509 	    templ = TREE_OPERAND (templ, 1);
13510 	  }
13511 	else
13512 	  object = NULL_TREE;
13513 	templ = lookup_template_function (templ, targs);
13514 
13515 	if (object)
13516 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
13517 			 object, templ, NULL_TREE));
13518 	else
13519 	  RETURN (baselink_for_fns (templ));
13520       }
13521 
13522     case INDIRECT_REF:
13523       {
13524 	tree r = RECUR (TREE_OPERAND (t, 0));
13525 
13526 	if (REFERENCE_REF_P (t))
13527 	  {
13528 	    /* A type conversion to reference type will be enclosed in
13529 	       such an indirect ref, but the substitution of the cast
13530 	       will have also added such an indirect ref.  */
13531 	    if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
13532 	      r = convert_from_reference (r);
13533 	  }
13534 	else
13535 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
13536 				    complain|decltype_flag);
13537 	RETURN (r);
13538       }
13539 
13540     case NOP_EXPR:
13541       RETURN (build_nop
13542 	(tsubst (TREE_TYPE (t), args, complain, in_decl),
13543 	 RECUR (TREE_OPERAND (t, 0))));
13544 
13545     case IMPLICIT_CONV_EXPR:
13546       {
13547 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13548 	tree expr = RECUR (TREE_OPERAND (t, 0));
13549 	int flags = LOOKUP_IMPLICIT;
13550 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
13551 	  flags = LOOKUP_NORMAL;
13552 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
13553 						  flags));
13554       }
13555 
13556     case CONVERT_EXPR:
13557       RETURN (build1
13558 	(CONVERT_EXPR,
13559 	 tsubst (TREE_TYPE (t), args, complain, in_decl),
13560 	 RECUR (TREE_OPERAND (t, 0))));
13561 
13562     case CAST_EXPR:
13563     case REINTERPRET_CAST_EXPR:
13564     case CONST_CAST_EXPR:
13565     case DYNAMIC_CAST_EXPR:
13566     case STATIC_CAST_EXPR:
13567       {
13568 	tree type;
13569 	tree op, r = NULL_TREE;
13570 
13571 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13572 	if (integral_constant_expression_p
13573 	    && !cast_valid_in_integral_constant_expression_p (type))
13574 	  {
13575             if (complain & tf_error)
13576               error ("a cast to a type other than an integral or "
13577                      "enumeration type cannot appear in a constant-expression");
13578 	    RETURN (error_mark_node);
13579 	  }
13580 
13581 	op = RECUR (TREE_OPERAND (t, 0));
13582 
13583 	++c_inhibit_evaluation_warnings;
13584 	switch (TREE_CODE (t))
13585 	  {
13586 	  case CAST_EXPR:
13587 	    r = build_functional_cast (type, op, complain);
13588 	    break;
13589 	  case REINTERPRET_CAST_EXPR:
13590 	    r = build_reinterpret_cast (type, op, complain);
13591 	    break;
13592 	  case CONST_CAST_EXPR:
13593 	    r = build_const_cast (type, op, complain);
13594 	    break;
13595 	  case DYNAMIC_CAST_EXPR:
13596 	    r = build_dynamic_cast (type, op, complain);
13597 	    break;
13598 	  case STATIC_CAST_EXPR:
13599 	    r = build_static_cast (type, op, complain);
13600 	    break;
13601 	  default:
13602 	    gcc_unreachable ();
13603 	  }
13604 	--c_inhibit_evaluation_warnings;
13605 
13606 	RETURN (r);
13607       }
13608 
13609     case POSTDECREMENT_EXPR:
13610     case POSTINCREMENT_EXPR:
13611       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13612 						args, complain, in_decl);
13613       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
13614 				complain|decltype_flag));
13615 
13616     case PREDECREMENT_EXPR:
13617     case PREINCREMENT_EXPR:
13618     case NEGATE_EXPR:
13619     case BIT_NOT_EXPR:
13620     case ABS_EXPR:
13621     case TRUTH_NOT_EXPR:
13622     case UNARY_PLUS_EXPR:  /* Unary + */
13623     case REALPART_EXPR:
13624     case IMAGPART_EXPR:
13625       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
13626 			       RECUR (TREE_OPERAND (t, 0)),
13627 				complain|decltype_flag));
13628 
13629     case FIX_TRUNC_EXPR:
13630       RETURN (cp_build_unary_op (FIX_TRUNC_EXPR, RECUR (TREE_OPERAND (t, 0)),
13631 				0, complain));
13632 
13633     case ADDR_EXPR:
13634       op1 = TREE_OPERAND (t, 0);
13635       if (TREE_CODE (op1) == LABEL_DECL)
13636 	RETURN (finish_label_address_expr (DECL_NAME (op1),
13637 					  EXPR_LOCATION (op1)));
13638       if (TREE_CODE (op1) == SCOPE_REF)
13639 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
13640 				   /*done=*/true, /*address_p=*/true);
13641       else
13642 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
13643 						  in_decl);
13644       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
13645 				complain|decltype_flag));
13646 
13647     case PLUS_EXPR:
13648     case MINUS_EXPR:
13649     case MULT_EXPR:
13650     case TRUNC_DIV_EXPR:
13651     case CEIL_DIV_EXPR:
13652     case FLOOR_DIV_EXPR:
13653     case ROUND_DIV_EXPR:
13654     case EXACT_DIV_EXPR:
13655     case BIT_AND_EXPR:
13656     case BIT_IOR_EXPR:
13657     case BIT_XOR_EXPR:
13658     case TRUNC_MOD_EXPR:
13659     case FLOOR_MOD_EXPR:
13660     case TRUTH_ANDIF_EXPR:
13661     case TRUTH_ORIF_EXPR:
13662     case TRUTH_AND_EXPR:
13663     case TRUTH_OR_EXPR:
13664     case RSHIFT_EXPR:
13665     case LSHIFT_EXPR:
13666     case RROTATE_EXPR:
13667     case LROTATE_EXPR:
13668     case EQ_EXPR:
13669     case NE_EXPR:
13670     case MAX_EXPR:
13671     case MIN_EXPR:
13672     case LE_EXPR:
13673     case GE_EXPR:
13674     case LT_EXPR:
13675     case GT_EXPR:
13676     case MEMBER_REF:
13677     case DOTSTAR_EXPR:
13678       {
13679 	tree r;
13680 
13681 	++c_inhibit_evaluation_warnings;
13682 
13683 	r = build_x_binary_op
13684 	  (input_location, TREE_CODE (t),
13685 	   RECUR (TREE_OPERAND (t, 0)),
13686 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
13687 	    ? ERROR_MARK
13688 	    : TREE_CODE (TREE_OPERAND (t, 0))),
13689 	   RECUR (TREE_OPERAND (t, 1)),
13690 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
13691 	    ? ERROR_MARK
13692 	    : TREE_CODE (TREE_OPERAND (t, 1))),
13693 	   /*overload=*/NULL,
13694 	   complain|decltype_flag);
13695 	if (EXPR_P (r) && TREE_NO_WARNING (t))
13696 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13697 
13698 	--c_inhibit_evaluation_warnings;
13699 
13700 	RETURN (r);
13701       }
13702 
13703     case SCOPE_REF:
13704       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
13705 				  /*address_p=*/false));
13706     case ARRAY_REF:
13707       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13708 						args, complain, in_decl);
13709       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
13710 				 RECUR (TREE_OPERAND (t, 1)),
13711 				 complain|decltype_flag));
13712 
13713     case SIZEOF_EXPR:
13714       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
13715 	RETURN (tsubst_copy (t, args, complain, in_decl));
13716       /* Fall through */
13717 
13718     case ALIGNOF_EXPR:
13719       {
13720 	tree r;
13721 
13722 	op1 = TREE_OPERAND (t, 0);
13723 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
13724 	  op1 = TREE_TYPE (op1);
13725         if (!args)
13726 	  {
13727 	    /* When there are no ARGS, we are trying to evaluate a
13728 	       non-dependent expression from the parser.  Trying to do
13729 	       the substitutions may not work.  */
13730 	    if (!TYPE_P (op1))
13731 	      op1 = TREE_TYPE (op1);
13732 	  }
13733 	else
13734 	  {
13735 	    ++cp_unevaluated_operand;
13736 	    ++c_inhibit_evaluation_warnings;
13737 	    if (TYPE_P (op1))
13738 	      op1 = tsubst (op1, args, complain, in_decl);
13739 	    else
13740 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13741 					   /*function_p=*/false,
13742 					   /*integral_constant_expression_p=*/
13743 					   false);
13744 	    --cp_unevaluated_operand;
13745 	    --c_inhibit_evaluation_warnings;
13746 	  }
13747         if (TYPE_P (op1))
13748 	  r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t),
13749 					  complain & tf_error);
13750 	else
13751 	  r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
13752 					  complain & tf_error);
13753 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
13754 	  {
13755 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
13756 	      {
13757 		if (!processing_template_decl && TYPE_P (op1))
13758 		  {
13759 		    r = build_min (SIZEOF_EXPR, size_type_node,
13760 				   build1 (NOP_EXPR, op1, error_mark_node));
13761 		    SIZEOF_EXPR_TYPE_P (r) = 1;
13762 		  }
13763 		else
13764 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
13765 		TREE_SIDE_EFFECTS (r) = 0;
13766 		TREE_READONLY (r) = 1;
13767 	      }
13768 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
13769 	  }
13770 	RETURN (r);
13771       }
13772 
13773     case AT_ENCODE_EXPR:
13774       {
13775 	op1 = TREE_OPERAND (t, 0);
13776 	++cp_unevaluated_operand;
13777 	++c_inhibit_evaluation_warnings;
13778 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13779 				     /*function_p=*/false,
13780 				     /*integral_constant_expression_p=*/false);
13781 	--cp_unevaluated_operand;
13782 	--c_inhibit_evaluation_warnings;
13783 	RETURN (objc_build_encode_expr (op1));
13784       }
13785 
13786     case NOEXCEPT_EXPR:
13787       op1 = TREE_OPERAND (t, 0);
13788       ++cp_unevaluated_operand;
13789       ++c_inhibit_evaluation_warnings;
13790       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
13791 				   /*function_p=*/false,
13792 				   /*integral_constant_expression_p=*/false);
13793       --cp_unevaluated_operand;
13794       --c_inhibit_evaluation_warnings;
13795       RETURN (finish_noexcept_expr (op1, complain));
13796 
13797     case MODOP_EXPR:
13798       {
13799 	tree r = build_x_modify_expr
13800 	  (EXPR_LOCATION (t),
13801 	   RECUR (TREE_OPERAND (t, 0)),
13802 	   TREE_CODE (TREE_OPERAND (t, 1)),
13803 	   RECUR (TREE_OPERAND (t, 2)),
13804 	   complain|decltype_flag);
13805 	/* TREE_NO_WARNING must be set if either the expression was
13806 	   parenthesized or it uses an operator such as >>= rather
13807 	   than plain assignment.  In the former case, it was already
13808 	   set and must be copied.  In the latter case,
13809 	   build_x_modify_expr sets it and it must not be reset
13810 	   here.  */
13811 	if (TREE_NO_WARNING (t))
13812 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
13813 	RETURN (r);
13814       }
13815 
13816     case ARROW_EXPR:
13817       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13818 						args, complain, in_decl);
13819       /* Remember that there was a reference to this entity.  */
13820       if (DECL_P (op1))
13821 	mark_used (op1);
13822       RETURN (build_x_arrow (input_location, op1, complain));
13823 
13824     case NEW_EXPR:
13825       {
13826 	tree placement = RECUR (TREE_OPERAND (t, 0));
13827 	tree init = RECUR (TREE_OPERAND (t, 3));
13828 	vec<tree, va_gc> *placement_vec;
13829 	vec<tree, va_gc> *init_vec;
13830 	tree ret;
13831 
13832 	if (placement == NULL_TREE)
13833 	  placement_vec = NULL;
13834 	else
13835 	  {
13836 	    placement_vec = make_tree_vector ();
13837 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
13838 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
13839 	  }
13840 
13841 	/* If there was an initializer in the original tree, but it
13842 	   instantiated to an empty list, then we should pass a
13843 	   non-NULL empty vector to tell build_new that it was an
13844 	   empty initializer() rather than no initializer.  This can
13845 	   only happen when the initializer is a pack expansion whose
13846 	   parameter packs are of length zero.  */
13847 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
13848 	  init_vec = NULL;
13849 	else
13850 	  {
13851 	    init_vec = make_tree_vector ();
13852 	    if (init == void_zero_node)
13853 	      gcc_assert (init_vec != NULL);
13854 	    else
13855 	      {
13856 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
13857 		  vec_safe_push (init_vec, TREE_VALUE (init));
13858 	      }
13859 	  }
13860 
13861 	ret = build_new (&placement_vec,
13862 			 tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
13863 			 RECUR (TREE_OPERAND (t, 2)),
13864 			 &init_vec,
13865 			 NEW_EXPR_USE_GLOBAL (t),
13866 			 complain);
13867 
13868 	if (placement_vec != NULL)
13869 	  release_tree_vector (placement_vec);
13870 	if (init_vec != NULL)
13871 	  release_tree_vector (init_vec);
13872 
13873 	RETURN (ret);
13874       }
13875 
13876     case DELETE_EXPR:
13877      RETURN (delete_sanity
13878        (RECUR (TREE_OPERAND (t, 0)),
13879 	RECUR (TREE_OPERAND (t, 1)),
13880 	DELETE_EXPR_USE_VEC (t),
13881 	DELETE_EXPR_USE_GLOBAL (t),
13882 	complain));
13883 
13884     case COMPOUND_EXPR:
13885       {
13886 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
13887 					  complain & ~tf_decltype, in_decl,
13888 					  /*function_p=*/false,
13889 					  integral_constant_expression_p);
13890 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
13891 				       op0,
13892 				       RECUR (TREE_OPERAND (t, 1)),
13893 				       complain|decltype_flag));
13894       }
13895 
13896     case CALL_EXPR:
13897       {
13898 	tree function;
13899 	vec<tree, va_gc> *call_args;
13900 	unsigned int nargs, i;
13901 	bool qualified_p;
13902 	bool koenig_p;
13903 	tree ret;
13904 
13905 	function = CALL_EXPR_FN (t);
13906 	/* When we parsed the expression,  we determined whether or
13907 	   not Koenig lookup should be performed.  */
13908 	koenig_p = KOENIG_LOOKUP_P (t);
13909 	if (TREE_CODE (function) == SCOPE_REF)
13910 	  {
13911 	    qualified_p = true;
13912 	    function = tsubst_qualified_id (function, args, complain, in_decl,
13913 					    /*done=*/false,
13914 					    /*address_p=*/false);
13915 	  }
13916 	else if (koenig_p && TREE_CODE (function) == IDENTIFIER_NODE)
13917 	  {
13918 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
13919 	       would incorrectly perform unqualified lookup again.
13920 
13921 	       Note that we can also have an IDENTIFIER_NODE if the earlier
13922 	       unqualified lookup found a member function; in that case
13923 	       koenig_p will be false and we do want to do the lookup
13924 	       again to find the instantiated member function.
13925 
13926 	       FIXME but doing that causes c++/15272, so we need to stop
13927 	       using IDENTIFIER_NODE in that situation.  */
13928 	    qualified_p = false;
13929 	  }
13930 	else
13931 	  {
13932 	    if (TREE_CODE (function) == COMPONENT_REF)
13933 	      {
13934 		tree op = TREE_OPERAND (function, 1);
13935 
13936 		qualified_p = (TREE_CODE (op) == SCOPE_REF
13937 			       || (BASELINK_P (op)
13938 				   && BASELINK_QUALIFIED_P (op)));
13939 	      }
13940 	    else
13941 	      qualified_p = false;
13942 
13943 	    if (TREE_CODE (function) == ADDR_EXPR
13944 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
13945 	      /* Avoid error about taking the address of a constructor.  */
13946 	      function = TREE_OPERAND (function, 0);
13947 
13948 	    function = tsubst_copy_and_build (function, args, complain,
13949 					      in_decl,
13950 					      !qualified_p,
13951 					      integral_constant_expression_p);
13952 
13953 	    if (BASELINK_P (function))
13954 	      qualified_p = true;
13955 	  }
13956 
13957 	nargs = call_expr_nargs (t);
13958 	call_args = make_tree_vector ();
13959 	for (i = 0; i < nargs; ++i)
13960 	  {
13961 	    tree arg = CALL_EXPR_ARG (t, i);
13962 
13963 	    if (!PACK_EXPANSION_P (arg))
13964 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
13965 	    else
13966 	      {
13967 		/* Expand the pack expansion and push each entry onto
13968 		   CALL_ARGS.  */
13969 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
13970 		if (TREE_CODE (arg) == TREE_VEC)
13971 		  {
13972 		    unsigned int len, j;
13973 
13974 		    len = TREE_VEC_LENGTH (arg);
13975 		    for (j = 0; j < len; ++j)
13976 		      {
13977 			tree value = TREE_VEC_ELT (arg, j);
13978 			if (value != NULL_TREE)
13979 			  value = convert_from_reference (value);
13980 			vec_safe_push (call_args, value);
13981 		      }
13982 		  }
13983 		else
13984 		  {
13985 		    /* A partial substitution.  Add one entry.  */
13986 		    vec_safe_push (call_args, arg);
13987 		  }
13988 	      }
13989 	  }
13990 
13991 	/* We do not perform argument-dependent lookup if normal
13992 	   lookup finds a non-function, in accordance with the
13993 	   expected resolution of DR 218.  */
13994 	if (koenig_p
13995 	    && ((is_overloaded_fn (function)
13996 		 /* If lookup found a member function, the Koenig lookup is
13997 		    not appropriate, even if an unqualified-name was used
13998 		    to denote the function.  */
13999 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
14000 		|| TREE_CODE (function) == IDENTIFIER_NODE)
14001 	    /* Only do this when substitution turns a dependent call
14002 	       into a non-dependent call.  */
14003 	    && type_dependent_expression_p_push (t)
14004 	    && !any_type_dependent_arguments_p (call_args))
14005 	  function = perform_koenig_lookup (function, call_args, false,
14006 					    tf_none);
14007 
14008 	if (TREE_CODE (function) == IDENTIFIER_NODE
14009 	    && !any_type_dependent_arguments_p (call_args))
14010 	  {
14011 	    if (koenig_p && (complain & tf_warning_or_error))
14012 	      {
14013 		/* For backwards compatibility and good diagnostics, try
14014 		   the unqualified lookup again if we aren't in SFINAE
14015 		   context.  */
14016 		tree unq = (tsubst_copy_and_build
14017 			    (function, args, complain, in_decl, true,
14018 			     integral_constant_expression_p));
14019 		if (unq == error_mark_node)
14020 		  RETURN (error_mark_node);
14021 
14022 		if (unq != function)
14023 		  {
14024 		    tree fn = unq;
14025 		    if (TREE_CODE (fn) == INDIRECT_REF)
14026 		      fn = TREE_OPERAND (fn, 0);
14027 		    if (TREE_CODE (fn) == COMPONENT_REF)
14028 		      fn = TREE_OPERAND (fn, 1);
14029 		    if (is_overloaded_fn (fn))
14030 		      fn = get_first_fn (fn);
14031 		    permerror (EXPR_LOC_OR_HERE (t),
14032 			       "%qD was not declared in this scope, "
14033 			       "and no declarations were found by "
14034 			       "argument-dependent lookup at the point "
14035 			       "of instantiation", function);
14036 		    if (!DECL_P (fn))
14037 		      /* Can't say anything more.  */;
14038 		    else if (DECL_CLASS_SCOPE_P (fn))
14039 		      {
14040 			inform (EXPR_LOC_OR_HERE (t),
14041 				"declarations in dependent base %qT are "
14042 				"not found by unqualified lookup",
14043 				DECL_CLASS_CONTEXT (fn));
14044 			if (current_class_ptr)
14045 			  inform (EXPR_LOC_OR_HERE (t),
14046 				  "use %<this->%D%> instead", function);
14047 			else
14048 			  inform (EXPR_LOC_OR_HERE (t),
14049 				  "use %<%T::%D%> instead",
14050 				  current_class_name, function);
14051 		      }
14052 		    else
14053 		      inform (0, "%q+D declared here, later in the "
14054 				"translation unit", fn);
14055 		    function = unq;
14056 		  }
14057 	      }
14058 	    if (TREE_CODE (function) == IDENTIFIER_NODE)
14059 	      {
14060 		if (complain & tf_error)
14061 		  unqualified_name_lookup_error (function);
14062 		release_tree_vector (call_args);
14063 		RETURN (error_mark_node);
14064 	      }
14065 	  }
14066 
14067 	/* Remember that there was a reference to this entity.  */
14068 	if (DECL_P (function))
14069 	  mark_used (function);
14070 
14071 	/* Put back tf_decltype for the actual call.  */
14072 	complain |= decltype_flag;
14073 
14074 	if (TREE_CODE (function) == OFFSET_REF)
14075 	  ret = build_offset_ref_call_from_tree (function, &call_args,
14076 						 complain);
14077 	else if (TREE_CODE (function) == COMPONENT_REF)
14078 	  {
14079 	    tree instance = TREE_OPERAND (function, 0);
14080 	    tree fn = TREE_OPERAND (function, 1);
14081 
14082 	    if (processing_template_decl
14083 		&& (type_dependent_expression_p (instance)
14084 		    || (!BASELINK_P (fn)
14085 			&& TREE_CODE (fn) != FIELD_DECL)
14086 		    || type_dependent_expression_p (fn)
14087 		    || any_type_dependent_arguments_p (call_args)))
14088 	      ret = build_nt_call_vec (function, call_args);
14089 	    else if (!BASELINK_P (fn))
14090 	      ret = finish_call_expr (function, &call_args,
14091 				       /*disallow_virtual=*/false,
14092 				       /*koenig_p=*/false,
14093 				       complain);
14094 	    else
14095 	      ret = (build_new_method_call
14096 		      (instance, fn,
14097 		       &call_args, NULL_TREE,
14098 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
14099 		       /*fn_p=*/NULL,
14100 		       complain));
14101 	  }
14102 	else
14103 	  ret = finish_call_expr (function, &call_args,
14104 				  /*disallow_virtual=*/qualified_p,
14105 				  koenig_p,
14106 				  complain);
14107 
14108 	release_tree_vector (call_args);
14109 
14110 	RETURN (ret);
14111       }
14112 
14113     case COND_EXPR:
14114       {
14115 	tree cond = RECUR (TREE_OPERAND (t, 0));
14116 	tree exp1, exp2;
14117 
14118 	if (TREE_CODE (cond) == INTEGER_CST)
14119 	  {
14120 	    if (integer_zerop (cond))
14121 	      {
14122 		++c_inhibit_evaluation_warnings;
14123 		exp1 = RECUR (TREE_OPERAND (t, 1));
14124 		--c_inhibit_evaluation_warnings;
14125 		exp2 = RECUR (TREE_OPERAND (t, 2));
14126 	      }
14127 	    else
14128 	      {
14129 		exp1 = RECUR (TREE_OPERAND (t, 1));
14130 		++c_inhibit_evaluation_warnings;
14131 		exp2 = RECUR (TREE_OPERAND (t, 2));
14132 		--c_inhibit_evaluation_warnings;
14133 	      }
14134 	  }
14135 	else
14136 	  {
14137 	    exp1 = RECUR (TREE_OPERAND (t, 1));
14138 	    exp2 = RECUR (TREE_OPERAND (t, 2));
14139 	  }
14140 
14141 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
14142 					 cond, exp1, exp2, complain));
14143       }
14144 
14145     case PSEUDO_DTOR_EXPR:
14146       RETURN (finish_pseudo_destructor_expr
14147 	(RECUR (TREE_OPERAND (t, 0)),
14148 	 RECUR (TREE_OPERAND (t, 1)),
14149 	 tsubst (TREE_OPERAND (t, 2), args, complain, in_decl)));
14150 
14151     case TREE_LIST:
14152       {
14153 	tree purpose, value, chain;
14154 
14155 	if (t == void_list_node)
14156 	  RETURN (t);
14157 
14158         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
14159             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
14160           {
14161             /* We have pack expansions, so expand those and
14162                create a new list out of it.  */
14163             tree purposevec = NULL_TREE;
14164             tree valuevec = NULL_TREE;
14165             tree chain;
14166             int i, len = -1;
14167 
14168             /* Expand the argument expressions.  */
14169             if (TREE_PURPOSE (t))
14170               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
14171                                                  complain, in_decl);
14172             if (TREE_VALUE (t))
14173               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
14174                                                complain, in_decl);
14175 
14176             /* Build the rest of the list.  */
14177             chain = TREE_CHAIN (t);
14178             if (chain && chain != void_type_node)
14179               chain = RECUR (chain);
14180 
14181             /* Determine the number of arguments.  */
14182             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
14183               {
14184                 len = TREE_VEC_LENGTH (purposevec);
14185                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
14186               }
14187             else if (TREE_CODE (valuevec) == TREE_VEC)
14188               len = TREE_VEC_LENGTH (valuevec);
14189             else
14190               {
14191                 /* Since we only performed a partial substitution into
14192                    the argument pack, we only RETURN (a single list
14193                    node.  */
14194                 if (purposevec == TREE_PURPOSE (t)
14195                     && valuevec == TREE_VALUE (t)
14196                     && chain == TREE_CHAIN (t))
14197                   RETURN (t);
14198 
14199                 RETURN (tree_cons (purposevec, valuevec, chain));
14200               }
14201 
14202             /* Convert the argument vectors into a TREE_LIST */
14203             i = len;
14204             while (i > 0)
14205               {
14206                 /* Grab the Ith values.  */
14207                 i--;
14208                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
14209 		                     : NULL_TREE;
14210                 value
14211 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
14212                              : NULL_TREE;
14213 
14214                 /* Build the list (backwards).  */
14215                 chain = tree_cons (purpose, value, chain);
14216               }
14217 
14218             RETURN (chain);
14219           }
14220 
14221 	purpose = TREE_PURPOSE (t);
14222 	if (purpose)
14223 	  purpose = RECUR (purpose);
14224 	value = TREE_VALUE (t);
14225 	if (value)
14226 	  value = RECUR (value);
14227 	chain = TREE_CHAIN (t);
14228 	if (chain && chain != void_type_node)
14229 	  chain = RECUR (chain);
14230 	if (purpose == TREE_PURPOSE (t)
14231 	    && value == TREE_VALUE (t)
14232 	    && chain == TREE_CHAIN (t))
14233 	  RETURN (t);
14234 	RETURN (tree_cons (purpose, value, chain));
14235       }
14236 
14237     case COMPONENT_REF:
14238       {
14239 	tree object;
14240 	tree object_type;
14241 	tree member;
14242 
14243 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
14244 						     args, complain, in_decl);
14245 	/* Remember that there was a reference to this entity.  */
14246 	if (DECL_P (object))
14247 	  mark_used (object);
14248 	object_type = TREE_TYPE (object);
14249 
14250 	member = TREE_OPERAND (t, 1);
14251 	if (BASELINK_P (member))
14252 	  member = tsubst_baselink (member,
14253 				    non_reference (TREE_TYPE (object)),
14254 				    args, complain, in_decl);
14255 	else
14256 	  member = tsubst_copy (member, args, complain, in_decl);
14257 	if (member == error_mark_node)
14258 	  RETURN (error_mark_node);
14259 
14260 	if (type_dependent_expression_p (object))
14261 	  /* We can't do much here.  */;
14262 	else if (!CLASS_TYPE_P (object_type))
14263 	  {
14264 	    if (scalarish_type_p (object_type))
14265 	      {
14266 		tree s = NULL_TREE;
14267 		tree dtor = member;
14268 
14269 		if (TREE_CODE (dtor) == SCOPE_REF)
14270 		  {
14271 		    s = TREE_OPERAND (dtor, 0);
14272 		    dtor = TREE_OPERAND (dtor, 1);
14273 		  }
14274 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
14275 		  {
14276 		    dtor = TREE_OPERAND (dtor, 0);
14277 		    if (TYPE_P (dtor))
14278 		      RETURN (finish_pseudo_destructor_expr (object, s, dtor));
14279 		  }
14280 	      }
14281 	  }
14282 	else if (TREE_CODE (member) == SCOPE_REF
14283 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
14284 	  {
14285 	    /* Lookup the template functions now that we know what the
14286 	       scope is.  */
14287 	    tree scope = TREE_OPERAND (member, 0);
14288 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
14289 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
14290 	    member = lookup_qualified_name (scope, tmpl,
14291 					    /*is_type_p=*/false,
14292 					    /*complain=*/false);
14293 	    if (BASELINK_P (member))
14294 	      {
14295 		BASELINK_FUNCTIONS (member)
14296 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
14297 			      args);
14298 		member = (adjust_result_of_qualified_name_lookup
14299 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
14300 			   object_type));
14301 	      }
14302 	    else
14303 	      {
14304 		qualified_name_lookup_error (scope, tmpl, member,
14305 					     input_location);
14306 		RETURN (error_mark_node);
14307 	      }
14308 	  }
14309 	else if (TREE_CODE (member) == SCOPE_REF
14310 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
14311 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
14312 	  {
14313 	    if (complain & tf_error)
14314 	      {
14315 		if (TYPE_P (TREE_OPERAND (member, 0)))
14316 		  error ("%qT is not a class or namespace",
14317 			 TREE_OPERAND (member, 0));
14318 		else
14319 		  error ("%qD is not a class or namespace",
14320 			 TREE_OPERAND (member, 0));
14321 	      }
14322 	    RETURN (error_mark_node);
14323 	  }
14324 	else if (TREE_CODE (member) == FIELD_DECL)
14325 	  RETURN (finish_non_static_data_member (member, object, NULL_TREE));
14326 
14327 	RETURN (finish_class_member_access_expr (object, member,
14328 						/*template_p=*/false,
14329 						complain));
14330       }
14331 
14332     case THROW_EXPR:
14333       RETURN (build_throw
14334 	(RECUR (TREE_OPERAND (t, 0))));
14335 
14336     case CONSTRUCTOR:
14337       {
14338 	vec<constructor_elt, va_gc> *n;
14339 	constructor_elt *ce;
14340 	unsigned HOST_WIDE_INT idx;
14341 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14342 	bool process_index_p;
14343         int newlen;
14344         bool need_copy_p = false;
14345 	tree r;
14346 
14347 	if (type == error_mark_node)
14348 	  RETURN (error_mark_node);
14349 
14350 	/* digest_init will do the wrong thing if we let it.  */
14351 	if (type && TYPE_PTRMEMFUNC_P (type))
14352 	  RETURN (t);
14353 
14354 	/* We do not want to process the index of aggregate
14355 	   initializers as they are identifier nodes which will be
14356 	   looked up by digest_init.  */
14357 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
14358 
14359 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
14360         newlen = vec_safe_length (n);
14361 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
14362 	  {
14363 	    if (ce->index && process_index_p
14364 		/* An identifier index is looked up in the type
14365 		   being initialized, not the current scope.  */
14366 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
14367 	      ce->index = RECUR (ce->index);
14368 
14369             if (PACK_EXPANSION_P (ce->value))
14370               {
14371                 /* Substitute into the pack expansion.  */
14372                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
14373                                                   in_decl);
14374 
14375 		if (ce->value == error_mark_node
14376 		    || PACK_EXPANSION_P (ce->value))
14377 		  ;
14378 		else if (TREE_VEC_LENGTH (ce->value) == 1)
14379                   /* Just move the argument into place.  */
14380                   ce->value = TREE_VEC_ELT (ce->value, 0);
14381                 else
14382                   {
14383                     /* Update the length of the final CONSTRUCTOR
14384                        arguments vector, and note that we will need to
14385                        copy.*/
14386                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
14387                     need_copy_p = true;
14388                   }
14389               }
14390             else
14391               ce->value = RECUR (ce->value);
14392 	  }
14393 
14394         if (need_copy_p)
14395           {
14396             vec<constructor_elt, va_gc> *old_n = n;
14397 
14398             vec_alloc (n, newlen);
14399             FOR_EACH_VEC_ELT (*old_n, idx, ce)
14400               {
14401                 if (TREE_CODE (ce->value) == TREE_VEC)
14402                   {
14403                     int i, len = TREE_VEC_LENGTH (ce->value);
14404                     for (i = 0; i < len; ++i)
14405                       CONSTRUCTOR_APPEND_ELT (n, 0,
14406                                               TREE_VEC_ELT (ce->value, i));
14407                   }
14408                 else
14409                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
14410               }
14411           }
14412 
14413 	r = build_constructor (init_list_type_node, n);
14414 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
14415 
14416 	if (TREE_HAS_CONSTRUCTOR (t))
14417 	  RETURN (finish_compound_literal (type, r, complain));
14418 
14419 	TREE_TYPE (r) = type;
14420 	RETURN (r);
14421       }
14422 
14423     case TYPEID_EXPR:
14424       {
14425 	tree operand_0 = TREE_OPERAND (t, 0);
14426 	if (TYPE_P (operand_0))
14427 	  {
14428 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
14429 	    RETURN (get_typeid (operand_0, complain));
14430 	  }
14431 	else
14432 	  {
14433 	    operand_0 = RECUR (operand_0);
14434 	    RETURN (build_typeid (operand_0, complain));
14435 	  }
14436       }
14437 
14438     case VAR_DECL:
14439       if (!args)
14440 	RETURN (t);
14441       /* Fall through */
14442 
14443     case PARM_DECL:
14444       {
14445 	tree r = tsubst_copy (t, args, complain, in_decl);
14446 
14447 	if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
14448 	  /* If the original type was a reference, we'll be wrapped in
14449 	     the appropriate INDIRECT_REF.  */
14450 	  r = convert_from_reference (r);
14451 	RETURN (r);
14452       }
14453 
14454     case VA_ARG_EXPR:
14455       RETURN (build_x_va_arg (EXPR_LOCATION (t),
14456 			     RECUR (TREE_OPERAND (t, 0)),
14457 			     tsubst (TREE_TYPE (t), args, complain, in_decl)));
14458 
14459     case OFFSETOF_EXPR:
14460       RETURN (finish_offsetof (RECUR (TREE_OPERAND (t, 0))));
14461 
14462     case TRAIT_EXPR:
14463       {
14464 	tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
14465 				  complain, in_decl);
14466 
14467 	tree type2 = TRAIT_EXPR_TYPE2 (t);
14468 	if (type2)
14469 	  type2 = tsubst_copy (type2, args, complain, in_decl);
14470 
14471 	RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
14472       }
14473 
14474     case STMT_EXPR:
14475       {
14476 	tree old_stmt_expr = cur_stmt_expr;
14477 	tree stmt_expr = begin_stmt_expr ();
14478 
14479 	cur_stmt_expr = stmt_expr;
14480 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
14481 		     integral_constant_expression_p);
14482 	stmt_expr = finish_stmt_expr (stmt_expr, false);
14483 	cur_stmt_expr = old_stmt_expr;
14484 
14485 	/* If the resulting list of expression statement is empty,
14486 	   fold it further into void_zero_node.  */
14487 	if (empty_expr_stmt_p (stmt_expr))
14488 	  stmt_expr = void_zero_node;
14489 
14490 	RETURN (stmt_expr);
14491       }
14492 
14493     case LAMBDA_EXPR:
14494       {
14495 	tree r = build_lambda_expr ();
14496 
14497 	tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
14498 	LAMBDA_EXPR_CLOSURE (r) = type;
14499 	CLASSTYPE_LAMBDA_EXPR (type) = r;
14500 
14501 	LAMBDA_EXPR_LOCATION (r)
14502 	  = LAMBDA_EXPR_LOCATION (t);
14503 	LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
14504 	  = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
14505 	LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
14506 	LAMBDA_EXPR_DISCRIMINATOR (r)
14507 	  = (LAMBDA_EXPR_DISCRIMINATOR (t));
14508 	/* For a function scope, we want to use tsubst so that we don't
14509 	   complain about referring to an auto function before its return
14510 	   type has been deduced.  Otherwise, we want to use tsubst_copy so
14511 	   that we look up the existing field/parameter/variable rather
14512 	   than build a new one.  */
14513 	tree scope = LAMBDA_EXPR_EXTRA_SCOPE (t);
14514 	if (scope && TREE_CODE (scope) == FUNCTION_DECL)
14515 	  scope = tsubst (scope, args, complain, in_decl);
14516 	else if (scope && TREE_CODE (scope) == PARM_DECL)
14517 	  {
14518 	    /* Look up the parameter we want directly, as tsubst_copy
14519 	       doesn't do what we need.  */
14520 	    tree fn = tsubst (DECL_CONTEXT (scope), args, complain, in_decl);
14521 	    tree parm = FUNCTION_FIRST_USER_PARM (fn);
14522 	    while (DECL_PARM_INDEX (parm) != DECL_PARM_INDEX (scope))
14523 	      parm = DECL_CHAIN (parm);
14524 	    scope = parm;
14525 	    /* FIXME Work around the parm not having DECL_CONTEXT set.  */
14526 	    if (DECL_CONTEXT (scope) == NULL_TREE)
14527 	      DECL_CONTEXT (scope) = fn;
14528 	  }
14529 	else
14530 	  scope = RECUR (scope);
14531 	LAMBDA_EXPR_EXTRA_SCOPE (r) = scope;
14532 	LAMBDA_EXPR_RETURN_TYPE (r)
14533 	  = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
14534 
14535 	gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
14536 		    && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
14537 
14538 	/* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
14539 	determine_visibility (TYPE_NAME (type));
14540 	/* Now that we know visibility, instantiate the type so we have a
14541 	   declaration of the op() for later calls to lambda_function.  */
14542 	complete_type (type);
14543 
14544 	LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
14545 
14546 	RETURN (build_lambda_object (r));
14547       }
14548 
14549     case TARGET_EXPR:
14550       /* We can get here for a constant initializer of non-dependent type.
14551          FIXME stop folding in cp_parser_initializer_clause.  */
14552       {
14553 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
14554 					 complain);
14555 	RETURN (r);
14556       }
14557 
14558     case TRANSACTION_EXPR:
14559       RETURN (tsubst_expr(t, args, complain, in_decl,
14560 	     integral_constant_expression_p));
14561 
14562     default:
14563       /* Handle Objective-C++ constructs, if appropriate.  */
14564       {
14565 	tree subst
14566 	  = objcp_tsubst_copy_and_build (t, args, complain,
14567 					 in_decl, /*function_p=*/false);
14568 	if (subst)
14569 	  RETURN (subst);
14570       }
14571       RETURN (tsubst_copy (t, args, complain, in_decl));
14572     }
14573 
14574 #undef RECUR
14575 #undef RETURN
14576  out:
14577   input_location = loc;
14578   return retval;
14579 }
14580 
14581 /* Verify that the instantiated ARGS are valid. For type arguments,
14582    make sure that the type's linkage is ok. For non-type arguments,
14583    make sure they are constants if they are integral or enumerations.
14584    Emit an error under control of COMPLAIN, and return TRUE on error.  */
14585 
14586 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)14587 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
14588 {
14589   if (dependent_template_arg_p (t))
14590     return false;
14591   if (ARGUMENT_PACK_P (t))
14592     {
14593       tree vec = ARGUMENT_PACK_ARGS (t);
14594       int len = TREE_VEC_LENGTH (vec);
14595       bool result = false;
14596       int i;
14597 
14598       for (i = 0; i < len; ++i)
14599 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
14600 	  result = true;
14601       return result;
14602     }
14603   else if (TYPE_P (t))
14604     {
14605       /* [basic.link]: A name with no linkage (notably, the name
14606 	 of a class or enumeration declared in a local scope)
14607 	 shall not be used to declare an entity with linkage.
14608 	 This implies that names with no linkage cannot be used as
14609 	 template arguments
14610 
14611 	 DR 757 relaxes this restriction for C++0x.  */
14612       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
14613 		 : no_linkage_check (t, /*relaxed_p=*/false));
14614 
14615       if (nt)
14616 	{
14617 	  /* DR 488 makes use of a type with no linkage cause
14618 	     type deduction to fail.  */
14619 	  if (complain & tf_error)
14620 	    {
14621 	      if (TYPE_ANONYMOUS_P (nt))
14622 		error ("%qT is/uses anonymous type", t);
14623 	      else
14624 		error ("template argument for %qD uses local type %qT",
14625 		       tmpl, t);
14626 	    }
14627 	  return true;
14628 	}
14629       /* In order to avoid all sorts of complications, we do not
14630 	 allow variably-modified types as template arguments.  */
14631       else if (variably_modified_type_p (t, NULL_TREE))
14632 	{
14633 	  if (complain & tf_error)
14634 	    error ("%qT is a variably modified type", t);
14635 	  return true;
14636 	}
14637     }
14638   /* Class template and alias template arguments should be OK.  */
14639   else if (DECL_TYPE_TEMPLATE_P (t))
14640     ;
14641   /* A non-type argument of integral or enumerated type must be a
14642      constant.  */
14643   else if (TREE_TYPE (t)
14644 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
14645 	   && !TREE_CONSTANT (t))
14646     {
14647       if (complain & tf_error)
14648 	error ("integral expression %qE is not constant", t);
14649       return true;
14650     }
14651   return false;
14652 }
14653 
14654 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)14655 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
14656 {
14657   int ix, len = DECL_NTPARMS (tmpl);
14658   bool result = false;
14659 
14660   for (ix = 0; ix != len; ix++)
14661     {
14662       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
14663 	result = true;
14664     }
14665   if (result && (complain & tf_error))
14666     error ("  trying to instantiate %qD", tmpl);
14667   return result;
14668 }
14669 
14670 /* We're out of SFINAE context now, so generate diagnostics for the access
14671    errors we saw earlier when instantiating D from TMPL and ARGS.  */
14672 
14673 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)14674 recheck_decl_substitution (tree d, tree tmpl, tree args)
14675 {
14676   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
14677   tree type = TREE_TYPE (pattern);
14678   location_t loc = input_location;
14679 
14680   push_access_scope (d);
14681   push_deferring_access_checks (dk_no_deferred);
14682   input_location = DECL_SOURCE_LOCATION (pattern);
14683   tsubst (type, args, tf_warning_or_error, d);
14684   input_location = loc;
14685   pop_deferring_access_checks ();
14686   pop_access_scope (d);
14687 }
14688 
14689 /* Instantiate the indicated variable, function, or alias template TMPL with
14690    the template arguments in TARG_PTR.  */
14691 
14692 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)14693 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
14694 {
14695   tree targ_ptr = orig_args;
14696   tree fndecl;
14697   tree gen_tmpl;
14698   tree spec;
14699   bool access_ok = true;
14700 
14701   if (tmpl == error_mark_node)
14702     return error_mark_node;
14703 
14704   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
14705 
14706   /* If this function is a clone, handle it specially.  */
14707   if (DECL_CLONED_FUNCTION_P (tmpl))
14708     {
14709       tree spec;
14710       tree clone;
14711 
14712       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
14713 	 DECL_CLONED_FUNCTION.  */
14714       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
14715 				   targ_ptr, complain);
14716       if (spec == error_mark_node)
14717 	return error_mark_node;
14718 
14719       /* Look for the clone.  */
14720       FOR_EACH_CLONE (clone, spec)
14721 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
14722 	  return clone;
14723       /* We should always have found the clone by now.  */
14724       gcc_unreachable ();
14725       return NULL_TREE;
14726     }
14727 
14728   /* Check to see if we already have this specialization.  */
14729   gen_tmpl = most_general_template (tmpl);
14730   if (tmpl != gen_tmpl)
14731     /* The TMPL is a partial instantiation.  To get a full set of
14732        arguments we must add the arguments used to perform the
14733        partial instantiation.  */
14734     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
14735 					    targ_ptr);
14736 
14737   /* It would be nice to avoid hashing here and then again in tsubst_decl,
14738      but it doesn't seem to be on the hot path.  */
14739   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
14740 
14741   gcc_assert (tmpl == gen_tmpl
14742 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
14743 		  == spec)
14744 	      || fndecl == NULL_TREE);
14745 
14746   if (spec != NULL_TREE)
14747     {
14748       if (FNDECL_HAS_ACCESS_ERRORS (spec))
14749 	{
14750 	  if (complain & tf_error)
14751 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
14752 	  return error_mark_node;
14753 	}
14754       return spec;
14755     }
14756 
14757   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
14758 			       complain))
14759     return error_mark_node;
14760 
14761   /* We are building a FUNCTION_DECL, during which the access of its
14762      parameters and return types have to be checked.  However this
14763      FUNCTION_DECL which is the desired context for access checking
14764      is not built yet.  We solve this chicken-and-egg problem by
14765      deferring all checks until we have the FUNCTION_DECL.  */
14766   push_deferring_access_checks (dk_deferred);
14767 
14768   /* Instantiation of the function happens in the context of the function
14769      template, not the context of the overload resolution we're doing.  */
14770   push_to_top_level ();
14771   /* If there are dependent arguments, e.g. because we're doing partial
14772      ordering, make sure processing_template_decl stays set.  */
14773   if (uses_template_parms (targ_ptr))
14774     ++processing_template_decl;
14775   if (DECL_CLASS_SCOPE_P (gen_tmpl))
14776     {
14777       tree ctx = tsubst (DECL_CONTEXT (gen_tmpl), targ_ptr,
14778 			 complain, gen_tmpl);
14779       push_nested_class (ctx);
14780     }
14781   /* Substitute template parameters to obtain the specialization.  */
14782   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
14783 		   targ_ptr, complain, gen_tmpl);
14784   if (DECL_CLASS_SCOPE_P (gen_tmpl))
14785     pop_nested_class ();
14786   pop_from_top_level ();
14787 
14788   if (fndecl == error_mark_node)
14789     {
14790       pop_deferring_access_checks ();
14791       return error_mark_node;
14792     }
14793 
14794   /* The DECL_TI_TEMPLATE should always be the immediate parent
14795      template, not the most general template.  */
14796   DECL_TI_TEMPLATE (fndecl) = tmpl;
14797 
14798   /* Now we know the specialization, compute access previously
14799      deferred.  */
14800   push_access_scope (fndecl);
14801   if (!perform_deferred_access_checks (complain))
14802     access_ok = false;
14803   pop_access_scope (fndecl);
14804   pop_deferring_access_checks ();
14805 
14806   /* If we've just instantiated the main entry point for a function,
14807      instantiate all the alternate entry points as well.  We do this
14808      by cloning the instantiation of the main entry point, not by
14809      instantiating the template clones.  */
14810   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
14811     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
14812 
14813   if (!access_ok)
14814     {
14815       if (!(complain & tf_error))
14816 	{
14817 	  /* Remember to reinstantiate when we're out of SFINAE so the user
14818 	     can see the errors.  */
14819 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
14820 	}
14821       return error_mark_node;
14822     }
14823   return fndecl;
14824 }
14825 
14826 /* Wrapper for instantiate_template_1.  */
14827 
14828 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)14829 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
14830 {
14831   tree ret;
14832   timevar_push (TV_TEMPLATE_INST);
14833   ret = instantiate_template_1 (tmpl, orig_args,  complain);
14834   timevar_pop (TV_TEMPLATE_INST);
14835   return ret;
14836 }
14837 
14838 /* Instantiate the alias template TMPL with ARGS.  Also push a template
14839    instantiation level, which instantiate_template doesn't do because
14840    functions and variables have sufficient context established by the
14841    callers.  */
14842 
14843 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)14844 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
14845 {
14846   struct pending_template *old_last_pend = last_pending_template;
14847   struct tinst_level *old_error_tinst = last_error_tinst_level;
14848   if (tmpl == error_mark_node || args == error_mark_node)
14849     return error_mark_node;
14850   tree tinst = build_tree_list (tmpl, args);
14851   if (!push_tinst_level (tinst))
14852     {
14853       ggc_free (tinst);
14854       return error_mark_node;
14855     }
14856 
14857   args =
14858     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
14859 				     args, tmpl, complain,
14860 				     /*require_all_args=*/true,
14861 				     /*use_default_args=*/true);
14862 
14863   tree r = instantiate_template (tmpl, args, complain);
14864   pop_tinst_level ();
14865   /* We can't free this if a pending_template entry or last_error_tinst_level
14866      is pointing at it.  */
14867   if (last_pending_template == old_last_pend
14868       && last_error_tinst_level == old_error_tinst)
14869     ggc_free (tinst);
14870 
14871   return r;
14872 }
14873 
14874 /* PARM is a template parameter pack for FN.  Returns true iff
14875    PARM is used in a deducible way in the argument list of FN.  */
14876 
14877 static bool
pack_deducible_p(tree parm,tree fn)14878 pack_deducible_p (tree parm, tree fn)
14879 {
14880   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
14881   for (; t; t = TREE_CHAIN (t))
14882     {
14883       tree type = TREE_VALUE (t);
14884       tree packs;
14885       if (!PACK_EXPANSION_P (type))
14886 	continue;
14887       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
14888 	   packs; packs = TREE_CHAIN (packs))
14889 	if (TREE_VALUE (packs) == parm)
14890 	  {
14891 	    /* The template parameter pack is used in a function parameter
14892 	       pack.  If this is the end of the parameter list, the
14893 	       template parameter pack is deducible.  */
14894 	    if (TREE_CHAIN (t) == void_list_node)
14895 	      return true;
14896 	    else
14897 	      /* Otherwise, not.  Well, it could be deduced from
14898 		 a non-pack parameter, but doing so would end up with
14899 		 a deduction mismatch, so don't bother.  */
14900 	      return false;
14901 	  }
14902     }
14903   /* The template parameter pack isn't used in any function parameter
14904      packs, but it might be used deeper, e.g. tuple<Args...>.  */
14905   return true;
14906 }
14907 
14908 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
14909    NARGS elements of the arguments that are being used when calling
14910    it.  TARGS is a vector into which the deduced template arguments
14911    are placed.
14912 
14913    Return zero for success, 2 for an incomplete match that doesn't resolve
14914    all the types, and 1 for complete failure.  An error message will be
14915    printed only for an incomplete match.
14916 
14917    If FN is a conversion operator, or we are trying to produce a specific
14918    specialization, RETURN_TYPE is the return type desired.
14919 
14920    The EXPLICIT_TARGS are explicit template arguments provided via a
14921    template-id.
14922 
14923    The parameter STRICT is one of:
14924 
14925    DEDUCE_CALL:
14926      We are deducing arguments for a function call, as in
14927      [temp.deduct.call].
14928 
14929    DEDUCE_CONV:
14930      We are deducing arguments for a conversion function, as in
14931      [temp.deduct.conv].
14932 
14933    DEDUCE_EXACT:
14934      We are deducing arguments when doing an explicit instantiation
14935      as in [temp.explicit], when determining an explicit specialization
14936      as in [temp.expl.spec], or when taking the address of a function
14937      template, as in [temp.deduct.funcaddr].  */
14938 
14939 tree
fn_type_unification(tree fn,tree explicit_targs,tree targs,const tree * args,unsigned int nargs,tree return_type,unification_kind_t strict,int flags,bool explain_p)14940 fn_type_unification (tree fn,
14941 		     tree explicit_targs,
14942 		     tree targs,
14943 		     const tree *args,
14944 		     unsigned int nargs,
14945 		     tree return_type,
14946 		     unification_kind_t strict,
14947 		     int flags,
14948 		     bool explain_p)
14949 {
14950   tree parms;
14951   tree fntype;
14952   tree decl = NULL_TREE;
14953   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
14954   bool ok;
14955   static int deduction_depth;
14956   struct pending_template *old_last_pend = last_pending_template;
14957   struct tinst_level *old_error_tinst = last_error_tinst_level;
14958   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
14959   tree tinst;
14960   tree r = error_mark_node;
14961 
14962   /* In C++0x, it's possible to have a function template whose type depends
14963      on itself recursively.  This is most obvious with decltype, but can also
14964      occur with enumeration scope (c++/48969).  So we need to catch infinite
14965      recursion and reject the substitution at deduction time; this function
14966      will return error_mark_node for any repeated substitution.
14967 
14968      This also catches excessive recursion such as when f<N> depends on
14969      f<N-1> across all integers, and returns error_mark_node for all the
14970      substitutions back up to the initial one.
14971 
14972      This is, of course, not reentrant.  */
14973   if (excessive_deduction_depth)
14974     return error_mark_node;
14975   tinst = build_tree_list (fn, NULL_TREE);
14976   ++deduction_depth;
14977   push_deferring_access_checks (dk_deferred);
14978 
14979   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
14980 
14981   fntype = TREE_TYPE (fn);
14982   if (explicit_targs)
14983     {
14984       /* [temp.deduct]
14985 
14986 	 The specified template arguments must match the template
14987 	 parameters in kind (i.e., type, nontype, template), and there
14988 	 must not be more arguments than there are parameters;
14989 	 otherwise type deduction fails.
14990 
14991 	 Nontype arguments must match the types of the corresponding
14992 	 nontype template parameters, or must be convertible to the
14993 	 types of the corresponding nontype parameters as specified in
14994 	 _temp.arg.nontype_, otherwise type deduction fails.
14995 
14996 	 All references in the function type of the function template
14997 	 to the corresponding template parameters are replaced by the
14998 	 specified template argument values.  If a substitution in a
14999 	 template parameter or in the function type of the function
15000 	 template results in an invalid type, type deduction fails.  */
15001       int i, len = TREE_VEC_LENGTH (tparms);
15002       location_t loc = input_location;
15003       bool incomplete = false;
15004 
15005       /* Adjust any explicit template arguments before entering the
15006 	 substitution context.  */
15007       explicit_targs
15008 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
15009 				  complain,
15010 				  /*require_all_args=*/false,
15011 				  /*use_default_args=*/false));
15012       if (explicit_targs == error_mark_node)
15013 	goto fail;
15014 
15015       /* Substitute the explicit args into the function type.  This is
15016 	 necessary so that, for instance, explicitly declared function
15017 	 arguments can match null pointed constants.  If we were given
15018 	 an incomplete set of explicit args, we must not do semantic
15019 	 processing during substitution as we could create partial
15020 	 instantiations.  */
15021       for (i = 0; i < len; i++)
15022         {
15023           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
15024           bool parameter_pack = false;
15025 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
15026 
15027           /* Dig out the actual parm.  */
15028           if (TREE_CODE (parm) == TYPE_DECL
15029               || TREE_CODE (parm) == TEMPLATE_DECL)
15030             {
15031               parm = TREE_TYPE (parm);
15032               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
15033             }
15034           else if (TREE_CODE (parm) == PARM_DECL)
15035             {
15036               parm = DECL_INITIAL (parm);
15037               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
15038             }
15039 
15040 	  if (!parameter_pack && targ == NULL_TREE)
15041 	    /* No explicit argument for this template parameter.  */
15042 	    incomplete = true;
15043 
15044           if (parameter_pack && pack_deducible_p (parm, fn))
15045             {
15046               /* Mark the argument pack as "incomplete". We could
15047                  still deduce more arguments during unification.
15048 	         We remove this mark in type_unification_real.  */
15049               if (targ)
15050                 {
15051                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
15052                   ARGUMENT_PACK_EXPLICIT_ARGS (targ)
15053                     = ARGUMENT_PACK_ARGS (targ);
15054                 }
15055 
15056               /* We have some incomplete argument packs.  */
15057               incomplete = true;
15058             }
15059         }
15060 
15061       TREE_VALUE (tinst) = explicit_targs;
15062       if (!push_tinst_level (tinst))
15063 	{
15064 	  excessive_deduction_depth = true;
15065 	  goto fail;
15066 	}
15067       processing_template_decl += incomplete;
15068       input_location = DECL_SOURCE_LOCATION (fn);
15069       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
15070 		       complain | tf_partial, NULL_TREE);
15071       input_location = loc;
15072       processing_template_decl -= incomplete;
15073       pop_tinst_level ();
15074 
15075       if (fntype == error_mark_node)
15076 	goto fail;
15077 
15078       /* Throw away these access checks; we'll see them again in
15079 	 instantiate_template and they might have the wrong
15080 	 access path at this point.  */
15081       pop_deferring_access_checks ();
15082       push_deferring_access_checks (dk_deferred);
15083 
15084       /* Place the explicitly specified arguments in TARGS.  */
15085       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
15086 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
15087     }
15088 
15089   /* Never do unification on the 'this' parameter.  */
15090   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
15091 
15092   if (return_type)
15093     {
15094       tree *new_args;
15095 
15096       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
15097       new_args = XALLOCAVEC (tree, nargs + 1);
15098       new_args[0] = return_type;
15099       memcpy (new_args + 1, args, nargs * sizeof (tree));
15100       args = new_args;
15101       ++nargs;
15102     }
15103 
15104   /* We allow incomplete unification without an error message here
15105      because the standard doesn't seem to explicitly prohibit it.  Our
15106      callers must be ready to deal with unification failures in any
15107      event.  */
15108 
15109   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
15110 			       targs, parms, args, nargs, /*subr=*/0,
15111 			       strict, flags, explain_p);
15112   if (!ok)
15113     goto fail;
15114 
15115   /* Now that we have bindings for all of the template arguments,
15116      ensure that the arguments deduced for the template template
15117      parameters have compatible template parameter lists.  We cannot
15118      check this property before we have deduced all template
15119      arguments, because the template parameter types of a template
15120      template parameter might depend on prior template parameters
15121      deduced after the template template parameter.  The following
15122      ill-formed example illustrates this issue:
15123 
15124        template<typename T, template<T> class C> void f(C<5>, T);
15125 
15126        template<int N> struct X {};
15127 
15128        void g() {
15129          f(X<5>(), 5l); // error: template argument deduction fails
15130        }
15131 
15132      The template parameter list of 'C' depends on the template type
15133      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
15134      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
15135      time that we deduce 'C'.  */
15136   if (!template_template_parm_bindings_ok_p
15137            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
15138     {
15139       unify_inconsistent_template_template_parameters (explain_p);
15140       goto fail;
15141     }
15142 
15143   /* All is well so far.  Now, check:
15144 
15145      [temp.deduct]
15146 
15147      When all template arguments have been deduced, all uses of
15148      template parameters in nondeduced contexts are replaced with
15149      the corresponding deduced argument values.  If the
15150      substitution results in an invalid type, as described above,
15151      type deduction fails.  */
15152   TREE_VALUE (tinst) = targs;
15153   if (!push_tinst_level (tinst))
15154     {
15155       excessive_deduction_depth = true;
15156       goto fail;
15157     }
15158   decl = instantiate_template (fn, targs, complain);
15159   pop_tinst_level ();
15160 
15161   if (decl == error_mark_node)
15162     goto fail;
15163 
15164   /* Now perform any access checks encountered during deduction, such as
15165      for default template arguments.  */
15166   push_access_scope (decl);
15167   ok = perform_deferred_access_checks (complain);
15168   pop_access_scope (decl);
15169   if (!ok)
15170     goto fail;
15171 
15172   /* If we're looking for an exact match, check that what we got
15173      is indeed an exact match.  It might not be if some template
15174      parameters are used in non-deduced contexts.  */
15175   if (strict == DEDUCE_EXACT)
15176     {
15177       tree substed = TREE_TYPE (decl);
15178       unsigned int i;
15179 
15180       tree sarg
15181 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
15182       if (return_type)
15183 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
15184       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
15185 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
15186 	  {
15187 	    unify_type_mismatch (explain_p, args[i],
15188 				 TREE_VALUE (sarg));
15189 	    goto fail;
15190 	  }
15191     }
15192 
15193   r = decl;
15194 
15195  fail:
15196   pop_deferring_access_checks ();
15197   --deduction_depth;
15198   if (excessive_deduction_depth)
15199     {
15200       if (deduction_depth == 0)
15201 	/* Reset once we're all the way out.  */
15202 	excessive_deduction_depth = false;
15203     }
15204 
15205   /* We can't free this if a pending_template entry or last_error_tinst_level
15206      is pointing at it.  */
15207   if (last_pending_template == old_last_pend
15208       && last_error_tinst_level == old_error_tinst)
15209     ggc_free (tinst);
15210 
15211   return r;
15212 }
15213 
15214 /* Adjust types before performing type deduction, as described in
15215    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
15216    sections are symmetric.  PARM is the type of a function parameter
15217    or the return type of the conversion function.  ARG is the type of
15218    the argument passed to the call, or the type of the value
15219    initialized with the result of the conversion function.
15220    ARG_EXPR is the original argument expression, which may be null.  */
15221 
15222 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)15223 maybe_adjust_types_for_deduction (unification_kind_t strict,
15224 				  tree* parm,
15225 				  tree* arg,
15226 				  tree arg_expr)
15227 {
15228   int result = 0;
15229 
15230   switch (strict)
15231     {
15232     case DEDUCE_CALL:
15233       break;
15234 
15235     case DEDUCE_CONV:
15236       {
15237 	/* Swap PARM and ARG throughout the remainder of this
15238 	   function; the handling is precisely symmetric since PARM
15239 	   will initialize ARG rather than vice versa.  */
15240 	tree* temp = parm;
15241 	parm = arg;
15242 	arg = temp;
15243 	break;
15244       }
15245 
15246     case DEDUCE_EXACT:
15247       /* Core issue #873: Do the DR606 thing (see below) for these cases,
15248 	 too, but here handle it by stripping the reference from PARM
15249 	 rather than by adding it to ARG.  */
15250       if (TREE_CODE (*parm) == REFERENCE_TYPE
15251 	  && TYPE_REF_IS_RVALUE (*parm)
15252 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
15253 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
15254 	  && TREE_CODE (*arg) == REFERENCE_TYPE
15255 	  && !TYPE_REF_IS_RVALUE (*arg))
15256 	*parm = TREE_TYPE (*parm);
15257       /* Nothing else to do in this case.  */
15258       return 0;
15259 
15260     default:
15261       gcc_unreachable ();
15262     }
15263 
15264   if (TREE_CODE (*parm) != REFERENCE_TYPE)
15265     {
15266       /* [temp.deduct.call]
15267 
15268 	 If P is not a reference type:
15269 
15270 	 --If A is an array type, the pointer type produced by the
15271 	 array-to-pointer standard conversion (_conv.array_) is
15272 	 used in place of A for type deduction; otherwise,
15273 
15274 	 --If A is a function type, the pointer type produced by
15275 	 the function-to-pointer standard conversion
15276 	 (_conv.func_) is used in place of A for type deduction;
15277 	 otherwise,
15278 
15279 	 --If A is a cv-qualified type, the top level
15280 	 cv-qualifiers of A's type are ignored for type
15281 	 deduction.  */
15282       if (TREE_CODE (*arg) == ARRAY_TYPE)
15283 	*arg = build_pointer_type (TREE_TYPE (*arg));
15284       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
15285 	*arg = build_pointer_type (*arg);
15286       else
15287 	*arg = TYPE_MAIN_VARIANT (*arg);
15288     }
15289 
15290   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
15291      of the form T&&, where T is a template parameter, and the argument
15292      is an lvalue, T is deduced as A& */
15293   if (TREE_CODE (*parm) == REFERENCE_TYPE
15294       && TYPE_REF_IS_RVALUE (*parm)
15295       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
15296       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
15297       && (arg_expr ? real_lvalue_p (arg_expr)
15298 	  /* try_one_overload doesn't provide an arg_expr, but
15299 	     functions are always lvalues.  */
15300 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
15301     *arg = build_reference_type (*arg);
15302 
15303   /* [temp.deduct.call]
15304 
15305      If P is a cv-qualified type, the top level cv-qualifiers
15306      of P's type are ignored for type deduction.  If P is a
15307      reference type, the type referred to by P is used for
15308      type deduction.  */
15309   *parm = TYPE_MAIN_VARIANT (*parm);
15310   if (TREE_CODE (*parm) == REFERENCE_TYPE)
15311     {
15312       *parm = TREE_TYPE (*parm);
15313       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15314     }
15315 
15316   /* DR 322. For conversion deduction, remove a reference type on parm
15317      too (which has been swapped into ARG).  */
15318   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
15319     *arg = TREE_TYPE (*arg);
15320 
15321   return result;
15322 }
15323 
15324 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
15325    template which does contain any deducible template parameters; check if
15326    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
15327    unify_one_argument.  */
15328 
15329 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,bool explain_p)15330 check_non_deducible_conversion (tree parm, tree arg, int strict,
15331 				int flags, bool explain_p)
15332 {
15333   tree type;
15334 
15335   if (!TYPE_P (arg))
15336     type = TREE_TYPE (arg);
15337   else
15338     type = arg;
15339 
15340   if (same_type_p (parm, type))
15341     return unify_success (explain_p);
15342 
15343   if (strict == DEDUCE_CONV)
15344     {
15345       if (can_convert_arg (type, parm, NULL_TREE, flags,
15346 			   explain_p ? tf_warning_or_error : tf_none))
15347 	return unify_success (explain_p);
15348     }
15349   else if (strict != DEDUCE_EXACT)
15350     {
15351       if (can_convert_arg (parm, type,
15352 			   TYPE_P (arg) ? NULL_TREE : arg,
15353 			   flags, explain_p ? tf_warning_or_error : tf_none))
15354 	return unify_success (explain_p);
15355     }
15356 
15357   if (strict == DEDUCE_EXACT)
15358     return unify_type_mismatch (explain_p, parm, arg);
15359   else
15360     return unify_arg_conversion (explain_p, parm, type, arg);
15361 }
15362 
15363 /* Subroutine of type_unification_real and unify_pack_expansion to
15364    handle unification of a single P/A pair.  Parameters are as
15365    for those functions.  */
15366 
15367 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,int flags,bool explain_p)15368 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
15369 		    int subr, unification_kind_t strict, int flags,
15370 		    bool explain_p)
15371 {
15372   tree arg_expr = NULL_TREE;
15373   int arg_strict;
15374 
15375   if (arg == error_mark_node || parm == error_mark_node)
15376     return unify_invalid (explain_p);
15377   if (arg == unknown_type_node)
15378     /* We can't deduce anything from this, but we might get all the
15379        template args from other function args.  */
15380     return unify_success (explain_p);
15381 
15382   /* FIXME uses_deducible_template_parms */
15383   if (TYPE_P (parm) && !uses_template_parms (parm))
15384     return check_non_deducible_conversion (parm, arg, strict, flags,
15385 					   explain_p);
15386 
15387   switch (strict)
15388     {
15389     case DEDUCE_CALL:
15390       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
15391 		    | UNIFY_ALLOW_MORE_CV_QUAL
15392 		    | UNIFY_ALLOW_DERIVED);
15393       break;
15394 
15395     case DEDUCE_CONV:
15396       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
15397       break;
15398 
15399     case DEDUCE_EXACT:
15400       arg_strict = UNIFY_ALLOW_NONE;
15401       break;
15402 
15403     default:
15404       gcc_unreachable ();
15405     }
15406 
15407   /* We only do these transformations if this is the top-level
15408      parameter_type_list in a call or declaration matching; in other
15409      situations (nested function declarators, template argument lists) we
15410      won't be comparing a type to an expression, and we don't do any type
15411      adjustments.  */
15412   if (!subr)
15413     {
15414       if (!TYPE_P (arg))
15415 	{
15416 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
15417 	  if (type_unknown_p (arg))
15418 	    {
15419 	      /* [temp.deduct.type] A template-argument can be
15420 		 deduced from a pointer to function or pointer
15421 		 to member function argument if the set of
15422 		 overloaded functions does not contain function
15423 		 templates and at most one of a set of
15424 		 overloaded functions provides a unique
15425 		 match.  */
15426 
15427 	      if (resolve_overloaded_unification
15428 		  (tparms, targs, parm, arg, strict,
15429 		   arg_strict, explain_p))
15430 		return unify_success (explain_p);
15431 	      return unify_overload_resolution_failure (explain_p, arg);
15432 	    }
15433 
15434 	  arg_expr = arg;
15435 	  arg = unlowered_expr_type (arg);
15436 	  if (arg == error_mark_node)
15437 	    return unify_invalid (explain_p);
15438 	}
15439 
15440       arg_strict |=
15441 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
15442     }
15443   else
15444     gcc_assert ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
15445 		== (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL));
15446 
15447   /* For deduction from an init-list we need the actual list.  */
15448   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
15449     arg = arg_expr;
15450   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
15451 }
15452 
15453 /* Most parms like fn_type_unification.
15454 
15455    If SUBR is 1, we're being called recursively (to unify the
15456    arguments of a function or method parameter of a function
15457    template). */
15458 
15459 static int
type_unification_real(tree tparms,tree targs,tree xparms,const tree * xargs,unsigned int xnargs,int subr,unification_kind_t strict,int flags,bool explain_p)15460 type_unification_real (tree tparms,
15461 		       tree targs,
15462 		       tree xparms,
15463 		       const tree *xargs,
15464 		       unsigned int xnargs,
15465 		       int subr,
15466 		       unification_kind_t strict,
15467 		       int flags,
15468 		       bool explain_p)
15469 {
15470   tree parm, arg;
15471   int i;
15472   int ntparms = TREE_VEC_LENGTH (tparms);
15473   int saw_undeduced = 0;
15474   tree parms;
15475   const tree *args;
15476   unsigned int nargs;
15477   unsigned int ia;
15478 
15479   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
15480   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
15481   gcc_assert (ntparms > 0);
15482 
15483   /* Reset the number of non-defaulted template arguments contained
15484      in TARGS.  */
15485   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
15486 
15487  again:
15488   parms = xparms;
15489   args = xargs;
15490   nargs = xnargs;
15491 
15492   ia = 0;
15493   while (parms && parms != void_list_node
15494 	 && ia < nargs)
15495     {
15496       parm = TREE_VALUE (parms);
15497 
15498       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
15499 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
15500 	/* For a function parameter pack that occurs at the end of the
15501 	   parameter-declaration-list, the type A of each remaining
15502 	   argument of the call is compared with the type P of the
15503 	   declarator-id of the function parameter pack.  */
15504 	break;
15505 
15506       parms = TREE_CHAIN (parms);
15507 
15508       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
15509 	/* For a function parameter pack that does not occur at the
15510 	   end of the parameter-declaration-list, the type of the
15511 	   parameter pack is a non-deduced context.  */
15512 	continue;
15513 
15514       arg = args[ia];
15515       ++ia;
15516 
15517       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
15518 			      flags, explain_p))
15519 	return 1;
15520     }
15521 
15522   if (parms
15523       && parms != void_list_node
15524       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
15525     {
15526       /* Unify the remaining arguments with the pack expansion type.  */
15527       tree argvec;
15528       tree parmvec = make_tree_vec (1);
15529 
15530       /* Allocate a TREE_VEC and copy in all of the arguments */
15531       argvec = make_tree_vec (nargs - ia);
15532       for (i = 0; ia < nargs; ++ia, ++i)
15533 	TREE_VEC_ELT (argvec, i) = args[ia];
15534 
15535       /* Copy the parameter into parmvec.  */
15536       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
15537       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
15538                                 /*subr=*/subr, explain_p))
15539         return 1;
15540 
15541       /* Advance to the end of the list of parameters.  */
15542       parms = TREE_CHAIN (parms);
15543     }
15544 
15545   /* Fail if we've reached the end of the parm list, and more args
15546      are present, and the parm list isn't variadic.  */
15547   if (ia < nargs && parms == void_list_node)
15548     return unify_too_many_arguments (explain_p, nargs, ia);
15549   /* Fail if parms are left and they don't have default values.  */
15550   if (parms && parms != void_list_node
15551       && TREE_PURPOSE (parms) == NULL_TREE)
15552     {
15553       unsigned int count = nargs;
15554       tree p = parms;
15555       while (p && p != void_list_node)
15556 	{
15557 	  count++;
15558 	  p = TREE_CHAIN (p);
15559 	}
15560       return unify_too_few_arguments (explain_p, ia, count);
15561     }
15562 
15563   if (!subr)
15564     {
15565       tsubst_flags_t complain = (explain_p
15566 				 ? tf_warning_or_error
15567 				 : tf_none);
15568 
15569       for (i = 0; i < ntparms; i++)
15570 	{
15571 	  tree targ = TREE_VEC_ELT (targs, i);
15572 	  tree tparm = TREE_VEC_ELT (tparms, i);
15573 
15574 	  /* Clear the "incomplete" flags on all argument packs now so that
15575 	     substituting them into later default arguments works.  */
15576 	  if (targ && ARGUMENT_PACK_P (targ))
15577             {
15578               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
15579               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
15580             }
15581 
15582 	  if (targ || tparm == error_mark_node)
15583 	    continue;
15584 	  tparm = TREE_VALUE (tparm);
15585 
15586 	  /* If this is an undeduced nontype parameter that depends on
15587 	     a type parameter, try another pass; its type may have been
15588 	     deduced from a later argument than the one from which
15589 	     this parameter can be deduced.  */
15590 	  if (TREE_CODE (tparm) == PARM_DECL
15591 	      && uses_template_parms (TREE_TYPE (tparm))
15592 	      && !saw_undeduced++)
15593 	    goto again;
15594 
15595 	  /* Core issue #226 (C++0x) [temp.deduct]:
15596 
15597 	     If a template argument has not been deduced, its
15598 	     default template argument, if any, is used.
15599 
15600 	     When we are in C++98 mode, TREE_PURPOSE will either
15601 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
15602 	     to explicitly check cxx_dialect here.  */
15603 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
15604 	    {
15605 	      tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
15606 	      tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
15607 	      location_t save_loc = input_location;
15608 	      if (DECL_P (parm))
15609 		input_location = DECL_SOURCE_LOCATION (parm);
15610 	      arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
15611 	      arg = convert_template_argument (parm, arg, targs, complain,
15612 					       i, NULL_TREE);
15613 	      input_location = save_loc;
15614 	      if (arg == error_mark_node)
15615 		return 1;
15616 	      else
15617 		{
15618 		  TREE_VEC_ELT (targs, i) = arg;
15619 		  /* The position of the first default template argument,
15620 		     is also the number of non-defaulted arguments in TARGS.
15621 		     Record that.  */
15622 		  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15623 		    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
15624 		  continue;
15625 		}
15626 	    }
15627 
15628 	  /* If the type parameter is a parameter pack, then it will
15629 	     be deduced to an empty parameter pack.  */
15630 	  if (template_parameter_pack_p (tparm))
15631 	    {
15632 	      tree arg;
15633 
15634 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
15635 		{
15636 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
15637 		  TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
15638 		  TREE_CONSTANT (arg) = 1;
15639 		}
15640 	      else
15641 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
15642 
15643 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
15644 
15645 	      TREE_VEC_ELT (targs, i) = arg;
15646 	      continue;
15647 	    }
15648 
15649 	  return unify_parameter_deduction_failure (explain_p, tparm);
15650 	}
15651     }
15652 #ifdef ENABLE_CHECKING
15653   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
15654     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
15655 #endif
15656 
15657   return unify_success (explain_p);
15658 }
15659 
15660 /* Subroutine of type_unification_real.  Args are like the variables
15661    at the call site.  ARG is an overloaded function (or template-id);
15662    we try deducing template args from each of the overloads, and if
15663    only one succeeds, we go with that.  Modifies TARGS and returns
15664    true on success.  */
15665 
15666 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)15667 resolve_overloaded_unification (tree tparms,
15668 				tree targs,
15669 				tree parm,
15670 				tree arg,
15671 				unification_kind_t strict,
15672 				int sub_strict,
15673 			        bool explain_p)
15674 {
15675   tree tempargs = copy_node (targs);
15676   int good = 0;
15677   tree goodfn = NULL_TREE;
15678   bool addr_p;
15679 
15680   if (TREE_CODE (arg) == ADDR_EXPR)
15681     {
15682       arg = TREE_OPERAND (arg, 0);
15683       addr_p = true;
15684     }
15685   else
15686     addr_p = false;
15687 
15688   if (TREE_CODE (arg) == COMPONENT_REF)
15689     /* Handle `&x' where `x' is some static or non-static member
15690        function name.  */
15691     arg = TREE_OPERAND (arg, 1);
15692 
15693   if (TREE_CODE (arg) == OFFSET_REF)
15694     arg = TREE_OPERAND (arg, 1);
15695 
15696   /* Strip baselink information.  */
15697   if (BASELINK_P (arg))
15698     arg = BASELINK_FUNCTIONS (arg);
15699 
15700   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
15701     {
15702       /* If we got some explicit template args, we need to plug them into
15703 	 the affected templates before we try to unify, in case the
15704 	 explicit args will completely resolve the templates in question.  */
15705 
15706       int ok = 0;
15707       tree expl_subargs = TREE_OPERAND (arg, 1);
15708       arg = TREE_OPERAND (arg, 0);
15709 
15710       for (; arg; arg = OVL_NEXT (arg))
15711 	{
15712 	  tree fn = OVL_CURRENT (arg);
15713 	  tree subargs, elem;
15714 
15715 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
15716 	    continue;
15717 
15718 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
15719 					   expl_subargs, NULL_TREE, tf_none,
15720 					   /*require_all_args=*/true,
15721 					   /*use_default_args=*/true);
15722 	  if (subargs != error_mark_node
15723 	      && !any_dependent_template_arguments_p (subargs))
15724 	    {
15725 	      elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
15726 	      if (try_one_overload (tparms, targs, tempargs, parm,
15727 				    elem, strict, sub_strict, addr_p, explain_p)
15728 		  && (!goodfn || !same_type_p (goodfn, elem)))
15729 		{
15730 		  goodfn = elem;
15731 		  ++good;
15732 		}
15733 	    }
15734 	  else if (subargs)
15735 	    ++ok;
15736 	}
15737       /* If no templates (or more than one) are fully resolved by the
15738 	 explicit arguments, this template-id is a non-deduced context; it
15739 	 could still be OK if we deduce all template arguments for the
15740 	 enclosing call through other arguments.  */
15741       if (good != 1)
15742 	good = ok;
15743     }
15744   else if (TREE_CODE (arg) != OVERLOAD
15745 	   && TREE_CODE (arg) != FUNCTION_DECL)
15746     /* If ARG is, for example, "(0, &f)" then its type will be unknown
15747        -- but the deduction does not succeed because the expression is
15748        not just the function on its own.  */
15749     return false;
15750   else
15751     for (; arg; arg = OVL_NEXT (arg))
15752       if (try_one_overload (tparms, targs, tempargs, parm,
15753 			    TREE_TYPE (OVL_CURRENT (arg)),
15754 			    strict, sub_strict, addr_p, explain_p)
15755 	  && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
15756 	{
15757 	  goodfn = OVL_CURRENT (arg);
15758 	  ++good;
15759 	}
15760 
15761   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15762      to function or pointer to member function argument if the set of
15763      overloaded functions does not contain function templates and at most
15764      one of a set of overloaded functions provides a unique match.
15765 
15766      So if we found multiple possibilities, we return success but don't
15767      deduce anything.  */
15768 
15769   if (good == 1)
15770     {
15771       int i = TREE_VEC_LENGTH (targs);
15772       for (; i--; )
15773 	if (TREE_VEC_ELT (tempargs, i))
15774 	  TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
15775     }
15776   if (good)
15777     return true;
15778 
15779   return false;
15780 }
15781 
15782 /* Core DR 115: In contexts where deduction is done and fails, or in
15783    contexts where deduction is not done, if a template argument list is
15784    specified and it, along with any default template arguments, identifies
15785    a single function template specialization, then the template-id is an
15786    lvalue for the function template specialization.  */
15787 
15788 tree
resolve_nondeduced_context(tree orig_expr)15789 resolve_nondeduced_context (tree orig_expr)
15790 {
15791   tree expr, offset, baselink;
15792   bool addr;
15793 
15794   if (!type_unknown_p (orig_expr))
15795     return orig_expr;
15796 
15797   expr = orig_expr;
15798   addr = false;
15799   offset = NULL_TREE;
15800   baselink = NULL_TREE;
15801 
15802   if (TREE_CODE (expr) == ADDR_EXPR)
15803     {
15804       expr = TREE_OPERAND (expr, 0);
15805       addr = true;
15806     }
15807   if (TREE_CODE (expr) == OFFSET_REF)
15808     {
15809       offset = expr;
15810       expr = TREE_OPERAND (expr, 1);
15811     }
15812   if (BASELINK_P (expr))
15813     {
15814       baselink = expr;
15815       expr = BASELINK_FUNCTIONS (expr);
15816     }
15817 
15818   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
15819     {
15820       int good = 0;
15821       tree goodfn = NULL_TREE;
15822 
15823       /* If we got some explicit template args, we need to plug them into
15824 	 the affected templates before we try to unify, in case the
15825 	 explicit args will completely resolve the templates in question.  */
15826 
15827       tree expl_subargs = TREE_OPERAND (expr, 1);
15828       tree arg = TREE_OPERAND (expr, 0);
15829       tree badfn = NULL_TREE;
15830       tree badargs = NULL_TREE;
15831 
15832       for (; arg; arg = OVL_NEXT (arg))
15833 	{
15834 	  tree fn = OVL_CURRENT (arg);
15835 	  tree subargs, elem;
15836 
15837 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
15838 	    continue;
15839 
15840 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
15841 					   expl_subargs, NULL_TREE, tf_none,
15842 					   /*require_all_args=*/true,
15843 					   /*use_default_args=*/true);
15844 	  if (subargs != error_mark_node
15845 	      && !any_dependent_template_arguments_p (subargs))
15846 	    {
15847 	      elem = instantiate_template (fn, subargs, tf_none);
15848 	      if (elem == error_mark_node)
15849 		{
15850 		  badfn = fn;
15851 		  badargs = subargs;
15852 		}
15853 	      else if (elem && (!goodfn || !decls_match (goodfn, elem)))
15854 		{
15855 		  goodfn = elem;
15856 		  ++good;
15857 		}
15858 	    }
15859 	}
15860       if (good == 1)
15861 	{
15862 	  mark_used (goodfn);
15863 	  expr = goodfn;
15864 	  if (baselink)
15865 	    expr = build_baselink (BASELINK_BINFO (baselink),
15866 				   BASELINK_ACCESS_BINFO (baselink),
15867 				   expr, BASELINK_OPTYPE (baselink));
15868 	  if (offset)
15869 	    {
15870 	      tree base
15871 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
15872 	      expr = build_offset_ref (base, expr, addr, tf_warning_or_error);
15873 	    }
15874 	  if (addr)
15875 	    expr = cp_build_addr_expr (expr, tf_warning_or_error);
15876 	  return expr;
15877 	}
15878       else if (good == 0 && badargs)
15879 	/* There were no good options and at least one bad one, so let the
15880 	   user know what the problem is.  */
15881 	instantiate_template (badfn, badargs, tf_warning_or_error);
15882     }
15883   return orig_expr;
15884 }
15885 
15886 /* Subroutine of resolve_overloaded_unification; does deduction for a single
15887    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
15888    different overloads deduce different arguments for a given parm.
15889    ADDR_P is true if the expression for which deduction is being
15890    performed was of the form "& fn" rather than simply "fn".
15891 
15892    Returns 1 on success.  */
15893 
15894 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,bool explain_p)15895 try_one_overload (tree tparms,
15896 		  tree orig_targs,
15897 		  tree targs,
15898 		  tree parm,
15899 		  tree arg,
15900 		  unification_kind_t strict,
15901 		  int sub_strict,
15902 		  bool addr_p,
15903 		  bool explain_p)
15904 {
15905   int nargs;
15906   tree tempargs;
15907   int i;
15908 
15909   if (arg == error_mark_node)
15910     return 0;
15911 
15912   /* [temp.deduct.type] A template-argument can be deduced from a pointer
15913      to function or pointer to member function argument if the set of
15914      overloaded functions does not contain function templates and at most
15915      one of a set of overloaded functions provides a unique match.
15916 
15917      So if this is a template, just return success.  */
15918 
15919   if (uses_template_parms (arg))
15920     return 1;
15921 
15922   if (TREE_CODE (arg) == METHOD_TYPE)
15923     arg = build_ptrmemfunc_type (build_pointer_type (arg));
15924   else if (addr_p)
15925     arg = build_pointer_type (arg);
15926 
15927   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
15928 
15929   /* We don't copy orig_targs for this because if we have already deduced
15930      some template args from previous args, unify would complain when we
15931      try to deduce a template parameter for the same argument, even though
15932      there isn't really a conflict.  */
15933   nargs = TREE_VEC_LENGTH (targs);
15934   tempargs = make_tree_vec (nargs);
15935 
15936   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
15937     return 0;
15938 
15939   /* First make sure we didn't deduce anything that conflicts with
15940      explicitly specified args.  */
15941   for (i = nargs; i--; )
15942     {
15943       tree elt = TREE_VEC_ELT (tempargs, i);
15944       tree oldelt = TREE_VEC_ELT (orig_targs, i);
15945 
15946       if (!elt)
15947 	/*NOP*/;
15948       else if (uses_template_parms (elt))
15949 	/* Since we're unifying against ourselves, we will fill in
15950 	   template args used in the function parm list with our own
15951 	   template parms.  Discard them.  */
15952 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
15953       else if (oldelt && !template_args_equal (oldelt, elt))
15954 	return 0;
15955     }
15956 
15957   for (i = nargs; i--; )
15958     {
15959       tree elt = TREE_VEC_ELT (tempargs, i);
15960 
15961       if (elt)
15962 	TREE_VEC_ELT (targs, i) = elt;
15963     }
15964 
15965   return 1;
15966 }
15967 
15968 /* PARM is a template class (perhaps with unbound template
15969    parameters).  ARG is a fully instantiated type.  If ARG can be
15970    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
15971    TARGS are as for unify.  */
15972 
15973 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)15974 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
15975 		       bool explain_p)
15976 {
15977   tree copy_of_targs;
15978 
15979   if (!CLASSTYPE_TEMPLATE_INFO (arg)
15980       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
15981 	  != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
15982     return NULL_TREE;
15983 
15984   /* We need to make a new template argument vector for the call to
15985      unify.  If we used TARGS, we'd clutter it up with the result of
15986      the attempted unification, even if this class didn't work out.
15987      We also don't want to commit ourselves to all the unifications
15988      we've already done, since unification is supposed to be done on
15989      an argument-by-argument basis.  In other words, consider the
15990      following pathological case:
15991 
15992        template <int I, int J, int K>
15993        struct S {};
15994 
15995        template <int I, int J>
15996        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
15997 
15998        template <int I, int J, int K>
15999        void f(S<I, J, K>, S<I, I, I>);
16000 
16001        void g() {
16002 	 S<0, 0, 0> s0;
16003 	 S<0, 1, 2> s2;
16004 
16005 	 f(s0, s2);
16006        }
16007 
16008      Now, by the time we consider the unification involving `s2', we
16009      already know that we must have `f<0, 0, 0>'.  But, even though
16010      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
16011      because there are two ways to unify base classes of S<0, 1, 2>
16012      with S<I, I, I>.  If we kept the already deduced knowledge, we
16013      would reject the possibility I=1.  */
16014   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
16015 
16016   /* If unification failed, we're done.  */
16017   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
16018 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
16019     return NULL_TREE;
16020 
16021   return arg;
16022 }
16023 
16024 /* Given a template type PARM and a class type ARG, find the unique
16025    base type in ARG that is an instance of PARM.  We do not examine
16026    ARG itself; only its base-classes.  If there is not exactly one
16027    appropriate base class, return NULL_TREE.  PARM may be the type of
16028    a partial specialization, as well as a plain template type.  Used
16029    by unify.  */
16030 
16031 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)16032 get_template_base (tree tparms, tree targs, tree parm, tree arg,
16033 		   bool explain_p, tree *result)
16034 {
16035   tree rval = NULL_TREE;
16036   tree binfo;
16037 
16038   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
16039 
16040   binfo = TYPE_BINFO (complete_type (arg));
16041   if (!binfo)
16042     {
16043       /* The type could not be completed.  */
16044       *result = NULL_TREE;
16045       return tbr_incomplete_type;
16046     }
16047 
16048   /* Walk in inheritance graph order.  The search order is not
16049      important, and this avoids multiple walks of virtual bases.  */
16050   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
16051     {
16052       tree r = try_class_unification (tparms, targs, parm,
16053 				      BINFO_TYPE (binfo), explain_p);
16054 
16055       if (r)
16056 	{
16057 	  /* If there is more than one satisfactory baseclass, then:
16058 
16059 	       [temp.deduct.call]
16060 
16061 	      If they yield more than one possible deduced A, the type
16062 	      deduction fails.
16063 
16064 	     applies.  */
16065 	  if (rval && !same_type_p (r, rval))
16066 	    {
16067 	      *result = NULL_TREE;
16068 	      return tbr_ambiguous_baseclass;
16069 	    }
16070 
16071 	  rval = r;
16072 	}
16073     }
16074 
16075   *result = rval;
16076   return tbr_success;
16077 }
16078 
16079 /* Returns the level of DECL, which declares a template parameter.  */
16080 
16081 static int
template_decl_level(tree decl)16082 template_decl_level (tree decl)
16083 {
16084   switch (TREE_CODE (decl))
16085     {
16086     case TYPE_DECL:
16087     case TEMPLATE_DECL:
16088       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
16089 
16090     case PARM_DECL:
16091       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
16092 
16093     default:
16094       gcc_unreachable ();
16095     }
16096   return 0;
16097 }
16098 
16099 /* Decide whether ARG can be unified with PARM, considering only the
16100    cv-qualifiers of each type, given STRICT as documented for unify.
16101    Returns nonzero iff the unification is OK on that basis.  */
16102 
16103 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)16104 check_cv_quals_for_unify (int strict, tree arg, tree parm)
16105 {
16106   int arg_quals = cp_type_quals (arg);
16107   int parm_quals = cp_type_quals (parm);
16108 
16109   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
16110       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
16111     {
16112       /*  Although a CVR qualifier is ignored when being applied to a
16113 	  substituted template parameter ([8.3.2]/1 for example), that
16114 	  does not allow us to unify "const T" with "int&" because both
16115 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
16116 	  It is ok when we're allowing additional CV qualifiers
16117 	  at the outer level [14.8.2.1]/3,1st bullet.  */
16118       if ((TREE_CODE (arg) == REFERENCE_TYPE
16119 	   || TREE_CODE (arg) == FUNCTION_TYPE
16120 	   || TREE_CODE (arg) == METHOD_TYPE)
16121 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
16122 	return 0;
16123 
16124       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
16125 	  && (parm_quals & TYPE_QUAL_RESTRICT))
16126 	return 0;
16127     }
16128 
16129   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
16130       && (arg_quals & parm_quals) != parm_quals)
16131     return 0;
16132 
16133   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
16134       && (parm_quals & arg_quals) != arg_quals)
16135     return 0;
16136 
16137   return 1;
16138 }
16139 
16140 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
16141 void
template_parm_level_and_index(tree parm,int * level,int * index)16142 template_parm_level_and_index (tree parm, int* level, int* index)
16143 {
16144   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
16145       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16146       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16147     {
16148       *index = TEMPLATE_TYPE_IDX (parm);
16149       *level = TEMPLATE_TYPE_LEVEL (parm);
16150     }
16151   else
16152     {
16153       *index = TEMPLATE_PARM_IDX (parm);
16154       *level = TEMPLATE_PARM_LEVEL (parm);
16155     }
16156 }
16157 
16158 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
16159   do {									\
16160     if (unify (TP, TA, P, A, S, EP))					\
16161       return 1;								\
16162   } while (0);
16163 
16164 /* Unifies the remaining arguments in PACKED_ARGS with the pack
16165    expansion at the end of PACKED_PARMS. Returns 0 if the type
16166    deduction succeeds, 1 otherwise. STRICT is the same as in
16167    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
16168    call argument list. We'll need to adjust the arguments to make them
16169    types. SUBR tells us if this is from a recursive call to
16170    type_unification_real, or for comparing two template argument
16171    lists. */
16172 
16173 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)16174 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
16175                       tree packed_args, unification_kind_t strict,
16176                       bool subr, bool explain_p)
16177 {
16178   tree parm
16179     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
16180   tree pattern = PACK_EXPANSION_PATTERN (parm);
16181   tree pack, packs = NULL_TREE;
16182   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
16183   int len = TREE_VEC_LENGTH (packed_args);
16184 
16185   /* Determine the parameter packs we will be deducing from the
16186      pattern, and record their current deductions.  */
16187   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
16188        pack; pack = TREE_CHAIN (pack))
16189     {
16190       tree parm_pack = TREE_VALUE (pack);
16191       int idx, level;
16192 
16193       /* Determine the index and level of this parameter pack.  */
16194       template_parm_level_and_index (parm_pack, &level, &idx);
16195 
16196       /* Keep track of the parameter packs and their corresponding
16197          argument packs.  */
16198       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
16199       TREE_TYPE (packs) = make_tree_vec (len - start);
16200     }
16201 
16202   /* Loop through all of the arguments that have not yet been
16203      unified and unify each with the pattern.  */
16204   for (i = start; i < len; i++)
16205     {
16206       tree parm;
16207       bool any_explicit = false;
16208       tree arg = TREE_VEC_ELT (packed_args, i);
16209 
16210       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
16211 	 or the element of its argument pack at the current index if
16212 	 this argument was explicitly specified.  */
16213       for (pack = packs; pack; pack = TREE_CHAIN (pack))
16214         {
16215           int idx, level;
16216           tree arg, pargs;
16217           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
16218 
16219           arg = NULL_TREE;
16220           if (TREE_VALUE (pack)
16221               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
16222               && (i - start < TREE_VEC_LENGTH (pargs)))
16223             {
16224               any_explicit = true;
16225               arg = TREE_VEC_ELT (pargs, i - start);
16226             }
16227           TMPL_ARG (targs, level, idx) = arg;
16228         }
16229 
16230       /* If we had explicit template arguments, substitute them into the
16231 	 pattern before deduction.  */
16232       if (any_explicit)
16233 	{
16234 	  /* Some arguments might still be unspecified or dependent.  */
16235 	  bool dependent;
16236 	  ++processing_template_decl;
16237 	  dependent = any_dependent_template_arguments_p (targs);
16238 	  if (!dependent)
16239 	    --processing_template_decl;
16240 	  parm = tsubst (pattern, targs,
16241 			 explain_p ? tf_warning_or_error : tf_none,
16242 			 NULL_TREE);
16243 	  if (dependent)
16244 	    --processing_template_decl;
16245 	  if (parm == error_mark_node)
16246 	    return 1;
16247 	}
16248       else
16249 	parm = pattern;
16250 
16251       /* Unify the pattern with the current argument.  */
16252       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
16253 			      LOOKUP_IMPLICIT, explain_p))
16254 	return 1;
16255 
16256       /* For each parameter pack, collect the deduced value.  */
16257       for (pack = packs; pack; pack = TREE_CHAIN (pack))
16258         {
16259           int idx, level;
16260           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
16261 
16262           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
16263             TMPL_ARG (targs, level, idx);
16264         }
16265     }
16266 
16267   /* Verify that the results of unification with the parameter packs
16268      produce results consistent with what we've seen before, and make
16269      the deduced argument packs available.  */
16270   for (pack = packs; pack; pack = TREE_CHAIN (pack))
16271     {
16272       tree old_pack = TREE_VALUE (pack);
16273       tree new_args = TREE_TYPE (pack);
16274       int i, len = TREE_VEC_LENGTH (new_args);
16275       int idx, level;
16276       bool nondeduced_p = false;
16277 
16278       /* By default keep the original deduced argument pack.
16279 	 If necessary, more specific code is going to update the
16280 	 resulting deduced argument later down in this function.  */
16281       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
16282       TMPL_ARG (targs, level, idx) = old_pack;
16283 
16284       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
16285 	 actually deduce anything.  */
16286       for (i = 0; i < len && !nondeduced_p; ++i)
16287 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
16288 	  nondeduced_p = true;
16289       if (nondeduced_p)
16290 	continue;
16291 
16292       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
16293         {
16294           /* If we had fewer function args than explicit template args,
16295              just use the explicits.  */
16296           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
16297           int explicit_len = TREE_VEC_LENGTH (explicit_args);
16298           if (len < explicit_len)
16299             new_args = explicit_args;
16300         }
16301 
16302       if (!old_pack)
16303         {
16304           tree result;
16305           /* Build the deduced *_ARGUMENT_PACK.  */
16306           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
16307             {
16308               result = make_node (NONTYPE_ARGUMENT_PACK);
16309               TREE_TYPE (result) =
16310                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
16311               TREE_CONSTANT (result) = 1;
16312             }
16313           else
16314             result = cxx_make_type (TYPE_ARGUMENT_PACK);
16315 
16316           SET_ARGUMENT_PACK_ARGS (result, new_args);
16317 
16318           /* Note the deduced argument packs for this parameter
16319              pack.  */
16320           TMPL_ARG (targs, level, idx) = result;
16321         }
16322       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
16323                && (ARGUMENT_PACK_ARGS (old_pack)
16324                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
16325         {
16326           /* We only had the explicitly-provided arguments before, but
16327              now we have a complete set of arguments.  */
16328           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
16329 
16330           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
16331           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
16332           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
16333         }
16334       else
16335 	{
16336 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
16337 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
16338 
16339 	  if (!comp_template_args_with_info (old_args, new_args,
16340 					     &bad_old_arg, &bad_new_arg))
16341 	    /* Inconsistent unification of this parameter pack.  */
16342 	    return unify_parameter_pack_inconsistent (explain_p,
16343 						      bad_old_arg,
16344 						      bad_new_arg);
16345 	}
16346     }
16347 
16348   return unify_success (explain_p);
16349 }
16350 
16351 /* Deduce the value of template parameters.  TPARMS is the (innermost)
16352    set of template parameters to a template.  TARGS is the bindings
16353    for those template parameters, as determined thus far; TARGS may
16354    include template arguments for outer levels of template parameters
16355    as well.  PARM is a parameter to a template function, or a
16356    subcomponent of that parameter; ARG is the corresponding argument.
16357    This function attempts to match PARM with ARG in a manner
16358    consistent with the existing assignments in TARGS.  If more values
16359    are deduced, then TARGS is updated.
16360 
16361    Returns 0 if the type deduction succeeds, 1 otherwise.  The
16362    parameter STRICT is a bitwise or of the following flags:
16363 
16364      UNIFY_ALLOW_NONE:
16365        Require an exact match between PARM and ARG.
16366      UNIFY_ALLOW_MORE_CV_QUAL:
16367        Allow the deduced ARG to be more cv-qualified (by qualification
16368        conversion) than ARG.
16369      UNIFY_ALLOW_LESS_CV_QUAL:
16370        Allow the deduced ARG to be less cv-qualified than ARG.
16371      UNIFY_ALLOW_DERIVED:
16372        Allow the deduced ARG to be a template base class of ARG,
16373        or a pointer to a template base class of the type pointed to by
16374        ARG.
16375      UNIFY_ALLOW_INTEGER:
16376        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
16377        case for more information.
16378      UNIFY_ALLOW_OUTER_LEVEL:
16379        This is the outermost level of a deduction. Used to determine validity
16380        of qualification conversions. A valid qualification conversion must
16381        have const qualified pointers leading up to the inner type which
16382        requires additional CV quals, except at the outer level, where const
16383        is not required [conv.qual]. It would be normal to set this flag in
16384        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
16385      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
16386        This is the outermost level of a deduction, and PARM can be more CV
16387        qualified at this point.
16388      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
16389        This is the outermost level of a deduction, and PARM can be less CV
16390        qualified at this point.  */
16391 
16392 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)16393 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
16394        bool explain_p)
16395 {
16396   int idx;
16397   tree targ;
16398   tree tparm;
16399   int strict_in = strict;
16400 
16401   /* I don't think this will do the right thing with respect to types.
16402      But the only case I've seen it in so far has been array bounds, where
16403      signedness is the only information lost, and I think that will be
16404      okay.  */
16405   while (TREE_CODE (parm) == NOP_EXPR)
16406     parm = TREE_OPERAND (parm, 0);
16407 
16408   if (arg == error_mark_node)
16409     return unify_invalid (explain_p);
16410   if (arg == unknown_type_node
16411       || arg == init_list_type_node)
16412     /* We can't deduce anything from this, but we might get all the
16413        template args from other function args.  */
16414     return unify_success (explain_p);
16415 
16416   /* If PARM uses template parameters, then we can't bail out here,
16417      even if ARG == PARM, since we won't record unifications for the
16418      template parameters.  We might need them if we're trying to
16419      figure out which of two things is more specialized.  */
16420   if (arg == parm && !uses_template_parms (parm))
16421     return unify_success (explain_p);
16422 
16423   /* Handle init lists early, so the rest of the function can assume
16424      we're dealing with a type. */
16425   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
16426     {
16427       tree elt, elttype;
16428       unsigned i;
16429       tree orig_parm = parm;
16430 
16431       /* Replace T with std::initializer_list<T> for deduction.  */
16432       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
16433 	  && flag_deduce_init_list)
16434 	parm = listify (parm);
16435 
16436       if (!is_std_init_list (parm))
16437 	/* We can only deduce from an initializer list argument if the
16438 	   parameter is std::initializer_list; otherwise this is a
16439 	   non-deduced context. */
16440 	return unify_success (explain_p);
16441 
16442       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
16443 
16444       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
16445 	{
16446 	  int elt_strict = strict;
16447 
16448 	  if (elt == error_mark_node)
16449 	    return unify_invalid (explain_p);
16450 
16451 	  if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
16452 	    {
16453 	      tree type = TREE_TYPE (elt);
16454 	      /* It should only be possible to get here for a call.  */
16455 	      gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
16456 	      elt_strict |= maybe_adjust_types_for_deduction
16457 		(DEDUCE_CALL, &elttype, &type, elt);
16458 	      elt = type;
16459 	    }
16460 
16461 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
16462 				   explain_p);
16463 	}
16464 
16465       /* If the std::initializer_list<T> deduction worked, replace the
16466 	 deduced A with std::initializer_list<A>.  */
16467       if (orig_parm != parm)
16468 	{
16469 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
16470 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16471 	  targ = listify (targ);
16472 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
16473 	}
16474       return unify_success (explain_p);
16475     }
16476 
16477   /* Immediately reject some pairs that won't unify because of
16478      cv-qualification mismatches.  */
16479   if (TREE_CODE (arg) == TREE_CODE (parm)
16480       && TYPE_P (arg)
16481       /* It is the elements of the array which hold the cv quals of an array
16482 	 type, and the elements might be template type parms. We'll check
16483 	 when we recurse.  */
16484       && TREE_CODE (arg) != ARRAY_TYPE
16485       /* We check the cv-qualifiers when unifying with template type
16486 	 parameters below.  We want to allow ARG `const T' to unify with
16487 	 PARM `T' for example, when computing which of two templates
16488 	 is more specialized, for example.  */
16489       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
16490       && !check_cv_quals_for_unify (strict_in, arg, parm))
16491     return unify_cv_qual_mismatch (explain_p, parm, arg);
16492 
16493   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
16494       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
16495     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
16496   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
16497   strict &= ~UNIFY_ALLOW_DERIVED;
16498   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
16499   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
16500 
16501   switch (TREE_CODE (parm))
16502     {
16503     case TYPENAME_TYPE:
16504     case SCOPE_REF:
16505     case UNBOUND_CLASS_TEMPLATE:
16506       /* In a type which contains a nested-name-specifier, template
16507 	 argument values cannot be deduced for template parameters used
16508 	 within the nested-name-specifier.  */
16509       return unify_success (explain_p);
16510 
16511     case TEMPLATE_TYPE_PARM:
16512     case TEMPLATE_TEMPLATE_PARM:
16513     case BOUND_TEMPLATE_TEMPLATE_PARM:
16514       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16515       if (tparm == error_mark_node)
16516 	return unify_invalid (explain_p);
16517 
16518       if (TEMPLATE_TYPE_LEVEL (parm)
16519 	  != template_decl_level (tparm))
16520 	/* The PARM is not one we're trying to unify.  Just check
16521 	   to see if it matches ARG.  */
16522 	{
16523 	  if (TREE_CODE (arg) == TREE_CODE (parm)
16524 	      && (is_auto (parm) ? is_auto (arg)
16525 		  : same_type_p (parm, arg)))
16526 	    return unify_success (explain_p);
16527 	  else
16528 	    return unify_type_mismatch (explain_p, parm, arg);
16529 	}
16530       idx = TEMPLATE_TYPE_IDX (parm);
16531       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16532       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
16533       if (tparm == error_mark_node)
16534 	return unify_invalid (explain_p);
16535 
16536       /* Check for mixed types and values.  */
16537       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
16538 	   && TREE_CODE (tparm) != TYPE_DECL)
16539 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16540 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
16541 	gcc_unreachable ();
16542 
16543       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16544 	{
16545 	  /* ARG must be constructed from a template class or a template
16546 	     template parameter.  */
16547 	  if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
16548 	      && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
16549 	    return unify_template_deduction_failure (explain_p, parm, arg);
16550 
16551 	  {
16552 	    tree parmvec = TYPE_TI_ARGS (parm);
16553 	    tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
16554 	    tree full_argvec = add_to_template_args (targs, argvec);
16555 	    tree parm_parms
16556               = DECL_INNERMOST_TEMPLATE_PARMS
16557 	          (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
16558 	    int i, len;
16559             int parm_variadic_p = 0;
16560 
16561 	    /* The resolution to DR150 makes clear that default
16562 	       arguments for an N-argument may not be used to bind T
16563 	       to a template template parameter with fewer than N
16564 	       parameters.  It is not safe to permit the binding of
16565 	       default arguments as an extension, as that may change
16566 	       the meaning of a conforming program.  Consider:
16567 
16568 		  struct Dense { static const unsigned int dim = 1; };
16569 
16570 		  template <template <typename> class View,
16571 			    typename Block>
16572 		  void operator+(float, View<Block> const&);
16573 
16574 		  template <typename Block,
16575 			    unsigned int Dim = Block::dim>
16576 		  struct Lvalue_proxy { operator float() const; };
16577 
16578 		  void
16579 		  test_1d (void) {
16580 		    Lvalue_proxy<Dense> p;
16581 		    float b;
16582 		    b + p;
16583 		  }
16584 
16585 	      Here, if Lvalue_proxy is permitted to bind to View, then
16586 	      the global operator+ will be used; if they are not, the
16587 	      Lvalue_proxy will be converted to float.  */
16588 	    if (coerce_template_parms (parm_parms,
16589                                        full_argvec,
16590 				       TYPE_TI_TEMPLATE (parm),
16591 				       (explain_p
16592 					? tf_warning_or_error
16593 					: tf_none),
16594 				       /*require_all_args=*/true,
16595 				       /*use_default_args=*/false)
16596 		== error_mark_node)
16597 	      return 1;
16598 
16599 	    /* Deduce arguments T, i from TT<T> or TT<i>.
16600 	       We check each element of PARMVEC and ARGVEC individually
16601 	       rather than the whole TREE_VEC since they can have
16602 	       different number of elements.  */
16603 
16604             parmvec = expand_template_argument_pack (parmvec);
16605             argvec = expand_template_argument_pack (argvec);
16606 
16607             len = TREE_VEC_LENGTH (parmvec);
16608 
16609             /* Check if the parameters end in a pack, making them
16610                variadic.  */
16611             if (len > 0
16612                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
16613               parm_variadic_p = 1;
16614 
16615              for (i = 0; i < len - parm_variadic_p; ++i)
16616 	       /* If the template argument list of P contains a pack
16617 		  expansion that is not the last template argument, the
16618 		  entire template argument list is a non-deduced
16619 		  context.  */
16620 	       if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
16621 		 return unify_success (explain_p);
16622 
16623             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
16624               return unify_too_few_arguments (explain_p,
16625 					      TREE_VEC_LENGTH (argvec), len);
16626 
16627              for (i = 0; i < len - parm_variadic_p; ++i)
16628 	      {
16629 		RECUR_AND_CHECK_FAILURE (tparms, targs,
16630 					 TREE_VEC_ELT (parmvec, i),
16631 					 TREE_VEC_ELT (argvec, i),
16632 					 UNIFY_ALLOW_NONE, explain_p);
16633 	      }
16634 
16635 	    if (parm_variadic_p
16636 		&& unify_pack_expansion (tparms, targs,
16637 					 parmvec, argvec,
16638 					 DEDUCE_EXACT,
16639 					 /*subr=*/true, explain_p))
16640 	      return 1;
16641 	  }
16642 	  arg = TYPE_TI_TEMPLATE (arg);
16643 
16644 	  /* Fall through to deduce template name.  */
16645 	}
16646 
16647       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
16648 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
16649 	{
16650 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
16651 
16652 	  /* Simple cases: Value already set, does match or doesn't.  */
16653 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
16654 	    return unify_success (explain_p);
16655 	  else if (targ)
16656 	    return unify_inconsistency (explain_p, parm, targ, arg);
16657 	}
16658       else
16659 	{
16660 	  /* If PARM is `const T' and ARG is only `int', we don't have
16661 	     a match unless we are allowing additional qualification.
16662 	     If ARG is `const int' and PARM is just `T' that's OK;
16663 	     that binds `const int' to `T'.  */
16664 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
16665 					 arg, parm))
16666 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
16667 
16668 	  /* Consider the case where ARG is `const volatile int' and
16669 	     PARM is `const T'.  Then, T should be `volatile int'.  */
16670 	  arg = cp_build_qualified_type_real
16671 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
16672 	  if (arg == error_mark_node)
16673 	    return unify_invalid (explain_p);
16674 
16675 	  /* Simple cases: Value already set, does match or doesn't.  */
16676 	  if (targ != NULL_TREE && same_type_p (targ, arg))
16677 	    return unify_success (explain_p);
16678 	  else if (targ)
16679 	    return unify_inconsistency (explain_p, parm, targ, arg);
16680 
16681 	  /* Make sure that ARG is not a variable-sized array.  (Note
16682 	     that were talking about variable-sized arrays (like
16683 	     `int[n]'), rather than arrays of unknown size (like
16684 	     `int[]').)  We'll get very confused by such a type since
16685 	     the bound of the array is not constant, and therefore
16686 	     not mangleable.  Besides, such types are not allowed in
16687 	     ISO C++, so we can do as we please here.  We do allow
16688 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
16689 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
16690 	    return unify_vla_arg (explain_p, arg);
16691 
16692 	  /* Strip typedefs as in convert_template_argument.  */
16693 	  arg = canonicalize_type_argument (arg, tf_none);
16694 	}
16695 
16696       /* If ARG is a parameter pack or an expansion, we cannot unify
16697 	 against it unless PARM is also a parameter pack.  */
16698       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16699 	  && !template_parameter_pack_p (parm))
16700 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
16701 
16702       /* If the argument deduction results is a METHOD_TYPE,
16703          then there is a problem.
16704          METHOD_TYPE doesn't map to any real C++ type the result of
16705 	 the deduction can not be of that type.  */
16706       if (TREE_CODE (arg) == METHOD_TYPE)
16707 	return unify_method_type_error (explain_p, arg);
16708 
16709       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16710       return unify_success (explain_p);
16711 
16712     case TEMPLATE_PARM_INDEX:
16713       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
16714       if (tparm == error_mark_node)
16715 	return unify_invalid (explain_p);
16716 
16717       if (TEMPLATE_PARM_LEVEL (parm)
16718 	  != template_decl_level (tparm))
16719 	{
16720 	  /* The PARM is not one we're trying to unify.  Just check
16721 	     to see if it matches ARG.  */
16722 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
16723 			 && cp_tree_equal (parm, arg));
16724 	  if (result)
16725 	    unify_expression_unequal (explain_p, parm, arg);
16726 	  return result;
16727 	}
16728 
16729       idx = TEMPLATE_PARM_IDX (parm);
16730       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
16731 
16732       if (targ)
16733 	{
16734 	  int x = !cp_tree_equal (targ, arg);
16735 	  if (x)
16736 	    unify_inconsistency (explain_p, parm, targ, arg);
16737 	  return x;
16738 	}
16739 
16740       /* [temp.deduct.type] If, in the declaration of a function template
16741 	 with a non-type template-parameter, the non-type
16742 	 template-parameter is used in an expression in the function
16743 	 parameter-list and, if the corresponding template-argument is
16744 	 deduced, the template-argument type shall match the type of the
16745 	 template-parameter exactly, except that a template-argument
16746 	 deduced from an array bound may be of any integral type.
16747 	 The non-type parameter might use already deduced type parameters.  */
16748       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
16749       if (!TREE_TYPE (arg))
16750 	/* Template-parameter dependent expression.  Just accept it for now.
16751 	   It will later be processed in convert_template_argument.  */
16752 	;
16753       else if (same_type_p (TREE_TYPE (arg), tparm))
16754 	/* OK */;
16755       else if ((strict & UNIFY_ALLOW_INTEGER)
16756 	       && (TREE_CODE (tparm) == INTEGER_TYPE
16757 		   || TREE_CODE (tparm) == BOOLEAN_TYPE))
16758 	/* Convert the ARG to the type of PARM; the deduced non-type
16759 	   template argument must exactly match the types of the
16760 	   corresponding parameter.  */
16761 	arg = fold (build_nop (tparm, arg));
16762       else if (uses_template_parms (tparm))
16763 	/* We haven't deduced the type of this parameter yet.  Try again
16764 	   later.  */
16765 	return unify_success (explain_p);
16766       else
16767 	return unify_type_mismatch (explain_p, tparm, arg);
16768 
16769       /* If ARG is a parameter pack or an expansion, we cannot unify
16770 	 against it unless PARM is also a parameter pack.  */
16771       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
16772 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
16773 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
16774 
16775       arg = strip_typedefs_expr (arg);
16776       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
16777       return unify_success (explain_p);
16778 
16779     case PTRMEM_CST:
16780      {
16781 	/* A pointer-to-member constant can be unified only with
16782 	 another constant.  */
16783       if (TREE_CODE (arg) != PTRMEM_CST)
16784 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
16785 
16786       /* Just unify the class member. It would be useless (and possibly
16787 	 wrong, depending on the strict flags) to unify also
16788 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
16789 	 arg refer to the same variable, even if through different
16790 	 classes. For instance:
16791 
16792 	 struct A { int x; };
16793 	 struct B : A { };
16794 
16795 	 Unification of &A::x and &B::x must succeed.  */
16796       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
16797 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
16798      }
16799 
16800     case POINTER_TYPE:
16801       {
16802 	if (TREE_CODE (arg) != POINTER_TYPE)
16803 	  return unify_type_mismatch (explain_p, parm, arg);
16804 
16805 	/* [temp.deduct.call]
16806 
16807 	   A can be another pointer or pointer to member type that can
16808 	   be converted to the deduced A via a qualification
16809 	   conversion (_conv.qual_).
16810 
16811 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
16812 	   This will allow for additional cv-qualification of the
16813 	   pointed-to types if appropriate.  */
16814 
16815 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
16816 	  /* The derived-to-base conversion only persists through one
16817 	     level of pointers.  */
16818 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
16819 
16820 	return unify (tparms, targs, TREE_TYPE (parm),
16821 		      TREE_TYPE (arg), strict, explain_p);
16822       }
16823 
16824     case REFERENCE_TYPE:
16825       if (TREE_CODE (arg) != REFERENCE_TYPE)
16826 	return unify_type_mismatch (explain_p, parm, arg);
16827       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16828 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16829 
16830     case ARRAY_TYPE:
16831       if (TREE_CODE (arg) != ARRAY_TYPE)
16832 	return unify_type_mismatch (explain_p, parm, arg);
16833       if ((TYPE_DOMAIN (parm) == NULL_TREE)
16834 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
16835 	return unify_type_mismatch (explain_p, parm, arg);
16836       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
16837 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
16838       if (TYPE_DOMAIN (parm) != NULL_TREE)
16839 	{
16840 	  tree parm_max;
16841 	  tree arg_max;
16842 	  bool parm_cst;
16843 	  bool arg_cst;
16844 
16845 	  /* Our representation of array types uses "N - 1" as the
16846 	     TYPE_MAX_VALUE for an array with "N" elements, if "N" is
16847 	     not an integer constant.  We cannot unify arbitrarily
16848 	     complex expressions, so we eliminate the MINUS_EXPRs
16849 	     here.  */
16850 	  parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
16851 	  parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
16852 	  if (!parm_cst)
16853 	    {
16854 	      gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
16855 	      parm_max = TREE_OPERAND (parm_max, 0);
16856 	    }
16857 	  arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
16858 	  arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
16859 	  if (!arg_cst)
16860 	    {
16861 	      /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
16862 		 trying to unify the type of a variable with the type
16863 		 of a template parameter.  For example:
16864 
16865                    template <unsigned int N>
16866 		   void f (char (&) [N]);
16867 		   int g();
16868 		   void h(int i) {
16869                      char a[g(i)];
16870 		     f(a);
16871                    }
16872 
16873                 Here, the type of the ARG will be "int [g(i)]", and
16874                 may be a SAVE_EXPR, etc.  */
16875 	      if (TREE_CODE (arg_max) != MINUS_EXPR)
16876 		return unify_vla_arg (explain_p, arg);
16877 	      arg_max = TREE_OPERAND (arg_max, 0);
16878 	    }
16879 
16880 	  /* If only one of the bounds used a MINUS_EXPR, compensate
16881 	     by adding one to the other bound.  */
16882 	  if (parm_cst && !arg_cst)
16883 	    parm_max = fold_build2_loc (input_location, PLUS_EXPR,
16884 				    integer_type_node,
16885 				    parm_max,
16886 				    integer_one_node);
16887 	  else if (arg_cst && !parm_cst)
16888 	    arg_max = fold_build2_loc (input_location, PLUS_EXPR,
16889 				   integer_type_node,
16890 				   arg_max,
16891 				   integer_one_node);
16892 
16893 	  RECUR_AND_CHECK_FAILURE (tparms, targs, parm_max, arg_max,
16894 				   UNIFY_ALLOW_INTEGER, explain_p);
16895 	}
16896       return unify_success (explain_p);
16897 
16898     case REAL_TYPE:
16899     case COMPLEX_TYPE:
16900     case VECTOR_TYPE:
16901     case INTEGER_TYPE:
16902     case BOOLEAN_TYPE:
16903     case ENUMERAL_TYPE:
16904     case VOID_TYPE:
16905     case NULLPTR_TYPE:
16906       if (TREE_CODE (arg) != TREE_CODE (parm))
16907 	return unify_type_mismatch (explain_p, parm, arg);
16908 
16909       /* We have already checked cv-qualification at the top of the
16910 	 function.  */
16911       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
16912 	return unify_type_mismatch (explain_p, parm, arg);
16913 
16914       /* As far as unification is concerned, this wins.	 Later checks
16915 	 will invalidate it if necessary.  */
16916       return unify_success (explain_p);
16917 
16918       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
16919       /* Type INTEGER_CST can come from ordinary constant template args.  */
16920     case INTEGER_CST:
16921       while (TREE_CODE (arg) == NOP_EXPR)
16922 	arg = TREE_OPERAND (arg, 0);
16923 
16924       if (TREE_CODE (arg) != INTEGER_CST)
16925 	return unify_template_argument_mismatch (explain_p, parm, arg);
16926       return (tree_int_cst_equal (parm, arg)
16927 	      ? unify_success (explain_p)
16928 	      : unify_template_argument_mismatch (explain_p, parm, arg));
16929 
16930     case TREE_VEC:
16931       {
16932 	int i, len, argslen;
16933 	int parm_variadic_p = 0;
16934 
16935 	if (TREE_CODE (arg) != TREE_VEC)
16936 	  return unify_template_argument_mismatch (explain_p, parm, arg);
16937 
16938 	len = TREE_VEC_LENGTH (parm);
16939 	argslen = TREE_VEC_LENGTH (arg);
16940 
16941 	/* Check for pack expansions in the parameters.  */
16942 	for (i = 0; i < len; ++i)
16943 	  {
16944 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
16945 	      {
16946 		if (i == len - 1)
16947 		  /* We can unify against something with a trailing
16948 		     parameter pack.  */
16949 		  parm_variadic_p = 1;
16950 		else
16951 		  /* [temp.deduct.type]/9: If the template argument list of
16952 		     P contains a pack expansion that is not the last
16953 		     template argument, the entire template argument list
16954 		     is a non-deduced context.  */
16955 		  return unify_success (explain_p);
16956 	      }
16957 	  }
16958 
16959         /* If we don't have enough arguments to satisfy the parameters
16960            (not counting the pack expression at the end), or we have
16961            too many arguments for a parameter list that doesn't end in
16962            a pack expression, we can't unify.  */
16963 	if (parm_variadic_p
16964 	    ? argslen < len - parm_variadic_p
16965 	    : argslen != len)
16966 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
16967 
16968 	/* Unify all of the parameters that precede the (optional)
16969 	   pack expression.  */
16970 	for (i = 0; i < len - parm_variadic_p; ++i)
16971 	  {
16972 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
16973 				     TREE_VEC_ELT (parm, i),
16974 				     TREE_VEC_ELT (arg, i),
16975 				     UNIFY_ALLOW_NONE, explain_p);
16976 	  }
16977 	if (parm_variadic_p)
16978 	  return unify_pack_expansion (tparms, targs, parm, arg,
16979 				       DEDUCE_EXACT,
16980 				       /*subr=*/true, explain_p);
16981 	return unify_success (explain_p);
16982       }
16983 
16984     case RECORD_TYPE:
16985     case UNION_TYPE:
16986       if (TREE_CODE (arg) != TREE_CODE (parm))
16987 	return unify_type_mismatch (explain_p, parm, arg);
16988 
16989       if (TYPE_PTRMEMFUNC_P (parm))
16990 	{
16991 	  if (!TYPE_PTRMEMFUNC_P (arg))
16992 	    return unify_type_mismatch (explain_p, parm, arg);
16993 
16994 	  return unify (tparms, targs,
16995 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
16996 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
16997 			strict, explain_p);
16998 	}
16999 
17000       if (CLASSTYPE_TEMPLATE_INFO (parm))
17001 	{
17002 	  tree t = NULL_TREE;
17003 
17004 	  if (strict_in & UNIFY_ALLOW_DERIVED)
17005 	    {
17006 	      /* First, we try to unify the PARM and ARG directly.  */
17007 	      t = try_class_unification (tparms, targs,
17008 					 parm, arg, explain_p);
17009 
17010 	      if (!t)
17011 		{
17012 		  /* Fallback to the special case allowed in
17013 		     [temp.deduct.call]:
17014 
17015 		       If P is a class, and P has the form
17016 		       template-id, then A can be a derived class of
17017 		       the deduced A.  Likewise, if P is a pointer to
17018 		       a class of the form template-id, A can be a
17019 		       pointer to a derived class pointed to by the
17020 		       deduced A.  */
17021 		  enum template_base_result r;
17022 		  r = get_template_base (tparms, targs, parm, arg,
17023 					 explain_p, &t);
17024 
17025 		  if (!t)
17026 		    return unify_no_common_base (explain_p, r, parm, arg);
17027 		}
17028 	    }
17029 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
17030 		   && (CLASSTYPE_TI_TEMPLATE (parm)
17031 		       == CLASSTYPE_TI_TEMPLATE (arg)))
17032 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
17033 	       Then, we should unify `int' and `U'.  */
17034 	    t = arg;
17035 	  else
17036 	    /* There's no chance of unification succeeding.  */
17037 	    return unify_type_mismatch (explain_p, parm, arg);
17038 
17039 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
17040 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
17041 	}
17042       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
17043 	return unify_type_mismatch (explain_p, parm, arg);
17044       return unify_success (explain_p);
17045 
17046     case METHOD_TYPE:
17047     case FUNCTION_TYPE:
17048       {
17049 	unsigned int nargs;
17050 	tree *args;
17051 	tree a;
17052 	unsigned int i;
17053 
17054 	if (TREE_CODE (arg) != TREE_CODE (parm))
17055 	  return unify_type_mismatch (explain_p, parm, arg);
17056 
17057 	/* CV qualifications for methods can never be deduced, they must
17058 	   match exactly.  We need to check them explicitly here,
17059 	   because type_unification_real treats them as any other
17060 	   cv-qualified parameter.  */
17061 	if (TREE_CODE (parm) == METHOD_TYPE
17062 	    && (!check_cv_quals_for_unify
17063 		(UNIFY_ALLOW_NONE,
17064 		 class_of_this_parm (arg),
17065 		 class_of_this_parm (parm))))
17066 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
17067 
17068 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
17069 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
17070 
17071 	nargs = list_length (TYPE_ARG_TYPES (arg));
17072 	args = XALLOCAVEC (tree, nargs);
17073 	for (a = TYPE_ARG_TYPES (arg), i = 0;
17074 	     a != NULL_TREE && a != void_list_node;
17075 	     a = TREE_CHAIN (a), ++i)
17076 	  args[i] = TREE_VALUE (a);
17077 	nargs = i;
17078 
17079 	return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
17080 				      args, nargs, 1, DEDUCE_EXACT,
17081 				      LOOKUP_NORMAL, explain_p);
17082       }
17083 
17084     case OFFSET_TYPE:
17085       /* Unify a pointer to member with a pointer to member function, which
17086 	 deduces the type of the member as a function type. */
17087       if (TYPE_PTRMEMFUNC_P (arg))
17088 	{
17089 	  tree method_type;
17090 	  tree fntype;
17091 
17092 	  /* Check top-level cv qualifiers */
17093 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
17094 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
17095 
17096 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
17097 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
17098 				   UNIFY_ALLOW_NONE, explain_p);
17099 
17100 	  /* Determine the type of the function we are unifying against. */
17101 	  method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
17102 	  fntype =
17103 	    build_function_type (TREE_TYPE (method_type),
17104 				 TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
17105 
17106 	  /* Extract the cv-qualifiers and ref-qualifier of the member
17107 	     function from the implicit object parameter and place them
17108 	     on the function type to be restored later. */
17109 	  fntype = apply_memfn_quals (fntype,
17110 				      type_memfn_quals (method_type),
17111 				      type_memfn_rqual (method_type));
17112 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
17113 	}
17114 
17115       if (TREE_CODE (arg) != OFFSET_TYPE)
17116 	return unify_type_mismatch (explain_p, parm, arg);
17117       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
17118 			       TYPE_OFFSET_BASETYPE (arg),
17119 			       UNIFY_ALLOW_NONE, explain_p);
17120       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
17121 		    strict, explain_p);
17122 
17123     case CONST_DECL:
17124       if (DECL_TEMPLATE_PARM_P (parm))
17125 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
17126       if (arg != integral_constant_value (parm))
17127 	return unify_template_argument_mismatch (explain_p, parm, arg);
17128       return unify_success (explain_p);
17129 
17130     case FIELD_DECL:
17131     case TEMPLATE_DECL:
17132       /* Matched cases are handled by the ARG == PARM test above.  */
17133       return unify_template_argument_mismatch (explain_p, parm, arg);
17134 
17135     case VAR_DECL:
17136       /* A non-type template parameter that is a variable should be a
17137 	 an integral constant, in which case, it whould have been
17138 	 folded into its (constant) value. So we should not be getting
17139 	 a variable here.  */
17140       gcc_unreachable ();
17141 
17142     case TYPE_ARGUMENT_PACK:
17143     case NONTYPE_ARGUMENT_PACK:
17144       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
17145 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
17146 
17147     case TYPEOF_TYPE:
17148     case DECLTYPE_TYPE:
17149     case UNDERLYING_TYPE:
17150       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
17151 	 or UNDERLYING_TYPE nodes.  */
17152       return unify_success (explain_p);
17153 
17154     case ERROR_MARK:
17155       /* Unification fails if we hit an error node.  */
17156       return unify_invalid (explain_p);
17157 
17158     default:
17159       /* An unresolved overload is a nondeduced context.  */
17160       if (is_overloaded_fn (parm) || type_unknown_p (parm))
17161 	return unify_success (explain_p);
17162       gcc_assert (EXPR_P (parm));
17163 
17164       /* We must be looking at an expression.  This can happen with
17165 	 something like:
17166 
17167 	   template <int I>
17168 	   void foo(S<I>, S<I + 2>);
17169 
17170 	 This is a "nondeduced context":
17171 
17172 	   [deduct.type]
17173 
17174 	   The nondeduced contexts are:
17175 
17176 	   --A type that is a template-id in which one or more of
17177 	     the template-arguments is an expression that references
17178 	     a template-parameter.
17179 
17180 	 In these cases, we assume deduction succeeded, but don't
17181 	 actually infer any unifications.  */
17182 
17183       if (!uses_template_parms (parm)
17184 	  && !template_args_equal (parm, arg))
17185 	return unify_expression_unequal (explain_p, parm, arg);
17186       else
17187 	return unify_success (explain_p);
17188     }
17189 }
17190 #undef RECUR_AND_CHECK_FAILURE
17191 
17192 /* Note that DECL can be defined in this translation unit, if
17193    required.  */
17194 
17195 static void
mark_definable(tree decl)17196 mark_definable (tree decl)
17197 {
17198   tree clone;
17199   DECL_NOT_REALLY_EXTERN (decl) = 1;
17200   FOR_EACH_CLONE (clone, decl)
17201     DECL_NOT_REALLY_EXTERN (clone) = 1;
17202 }
17203 
17204 /* Called if RESULT is explicitly instantiated, or is a member of an
17205    explicitly instantiated class.  */
17206 
17207 void
mark_decl_instantiated(tree result,int extern_p)17208 mark_decl_instantiated (tree result, int extern_p)
17209 {
17210   SET_DECL_EXPLICIT_INSTANTIATION (result);
17211 
17212   /* If this entity has already been written out, it's too late to
17213      make any modifications.  */
17214   if (TREE_ASM_WRITTEN (result))
17215     return;
17216 
17217   if (TREE_CODE (result) != FUNCTION_DECL)
17218     /* The TREE_PUBLIC flag for function declarations will have been
17219        set correctly by tsubst.  */
17220     TREE_PUBLIC (result) = 1;
17221 
17222   /* This might have been set by an earlier implicit instantiation.  */
17223   DECL_COMDAT (result) = 0;
17224 
17225   if (extern_p)
17226     DECL_NOT_REALLY_EXTERN (result) = 0;
17227   else
17228     {
17229       mark_definable (result);
17230       /* Always make artificials weak.  */
17231       if (DECL_ARTIFICIAL (result) && flag_weak)
17232 	comdat_linkage (result);
17233       /* For WIN32 we also want to put explicit instantiations in
17234 	 linkonce sections.  */
17235       else if (TREE_PUBLIC (result))
17236 	maybe_make_one_only (result);
17237     }
17238 
17239   /* If EXTERN_P, then this function will not be emitted -- unless
17240      followed by an explicit instantiation, at which point its linkage
17241      will be adjusted.  If !EXTERN_P, then this function will be
17242      emitted here.  In neither circumstance do we want
17243      import_export_decl to adjust the linkage.  */
17244   DECL_INTERFACE_KNOWN (result) = 1;
17245 }
17246 
17247 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
17248    important template arguments.  If any are missing, we check whether
17249    they're important by using error_mark_node for substituting into any
17250    args that were used for partial ordering (the ones between ARGS and END)
17251    and seeing if it bubbles up.  */
17252 
17253 static bool
check_undeduced_parms(tree targs,tree args,tree end)17254 check_undeduced_parms (tree targs, tree args, tree end)
17255 {
17256   bool found = false;
17257   int i;
17258   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
17259     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
17260       {
17261 	found = true;
17262 	TREE_VEC_ELT (targs, i) = error_mark_node;
17263       }
17264   if (found)
17265     {
17266       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
17267       if (substed == error_mark_node)
17268 	return true;
17269     }
17270   return false;
17271 }
17272 
17273 /* Given two function templates PAT1 and PAT2, return:
17274 
17275    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
17276    -1 if PAT2 is more specialized than PAT1.
17277    0 if neither is more specialized.
17278 
17279    LEN indicates the number of parameters we should consider
17280    (defaulted parameters should not be considered).
17281 
17282    The 1998 std underspecified function template partial ordering, and
17283    DR214 addresses the issue.  We take pairs of arguments, one from
17284    each of the templates, and deduce them against each other.  One of
17285    the templates will be more specialized if all the *other*
17286    template's arguments deduce against its arguments and at least one
17287    of its arguments *does* *not* deduce against the other template's
17288    corresponding argument.  Deduction is done as for class templates.
17289    The arguments used in deduction have reference and top level cv
17290    qualifiers removed.  Iff both arguments were originally reference
17291    types *and* deduction succeeds in both directions, the template
17292    with the more cv-qualified argument wins for that pairing (if
17293    neither is more cv-qualified, they both are equal).  Unlike regular
17294    deduction, after all the arguments have been deduced in this way,
17295    we do *not* verify the deduced template argument values can be
17296    substituted into non-deduced contexts.
17297 
17298    The logic can be a bit confusing here, because we look at deduce1 and
17299    targs1 to see if pat2 is at least as specialized, and vice versa; if we
17300    can find template arguments for pat1 to make arg1 look like arg2, that
17301    means that arg2 is at least as specialized as arg1.  */
17302 
17303 int
more_specialized_fn(tree pat1,tree pat2,int len)17304 more_specialized_fn (tree pat1, tree pat2, int len)
17305 {
17306   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
17307   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
17308   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
17309   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
17310   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
17311   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
17312   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
17313   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
17314   tree origs1, origs2;
17315   bool lose1 = false;
17316   bool lose2 = false;
17317 
17318   /* Remove the this parameter from non-static member functions.  If
17319      one is a non-static member function and the other is not a static
17320      member function, remove the first parameter from that function
17321      also.  This situation occurs for operator functions where we
17322      locate both a member function (with this pointer) and non-member
17323      operator (with explicit first operand).  */
17324   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
17325     {
17326       len--; /* LEN is the number of significant arguments for DECL1 */
17327       args1 = TREE_CHAIN (args1);
17328       if (!DECL_STATIC_FUNCTION_P (decl2))
17329 	args2 = TREE_CHAIN (args2);
17330     }
17331   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
17332     {
17333       args2 = TREE_CHAIN (args2);
17334       if (!DECL_STATIC_FUNCTION_P (decl1))
17335 	{
17336 	  len--;
17337 	  args1 = TREE_CHAIN (args1);
17338 	}
17339     }
17340 
17341   /* If only one is a conversion operator, they are unordered.  */
17342   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
17343     return 0;
17344 
17345   /* Consider the return type for a conversion function */
17346   if (DECL_CONV_FN_P (decl1))
17347     {
17348       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
17349       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
17350       len++;
17351     }
17352 
17353   processing_template_decl++;
17354 
17355   origs1 = args1;
17356   origs2 = args2;
17357 
17358   while (len--
17359 	 /* Stop when an ellipsis is seen.  */
17360 	 && args1 != NULL_TREE && args2 != NULL_TREE)
17361     {
17362       tree arg1 = TREE_VALUE (args1);
17363       tree arg2 = TREE_VALUE (args2);
17364       int deduce1, deduce2;
17365       int quals1 = -1;
17366       int quals2 = -1;
17367 
17368       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
17369           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
17370         {
17371           /* When both arguments are pack expansions, we need only
17372              unify the patterns themselves.  */
17373           arg1 = PACK_EXPANSION_PATTERN (arg1);
17374           arg2 = PACK_EXPANSION_PATTERN (arg2);
17375 
17376           /* This is the last comparison we need to do.  */
17377           len = 0;
17378         }
17379 
17380       if (TREE_CODE (arg1) == REFERENCE_TYPE)
17381 	{
17382 	  arg1 = TREE_TYPE (arg1);
17383 	  quals1 = cp_type_quals (arg1);
17384 	}
17385 
17386       if (TREE_CODE (arg2) == REFERENCE_TYPE)
17387 	{
17388 	  arg2 = TREE_TYPE (arg2);
17389 	  quals2 = cp_type_quals (arg2);
17390 	}
17391 
17392       arg1 = TYPE_MAIN_VARIANT (arg1);
17393       arg2 = TYPE_MAIN_VARIANT (arg2);
17394 
17395       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
17396         {
17397           int i, len2 = list_length (args2);
17398           tree parmvec = make_tree_vec (1);
17399           tree argvec = make_tree_vec (len2);
17400           tree ta = args2;
17401 
17402           /* Setup the parameter vector, which contains only ARG1.  */
17403           TREE_VEC_ELT (parmvec, 0) = arg1;
17404 
17405           /* Setup the argument vector, which contains the remaining
17406              arguments.  */
17407           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
17408             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
17409 
17410           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
17411 					   argvec, DEDUCE_EXACT,
17412 					   /*subr=*/true, /*explain_p=*/false)
17413 		     == 0);
17414 
17415           /* We cannot deduce in the other direction, because ARG1 is
17416              a pack expansion but ARG2 is not.  */
17417           deduce2 = 0;
17418         }
17419       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
17420         {
17421           int i, len1 = list_length (args1);
17422           tree parmvec = make_tree_vec (1);
17423           tree argvec = make_tree_vec (len1);
17424           tree ta = args1;
17425 
17426           /* Setup the parameter vector, which contains only ARG1.  */
17427           TREE_VEC_ELT (parmvec, 0) = arg2;
17428 
17429           /* Setup the argument vector, which contains the remaining
17430              arguments.  */
17431           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
17432             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
17433 
17434           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
17435 					   argvec, DEDUCE_EXACT,
17436 					   /*subr=*/true, /*explain_p=*/false)
17437 		     == 0);
17438 
17439           /* We cannot deduce in the other direction, because ARG2 is
17440              a pack expansion but ARG1 is not.*/
17441           deduce1 = 0;
17442         }
17443 
17444       else
17445         {
17446           /* The normal case, where neither argument is a pack
17447              expansion.  */
17448           deduce1 = (unify (tparms1, targs1, arg1, arg2,
17449 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
17450 		     == 0);
17451           deduce2 = (unify (tparms2, targs2, arg2, arg1,
17452 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
17453 		     == 0);
17454         }
17455 
17456       /* If we couldn't deduce arguments for tparms1 to make arg1 match
17457 	 arg2, then arg2 is not as specialized as arg1.  */
17458       if (!deduce1)
17459 	lose2 = true;
17460       if (!deduce2)
17461 	lose1 = true;
17462 
17463       /* "If, for a given type, deduction succeeds in both directions
17464 	 (i.e., the types are identical after the transformations above)
17465 	 and if the type from the argument template is more cv-qualified
17466 	 than the type from the parameter template (as described above)
17467 	 that type is considered to be more specialized than the other. If
17468 	 neither type is more cv-qualified than the other then neither type
17469 	 is more specialized than the other."  */
17470 
17471       if (deduce1 && deduce2
17472 	  && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
17473 	{
17474 	  if ((quals1 & quals2) == quals2)
17475 	    lose2 = true;
17476 	  if ((quals1 & quals2) == quals1)
17477 	    lose1 = true;
17478 	}
17479 
17480       if (lose1 && lose2)
17481 	/* We've failed to deduce something in either direction.
17482 	   These must be unordered.  */
17483 	break;
17484 
17485       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
17486           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
17487         /* We have already processed all of the arguments in our
17488            handing of the pack expansion type.  */
17489         len = 0;
17490 
17491       args1 = TREE_CHAIN (args1);
17492       args2 = TREE_CHAIN (args2);
17493     }
17494 
17495   /* "In most cases, all template parameters must have values in order for
17496      deduction to succeed, but for partial ordering purposes a template
17497      parameter may remain without a value provided it is not used in the
17498      types being used for partial ordering."
17499 
17500      Thus, if we are missing any of the targs1 we need to substitute into
17501      origs1, then pat2 is not as specialized as pat1.  This can happen when
17502      there is a nondeduced context.  */
17503   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
17504     lose2 = true;
17505   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
17506     lose1 = true;
17507 
17508   processing_template_decl--;
17509 
17510   /* All things being equal, if the next argument is a pack expansion
17511      for one function but not for the other, prefer the
17512      non-variadic function.  FIXME this is bogus; see c++/41958.  */
17513   if (lose1 == lose2
17514       && args1 && TREE_VALUE (args1)
17515       && args2 && TREE_VALUE (args2))
17516     {
17517       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
17518       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
17519     }
17520 
17521   if (lose1 == lose2)
17522     return 0;
17523   else if (!lose1)
17524     return 1;
17525   else
17526     return -1;
17527 }
17528 
17529 /* Determine which of two partial specializations of MAIN_TMPL is more
17530    specialized.
17531 
17532    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
17533    to the first partial specialization.  The TREE_VALUE is the
17534    innermost set of template parameters for the partial
17535    specialization.  PAT2 is similar, but for the second template.
17536 
17537    Return 1 if the first partial specialization is more specialized;
17538    -1 if the second is more specialized; 0 if neither is more
17539    specialized.
17540 
17541    See [temp.class.order] for information about determining which of
17542    two templates is more specialized.  */
17543 
17544 static int
more_specialized_class(tree main_tmpl,tree pat1,tree pat2)17545 more_specialized_class (tree main_tmpl, tree pat1, tree pat2)
17546 {
17547   tree targs;
17548   tree tmpl1, tmpl2;
17549   int winner = 0;
17550   bool any_deductions = false;
17551 
17552   tmpl1 = TREE_TYPE (pat1);
17553   tmpl2 = TREE_TYPE (pat2);
17554 
17555   /* Just like what happens for functions, if we are ordering between
17556      different class template specializations, we may encounter dependent
17557      types in the arguments, and we need our dependency check functions
17558      to behave correctly.  */
17559   ++processing_template_decl;
17560   targs = get_class_bindings (main_tmpl, TREE_VALUE (pat1),
17561 			      CLASSTYPE_TI_ARGS (tmpl1),
17562 			      CLASSTYPE_TI_ARGS (tmpl2));
17563   if (targs)
17564     {
17565       --winner;
17566       any_deductions = true;
17567     }
17568 
17569   targs = get_class_bindings (main_tmpl, TREE_VALUE (pat2),
17570 			      CLASSTYPE_TI_ARGS (tmpl2),
17571 			      CLASSTYPE_TI_ARGS (tmpl1));
17572   if (targs)
17573     {
17574       ++winner;
17575       any_deductions = true;
17576     }
17577   --processing_template_decl;
17578 
17579   /* In the case of a tie where at least one of the class templates
17580      has a parameter pack at the end, the template with the most
17581      non-packed parameters wins.  */
17582   if (winner == 0
17583       && any_deductions
17584       && (template_args_variadic_p (TREE_PURPOSE (pat1))
17585           || template_args_variadic_p (TREE_PURPOSE (pat2))))
17586     {
17587       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
17588       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
17589       int len1 = TREE_VEC_LENGTH (args1);
17590       int len2 = TREE_VEC_LENGTH (args2);
17591 
17592       /* We don't count the pack expansion at the end.  */
17593       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
17594         --len1;
17595       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
17596         --len2;
17597 
17598       if (len1 > len2)
17599         return 1;
17600       else if (len1 < len2)
17601         return -1;
17602     }
17603 
17604   return winner;
17605 }
17606 
17607 /* Return the template arguments that will produce the function signature
17608    DECL from the function template FN, with the explicit template
17609    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
17610    also match.  Return NULL_TREE if no satisfactory arguments could be
17611    found.  */
17612 
17613 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)17614 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
17615 {
17616   int ntparms = DECL_NTPARMS (fn);
17617   tree targs = make_tree_vec (ntparms);
17618   tree decl_type = TREE_TYPE (decl);
17619   tree decl_arg_types;
17620   tree *args;
17621   unsigned int nargs, ix;
17622   tree arg;
17623 
17624   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
17625 
17626   /* Never do unification on the 'this' parameter.  */
17627   decl_arg_types = skip_artificial_parms_for (decl,
17628 					      TYPE_ARG_TYPES (decl_type));
17629 
17630   nargs = list_length (decl_arg_types);
17631   args = XALLOCAVEC (tree, nargs);
17632   for (arg = decl_arg_types, ix = 0;
17633        arg != NULL_TREE && arg != void_list_node;
17634        arg = TREE_CHAIN (arg), ++ix)
17635     args[ix] = TREE_VALUE (arg);
17636 
17637   if (fn_type_unification (fn, explicit_args, targs,
17638 			   args, ix,
17639 			   (check_rettype || DECL_CONV_FN_P (fn)
17640 			    ? TREE_TYPE (decl_type) : NULL_TREE),
17641 			   DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false)
17642       == error_mark_node)
17643     return NULL_TREE;
17644 
17645   return targs;
17646 }
17647 
17648 /* Return the innermost template arguments that, when applied to a partial
17649    specialization of MAIN_TMPL whose innermost template parameters are
17650    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
17651    ARGS.
17652 
17653    For example, suppose we have:
17654 
17655      template <class T, class U> struct S {};
17656      template <class T> struct S<T*, int> {};
17657 
17658    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
17659    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
17660    int}.  The resulting vector will be {double}, indicating that `T'
17661    is bound to `double'.  */
17662 
17663 static tree
get_class_bindings(tree main_tmpl,tree tparms,tree spec_args,tree args)17664 get_class_bindings (tree main_tmpl, tree tparms, tree spec_args, tree args)
17665 {
17666   int i, ntparms = TREE_VEC_LENGTH (tparms);
17667   tree deduced_args;
17668   tree innermost_deduced_args;
17669 
17670   innermost_deduced_args = make_tree_vec (ntparms);
17671   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17672     {
17673       deduced_args = copy_node (args);
17674       SET_TMPL_ARGS_LEVEL (deduced_args,
17675 			   TMPL_ARGS_DEPTH (deduced_args),
17676 			   innermost_deduced_args);
17677     }
17678   else
17679     deduced_args = innermost_deduced_args;
17680 
17681   if (unify (tparms, deduced_args,
17682 	     INNERMOST_TEMPLATE_ARGS (spec_args),
17683 	     INNERMOST_TEMPLATE_ARGS (args),
17684 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
17685     return NULL_TREE;
17686 
17687   for (i =  0; i < ntparms; ++i)
17688     if (! TREE_VEC_ELT (innermost_deduced_args, i))
17689       return NULL_TREE;
17690 
17691   /* Verify that nondeduced template arguments agree with the type
17692      obtained from argument deduction.
17693 
17694      For example:
17695 
17696        struct A { typedef int X; };
17697        template <class T, class U> struct C {};
17698        template <class T> struct C<T, typename T::X> {};
17699 
17700      Then with the instantiation `C<A, int>', we can deduce that
17701      `T' is `A' but unify () does not check whether `typename T::X'
17702      is `int'.  */
17703   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
17704   spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (main_tmpl),
17705 				     spec_args, main_tmpl,
17706 				     tf_none, false, false);
17707   if (spec_args == error_mark_node
17708       /* We only need to check the innermost arguments; the other
17709 	 arguments will always agree.  */
17710       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
17711 			      INNERMOST_TEMPLATE_ARGS (args)))
17712     return NULL_TREE;
17713 
17714   /* Now that we have bindings for all of the template arguments,
17715      ensure that the arguments deduced for the template template
17716      parameters have compatible template parameter lists.  See the use
17717      of template_template_parm_bindings_ok_p in fn_type_unification
17718      for more information.  */
17719   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
17720     return NULL_TREE;
17721 
17722   return deduced_args;
17723 }
17724 
17725 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
17726    Return the TREE_LIST node with the most specialized template, if
17727    any.  If there is no most specialized template, the error_mark_node
17728    is returned.
17729 
17730    Note that this function does not look at, or modify, the
17731    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
17732    returned is one of the elements of INSTANTIATIONS, callers may
17733    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
17734    and retrieve it from the value returned.  */
17735 
17736 tree
most_specialized_instantiation(tree templates)17737 most_specialized_instantiation (tree templates)
17738 {
17739   tree fn, champ;
17740 
17741   ++processing_template_decl;
17742 
17743   champ = templates;
17744   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
17745     {
17746       int fate = 0;
17747 
17748       if (get_bindings (TREE_VALUE (champ),
17749 			DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17750 			NULL_TREE, /*check_ret=*/true))
17751 	fate--;
17752 
17753       if (get_bindings (TREE_VALUE (fn),
17754 			DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17755 			NULL_TREE, /*check_ret=*/true))
17756 	fate++;
17757 
17758       if (fate == -1)
17759 	champ = fn;
17760       else if (!fate)
17761 	{
17762 	  /* Equally specialized, move to next function.  If there
17763 	     is no next function, nothing's most specialized.  */
17764 	  fn = TREE_CHAIN (fn);
17765 	  champ = fn;
17766 	  if (!fn)
17767 	    break;
17768 	}
17769     }
17770 
17771   if (champ)
17772     /* Now verify that champ is better than everything earlier in the
17773        instantiation list.  */
17774     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
17775       if (get_bindings (TREE_VALUE (champ),
17776 			DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
17777 			NULL_TREE, /*check_ret=*/true)
17778 	  || !get_bindings (TREE_VALUE (fn),
17779 			    DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
17780 			    NULL_TREE, /*check_ret=*/true))
17781 	{
17782 	  champ = NULL_TREE;
17783 	  break;
17784 	}
17785 
17786   processing_template_decl--;
17787 
17788   if (!champ)
17789     return error_mark_node;
17790 
17791   return champ;
17792 }
17793 
17794 /* If DECL is a specialization of some template, return the most
17795    general such template.  Otherwise, returns NULL_TREE.
17796 
17797    For example, given:
17798 
17799      template <class T> struct S { template <class U> void f(U); };
17800 
17801    if TMPL is `template <class U> void S<int>::f(U)' this will return
17802    the full template.  This function will not trace past partial
17803    specializations, however.  For example, given in addition:
17804 
17805      template <class T> struct S<T*> { template <class U> void f(U); };
17806 
17807    if TMPL is `template <class U> void S<int*>::f(U)' this will return
17808    `template <class T> template <class U> S<T*>::f(U)'.  */
17809 
17810 tree
most_general_template(tree decl)17811 most_general_template (tree decl)
17812 {
17813   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
17814      an immediate specialization.  */
17815   if (TREE_CODE (decl) == FUNCTION_DECL)
17816     {
17817       if (DECL_TEMPLATE_INFO (decl)) {
17818 	decl = DECL_TI_TEMPLATE (decl);
17819 
17820 	/* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
17821 	   template friend.  */
17822 	if (TREE_CODE (decl) != TEMPLATE_DECL)
17823 	  return NULL_TREE;
17824       } else
17825 	return NULL_TREE;
17826     }
17827 
17828   /* Look for more and more general templates.  */
17829   while (DECL_TEMPLATE_INFO (decl))
17830     {
17831       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
17832 	 (See cp-tree.h for details.)  */
17833       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
17834 	break;
17835 
17836       if (CLASS_TYPE_P (TREE_TYPE (decl))
17837 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
17838 	break;
17839 
17840       /* Stop if we run into an explicitly specialized class template.  */
17841       if (!DECL_NAMESPACE_SCOPE_P (decl)
17842 	  && DECL_CONTEXT (decl)
17843 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
17844 	break;
17845 
17846       decl = DECL_TI_TEMPLATE (decl);
17847     }
17848 
17849   return decl;
17850 }
17851 
17852 /* Return the most specialized of the class template partial
17853    specializations of TMPL which can produce TYPE, a specialization of
17854    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
17855    a _TYPE node corresponding to the partial specialization, while the
17856    TREE_PURPOSE is the set of template arguments that must be
17857    substituted into the TREE_TYPE in order to generate TYPE.
17858 
17859    If the choice of partial specialization is ambiguous, a diagnostic
17860    is issued, and the error_mark_node is returned.  If there are no
17861    partial specializations of TMPL matching TYPE, then NULL_TREE is
17862    returned.  */
17863 
17864 static tree
most_specialized_class(tree type,tree tmpl,tsubst_flags_t complain)17865 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
17866 {
17867   tree list = NULL_TREE;
17868   tree t;
17869   tree champ;
17870   int fate;
17871   bool ambiguous_p;
17872   tree args;
17873   tree outer_args = NULL_TREE;
17874 
17875   tmpl = most_general_template (tmpl);
17876   args = CLASSTYPE_TI_ARGS (type);
17877 
17878   /* For determining which partial specialization to use, only the
17879      innermost args are interesting.  */
17880   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
17881     {
17882       outer_args = strip_innermost_template_args (args, 1);
17883       args = INNERMOST_TEMPLATE_ARGS (args);
17884     }
17885 
17886   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
17887     {
17888       tree partial_spec_args;
17889       tree spec_args;
17890       tree parms = TREE_VALUE (t);
17891 
17892       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
17893 
17894       ++processing_template_decl;
17895 
17896       if (outer_args)
17897 	{
17898 	  int i;
17899 
17900 	  /* Discard the outer levels of args, and then substitute in the
17901 	     template args from the enclosing class.  */
17902 	  partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
17903 	  partial_spec_args = tsubst_template_args
17904 	    (partial_spec_args, outer_args, tf_none, NULL_TREE);
17905 
17906 	  /* PARMS already refers to just the innermost parms, but the
17907 	     template parms in partial_spec_args had their levels lowered
17908 	     by tsubst, so we need to do the same for the parm list.  We
17909 	     can't just tsubst the TREE_VEC itself, as tsubst wants to
17910 	     treat a TREE_VEC as an argument vector.  */
17911 	  parms = copy_node (parms);
17912 	  for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
17913 	    TREE_VEC_ELT (parms, i) =
17914 	      tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
17915 
17916 	}
17917 
17918       partial_spec_args =
17919 	  coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
17920 				 add_to_template_args (outer_args,
17921 						       partial_spec_args),
17922 				 tmpl, tf_none,
17923 				 /*require_all_args=*/true,
17924 				 /*use_default_args=*/true);
17925 
17926       --processing_template_decl;
17927 
17928       if (partial_spec_args == error_mark_node)
17929 	return error_mark_node;
17930 
17931       spec_args = get_class_bindings (tmpl, parms,
17932 				      partial_spec_args,
17933 				      args);
17934       if (spec_args)
17935 	{
17936 	  if (outer_args)
17937 	    spec_args = add_to_template_args (outer_args, spec_args);
17938 	  list = tree_cons (spec_args, TREE_VALUE (t), list);
17939 	  TREE_TYPE (list) = TREE_TYPE (t);
17940 	}
17941     }
17942 
17943   if (! list)
17944     return NULL_TREE;
17945 
17946   ambiguous_p = false;
17947   t = list;
17948   champ = t;
17949   t = TREE_CHAIN (t);
17950   for (; t; t = TREE_CHAIN (t))
17951     {
17952       fate = more_specialized_class (tmpl, champ, t);
17953       if (fate == 1)
17954 	;
17955       else
17956 	{
17957 	  if (fate == 0)
17958 	    {
17959 	      t = TREE_CHAIN (t);
17960 	      if (! t)
17961 		{
17962 		  ambiguous_p = true;
17963 		  break;
17964 		}
17965 	    }
17966 	  champ = t;
17967 	}
17968     }
17969 
17970   if (!ambiguous_p)
17971     for (t = list; t && t != champ; t = TREE_CHAIN (t))
17972       {
17973 	fate = more_specialized_class (tmpl, champ, t);
17974 	if (fate != 1)
17975 	  {
17976 	    ambiguous_p = true;
17977 	    break;
17978 	  }
17979       }
17980 
17981   if (ambiguous_p)
17982     {
17983       const char *str;
17984       char *spaces = NULL;
17985       if (!(complain & tf_error))
17986 	return error_mark_node;
17987       error ("ambiguous class template instantiation for %q#T", type);
17988       str = ngettext ("candidate is:", "candidates are:", list_length (list));
17989       for (t = list; t; t = TREE_CHAIN (t))
17990         {
17991           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
17992           spaces = spaces ? spaces : get_spaces (str);
17993         }
17994       free (spaces);
17995       return error_mark_node;
17996     }
17997 
17998   return champ;
17999 }
18000 
18001 /* Explicitly instantiate DECL.  */
18002 
18003 void
do_decl_instantiation(tree decl,tree storage)18004 do_decl_instantiation (tree decl, tree storage)
18005 {
18006   tree result = NULL_TREE;
18007   int extern_p = 0;
18008 
18009   if (!decl || decl == error_mark_node)
18010     /* An error occurred, for which grokdeclarator has already issued
18011        an appropriate message.  */
18012     return;
18013   else if (! DECL_LANG_SPECIFIC (decl))
18014     {
18015       error ("explicit instantiation of non-template %q#D", decl);
18016       return;
18017     }
18018   else if (TREE_CODE (decl) == VAR_DECL)
18019     {
18020       /* There is an asymmetry here in the way VAR_DECLs and
18021 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
18022 	 the latter, the DECL we get back will be marked as a
18023 	 template instantiation, and the appropriate
18024 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
18025 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
18026 	 should handle VAR_DECLs as it currently handles
18027 	 FUNCTION_DECLs.  */
18028       if (!DECL_CLASS_SCOPE_P (decl))
18029 	{
18030 	  error ("%qD is not a static data member of a class template", decl);
18031 	  return;
18032 	}
18033       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
18034       if (!result || TREE_CODE (result) != VAR_DECL)
18035 	{
18036 	  error ("no matching template for %qD found", decl);
18037 	  return;
18038 	}
18039       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
18040 	{
18041 	  error ("type %qT for explicit instantiation %qD does not match "
18042 		 "declared type %qT", TREE_TYPE (result), decl,
18043 		 TREE_TYPE (decl));
18044 	  return;
18045 	}
18046     }
18047   else if (TREE_CODE (decl) != FUNCTION_DECL)
18048     {
18049       error ("explicit instantiation of %q#D", decl);
18050       return;
18051     }
18052   else
18053     result = decl;
18054 
18055   /* Check for various error cases.  Note that if the explicit
18056      instantiation is valid the RESULT will currently be marked as an
18057      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
18058      until we get here.  */
18059 
18060   if (DECL_TEMPLATE_SPECIALIZATION (result))
18061     {
18062       /* DR 259 [temp.spec].
18063 
18064 	 Both an explicit instantiation and a declaration of an explicit
18065 	 specialization shall not appear in a program unless the explicit
18066 	 instantiation follows a declaration of the explicit specialization.
18067 
18068 	 For a given set of template parameters, if an explicit
18069 	 instantiation of a template appears after a declaration of an
18070 	 explicit specialization for that template, the explicit
18071 	 instantiation has no effect.  */
18072       return;
18073     }
18074   else if (DECL_EXPLICIT_INSTANTIATION (result))
18075     {
18076       /* [temp.spec]
18077 
18078 	 No program shall explicitly instantiate any template more
18079 	 than once.
18080 
18081 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
18082 	 the first instantiation was `extern' and the second is not,
18083 	 and EXTERN_P for the opposite case.  */
18084       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
18085 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
18086       /* If an "extern" explicit instantiation follows an ordinary
18087 	 explicit instantiation, the template is instantiated.  */
18088       if (extern_p)
18089 	return;
18090     }
18091   else if (!DECL_IMPLICIT_INSTANTIATION (result))
18092     {
18093       error ("no matching template for %qD found", result);
18094       return;
18095     }
18096   else if (!DECL_TEMPLATE_INFO (result))
18097     {
18098       permerror (input_location, "explicit instantiation of non-template %q#D", result);
18099       return;
18100     }
18101 
18102   if (storage == NULL_TREE)
18103     ;
18104   else if (storage == ridpointers[(int) RID_EXTERN])
18105     {
18106       if (!in_system_header && (cxx_dialect == cxx98))
18107 	pedwarn (input_location, OPT_Wpedantic,
18108 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
18109 		 "instantiations");
18110       extern_p = 1;
18111     }
18112   else
18113     error ("storage class %qD applied to template instantiation", storage);
18114 
18115   check_explicit_instantiation_namespace (result);
18116   mark_decl_instantiated (result, extern_p);
18117   if (! extern_p)
18118     instantiate_decl (result, /*defer_ok=*/1,
18119 		      /*expl_inst_class_mem_p=*/false);
18120 }
18121 
18122 static void
mark_class_instantiated(tree t,int extern_p)18123 mark_class_instantiated (tree t, int extern_p)
18124 {
18125   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
18126   SET_CLASSTYPE_INTERFACE_KNOWN (t);
18127   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
18128   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
18129   if (! extern_p)
18130     {
18131       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
18132       rest_of_type_compilation (t, 1);
18133     }
18134 }
18135 
18136 /* Called from do_type_instantiation through binding_table_foreach to
18137    do recursive instantiation for the type bound in ENTRY.  */
18138 static void
bt_instantiate_type_proc(binding_entry entry,void * data)18139 bt_instantiate_type_proc (binding_entry entry, void *data)
18140 {
18141   tree storage = *(tree *) data;
18142 
18143   if (MAYBE_CLASS_TYPE_P (entry->type)
18144       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
18145     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
18146 }
18147 
18148 /* Called from do_type_instantiation to instantiate a member
18149    (a member function or a static member variable) of an
18150    explicitly instantiated class template.  */
18151 static void
instantiate_class_member(tree decl,int extern_p)18152 instantiate_class_member (tree decl, int extern_p)
18153 {
18154   mark_decl_instantiated (decl, extern_p);
18155   if (! extern_p)
18156     instantiate_decl (decl, /*defer_ok=*/1,
18157 		      /*expl_inst_class_mem_p=*/true);
18158 }
18159 
18160 /* Perform an explicit instantiation of template class T.  STORAGE, if
18161    non-null, is the RID for extern, inline or static.  COMPLAIN is
18162    nonzero if this is called from the parser, zero if called recursively,
18163    since the standard is unclear (as detailed below).  */
18164 
18165 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)18166 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
18167 {
18168   int extern_p = 0;
18169   int nomem_p = 0;
18170   int static_p = 0;
18171   int previous_instantiation_extern_p = 0;
18172 
18173   if (TREE_CODE (t) == TYPE_DECL)
18174     t = TREE_TYPE (t);
18175 
18176   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
18177     {
18178       tree tmpl =
18179 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
18180       if (tmpl)
18181 	error ("explicit instantiation of non-class template %qD", tmpl);
18182       else
18183 	error ("explicit instantiation of non-template type %qT", t);
18184       return;
18185     }
18186 
18187   complete_type (t);
18188 
18189   if (!COMPLETE_TYPE_P (t))
18190     {
18191       if (complain & tf_error)
18192 	error ("explicit instantiation of %q#T before definition of template",
18193 	       t);
18194       return;
18195     }
18196 
18197   if (storage != NULL_TREE)
18198     {
18199       if (!in_system_header)
18200 	{
18201 	  if (storage == ridpointers[(int) RID_EXTERN])
18202 	    {
18203 	      if (cxx_dialect == cxx98)
18204 		pedwarn (input_location, OPT_Wpedantic,
18205 			 "ISO C++ 1998 forbids the use of %<extern%> on "
18206 			 "explicit instantiations");
18207 	    }
18208 	  else
18209 	    pedwarn (input_location, OPT_Wpedantic,
18210 		     "ISO C++ forbids the use of %qE"
18211 		     " on explicit instantiations", storage);
18212 	}
18213 
18214       if (storage == ridpointers[(int) RID_INLINE])
18215 	nomem_p = 1;
18216       else if (storage == ridpointers[(int) RID_EXTERN])
18217 	extern_p = 1;
18218       else if (storage == ridpointers[(int) RID_STATIC])
18219 	static_p = 1;
18220       else
18221 	{
18222 	  error ("storage class %qD applied to template instantiation",
18223 		 storage);
18224 	  extern_p = 0;
18225 	}
18226     }
18227 
18228   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
18229     {
18230       /* DR 259 [temp.spec].
18231 
18232 	 Both an explicit instantiation and a declaration of an explicit
18233 	 specialization shall not appear in a program unless the explicit
18234 	 instantiation follows a declaration of the explicit specialization.
18235 
18236 	 For a given set of template parameters, if an explicit
18237 	 instantiation of a template appears after a declaration of an
18238 	 explicit specialization for that template, the explicit
18239 	 instantiation has no effect.  */
18240       return;
18241     }
18242   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
18243     {
18244       /* [temp.spec]
18245 
18246 	 No program shall explicitly instantiate any template more
18247 	 than once.
18248 
18249 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
18250 	 instantiation was `extern'.  If EXTERN_P then the second is.
18251 	 These cases are OK.  */
18252       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
18253 
18254       if (!previous_instantiation_extern_p && !extern_p
18255 	  && (complain & tf_error))
18256 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
18257 
18258       /* If we've already instantiated the template, just return now.  */
18259       if (!CLASSTYPE_INTERFACE_ONLY (t))
18260 	return;
18261     }
18262 
18263   check_explicit_instantiation_namespace (TYPE_NAME (t));
18264   mark_class_instantiated (t, extern_p);
18265 
18266   if (nomem_p)
18267     return;
18268 
18269   {
18270     tree tmp;
18271 
18272     /* In contrast to implicit instantiation, where only the
18273        declarations, and not the definitions, of members are
18274        instantiated, we have here:
18275 
18276 	 [temp.explicit]
18277 
18278 	 The explicit instantiation of a class template specialization
18279 	 implies the instantiation of all of its members not
18280 	 previously explicitly specialized in the translation unit
18281 	 containing the explicit instantiation.
18282 
18283        Of course, we can't instantiate member template classes, since
18284        we don't have any arguments for them.  Note that the standard
18285        is unclear on whether the instantiation of the members are
18286        *explicit* instantiations or not.  However, the most natural
18287        interpretation is that it should be an explicit instantiation.  */
18288 
18289     if (! static_p)
18290       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
18291 	if (TREE_CODE (tmp) == FUNCTION_DECL
18292 	    && DECL_TEMPLATE_INSTANTIATION (tmp))
18293 	  instantiate_class_member (tmp, extern_p);
18294 
18295     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
18296       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
18297 	instantiate_class_member (tmp, extern_p);
18298 
18299     if (CLASSTYPE_NESTED_UTDS (t))
18300       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
18301 			     bt_instantiate_type_proc, &storage);
18302   }
18303 }
18304 
18305 /* Given a function DECL, which is a specialization of TMPL, modify
18306    DECL to be a re-instantiation of TMPL with the same template
18307    arguments.  TMPL should be the template into which tsubst'ing
18308    should occur for DECL, not the most general template.
18309 
18310    One reason for doing this is a scenario like this:
18311 
18312      template <class T>
18313      void f(const T&, int i);
18314 
18315      void g() { f(3, 7); }
18316 
18317      template <class T>
18318      void f(const T& t, const int i) { }
18319 
18320    Note that when the template is first instantiated, with
18321    instantiate_template, the resulting DECL will have no name for the
18322    first parameter, and the wrong type for the second.  So, when we go
18323    to instantiate the DECL, we regenerate it.  */
18324 
18325 static void
regenerate_decl_from_template(tree decl,tree tmpl)18326 regenerate_decl_from_template (tree decl, tree tmpl)
18327 {
18328   /* The arguments used to instantiate DECL, from the most general
18329      template.  */
18330   tree args;
18331   tree code_pattern;
18332 
18333   args = DECL_TI_ARGS (decl);
18334   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
18335 
18336   /* Make sure that we can see identifiers, and compute access
18337      correctly.  */
18338   push_access_scope (decl);
18339 
18340   if (TREE_CODE (decl) == FUNCTION_DECL)
18341     {
18342       tree decl_parm;
18343       tree pattern_parm;
18344       tree specs;
18345       int args_depth;
18346       int parms_depth;
18347 
18348       args_depth = TMPL_ARGS_DEPTH (args);
18349       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
18350       if (args_depth > parms_depth)
18351 	args = get_innermost_template_args (args, parms_depth);
18352 
18353       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
18354 					      args, tf_error, NULL_TREE,
18355 					      /*defer_ok*/false);
18356       if (specs && specs != error_mark_node)
18357 	TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
18358 						    specs);
18359 
18360       /* Merge parameter declarations.  */
18361       decl_parm = skip_artificial_parms_for (decl,
18362 					     DECL_ARGUMENTS (decl));
18363       pattern_parm
18364 	= skip_artificial_parms_for (code_pattern,
18365 				     DECL_ARGUMENTS (code_pattern));
18366       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
18367 	{
18368 	  tree parm_type;
18369 	  tree attributes;
18370 
18371 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
18372 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
18373 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
18374 			      NULL_TREE);
18375 	  parm_type = type_decays_to (parm_type);
18376 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
18377 	    TREE_TYPE (decl_parm) = parm_type;
18378 	  attributes = DECL_ATTRIBUTES (pattern_parm);
18379 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
18380 	    {
18381 	      DECL_ATTRIBUTES (decl_parm) = attributes;
18382 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
18383 	    }
18384 	  decl_parm = DECL_CHAIN (decl_parm);
18385 	  pattern_parm = DECL_CHAIN (pattern_parm);
18386 	}
18387       /* Merge any parameters that match with the function parameter
18388          pack.  */
18389       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
18390         {
18391           int i, len;
18392           tree expanded_types;
18393           /* Expand the TYPE_PACK_EXPANSION that provides the types for
18394              the parameters in this function parameter pack.  */
18395           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
18396                                                  args, tf_error, NULL_TREE);
18397           len = TREE_VEC_LENGTH (expanded_types);
18398           for (i = 0; i < len; i++)
18399             {
18400               tree parm_type;
18401               tree attributes;
18402 
18403               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
18404                 /* Rename the parameter to include the index.  */
18405                 DECL_NAME (decl_parm) =
18406                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
18407               parm_type = TREE_VEC_ELT (expanded_types, i);
18408               parm_type = type_decays_to (parm_type);
18409               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
18410                 TREE_TYPE (decl_parm) = parm_type;
18411               attributes = DECL_ATTRIBUTES (pattern_parm);
18412               if (DECL_ATTRIBUTES (decl_parm) != attributes)
18413                 {
18414                   DECL_ATTRIBUTES (decl_parm) = attributes;
18415                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
18416                 }
18417               decl_parm = DECL_CHAIN (decl_parm);
18418             }
18419         }
18420       /* Merge additional specifiers from the CODE_PATTERN.  */
18421       if (DECL_DECLARED_INLINE_P (code_pattern)
18422 	  && !DECL_DECLARED_INLINE_P (decl))
18423 	DECL_DECLARED_INLINE_P (decl) = 1;
18424     }
18425   else if (TREE_CODE (decl) == VAR_DECL)
18426     {
18427       DECL_INITIAL (decl) =
18428 	tsubst_expr (DECL_INITIAL (code_pattern), args,
18429 		     tf_error, DECL_TI_TEMPLATE (decl),
18430 		     /*integral_constant_expression_p=*/false);
18431       if (VAR_HAD_UNKNOWN_BOUND (decl))
18432 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
18433 				   tf_error, DECL_TI_TEMPLATE (decl));
18434     }
18435   else
18436     gcc_unreachable ();
18437 
18438   pop_access_scope (decl);
18439 }
18440 
18441 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
18442    substituted to get DECL.  */
18443 
18444 tree
template_for_substitution(tree decl)18445 template_for_substitution (tree decl)
18446 {
18447   tree tmpl = DECL_TI_TEMPLATE (decl);
18448 
18449   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
18450      for the instantiation.  This is not always the most general
18451      template.  Consider, for example:
18452 
18453 	template <class T>
18454 	struct S { template <class U> void f();
18455 		   template <> void f<int>(); };
18456 
18457      and an instantiation of S<double>::f<int>.  We want TD to be the
18458      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
18459   while (/* An instantiation cannot have a definition, so we need a
18460 	    more general template.  */
18461 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
18462 	   /* We must also deal with friend templates.  Given:
18463 
18464 		template <class T> struct S {
18465 		  template <class U> friend void f() {};
18466 		};
18467 
18468 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
18469 	      so far as the language is concerned, but that's still
18470 	      where we get the pattern for the instantiation from.  On
18471 	      other hand, if the definition comes outside the class, say:
18472 
18473 		template <class T> struct S {
18474 		  template <class U> friend void f();
18475 		};
18476 		template <class U> friend void f() {}
18477 
18478 	      we don't need to look any further.  That's what the check for
18479 	      DECL_INITIAL is for.  */
18480 	  || (TREE_CODE (decl) == FUNCTION_DECL
18481 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
18482 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
18483     {
18484       /* The present template, TD, should not be a definition.  If it
18485 	 were a definition, we should be using it!  Note that we
18486 	 cannot restructure the loop to just keep going until we find
18487 	 a template with a definition, since that might go too far if
18488 	 a specialization was declared, but not defined.  */
18489       gcc_assert (TREE_CODE (decl) != VAR_DECL
18490 		  || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
18491 
18492       /* Fetch the more general template.  */
18493       tmpl = DECL_TI_TEMPLATE (tmpl);
18494     }
18495 
18496   return tmpl;
18497 }
18498 
18499 /* Returns true if we need to instantiate this template instance even if we
18500    know we aren't going to emit it..  */
18501 
18502 bool
always_instantiate_p(tree decl)18503 always_instantiate_p (tree decl)
18504 {
18505   /* We always instantiate inline functions so that we can inline them.  An
18506      explicit instantiation declaration prohibits implicit instantiation of
18507      non-inline functions.  With high levels of optimization, we would
18508      normally inline non-inline functions -- but we're not allowed to do
18509      that for "extern template" functions.  Therefore, we check
18510      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
18511   return ((TREE_CODE (decl) == FUNCTION_DECL
18512 	   && (DECL_DECLARED_INLINE_P (decl)
18513 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
18514 	  /* And we need to instantiate static data members so that
18515 	     their initializers are available in integral constant
18516 	     expressions.  */
18517 	  || (TREE_CODE (decl) == VAR_DECL
18518 	      && decl_maybe_constant_var_p (decl)));
18519 }
18520 
18521 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
18522    instantiate it now, modifying TREE_TYPE (fn).  */
18523 
18524 void
maybe_instantiate_noexcept(tree fn)18525 maybe_instantiate_noexcept (tree fn)
18526 {
18527   tree fntype, spec, noex, clone;
18528 
18529   if (DECL_CLONED_FUNCTION_P (fn))
18530     fn = DECL_CLONED_FUNCTION (fn);
18531   fntype = TREE_TYPE (fn);
18532   spec = TYPE_RAISES_EXCEPTIONS (fntype);
18533 
18534   if (!DEFERRED_NOEXCEPT_SPEC_P (spec))
18535     return;
18536 
18537   noex = TREE_PURPOSE (spec);
18538 
18539   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
18540     {
18541       if (push_tinst_level (fn))
18542 	{
18543 	  push_access_scope (fn);
18544 	  push_deferring_access_checks (dk_no_deferred);
18545 	  input_location = DECL_SOURCE_LOCATION (fn);
18546 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
18547 					DEFERRED_NOEXCEPT_ARGS (noex),
18548 					tf_warning_or_error, fn,
18549 					/*function_p=*/false,
18550 					/*integral_constant_expression_p=*/true);
18551 	  pop_deferring_access_checks ();
18552 	  pop_access_scope (fn);
18553 	  pop_tinst_level ();
18554 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
18555 	  if (spec == error_mark_node)
18556 	    spec = noexcept_false_spec;
18557 	}
18558       else
18559 	spec = noexcept_false_spec;
18560     }
18561   else
18562     {
18563       /* This is an implicitly declared function, so NOEX is a list of
18564 	 other functions to evaluate and merge.  */
18565       tree elt;
18566       spec = noexcept_true_spec;
18567       for (elt = noex; elt; elt = OVL_NEXT (elt))
18568 	{
18569 	  tree fn = OVL_CURRENT (elt);
18570 	  tree subspec;
18571 	  maybe_instantiate_noexcept (fn);
18572 	  subspec = TYPE_RAISES_EXCEPTIONS (TREE_TYPE (fn));
18573 	  spec = merge_exception_specifiers (spec, subspec, NULL_TREE);
18574 	}
18575     }
18576 
18577   TREE_TYPE (fn) = build_exception_variant (fntype, spec);
18578 
18579   FOR_EACH_CLONE (clone, fn)
18580     {
18581       if (TREE_TYPE (clone) == fntype)
18582 	TREE_TYPE (clone) = TREE_TYPE (fn);
18583       else
18584 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
18585     }
18586 }
18587 
18588 /* Produce the definition of D, a _DECL generated from a template.  If
18589    DEFER_OK is nonzero, then we don't have to actually do the
18590    instantiation now; we just have to do it sometime.  Normally it is
18591    an error if this is an explicit instantiation but D is undefined.
18592    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
18593    explicitly instantiated class template.  */
18594 
18595 tree
instantiate_decl(tree d,int defer_ok,bool expl_inst_class_mem_p)18596 instantiate_decl (tree d, int defer_ok,
18597 		  bool expl_inst_class_mem_p)
18598 {
18599   tree tmpl = DECL_TI_TEMPLATE (d);
18600   tree gen_args;
18601   tree args;
18602   tree td;
18603   tree code_pattern;
18604   tree spec;
18605   tree gen_tmpl;
18606   bool pattern_defined;
18607   location_t saved_loc = input_location;
18608   bool external_p;
18609   tree fn_context;
18610   bool nested;
18611 
18612   /* This function should only be used to instantiate templates for
18613      functions and static member variables.  */
18614   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
18615 	      || TREE_CODE (d) == VAR_DECL);
18616 
18617   /* Variables are never deferred; if instantiation is required, they
18618      are instantiated right away.  That allows for better code in the
18619      case that an expression refers to the value of the variable --
18620      if the variable has a constant value the referring expression can
18621      take advantage of that fact.  */
18622   if (TREE_CODE (d) == VAR_DECL
18623       || DECL_DECLARED_CONSTEXPR_P (d))
18624     defer_ok = 0;
18625 
18626   /* Don't instantiate cloned functions.  Instead, instantiate the
18627      functions they cloned.  */
18628   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
18629     d = DECL_CLONED_FUNCTION (d);
18630 
18631   if (DECL_TEMPLATE_INSTANTIATED (d)
18632       || (TREE_CODE (d) == FUNCTION_DECL
18633 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
18634       || DECL_TEMPLATE_SPECIALIZATION (d))
18635     /* D has already been instantiated or explicitly specialized, so
18636        there's nothing for us to do here.
18637 
18638        It might seem reasonable to check whether or not D is an explicit
18639        instantiation, and, if so, stop here.  But when an explicit
18640        instantiation is deferred until the end of the compilation,
18641        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
18642        the instantiation.  */
18643     return d;
18644 
18645   /* Check to see whether we know that this template will be
18646      instantiated in some other file, as with "extern template"
18647      extension.  */
18648   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
18649 
18650   /* In general, we do not instantiate such templates.  */
18651   if (external_p && !always_instantiate_p (d))
18652     return d;
18653 
18654   gen_tmpl = most_general_template (tmpl);
18655   gen_args = DECL_TI_ARGS (d);
18656 
18657   if (tmpl != gen_tmpl)
18658     /* We should already have the extra args.  */
18659     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
18660 		== TMPL_ARGS_DEPTH (gen_args));
18661   /* And what's in the hash table should match D.  */
18662   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
18663 	      || spec == NULL_TREE);
18664 
18665   /* This needs to happen before any tsubsting.  */
18666   if (! push_tinst_level (d))
18667     return d;
18668 
18669   timevar_push (TV_TEMPLATE_INST);
18670 
18671   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
18672      for the instantiation.  */
18673   td = template_for_substitution (d);
18674   code_pattern = DECL_TEMPLATE_RESULT (td);
18675 
18676   /* We should never be trying to instantiate a member of a class
18677      template or partial specialization.  */
18678   gcc_assert (d != code_pattern);
18679 
18680   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
18681       || DECL_TEMPLATE_SPECIALIZATION (td))
18682     /* In the case of a friend template whose definition is provided
18683        outside the class, we may have too many arguments.  Drop the
18684        ones we don't need.  The same is true for specializations.  */
18685     args = get_innermost_template_args
18686       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
18687   else
18688     args = gen_args;
18689 
18690   if (TREE_CODE (d) == FUNCTION_DECL)
18691     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE
18692 		       || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern));
18693   else
18694     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
18695 
18696   /* We may be in the middle of deferred access check.  Disable it now.  */
18697   push_deferring_access_checks (dk_no_deferred);
18698 
18699   /* Unless an explicit instantiation directive has already determined
18700      the linkage of D, remember that a definition is available for
18701      this entity.  */
18702   if (pattern_defined
18703       && !DECL_INTERFACE_KNOWN (d)
18704       && !DECL_NOT_REALLY_EXTERN (d))
18705     mark_definable (d);
18706 
18707   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
18708   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
18709   input_location = DECL_SOURCE_LOCATION (d);
18710 
18711   /* If D is a member of an explicitly instantiated class template,
18712      and no definition is available, treat it like an implicit
18713      instantiation.  */
18714   if (!pattern_defined && expl_inst_class_mem_p
18715       && DECL_EXPLICIT_INSTANTIATION (d))
18716     {
18717       /* Leave linkage flags alone on instantiations with anonymous
18718 	 visibility.  */
18719       if (TREE_PUBLIC (d))
18720 	{
18721 	  DECL_NOT_REALLY_EXTERN (d) = 0;
18722 	  DECL_INTERFACE_KNOWN (d) = 0;
18723 	}
18724       SET_DECL_IMPLICIT_INSTANTIATION (d);
18725     }
18726 
18727   if (TREE_CODE (d) == FUNCTION_DECL)
18728     maybe_instantiate_noexcept (d);
18729 
18730   /* Defer all other templates, unless we have been explicitly
18731      forbidden from doing so.  */
18732   if (/* If there is no definition, we cannot instantiate the
18733 	 template.  */
18734       ! pattern_defined
18735       /* If it's OK to postpone instantiation, do so.  */
18736       || defer_ok
18737       /* If this is a static data member that will be defined
18738 	 elsewhere, we don't want to instantiate the entire data
18739 	 member, but we do want to instantiate the initializer so that
18740 	 we can substitute that elsewhere.  */
18741       || (external_p && TREE_CODE (d) == VAR_DECL))
18742     {
18743       /* The definition of the static data member is now required so
18744 	 we must substitute the initializer.  */
18745       if (TREE_CODE (d) == VAR_DECL
18746 	  && !DECL_INITIAL (d)
18747 	  && DECL_INITIAL (code_pattern))
18748 	{
18749 	  tree ns;
18750 	  tree init;
18751 	  bool const_init = false;
18752 
18753 	  ns = decl_namespace_context (d);
18754 	  push_nested_namespace (ns);
18755 	  push_nested_class (DECL_CONTEXT (d));
18756 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
18757 			      args,
18758 			      tf_warning_or_error, NULL_TREE,
18759 			      /*integral_constant_expression_p=*/false);
18760 	  /* Make sure the initializer is still constant, in case of
18761 	     circular dependency (template/instantiate6.C). */
18762 	  const_init
18763 	    = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18764 	  cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
18765 			  /*asmspec_tree=*/NULL_TREE,
18766 			  LOOKUP_ONLYCONVERTING);
18767 	  pop_nested_class ();
18768 	  pop_nested_namespace (ns);
18769 	}
18770 
18771       /* We restore the source position here because it's used by
18772 	 add_pending_template.  */
18773       input_location = saved_loc;
18774 
18775       if (at_eof && !pattern_defined
18776 	  && DECL_EXPLICIT_INSTANTIATION (d)
18777 	  && DECL_NOT_REALLY_EXTERN (d))
18778 	/* [temp.explicit]
18779 
18780 	   The definition of a non-exported function template, a
18781 	   non-exported member function template, or a non-exported
18782 	   member function or static data member of a class template
18783 	   shall be present in every translation unit in which it is
18784 	   explicitly instantiated.  */
18785 	permerror (input_location,  "explicit instantiation of %qD "
18786 		   "but no definition available", d);
18787 
18788       /* If we're in unevaluated context, we just wanted to get the
18789 	 constant value; this isn't an odr use, so don't queue
18790 	 a full instantiation.  */
18791       if (cp_unevaluated_operand != 0)
18792 	goto out;
18793       /* ??? Historically, we have instantiated inline functions, even
18794 	 when marked as "extern template".  */
18795       if (!(external_p && TREE_CODE (d) == VAR_DECL))
18796 	add_pending_template (d);
18797       goto out;
18798     }
18799   /* Tell the repository that D is available in this translation unit
18800      -- and see if it is supposed to be instantiated here.  */
18801   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
18802     {
18803       /* In a PCH file, despite the fact that the repository hasn't
18804 	 requested instantiation in the PCH it is still possible that
18805 	 an instantiation will be required in a file that includes the
18806 	 PCH.  */
18807       if (pch_file)
18808 	add_pending_template (d);
18809       /* Instantiate inline functions so that the inliner can do its
18810 	 job, even though we'll not be emitting a copy of this
18811 	 function.  */
18812       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
18813 	goto out;
18814     }
18815 
18816   fn_context = decl_function_context (d);
18817   nested = (current_function_decl != NULL_TREE);
18818   if (!fn_context)
18819     push_to_top_level ();
18820   else if (nested)
18821     push_function_context ();
18822 
18823   /* Mark D as instantiated so that recursive calls to
18824      instantiate_decl do not try to instantiate it again.  */
18825   DECL_TEMPLATE_INSTANTIATED (d) = 1;
18826 
18827   /* Regenerate the declaration in case the template has been modified
18828      by a subsequent redeclaration.  */
18829   regenerate_decl_from_template (d, td);
18830 
18831   /* We already set the file and line above.  Reset them now in case
18832      they changed as a result of calling regenerate_decl_from_template.  */
18833   input_location = DECL_SOURCE_LOCATION (d);
18834 
18835   if (TREE_CODE (d) == VAR_DECL)
18836     {
18837       tree init;
18838       bool const_init = false;
18839 
18840       /* Clear out DECL_RTL; whatever was there before may not be right
18841 	 since we've reset the type of the declaration.  */
18842       SET_DECL_RTL (d, NULL);
18843       DECL_IN_AGGR_P (d) = 0;
18844 
18845       /* The initializer is placed in DECL_INITIAL by
18846 	 regenerate_decl_from_template so we don't need to
18847 	 push/pop_access_scope again here.  Pull it out so that
18848 	 cp_finish_decl can process it.  */
18849       init = DECL_INITIAL (d);
18850       DECL_INITIAL (d) = NULL_TREE;
18851       DECL_INITIALIZED_P (d) = 0;
18852 
18853       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
18854 	 initializer.  That function will defer actual emission until
18855 	 we have a chance to determine linkage.  */
18856       DECL_EXTERNAL (d) = 0;
18857 
18858       /* Enter the scope of D so that access-checking works correctly.  */
18859       push_nested_class (DECL_CONTEXT (d));
18860       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
18861       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
18862       pop_nested_class ();
18863     }
18864   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
18865     synthesize_method (d);
18866   else if (TREE_CODE (d) == FUNCTION_DECL)
18867     {
18868       struct pointer_map_t *saved_local_specializations;
18869       tree subst_decl;
18870       tree tmpl_parm;
18871       tree spec_parm;
18872 
18873       /* Save away the current list, in case we are instantiating one
18874 	 template from within the body of another.  */
18875       saved_local_specializations = local_specializations;
18876 
18877       /* Set up the list of local specializations.  */
18878       local_specializations = pointer_map_create ();
18879 
18880       /* Set up context.  */
18881       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
18882 
18883       /* Some typedefs referenced from within the template code need to be
18884 	 access checked at template instantiation time, i.e now. These
18885 	 types were added to the template at parsing time. Let's get those
18886 	 and perform the access checks then.  */
18887       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (gen_tmpl),
18888 				     gen_args);
18889 
18890       /* Create substitution entries for the parameters.  */
18891       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
18892       tmpl_parm = DECL_ARGUMENTS (subst_decl);
18893       spec_parm = DECL_ARGUMENTS (d);
18894       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
18895 	{
18896 	  register_local_specialization (spec_parm, tmpl_parm);
18897 	  spec_parm = skip_artificial_parms_for (d, spec_parm);
18898 	  tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
18899 	}
18900       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
18901 	{
18902 	  if (!FUNCTION_PARAMETER_PACK_P (tmpl_parm))
18903 	    {
18904 	      register_local_specialization (spec_parm, tmpl_parm);
18905 	      spec_parm = DECL_CHAIN (spec_parm);
18906 	    }
18907 	  else
18908 	    {
18909 	      /* Register the (value) argument pack as a specialization of
18910 		 TMPL_PARM, then move on.  */
18911 	      tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
18912 	      register_local_specialization (argpack, tmpl_parm);
18913 	    }
18914 	}
18915       gcc_assert (!spec_parm);
18916 
18917       /* Substitute into the body of the function.  */
18918       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
18919 		   tf_warning_or_error, tmpl,
18920 		   /*integral_constant_expression_p=*/false);
18921 
18922       /* Set the current input_location to the end of the function
18923          so that finish_function knows where we are.  */
18924       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
18925 
18926       /* We don't need the local specializations any more.  */
18927       pointer_map_destroy (local_specializations);
18928       local_specializations = saved_local_specializations;
18929 
18930       /* Finish the function.  */
18931       d = finish_function (0);
18932       expand_or_defer_fn (d);
18933     }
18934 
18935   /* We're not deferring instantiation any more.  */
18936   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
18937 
18938   if (!fn_context)
18939     pop_from_top_level ();
18940   else if (nested)
18941     pop_function_context ();
18942 
18943 out:
18944   input_location = saved_loc;
18945   pop_deferring_access_checks ();
18946   pop_tinst_level ();
18947 
18948   timevar_pop (TV_TEMPLATE_INST);
18949 
18950   return d;
18951 }
18952 
18953 /* Run through the list of templates that we wish we could
18954    instantiate, and instantiate any we can.  RETRIES is the
18955    number of times we retry pending template instantiation.  */
18956 
18957 void
instantiate_pending_templates(int retries)18958 instantiate_pending_templates (int retries)
18959 {
18960   int reconsider;
18961   location_t saved_loc = input_location;
18962 
18963   /* Instantiating templates may trigger vtable generation.  This in turn
18964      may require further template instantiations.  We place a limit here
18965      to avoid infinite loop.  */
18966   if (pending_templates && retries >= max_tinst_depth)
18967     {
18968       tree decl = pending_templates->tinst->decl;
18969 
18970       error ("template instantiation depth exceeds maximum of %d"
18971 	     " instantiating %q+D, possibly from virtual table generation"
18972 	     " (use -ftemplate-depth= to increase the maximum)",
18973 	     max_tinst_depth, decl);
18974       if (TREE_CODE (decl) == FUNCTION_DECL)
18975 	/* Pretend that we defined it.  */
18976 	DECL_INITIAL (decl) = error_mark_node;
18977       return;
18978     }
18979 
18980   do
18981     {
18982       struct pending_template **t = &pending_templates;
18983       struct pending_template *last = NULL;
18984       reconsider = 0;
18985       while (*t)
18986 	{
18987 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
18988 	  bool complete = false;
18989 
18990 	  if (TYPE_P (instantiation))
18991 	    {
18992 	      tree fn;
18993 
18994 	      if (!COMPLETE_TYPE_P (instantiation))
18995 		{
18996 		  instantiate_class_template (instantiation);
18997 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
18998 		    for (fn = TYPE_METHODS (instantiation);
18999 			 fn;
19000 			 fn = TREE_CHAIN (fn))
19001 		      if (! DECL_ARTIFICIAL (fn))
19002 			instantiate_decl (fn,
19003 					  /*defer_ok=*/0,
19004 					  /*expl_inst_class_mem_p=*/false);
19005 		  if (COMPLETE_TYPE_P (instantiation))
19006 		    reconsider = 1;
19007 		}
19008 
19009 	      complete = COMPLETE_TYPE_P (instantiation);
19010 	    }
19011 	  else
19012 	    {
19013 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
19014 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
19015 		{
19016 		  instantiation
19017 		    = instantiate_decl (instantiation,
19018 					/*defer_ok=*/0,
19019 					/*expl_inst_class_mem_p=*/false);
19020 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
19021 		    reconsider = 1;
19022 		}
19023 
19024 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
19025 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
19026 	    }
19027 
19028 	  if (complete)
19029 	    /* If INSTANTIATION has been instantiated, then we don't
19030 	       need to consider it again in the future.  */
19031 	    *t = (*t)->next;
19032 	  else
19033 	    {
19034 	      last = *t;
19035 	      t = &(*t)->next;
19036 	    }
19037 	  tinst_depth = 0;
19038 	  current_tinst_level = NULL;
19039 	}
19040       last_pending_template = last;
19041     }
19042   while (reconsider);
19043 
19044   input_location = saved_loc;
19045 }
19046 
19047 /* Substitute ARGVEC into T, which is a list of initializers for
19048    either base class or a non-static data member.  The TREE_PURPOSEs
19049    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
19050    instantiate_decl.  */
19051 
19052 static tree
tsubst_initializer_list(tree t,tree argvec)19053 tsubst_initializer_list (tree t, tree argvec)
19054 {
19055   tree inits = NULL_TREE;
19056 
19057   for (; t; t = TREE_CHAIN (t))
19058     {
19059       tree decl;
19060       tree init;
19061       tree expanded_bases = NULL_TREE;
19062       tree expanded_arguments = NULL_TREE;
19063       int i, len = 1;
19064 
19065       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
19066         {
19067           tree expr;
19068           tree arg;
19069 
19070           /* Expand the base class expansion type into separate base
19071              classes.  */
19072           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
19073                                                  tf_warning_or_error,
19074                                                  NULL_TREE);
19075           if (expanded_bases == error_mark_node)
19076             continue;
19077 
19078           /* We'll be building separate TREE_LISTs of arguments for
19079              each base.  */
19080           len = TREE_VEC_LENGTH (expanded_bases);
19081           expanded_arguments = make_tree_vec (len);
19082           for (i = 0; i < len; i++)
19083             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
19084 
19085           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
19086              expand each argument in the TREE_VALUE of t.  */
19087           expr = make_node (EXPR_PACK_EXPANSION);
19088 	  PACK_EXPANSION_LOCAL_P (expr) = true;
19089           PACK_EXPANSION_PARAMETER_PACKS (expr) =
19090             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
19091 
19092 	  if (TREE_VALUE (t) == void_type_node)
19093 	    /* VOID_TYPE_NODE is used to indicate
19094 	       value-initialization.  */
19095 	    {
19096 	      for (i = 0; i < len; i++)
19097 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
19098 	    }
19099 	  else
19100 	    {
19101 	      /* Substitute parameter packs into each argument in the
19102 		 TREE_LIST.  */
19103 	      in_base_initializer = 1;
19104 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
19105 		{
19106 		  tree expanded_exprs;
19107 
19108 		  /* Expand the argument.  */
19109 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
19110 		  expanded_exprs
19111 		    = tsubst_pack_expansion (expr, argvec,
19112 					     tf_warning_or_error,
19113 					     NULL_TREE);
19114 		  if (expanded_exprs == error_mark_node)
19115 		    continue;
19116 
19117 		  /* Prepend each of the expanded expressions to the
19118 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
19119 		  for (i = 0; i < len; i++)
19120 		    {
19121 		      TREE_VEC_ELT (expanded_arguments, i) =
19122 			tree_cons (NULL_TREE,
19123 				   TREE_VEC_ELT (expanded_exprs, i),
19124 				   TREE_VEC_ELT (expanded_arguments, i));
19125 		    }
19126 		}
19127 	      in_base_initializer = 0;
19128 
19129 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
19130 		 since we built them backwards.  */
19131 	      for (i = 0; i < len; i++)
19132 		{
19133 		  TREE_VEC_ELT (expanded_arguments, i) =
19134 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
19135 		}
19136 	    }
19137         }
19138 
19139       for (i = 0; i < len; ++i)
19140         {
19141           if (expanded_bases)
19142             {
19143               decl = TREE_VEC_ELT (expanded_bases, i);
19144               decl = expand_member_init (decl);
19145               init = TREE_VEC_ELT (expanded_arguments, i);
19146             }
19147           else
19148             {
19149 	      tree tmp;
19150               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
19151                                   tf_warning_or_error, NULL_TREE);
19152 
19153               decl = expand_member_init (decl);
19154               if (decl && !DECL_P (decl))
19155                 in_base_initializer = 1;
19156 
19157 	      init = TREE_VALUE (t);
19158 	      tmp = init;
19159 	      if (init != void_type_node)
19160 		init = tsubst_expr (init, argvec,
19161 				    tf_warning_or_error, NULL_TREE,
19162 				    /*integral_constant_expression_p=*/false);
19163 	      if (init == NULL_TREE && tmp != NULL_TREE)
19164 		/* If we had an initializer but it instantiated to nothing,
19165 		   value-initialize the object.  This will only occur when
19166 		   the initializer was a pack expansion where the parameter
19167 		   packs used in that expansion were of length zero.  */
19168 		init = void_type_node;
19169               in_base_initializer = 0;
19170             }
19171 
19172           if (decl)
19173             {
19174               init = build_tree_list (decl, init);
19175               TREE_CHAIN (init) = inits;
19176               inits = init;
19177             }
19178         }
19179     }
19180   return inits;
19181 }
19182 
19183 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
19184 
19185 static void
set_current_access_from_decl(tree decl)19186 set_current_access_from_decl (tree decl)
19187 {
19188   if (TREE_PRIVATE (decl))
19189     current_access_specifier = access_private_node;
19190   else if (TREE_PROTECTED (decl))
19191     current_access_specifier = access_protected_node;
19192   else
19193     current_access_specifier = access_public_node;
19194 }
19195 
19196 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
19197    is the instantiation (which should have been created with
19198    start_enum) and ARGS are the template arguments to use.  */
19199 
19200 static void
tsubst_enum(tree tag,tree newtag,tree args)19201 tsubst_enum (tree tag, tree newtag, tree args)
19202 {
19203   tree e;
19204 
19205   if (SCOPED_ENUM_P (newtag))
19206     begin_scope (sk_scoped_enum, newtag);
19207 
19208   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
19209     {
19210       tree value;
19211       tree decl;
19212 
19213       decl = TREE_VALUE (e);
19214       /* Note that in a template enum, the TREE_VALUE is the
19215 	 CONST_DECL, not the corresponding INTEGER_CST.  */
19216       value = tsubst_expr (DECL_INITIAL (decl),
19217 			   args, tf_warning_or_error, NULL_TREE,
19218 			   /*integral_constant_expression_p=*/true);
19219 
19220       /* Give this enumeration constant the correct access.  */
19221       set_current_access_from_decl (decl);
19222 
19223       /* Actually build the enumerator itself.  */
19224       build_enumerator
19225 	(DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
19226     }
19227 
19228   if (SCOPED_ENUM_P (newtag))
19229     finish_scope ();
19230 
19231   finish_enum_value_list (newtag);
19232   finish_enum (newtag);
19233 
19234   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
19235     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
19236 }
19237 
19238 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
19239    its type -- but without substituting the innermost set of template
19240    arguments.  So, innermost set of template parameters will appear in
19241    the type.  */
19242 
19243 tree
get_mostly_instantiated_function_type(tree decl)19244 get_mostly_instantiated_function_type (tree decl)
19245 {
19246   tree fn_type;
19247   tree tmpl;
19248   tree targs;
19249   tree tparms;
19250   int parm_depth;
19251 
19252   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
19253   targs = DECL_TI_ARGS (decl);
19254   tparms = DECL_TEMPLATE_PARMS (tmpl);
19255   parm_depth = TMPL_PARMS_DEPTH (tparms);
19256 
19257   /* There should be as many levels of arguments as there are levels
19258      of parameters.  */
19259   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
19260 
19261   fn_type = TREE_TYPE (tmpl);
19262 
19263   if (parm_depth == 1)
19264     /* No substitution is necessary.  */
19265     ;
19266   else
19267     {
19268       int i;
19269       tree partial_args;
19270 
19271       /* Replace the innermost level of the TARGS with NULL_TREEs to
19272 	 let tsubst know not to substitute for those parameters.  */
19273       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
19274       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
19275 	SET_TMPL_ARGS_LEVEL (partial_args, i,
19276 			     TMPL_ARGS_LEVEL (targs, i));
19277       SET_TMPL_ARGS_LEVEL (partial_args,
19278 			   TMPL_ARGS_DEPTH (targs),
19279 			   make_tree_vec (DECL_NTPARMS (tmpl)));
19280 
19281       /* Make sure that we can see identifiers, and compute access
19282 	 correctly.  */
19283       push_access_scope (decl);
19284 
19285       ++processing_template_decl;
19286       /* Now, do the (partial) substitution to figure out the
19287 	 appropriate function type.  */
19288       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
19289       --processing_template_decl;
19290 
19291       /* Substitute into the template parameters to obtain the real
19292 	 innermost set of parameters.  This step is important if the
19293 	 innermost set of template parameters contains value
19294 	 parameters whose types depend on outer template parameters.  */
19295       TREE_VEC_LENGTH (partial_args)--;
19296       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
19297 
19298       pop_access_scope (decl);
19299     }
19300 
19301   return fn_type;
19302 }
19303 
19304 /* Return truthvalue if we're processing a template different from
19305    the last one involved in diagnostics.  */
19306 int
problematic_instantiation_changed(void)19307 problematic_instantiation_changed (void)
19308 {
19309   return current_tinst_level != last_error_tinst_level;
19310 }
19311 
19312 /* Remember current template involved in diagnostics.  */
19313 void
record_last_problematic_instantiation(void)19314 record_last_problematic_instantiation (void)
19315 {
19316   last_error_tinst_level = current_tinst_level;
19317 }
19318 
19319 struct tinst_level *
current_instantiation(void)19320 current_instantiation (void)
19321 {
19322   return current_tinst_level;
19323 }
19324 
19325 /* [temp.param] Check that template non-type parm TYPE is of an allowable
19326    type. Return zero for ok, nonzero for disallowed. Issue error and
19327    warning messages under control of COMPLAIN.  */
19328 
19329 static int
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)19330 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
19331 {
19332   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
19333     return 0;
19334   else if (POINTER_TYPE_P (type))
19335     return 0;
19336   else if (TYPE_PTRMEM_P (type))
19337     return 0;
19338   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
19339     return 0;
19340   else if (TREE_CODE (type) == TYPENAME_TYPE)
19341     return 0;
19342   else if (TREE_CODE (type) == DECLTYPE_TYPE)
19343     return 0;
19344   else if (TREE_CODE (type) == NULLPTR_TYPE)
19345     return 0;
19346 
19347   if (complain & tf_error)
19348     {
19349       if (type == error_mark_node)
19350 	inform (input_location, "invalid template non-type parameter");
19351       else
19352 	error ("%q#T is not a valid type for a template non-type parameter",
19353 	       type);
19354     }
19355   return 1;
19356 }
19357 
19358 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
19359    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
19360 
19361 static bool
dependent_type_p_r(tree type)19362 dependent_type_p_r (tree type)
19363 {
19364   tree scope;
19365 
19366   /* [temp.dep.type]
19367 
19368      A type is dependent if it is:
19369 
19370      -- a template parameter. Template template parameters are types
19371 	for us (since TYPE_P holds true for them) so we handle
19372 	them here.  */
19373   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19374       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
19375     return true;
19376   /* -- a qualified-id with a nested-name-specifier which contains a
19377 	class-name that names a dependent type or whose unqualified-id
19378 	names a dependent type.  */
19379   if (TREE_CODE (type) == TYPENAME_TYPE)
19380     return true;
19381   /* -- a cv-qualified type where the cv-unqualified type is
19382 	dependent.  */
19383   type = TYPE_MAIN_VARIANT (type);
19384   /* -- a compound type constructed from any dependent type.  */
19385   if (TYPE_PTRMEM_P (type))
19386     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
19387 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
19388 					   (type)));
19389   else if (TREE_CODE (type) == POINTER_TYPE
19390 	   || TREE_CODE (type) == REFERENCE_TYPE)
19391     return dependent_type_p (TREE_TYPE (type));
19392   else if (TREE_CODE (type) == FUNCTION_TYPE
19393 	   || TREE_CODE (type) == METHOD_TYPE)
19394     {
19395       tree arg_type;
19396 
19397       if (dependent_type_p (TREE_TYPE (type)))
19398 	return true;
19399       for (arg_type = TYPE_ARG_TYPES (type);
19400 	   arg_type;
19401 	   arg_type = TREE_CHAIN (arg_type))
19402 	if (dependent_type_p (TREE_VALUE (arg_type)))
19403 	  return true;
19404       return false;
19405     }
19406   /* -- an array type constructed from any dependent type or whose
19407 	size is specified by a constant expression that is
19408 	value-dependent.
19409 
19410         We checked for type- and value-dependence of the bounds in
19411         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
19412   if (TREE_CODE (type) == ARRAY_TYPE)
19413     {
19414       if (TYPE_DOMAIN (type)
19415 	  && dependent_type_p (TYPE_DOMAIN (type)))
19416 	return true;
19417       return dependent_type_p (TREE_TYPE (type));
19418     }
19419 
19420   /* -- a template-id in which either the template name is a template
19421      parameter ...  */
19422   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
19423     return true;
19424   /* ... or any of the template arguments is a dependent type or
19425 	an expression that is type-dependent or value-dependent.  */
19426   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
19427 	   && (any_dependent_template_arguments_p
19428 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
19429     return true;
19430 
19431   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
19432      dependent; if the argument of the `typeof' expression is not
19433      type-dependent, then it should already been have resolved.  */
19434   if (TREE_CODE (type) == TYPEOF_TYPE
19435       || TREE_CODE (type) == DECLTYPE_TYPE
19436       || TREE_CODE (type) == UNDERLYING_TYPE)
19437     return true;
19438 
19439   /* A template argument pack is dependent if any of its packed
19440      arguments are.  */
19441   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
19442     {
19443       tree args = ARGUMENT_PACK_ARGS (type);
19444       int i, len = TREE_VEC_LENGTH (args);
19445       for (i = 0; i < len; ++i)
19446         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
19447           return true;
19448     }
19449 
19450   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
19451      be template parameters.  */
19452   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
19453     return true;
19454 
19455   /* The standard does not specifically mention types that are local
19456      to template functions or local classes, but they should be
19457      considered dependent too.  For example:
19458 
19459        template <int I> void f() {
19460 	 enum E { a = I };
19461 	 S<sizeof (E)> s;
19462        }
19463 
19464      The size of `E' cannot be known until the value of `I' has been
19465      determined.  Therefore, `E' must be considered dependent.  */
19466   scope = TYPE_CONTEXT (type);
19467   if (scope && TYPE_P (scope))
19468     return dependent_type_p (scope);
19469   /* Don't use type_dependent_expression_p here, as it can lead
19470      to infinite recursion trying to determine whether a lambda
19471      nested in a lambda is dependent (c++/47687).  */
19472   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
19473 	   && DECL_LANG_SPECIFIC (scope)
19474 	   && DECL_TEMPLATE_INFO (scope)
19475 	   && (any_dependent_template_arguments_p
19476 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
19477     return true;
19478 
19479   /* Other types are non-dependent.  */
19480   return false;
19481 }
19482 
19483 /* Returns TRUE if TYPE is dependent, in the sense of
19484    [temp.dep.type].  Note that a NULL type is considered dependent.  */
19485 
19486 bool
dependent_type_p(tree type)19487 dependent_type_p (tree type)
19488 {
19489   /* If there are no template parameters in scope, then there can't be
19490      any dependent types.  */
19491   if (!processing_template_decl)
19492     {
19493       /* If we are not processing a template, then nobody should be
19494 	 providing us with a dependent type.  */
19495       gcc_assert (type);
19496       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
19497       return false;
19498     }
19499 
19500   /* If the type is NULL, we have not computed a type for the entity
19501      in question; in that case, the type is dependent.  */
19502   if (!type)
19503     return true;
19504 
19505   /* Erroneous types can be considered non-dependent.  */
19506   if (type == error_mark_node)
19507     return false;
19508 
19509   /* If we have not already computed the appropriate value for TYPE,
19510      do so now.  */
19511   if (!TYPE_DEPENDENT_P_VALID (type))
19512     {
19513       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
19514       TYPE_DEPENDENT_P_VALID (type) = 1;
19515     }
19516 
19517   return TYPE_DEPENDENT_P (type);
19518 }
19519 
19520 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
19521    lookup.  In other words, a dependent type that is not the current
19522    instantiation.  */
19523 
19524 bool
dependent_scope_p(tree scope)19525 dependent_scope_p (tree scope)
19526 {
19527   return (scope && TYPE_P (scope) && dependent_type_p (scope)
19528 	  && !currently_open_class (scope));
19529 }
19530 
19531 /* T is a SCOPE_REF; return whether we need to consider it
19532     instantiation-dependent so that we can check access at instantiation
19533     time even though we know which member it resolves to.  */
19534 
19535 static bool
instantiation_dependent_scope_ref_p(tree t)19536 instantiation_dependent_scope_ref_p (tree t)
19537 {
19538   if (DECL_P (TREE_OPERAND (t, 1))
19539       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
19540       && accessible_in_template_p (TREE_OPERAND (t, 0),
19541 				   TREE_OPERAND (t, 1)))
19542     return false;
19543   else
19544     return true;
19545 }
19546 
19547 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
19548    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
19549    expression.  */
19550 
19551 /* Note that this predicate is not appropriate for general expressions;
19552    only constant expressions (that satisfy potential_constant_expression)
19553    can be tested for value dependence.  */
19554 
19555 bool
value_dependent_expression_p(tree expression)19556 value_dependent_expression_p (tree expression)
19557 {
19558   if (!processing_template_decl)
19559     return false;
19560 
19561   /* A name declared with a dependent type.  */
19562   if (DECL_P (expression) && type_dependent_expression_p (expression))
19563     return true;
19564 
19565   switch (TREE_CODE (expression))
19566     {
19567     case IDENTIFIER_NODE:
19568       /* A name that has not been looked up -- must be dependent.  */
19569       return true;
19570 
19571     case TEMPLATE_PARM_INDEX:
19572       /* A non-type template parm.  */
19573       return true;
19574 
19575     case CONST_DECL:
19576       /* A non-type template parm.  */
19577       if (DECL_TEMPLATE_PARM_P (expression))
19578 	return true;
19579       return value_dependent_expression_p (DECL_INITIAL (expression));
19580 
19581     case VAR_DECL:
19582        /* A constant with literal type and is initialized
19583 	  with an expression that is value-dependent.
19584 
19585           Note that a non-dependent parenthesized initializer will have
19586           already been replaced with its constant value, so if we see
19587           a TREE_LIST it must be dependent.  */
19588       if (DECL_INITIAL (expression)
19589 	  && decl_constant_var_p (expression)
19590 	  && (TREE_CODE (DECL_INITIAL (expression)) == TREE_LIST
19591 	      || value_dependent_expression_p (DECL_INITIAL (expression))))
19592 	return true;
19593       return false;
19594 
19595     case DYNAMIC_CAST_EXPR:
19596     case STATIC_CAST_EXPR:
19597     case CONST_CAST_EXPR:
19598     case REINTERPRET_CAST_EXPR:
19599     case CAST_EXPR:
19600       /* These expressions are value-dependent if the type to which
19601 	 the cast occurs is dependent or the expression being casted
19602 	 is value-dependent.  */
19603       {
19604 	tree type = TREE_TYPE (expression);
19605 
19606 	if (dependent_type_p (type))
19607 	  return true;
19608 
19609 	/* A functional cast has a list of operands.  */
19610 	expression = TREE_OPERAND (expression, 0);
19611 	if (!expression)
19612 	  {
19613 	    /* If there are no operands, it must be an expression such
19614 	       as "int()". This should not happen for aggregate types
19615 	       because it would form non-constant expressions.  */
19616 	    gcc_assert (cxx_dialect >= cxx0x
19617 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
19618 
19619 	    return false;
19620 	  }
19621 
19622 	if (TREE_CODE (expression) == TREE_LIST)
19623 	  return any_value_dependent_elements_p (expression);
19624 
19625 	return value_dependent_expression_p (expression);
19626       }
19627 
19628     case SIZEOF_EXPR:
19629       if (SIZEOF_EXPR_TYPE_P (expression))
19630 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
19631       /* FALLTHRU */
19632     case ALIGNOF_EXPR:
19633     case TYPEID_EXPR:
19634       /* A `sizeof' expression is value-dependent if the operand is
19635 	 type-dependent or is a pack expansion.  */
19636       expression = TREE_OPERAND (expression, 0);
19637       if (PACK_EXPANSION_P (expression))
19638         return true;
19639       else if (TYPE_P (expression))
19640 	return dependent_type_p (expression);
19641       return instantiation_dependent_expression_p (expression);
19642 
19643     case AT_ENCODE_EXPR:
19644       /* An 'encode' expression is value-dependent if the operand is
19645 	 type-dependent.  */
19646       expression = TREE_OPERAND (expression, 0);
19647       return dependent_type_p (expression);
19648 
19649     case NOEXCEPT_EXPR:
19650       expression = TREE_OPERAND (expression, 0);
19651       return instantiation_dependent_expression_p (expression);
19652 
19653     case SCOPE_REF:
19654       /* All instantiation-dependent expressions should also be considered
19655 	 value-dependent.  */
19656       return instantiation_dependent_scope_ref_p (expression);
19657 
19658     case COMPONENT_REF:
19659       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
19660 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
19661 
19662     case NONTYPE_ARGUMENT_PACK:
19663       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
19664          is value-dependent.  */
19665       {
19666         tree values = ARGUMENT_PACK_ARGS (expression);
19667         int i, len = TREE_VEC_LENGTH (values);
19668 
19669         for (i = 0; i < len; ++i)
19670           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
19671             return true;
19672 
19673         return false;
19674       }
19675 
19676     case TRAIT_EXPR:
19677       {
19678 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
19679 	return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
19680 		|| (type2 ? dependent_type_p (type2) : false));
19681       }
19682 
19683     case MODOP_EXPR:
19684       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19685 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
19686 
19687     case ARRAY_REF:
19688       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
19689 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
19690 
19691     case ADDR_EXPR:
19692       {
19693 	tree op = TREE_OPERAND (expression, 0);
19694 	return (value_dependent_expression_p (op)
19695 		|| has_value_dependent_address (op));
19696       }
19697 
19698     case CALL_EXPR:
19699       {
19700 	tree fn = get_callee_fndecl (expression);
19701 	int i, nargs;
19702 	if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
19703 	  return true;
19704 	nargs = call_expr_nargs (expression);
19705 	for (i = 0; i < nargs; ++i)
19706 	  {
19707 	    tree op = CALL_EXPR_ARG (expression, i);
19708 	    /* In a call to a constexpr member function, look through the
19709 	       implicit ADDR_EXPR on the object argument so that it doesn't
19710 	       cause the call to be considered value-dependent.  We also
19711 	       look through it in potential_constant_expression.  */
19712 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
19713 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
19714 		&& TREE_CODE (op) == ADDR_EXPR)
19715 	      op = TREE_OPERAND (op, 0);
19716 	    if (value_dependent_expression_p (op))
19717 	      return true;
19718 	  }
19719 	return false;
19720       }
19721 
19722     case TEMPLATE_ID_EXPR:
19723       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
19724 	 type-dependent.  */
19725       return type_dependent_expression_p (expression);
19726 
19727     case CONSTRUCTOR:
19728       {
19729 	unsigned ix;
19730 	tree val;
19731 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
19732 	  if (value_dependent_expression_p (val))
19733 	    return true;
19734 	return false;
19735       }
19736 
19737     case STMT_EXPR:
19738       /* Treat a GNU statement expression as dependent to avoid crashing
19739 	 under fold_non_dependent_expr; it can't be constant.  */
19740       return true;
19741 
19742     default:
19743       /* A constant expression is value-dependent if any subexpression is
19744 	 value-dependent.  */
19745       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
19746 	{
19747 	case tcc_reference:
19748 	case tcc_unary:
19749 	case tcc_comparison:
19750 	case tcc_binary:
19751 	case tcc_expression:
19752 	case tcc_vl_exp:
19753 	  {
19754 	    int i, len = cp_tree_operand_length (expression);
19755 
19756 	    for (i = 0; i < len; i++)
19757 	      {
19758 		tree t = TREE_OPERAND (expression, i);
19759 
19760 		/* In some cases, some of the operands may be missing.l
19761 		   (For example, in the case of PREDECREMENT_EXPR, the
19762 		   amount to increment by may be missing.)  That doesn't
19763 		   make the expression dependent.  */
19764 		if (t && value_dependent_expression_p (t))
19765 		  return true;
19766 	      }
19767 	  }
19768 	  break;
19769 	default:
19770 	  break;
19771 	}
19772       break;
19773     }
19774 
19775   /* The expression is not value-dependent.  */
19776   return false;
19777 }
19778 
19779 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
19780    [temp.dep.expr].  Note that an expression with no type is
19781    considered dependent.  Other parts of the compiler arrange for an
19782    expression with type-dependent subexpressions to have no type, so
19783    this function doesn't have to be fully recursive.  */
19784 
19785 bool
type_dependent_expression_p(tree expression)19786 type_dependent_expression_p (tree expression)
19787 {
19788   if (!processing_template_decl)
19789     return false;
19790 
19791   if (expression == error_mark_node)
19792     return false;
19793 
19794   /* An unresolved name is always dependent.  */
19795   if (TREE_CODE (expression) == IDENTIFIER_NODE
19796       || TREE_CODE (expression) == USING_DECL)
19797     return true;
19798 
19799   /* Some expression forms are never type-dependent.  */
19800   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
19801       || TREE_CODE (expression) == SIZEOF_EXPR
19802       || TREE_CODE (expression) == ALIGNOF_EXPR
19803       || TREE_CODE (expression) == AT_ENCODE_EXPR
19804       || TREE_CODE (expression) == NOEXCEPT_EXPR
19805       || TREE_CODE (expression) == TRAIT_EXPR
19806       || TREE_CODE (expression) == TYPEID_EXPR
19807       || TREE_CODE (expression) == DELETE_EXPR
19808       || TREE_CODE (expression) == VEC_DELETE_EXPR
19809       || TREE_CODE (expression) == THROW_EXPR)
19810     return false;
19811 
19812   /* The types of these expressions depends only on the type to which
19813      the cast occurs.  */
19814   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
19815       || TREE_CODE (expression) == STATIC_CAST_EXPR
19816       || TREE_CODE (expression) == CONST_CAST_EXPR
19817       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
19818       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
19819       || TREE_CODE (expression) == CAST_EXPR)
19820     return dependent_type_p (TREE_TYPE (expression));
19821 
19822   /* The types of these expressions depends only on the type created
19823      by the expression.  */
19824   if (TREE_CODE (expression) == NEW_EXPR
19825       || TREE_CODE (expression) == VEC_NEW_EXPR)
19826     {
19827       /* For NEW_EXPR tree nodes created inside a template, either
19828 	 the object type itself or a TREE_LIST may appear as the
19829 	 operand 1.  */
19830       tree type = TREE_OPERAND (expression, 1);
19831       if (TREE_CODE (type) == TREE_LIST)
19832 	/* This is an array type.  We need to check array dimensions
19833 	   as well.  */
19834 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
19835 	       || value_dependent_expression_p
19836 		    (TREE_OPERAND (TREE_VALUE (type), 1));
19837       else
19838 	return dependent_type_p (type);
19839     }
19840 
19841   if (TREE_CODE (expression) == SCOPE_REF)
19842     {
19843       tree scope = TREE_OPERAND (expression, 0);
19844       tree name = TREE_OPERAND (expression, 1);
19845 
19846       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
19847 	 contains an identifier associated by name lookup with one or more
19848 	 declarations declared with a dependent type, or...a
19849 	 nested-name-specifier or qualified-id that names a member of an
19850 	 unknown specialization.  */
19851       return (type_dependent_expression_p (name)
19852 	      || dependent_scope_p (scope));
19853     }
19854 
19855   if (TREE_CODE (expression) == FUNCTION_DECL
19856       && DECL_LANG_SPECIFIC (expression)
19857       && DECL_TEMPLATE_INFO (expression)
19858       && (any_dependent_template_arguments_p
19859 	  (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
19860     return true;
19861 
19862   if (TREE_CODE (expression) == TEMPLATE_DECL
19863       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
19864     return false;
19865 
19866   if (TREE_CODE (expression) == STMT_EXPR)
19867     expression = stmt_expr_value_expr (expression);
19868 
19869   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
19870     {
19871       tree elt;
19872       unsigned i;
19873 
19874       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
19875 	{
19876 	  if (type_dependent_expression_p (elt))
19877 	    return true;
19878 	}
19879       return false;
19880     }
19881 
19882   /* A static data member of the current instantiation with incomplete
19883      array type is type-dependent, as the definition and specializations
19884      can have different bounds.  */
19885   if (TREE_CODE (expression) == VAR_DECL
19886       && DECL_CLASS_SCOPE_P (expression)
19887       && dependent_type_p (DECL_CONTEXT (expression))
19888       && VAR_HAD_UNKNOWN_BOUND (expression))
19889     return true;
19890 
19891   if (TREE_TYPE (expression) == unknown_type_node)
19892     {
19893       if (TREE_CODE (expression) == ADDR_EXPR)
19894 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
19895       if (TREE_CODE (expression) == COMPONENT_REF
19896 	  || TREE_CODE (expression) == OFFSET_REF)
19897 	{
19898 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
19899 	    return true;
19900 	  expression = TREE_OPERAND (expression, 1);
19901 	  if (TREE_CODE (expression) == IDENTIFIER_NODE)
19902 	    return false;
19903 	}
19904       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
19905       if (TREE_CODE (expression) == SCOPE_REF)
19906 	return false;
19907 
19908       if (BASELINK_P (expression))
19909 	expression = BASELINK_FUNCTIONS (expression);
19910 
19911       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
19912 	{
19913 	  if (any_dependent_template_arguments_p
19914 	      (TREE_OPERAND (expression, 1)))
19915 	    return true;
19916 	  expression = TREE_OPERAND (expression, 0);
19917 	}
19918       gcc_assert (TREE_CODE (expression) == OVERLOAD
19919 		  || TREE_CODE (expression) == FUNCTION_DECL);
19920 
19921       while (expression)
19922 	{
19923 	  if (type_dependent_expression_p (OVL_CURRENT (expression)))
19924 	    return true;
19925 	  expression = OVL_NEXT (expression);
19926 	}
19927       return false;
19928     }
19929 
19930   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
19931 
19932   return (dependent_type_p (TREE_TYPE (expression)));
19933 }
19934 
19935 /* walk_tree callback function for instantiation_dependent_expression_p,
19936    below.  Returns non-zero if a dependent subexpression is found.  */
19937 
19938 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)19939 instantiation_dependent_r (tree *tp, int *walk_subtrees,
19940 			   void * /*data*/)
19941 {
19942   if (TYPE_P (*tp))
19943     {
19944       /* We don't have to worry about decltype currently because decltype
19945 	 of an instantiation-dependent expr is a dependent type.  This
19946 	 might change depending on the resolution of DR 1172.  */
19947       *walk_subtrees = false;
19948       return NULL_TREE;
19949     }
19950   enum tree_code code = TREE_CODE (*tp);
19951   switch (code)
19952     {
19953       /* Don't treat an argument list as dependent just because it has no
19954 	 TREE_TYPE.  */
19955     case TREE_LIST:
19956     case TREE_VEC:
19957       return NULL_TREE;
19958 
19959     case TEMPLATE_PARM_INDEX:
19960       return *tp;
19961 
19962       /* Handle expressions with type operands.  */
19963     case SIZEOF_EXPR:
19964     case ALIGNOF_EXPR:
19965     case TYPEID_EXPR:
19966     case AT_ENCODE_EXPR:
19967       {
19968 	tree op = TREE_OPERAND (*tp, 0);
19969 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
19970 	  op = TREE_TYPE (op);
19971 	if (TYPE_P (op))
19972 	  {
19973 	    if (dependent_type_p (op))
19974 	      return *tp;
19975 	    else
19976 	      {
19977 		*walk_subtrees = false;
19978 		return NULL_TREE;
19979 	      }
19980 	  }
19981 	break;
19982       }
19983 
19984     case TRAIT_EXPR:
19985       if (dependent_type_p (TRAIT_EXPR_TYPE1 (*tp))
19986 	  || (TRAIT_EXPR_TYPE2 (*tp)
19987 	      && dependent_type_p (TRAIT_EXPR_TYPE2 (*tp))))
19988 	return *tp;
19989       *walk_subtrees = false;
19990       return NULL_TREE;
19991 
19992     case COMPONENT_REF:
19993       if (TREE_CODE (TREE_OPERAND (*tp, 1)) == IDENTIFIER_NODE)
19994 	/* In a template, finish_class_member_access_expr creates a
19995 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
19996 	   type-dependent, so that we can check access control at
19997 	   instantiation time (PR 42277).  See also Core issue 1273.  */
19998 	return *tp;
19999       break;
20000 
20001     case SCOPE_REF:
20002       if (instantiation_dependent_scope_ref_p (*tp))
20003 	return *tp;
20004       else
20005 	break;
20006 
20007       /* Treat statement-expressions as dependent.  */
20008     case BIND_EXPR:
20009       return *tp;
20010 
20011     default:
20012       break;
20013     }
20014 
20015   if (type_dependent_expression_p (*tp))
20016     return *tp;
20017   else
20018     return NULL_TREE;
20019 }
20020 
20021 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
20022    sense defined by the ABI:
20023 
20024    "An expression is instantiation-dependent if it is type-dependent
20025    or value-dependent, or it has a subexpression that is type-dependent
20026    or value-dependent."  */
20027 
20028 bool
instantiation_dependent_expression_p(tree expression)20029 instantiation_dependent_expression_p (tree expression)
20030 {
20031   tree result;
20032 
20033   if (!processing_template_decl)
20034     return false;
20035 
20036   if (expression == error_mark_node)
20037     return false;
20038 
20039   result = cp_walk_tree_without_duplicates (&expression,
20040 					    instantiation_dependent_r, NULL);
20041   return result != NULL_TREE;
20042 }
20043 
20044 /* Like type_dependent_expression_p, but it also works while not processing
20045    a template definition, i.e. during substitution or mangling.  */
20046 
20047 bool
type_dependent_expression_p_push(tree expr)20048 type_dependent_expression_p_push (tree expr)
20049 {
20050   bool b;
20051   ++processing_template_decl;
20052   b = type_dependent_expression_p (expr);
20053   --processing_template_decl;
20054   return b;
20055 }
20056 
20057 /* Returns TRUE if ARGS contains a type-dependent expression.  */
20058 
20059 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)20060 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
20061 {
20062   unsigned int i;
20063   tree arg;
20064 
20065   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
20066     {
20067       if (type_dependent_expression_p (arg))
20068 	return true;
20069     }
20070   return false;
20071 }
20072 
20073 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
20074    expressions) contains any type-dependent expressions.  */
20075 
20076 bool
any_type_dependent_elements_p(const_tree list)20077 any_type_dependent_elements_p (const_tree list)
20078 {
20079   for (; list; list = TREE_CHAIN (list))
20080     if (value_dependent_expression_p (TREE_VALUE (list)))
20081       return true;
20082 
20083   return false;
20084 }
20085 
20086 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
20087    expressions) contains any value-dependent expressions.  */
20088 
20089 bool
any_value_dependent_elements_p(const_tree list)20090 any_value_dependent_elements_p (const_tree list)
20091 {
20092   for (; list; list = TREE_CHAIN (list))
20093     if (value_dependent_expression_p (TREE_VALUE (list)))
20094       return true;
20095 
20096   return false;
20097 }
20098 
20099 /* Returns TRUE if the ARG (a template argument) is dependent.  */
20100 
20101 bool
dependent_template_arg_p(tree arg)20102 dependent_template_arg_p (tree arg)
20103 {
20104   if (!processing_template_decl)
20105     return false;
20106 
20107   /* Assume a template argument that was wrongly written by the user
20108      is dependent. This is consistent with what
20109      any_dependent_template_arguments_p [that calls this function]
20110      does.  */
20111   if (!arg || arg == error_mark_node)
20112     return true;
20113 
20114   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
20115     arg = ARGUMENT_PACK_SELECT_ARG (arg);
20116 
20117   if (TREE_CODE (arg) == TEMPLATE_DECL
20118       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
20119     return dependent_template_p (arg);
20120   else if (ARGUMENT_PACK_P (arg))
20121     {
20122       tree args = ARGUMENT_PACK_ARGS (arg);
20123       int i, len = TREE_VEC_LENGTH (args);
20124       for (i = 0; i < len; ++i)
20125         {
20126           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
20127             return true;
20128         }
20129 
20130       return false;
20131     }
20132   else if (TYPE_P (arg))
20133     return dependent_type_p (arg);
20134   else
20135     return (type_dependent_expression_p (arg)
20136 	    || value_dependent_expression_p (arg));
20137 }
20138 
20139 /* Returns true if ARGS (a collection of template arguments) contains
20140    any types that require structural equality testing.  */
20141 
20142 bool
any_template_arguments_need_structural_equality_p(tree args)20143 any_template_arguments_need_structural_equality_p (tree args)
20144 {
20145   int i;
20146   int j;
20147 
20148   if (!args)
20149     return false;
20150   if (args == error_mark_node)
20151     return true;
20152 
20153   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
20154     {
20155       tree level = TMPL_ARGS_LEVEL (args, i + 1);
20156       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
20157 	{
20158 	  tree arg = TREE_VEC_ELT (level, j);
20159 	  tree packed_args = NULL_TREE;
20160 	  int k, len = 1;
20161 
20162 	  if (ARGUMENT_PACK_P (arg))
20163 	    {
20164 	      /* Look inside the argument pack.  */
20165 	      packed_args = ARGUMENT_PACK_ARGS (arg);
20166 	      len = TREE_VEC_LENGTH (packed_args);
20167 	    }
20168 
20169 	  for (k = 0; k < len; ++k)
20170 	    {
20171 	      if (packed_args)
20172 		arg = TREE_VEC_ELT (packed_args, k);
20173 
20174 	      if (error_operand_p (arg))
20175 		return true;
20176 	      else if (TREE_CODE (arg) == TEMPLATE_DECL
20177 		       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
20178 		continue;
20179 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
20180 		return true;
20181 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
20182 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
20183 		return true;
20184 	    }
20185 	}
20186     }
20187 
20188   return false;
20189 }
20190 
20191 /* Returns true if ARGS (a collection of template arguments) contains
20192    any dependent arguments.  */
20193 
20194 bool
any_dependent_template_arguments_p(const_tree args)20195 any_dependent_template_arguments_p (const_tree args)
20196 {
20197   int i;
20198   int j;
20199 
20200   if (!args)
20201     return false;
20202   if (args == error_mark_node)
20203     return true;
20204 
20205   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
20206     {
20207       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
20208       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
20209 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
20210 	  return true;
20211     }
20212 
20213   return false;
20214 }
20215 
20216 /* Returns TRUE if the template TMPL is dependent.  */
20217 
20218 bool
dependent_template_p(tree tmpl)20219 dependent_template_p (tree tmpl)
20220 {
20221   if (TREE_CODE (tmpl) == OVERLOAD)
20222     {
20223       while (tmpl)
20224 	{
20225 	  if (dependent_template_p (OVL_CURRENT (tmpl)))
20226 	    return true;
20227 	  tmpl = OVL_NEXT (tmpl);
20228 	}
20229       return false;
20230     }
20231 
20232   /* Template template parameters are dependent.  */
20233   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
20234       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
20235     return true;
20236   /* So are names that have not been looked up.  */
20237   if (TREE_CODE (tmpl) == SCOPE_REF
20238       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
20239     return true;
20240   /* So are member templates of dependent classes.  */
20241   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
20242     return dependent_type_p (DECL_CONTEXT (tmpl));
20243   return false;
20244 }
20245 
20246 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
20247 
20248 bool
dependent_template_id_p(tree tmpl,tree args)20249 dependent_template_id_p (tree tmpl, tree args)
20250 {
20251   return (dependent_template_p (tmpl)
20252 	  || any_dependent_template_arguments_p (args));
20253 }
20254 
20255 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
20256    is dependent.  */
20257 
20258 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)20259 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
20260 {
20261   int i;
20262 
20263   if (!processing_template_decl)
20264     return false;
20265 
20266   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
20267     {
20268       tree decl = TREE_VEC_ELT (declv, i);
20269       tree init = TREE_VEC_ELT (initv, i);
20270       tree cond = TREE_VEC_ELT (condv, i);
20271       tree incr = TREE_VEC_ELT (incrv, i);
20272 
20273       if (type_dependent_expression_p (decl))
20274 	return true;
20275 
20276       if (init && type_dependent_expression_p (init))
20277 	return true;
20278 
20279       if (type_dependent_expression_p (cond))
20280 	return true;
20281 
20282       if (COMPARISON_CLASS_P (cond)
20283 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
20284 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
20285 	return true;
20286 
20287       if (TREE_CODE (incr) == MODOP_EXPR)
20288 	{
20289 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
20290 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
20291 	    return true;
20292 	}
20293       else if (type_dependent_expression_p (incr))
20294 	return true;
20295       else if (TREE_CODE (incr) == MODIFY_EXPR)
20296 	{
20297 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
20298 	    return true;
20299 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
20300 	    {
20301 	      tree t = TREE_OPERAND (incr, 1);
20302 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
20303 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
20304 		return true;
20305 	    }
20306 	}
20307     }
20308 
20309   return false;
20310 }
20311 
20312 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
20313    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
20314    no such TYPE can be found.  Note that this function peers inside
20315    uninstantiated templates and therefore should be used only in
20316    extremely limited situations.  ONLY_CURRENT_P restricts this
20317    peering to the currently open classes hierarchy (which is required
20318    when comparing types).  */
20319 
20320 tree
resolve_typename_type(tree type,bool only_current_p)20321 resolve_typename_type (tree type, bool only_current_p)
20322 {
20323   tree scope;
20324   tree name;
20325   tree decl;
20326   int quals;
20327   tree pushed_scope;
20328   tree result;
20329 
20330   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
20331 
20332   scope = TYPE_CONTEXT (type);
20333   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
20334      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
20335      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
20336      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
20337      identifier  of the TYPENAME_TYPE anymore.
20338      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
20339      TYPENAME_TYPE instead, we avoid messing up with a possible
20340      typedef variant case.  */
20341   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
20342 
20343   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
20344      it first before we can figure out what NAME refers to.  */
20345   if (TREE_CODE (scope) == TYPENAME_TYPE)
20346     {
20347       if (TYPENAME_IS_RESOLVING_P (scope))
20348 	/* Given a class template A with a dependent base with nested type C,
20349 	   typedef typename A::C::C C will land us here, as trying to resolve
20350 	   the initial A::C leads to the local C typedef, which leads back to
20351 	   A::C::C.  So we break the recursion now.  */
20352 	return type;
20353       else
20354 	scope = resolve_typename_type (scope, only_current_p);
20355     }
20356   /* If we don't know what SCOPE refers to, then we cannot resolve the
20357      TYPENAME_TYPE.  */
20358   if (TREE_CODE (scope) == TYPENAME_TYPE)
20359     return type;
20360   /* If the SCOPE is a template type parameter, we have no way of
20361      resolving the name.  */
20362   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
20363     return type;
20364   /* If the SCOPE is not the current instantiation, there's no reason
20365      to look inside it.  */
20366   if (only_current_p && !currently_open_class (scope))
20367     return type;
20368   /* If this is a typedef, we don't want to look inside (c++/11987).  */
20369   if (typedef_variant_p (type))
20370     return type;
20371   /* If SCOPE isn't the template itself, it will not have a valid
20372      TYPE_FIELDS list.  */
20373   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
20374     /* scope is either the template itself or a compatible instantiation
20375        like X<T>, so look up the name in the original template.  */
20376     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
20377   else
20378     /* scope is a partial instantiation, so we can't do the lookup or we
20379        will lose the template arguments.  */
20380     return type;
20381   /* Enter the SCOPE so that name lookup will be resolved as if we
20382      were in the class definition.  In particular, SCOPE will no
20383      longer be considered a dependent type.  */
20384   pushed_scope = push_scope (scope);
20385   /* Look up the declaration.  */
20386   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
20387 			tf_warning_or_error);
20388 
20389   result = NULL_TREE;
20390 
20391   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
20392      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
20393   if (!decl)
20394     /*nop*/;
20395   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
20396 	   && TREE_CODE (decl) == TYPE_DECL)
20397     {
20398       result = TREE_TYPE (decl);
20399       if (result == error_mark_node)
20400 	result = NULL_TREE;
20401     }
20402   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
20403 	   && DECL_CLASS_TEMPLATE_P (decl))
20404     {
20405       tree tmpl;
20406       tree args;
20407       /* Obtain the template and the arguments.  */
20408       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
20409       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
20410       /* Instantiate the template.  */
20411       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
20412 				      /*entering_scope=*/0,
20413 				      tf_error | tf_user);
20414       if (result == error_mark_node)
20415 	result = NULL_TREE;
20416     }
20417 
20418   /* Leave the SCOPE.  */
20419   if (pushed_scope)
20420     pop_scope (pushed_scope);
20421 
20422   /* If we failed to resolve it, return the original typename.  */
20423   if (!result)
20424     return type;
20425 
20426   /* If lookup found a typename type, resolve that too.  */
20427   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
20428     {
20429       /* Ill-formed programs can cause infinite recursion here, so we
20430 	 must catch that.  */
20431       TYPENAME_IS_RESOLVING_P (type) = 1;
20432       result = resolve_typename_type (result, only_current_p);
20433       TYPENAME_IS_RESOLVING_P (type) = 0;
20434     }
20435 
20436   /* Qualify the resulting type.  */
20437   quals = cp_type_quals (type);
20438   if (quals)
20439     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
20440 
20441   return result;
20442 }
20443 
20444 /* EXPR is an expression which is not type-dependent.  Return a proxy
20445    for EXPR that can be used to compute the types of larger
20446    expressions containing EXPR.  */
20447 
20448 tree
build_non_dependent_expr(tree expr)20449 build_non_dependent_expr (tree expr)
20450 {
20451   tree inner_expr;
20452 
20453 #ifdef ENABLE_CHECKING
20454   /* Try to get a constant value for all non-dependent expressions in
20455       order to expose bugs in *_dependent_expression_p and constexpr.  */
20456   if (cxx_dialect >= cxx0x
20457       && !instantiation_dependent_expression_p (expr))
20458     maybe_constant_value (fold_non_dependent_expr_sfinae (expr, tf_none));
20459 #endif
20460 
20461   /* Preserve OVERLOADs; the functions must be available to resolve
20462      types.  */
20463   inner_expr = expr;
20464   if (TREE_CODE (inner_expr) == STMT_EXPR)
20465     inner_expr = stmt_expr_value_expr (inner_expr);
20466   if (TREE_CODE (inner_expr) == ADDR_EXPR)
20467     inner_expr = TREE_OPERAND (inner_expr, 0);
20468   if (TREE_CODE (inner_expr) == COMPONENT_REF)
20469     inner_expr = TREE_OPERAND (inner_expr, 1);
20470   if (is_overloaded_fn (inner_expr)
20471       || TREE_CODE (inner_expr) == OFFSET_REF)
20472     return expr;
20473   /* There is no need to return a proxy for a variable.  */
20474   if (TREE_CODE (expr) == VAR_DECL)
20475     return expr;
20476   /* Preserve string constants; conversions from string constants to
20477      "char *" are allowed, even though normally a "const char *"
20478      cannot be used to initialize a "char *".  */
20479   if (TREE_CODE (expr) == STRING_CST)
20480     return expr;
20481   /* Preserve arithmetic constants, as an optimization -- there is no
20482      reason to create a new node.  */
20483   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
20484     return expr;
20485   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
20486      There is at least one place where we want to know that a
20487      particular expression is a throw-expression: when checking a ?:
20488      expression, there are special rules if the second or third
20489      argument is a throw-expression.  */
20490   if (TREE_CODE (expr) == THROW_EXPR)
20491     return expr;
20492 
20493   /* Don't wrap an initializer list, we need to be able to look inside.  */
20494   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
20495     return expr;
20496 
20497   /* Don't wrap a dummy object, we need to be able to test for it.  */
20498   if (is_dummy_object (expr))
20499     return expr;
20500 
20501   if (TREE_CODE (expr) == COND_EXPR)
20502     return build3 (COND_EXPR,
20503 		   TREE_TYPE (expr),
20504 		   TREE_OPERAND (expr, 0),
20505 		   (TREE_OPERAND (expr, 1)
20506 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
20507 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
20508 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
20509   if (TREE_CODE (expr) == COMPOUND_EXPR
20510       && !COMPOUND_EXPR_OVERLOADED (expr))
20511     return build2 (COMPOUND_EXPR,
20512 		   TREE_TYPE (expr),
20513 		   TREE_OPERAND (expr, 0),
20514 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
20515 
20516   /* If the type is unknown, it can't really be non-dependent */
20517   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
20518 
20519   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
20520   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
20521 }
20522 
20523 /* ARGS is a vector of expressions as arguments to a function call.
20524    Replace the arguments with equivalent non-dependent expressions.
20525    This modifies ARGS in place.  */
20526 
20527 void
make_args_non_dependent(vec<tree,va_gc> * args)20528 make_args_non_dependent (vec<tree, va_gc> *args)
20529 {
20530   unsigned int ix;
20531   tree arg;
20532 
20533   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
20534     {
20535       tree newarg = build_non_dependent_expr (arg);
20536       if (newarg != arg)
20537 	(*args)[ix] = newarg;
20538     }
20539 }
20540 
20541 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
20542    with a level one deeper than the actual template parms.  */
20543 
20544 tree
make_auto(void)20545 make_auto (void)
20546 {
20547   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
20548   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
20549 			       TYPE_DECL, get_identifier ("auto"), au);
20550   TYPE_STUB_DECL (au) = TYPE_NAME (au);
20551   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
20552     (0, processing_template_decl + 1, processing_template_decl + 1,
20553      TYPE_NAME (au), NULL_TREE);
20554   TYPE_CANONICAL (au) = canonical_type_parameter (au);
20555   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
20556   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
20557 
20558   return au;
20559 }
20560 
20561 /* Given type ARG, return std::initializer_list<ARG>.  */
20562 
20563 static tree
listify(tree arg)20564 listify (tree arg)
20565 {
20566   tree std_init_list = namespace_binding
20567     (get_identifier ("initializer_list"), std_node);
20568   tree argvec;
20569   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
20570     {
20571       error ("deducing from brace-enclosed initializer list requires "
20572 	     "#include <initializer_list>");
20573       return error_mark_node;
20574     }
20575   argvec = make_tree_vec (1);
20576   TREE_VEC_ELT (argvec, 0) = arg;
20577   return lookup_template_class (std_init_list, argvec, NULL_TREE,
20578 				NULL_TREE, 0, tf_warning_or_error);
20579 }
20580 
20581 /* Replace auto in TYPE with std::initializer_list<auto>.  */
20582 
20583 static tree
listify_autos(tree type,tree auto_node)20584 listify_autos (tree type, tree auto_node)
20585 {
20586   tree init_auto = listify (auto_node);
20587   tree argvec = make_tree_vec (1);
20588   TREE_VEC_ELT (argvec, 0) = init_auto;
20589   if (processing_template_decl)
20590     argvec = add_to_template_args (current_template_args (), argvec);
20591   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
20592 }
20593 
20594 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
20595    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
20596 
20597 tree
do_auto_deduction(tree type,tree init,tree auto_node)20598 do_auto_deduction (tree type, tree init, tree auto_node)
20599 {
20600   tree parms, tparms, targs;
20601   tree args[1];
20602   int val;
20603 
20604   if (init == error_mark_node)
20605     return error_mark_node;
20606 
20607   if (type_dependent_expression_p (init))
20608     /* Defining a subset of type-dependent expressions that we can deduce
20609        from ahead of time isn't worth the trouble.  */
20610     return type;
20611 
20612   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
20613      with either a new invented type template parameter U or, if the
20614      initializer is a braced-init-list (8.5.4), with
20615      std::initializer_list<U>.  */
20616   if (BRACE_ENCLOSED_INITIALIZER_P (init))
20617     type = listify_autos (type, auto_node);
20618 
20619   init = resolve_nondeduced_context (init);
20620 
20621   parms = build_tree_list (NULL_TREE, type);
20622   args[0] = init;
20623   tparms = make_tree_vec (1);
20624   targs = make_tree_vec (1);
20625   TREE_VEC_ELT (tparms, 0)
20626     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
20627   val = type_unification_real (tparms, targs, parms, args, 1, 0,
20628 			       DEDUCE_CALL, LOOKUP_NORMAL,
20629 			       /*explain_p=*/false);
20630   if (val > 0)
20631     {
20632       if (processing_template_decl)
20633 	/* Try again at instantiation time.  */
20634 	return type;
20635       if (type && type != error_mark_node)
20636 	/* If type is error_mark_node a diagnostic must have been
20637 	   emitted by now.  Also, having a mention to '<type error>'
20638 	   in the diagnostic is not really useful to the user.  */
20639 	{
20640 	  if (cfun && auto_node == current_function_auto_return_pattern
20641 	      && LAMBDA_FUNCTION_P (current_function_decl))
20642 	    error ("unable to deduce lambda return type from %qE", init);
20643 	  else
20644 	    error ("unable to deduce %qT from %qE", type, init);
20645 	}
20646       return error_mark_node;
20647     }
20648 
20649   /* If the list of declarators contains more than one declarator, the type
20650      of each declared variable is determined as described above. If the
20651      type deduced for the template parameter U is not the same in each
20652      deduction, the program is ill-formed.  */
20653   if (TREE_TYPE (auto_node)
20654       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
20655     {
20656       if (cfun && auto_node == current_function_auto_return_pattern
20657 	  && LAMBDA_FUNCTION_P (current_function_decl))
20658 	error ("inconsistent types %qT and %qT deduced for "
20659 	       "lambda return type", TREE_TYPE (auto_node),
20660 	       TREE_VEC_ELT (targs, 0));
20661       else
20662 	error ("inconsistent deduction for %qT: %qT and then %qT",
20663 	       auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
20664       return error_mark_node;
20665     }
20666   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
20667 
20668   if (processing_template_decl)
20669     targs = add_to_template_args (current_template_args (), targs);
20670   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
20671 }
20672 
20673 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
20674    result.  */
20675 
20676 tree
splice_late_return_type(tree type,tree late_return_type)20677 splice_late_return_type (tree type, tree late_return_type)
20678 {
20679   tree argvec;
20680 
20681   if (late_return_type == NULL_TREE)
20682     return type;
20683   argvec = make_tree_vec (1);
20684   TREE_VEC_ELT (argvec, 0) = late_return_type;
20685   if (processing_template_parmlist)
20686     /* For a late-specified return type in a template type-parameter, we
20687        need to add a dummy argument level for its parmlist.  */
20688     argvec = add_to_template_args
20689       (make_tree_vec (processing_template_parmlist), argvec);
20690   if (current_template_parms)
20691     argvec = add_to_template_args (current_template_args (), argvec);
20692   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
20693 }
20694 
20695 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
20696 
20697 bool
is_auto(const_tree type)20698 is_auto (const_tree type)
20699 {
20700   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
20701       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
20702     return true;
20703   else
20704     return false;
20705 }
20706 
20707 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
20708    appear as a type-specifier for the declaration in question, we don't
20709    have to look through the whole type.  */
20710 
20711 tree
type_uses_auto(tree type)20712 type_uses_auto (tree type)
20713 {
20714   enum tree_code code;
20715   if (is_auto (type))
20716     return type;
20717 
20718   code = TREE_CODE (type);
20719 
20720   if (code == POINTER_TYPE || code == REFERENCE_TYPE
20721       || code == OFFSET_TYPE || code == FUNCTION_TYPE
20722       || code == METHOD_TYPE || code == ARRAY_TYPE)
20723     return type_uses_auto (TREE_TYPE (type));
20724 
20725   if (TYPE_PTRMEMFUNC_P (type))
20726     return type_uses_auto (TREE_TYPE (TREE_TYPE
20727 				   (TYPE_PTRMEMFUNC_FN_TYPE (type))));
20728 
20729   return NULL_TREE;
20730 }
20731 
20732 /* For a given template T, return the vector of typedefs referenced
20733    in T for which access check is needed at T instantiation time.
20734    T is either  a FUNCTION_DECL or a RECORD_TYPE.
20735    Those typedefs were added to T by the function
20736    append_type_to_template_for_access_check.  */
20737 
20738 vec<qualified_typedef_usage_t, va_gc> *
get_types_needing_access_check(tree t)20739 get_types_needing_access_check (tree t)
20740 {
20741   tree ti;
20742   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
20743 
20744   if (!t || t == error_mark_node)
20745     return NULL;
20746 
20747   if (!(ti = get_template_info (t)))
20748     return NULL;
20749 
20750   if (CLASS_TYPE_P (t)
20751       || TREE_CODE (t) == FUNCTION_DECL)
20752     {
20753       if (!TI_TEMPLATE (ti))
20754 	return NULL;
20755 
20756       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
20757     }
20758 
20759   return result;
20760 }
20761 
20762 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
20763    tied to T. That list of typedefs will be access checked at
20764    T instantiation time.
20765    T is either a FUNCTION_DECL or a RECORD_TYPE.
20766    TYPE_DECL is a TYPE_DECL node representing a typedef.
20767    SCOPE is the scope through which TYPE_DECL is accessed.
20768    LOCATION is the location of the usage point of TYPE_DECL.
20769 
20770    This function is a subroutine of
20771    append_type_to_template_for_access_check.  */
20772 
20773 static void
append_type_to_template_for_access_check_1(tree t,tree type_decl,tree scope,location_t location)20774 append_type_to_template_for_access_check_1 (tree t,
20775 					    tree type_decl,
20776 					    tree scope,
20777 					    location_t location)
20778 {
20779   qualified_typedef_usage_t typedef_usage;
20780   tree ti;
20781 
20782   if (!t || t == error_mark_node)
20783     return;
20784 
20785   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
20786 	       || CLASS_TYPE_P (t))
20787 	      && type_decl
20788 	      && TREE_CODE (type_decl) == TYPE_DECL
20789 	      && scope);
20790 
20791   if (!(ti = get_template_info (t)))
20792     return;
20793 
20794   gcc_assert (TI_TEMPLATE (ti));
20795 
20796   typedef_usage.typedef_decl = type_decl;
20797   typedef_usage.context = scope;
20798   typedef_usage.locus = location;
20799 
20800   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
20801 }
20802 
20803 /* Append TYPE_DECL to the template TEMPL.
20804    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
20805    At TEMPL instanciation time, TYPE_DECL will be checked to see
20806    if it can be accessed through SCOPE.
20807    LOCATION is the location of the usage point of TYPE_DECL.
20808 
20809    e.g. consider the following code snippet:
20810 
20811      class C
20812      {
20813        typedef int myint;
20814      };
20815 
20816      template<class U> struct S
20817      {
20818        C::myint mi; // <-- usage point of the typedef C::myint
20819      };
20820 
20821      S<char> s;
20822 
20823    At S<char> instantiation time, we need to check the access of C::myint
20824    In other words, we need to check the access of the myint typedef through
20825    the C scope. For that purpose, this function will add the myint typedef
20826    and the scope C through which its being accessed to a list of typedefs
20827    tied to the template S. That list will be walked at template instantiation
20828    time and access check performed on each typedefs it contains.
20829    Note that this particular code snippet should yield an error because
20830    myint is private to C.  */
20831 
20832 void
append_type_to_template_for_access_check(tree templ,tree type_decl,tree scope,location_t location)20833 append_type_to_template_for_access_check (tree templ,
20834                                           tree type_decl,
20835 					  tree scope,
20836 					  location_t location)
20837 {
20838   qualified_typedef_usage_t *iter;
20839   unsigned i;
20840 
20841   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
20842 
20843   /* Make sure we don't append the type to the template twice.  */
20844   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
20845     if (iter->typedef_decl == type_decl && scope == iter->context)
20846       return;
20847 
20848   append_type_to_template_for_access_check_1 (templ, type_decl,
20849 					      scope, location);
20850 }
20851 
20852 /* Set up the hash tables for template instantiations.  */
20853 
20854 void
init_template_processing(void)20855 init_template_processing (void)
20856 {
20857   decl_specializations = htab_create_ggc (37,
20858 					  hash_specialization,
20859 					  eq_specializations,
20860 					  ggc_free);
20861   type_specializations = htab_create_ggc (37,
20862 					  hash_specialization,
20863 					  eq_specializations,
20864 					  ggc_free);
20865 }
20866 
20867 /* Print stats about the template hash tables for -fstats.  */
20868 
20869 void
print_template_statistics(void)20870 print_template_statistics (void)
20871 {
20872   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
20873 	   "%f collisions\n", (long) htab_size (decl_specializations),
20874 	   (long) htab_elements (decl_specializations),
20875 	   htab_collisions (decl_specializations));
20876   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
20877 	   "%f collisions\n", (long) htab_size (type_specializations),
20878 	   (long) htab_elements (type_specializations),
20879 	   htab_collisions (type_specializations));
20880 }
20881 
20882 #include "gt-cp-pt.h"
20883