pt.c 289 KB
Newer Older
mrs's avatar
mrs committed
1
/* Handle parameterized types (templates) for GNU C++.
2 3
   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000
   Free Software Foundation, Inc.
mrs's avatar
mrs committed
4
   Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
mrs's avatar
mrs committed
5
   Rewritten by Jason Merrill (jason@cygnus.com).
mrs's avatar
mrs committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

This file is part of GNU CC.

GNU CC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU CC is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU CC; see the file COPYING.  If not, write to
kenner's avatar
kenner committed
21 22
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */
mrs's avatar
mrs committed
23 24

/* Known bugs or deficiencies include:
mrs's avatar
mrs committed
25 26 27

     all methods must be provided in header files; can't use a source
     file that contains only the method templates and "just win".  */
mrs's avatar
mrs committed
28 29

#include "config.h"
30
#include "system.h"
mrs's avatar
mrs committed
31 32 33 34 35 36 37
#include "obstack.h"

#include "tree.h"
#include "flags.h"
#include "cp-tree.h"
#include "decl.h"
#include "parse.h"
mrs's avatar
mrs committed
38
#include "lex.h"
mrs's avatar
mrs committed
39
#include "output.h"
mrs's avatar
mrs committed
40
#include "defaults.h"
41
#include "except.h"
42
#include "toplev.h"
43
#include "rtl.h"
44
#include "defaults.h"
mmitchel's avatar
mmitchel committed
45
#include "ggc.h"
46
#include "hashtab.h"
47

48 49
/* The type of functions taking a tree, and some additional data, and
   returning an int.  */
ghazi's avatar
ghazi committed
50
typedef int (*tree_fn_t) PARAMS ((tree, void*));
51

mrs's avatar
mrs committed
52 53 54 55 56
extern struct obstack permanent_obstack;

extern int lineno;
extern char *input_filename;

57 58 59 60 61 62 63 64
/* The PENDING_TEMPLATES is a TREE_LIST of templates whose
   instantiations have been deferred, either because their definitions
   were not yet available, or because we were putting off doing the
   work.  The TREE_PURPOSE of each entry is a SRCLOC indicating where
   the instantiate request occurred; the TREE_VALUE is a either a DECL
   (for a function or static data member), or a TYPE (for a class)
   indicating what we are hoping to instantiate.  */
static tree pending_templates;
mrs's avatar
mrs committed
65 66
static tree *template_tail = &pending_templates;

67
static tree maybe_templates;
mrs's avatar
mrs committed
68 69
static tree *maybe_template_tail = &maybe_templates;

70
int processing_template_parmlist;
71 72
static int template_header_count;

73
static tree saved_trees;
74 75
static varray_type inline_parm_levels;
static size_t inline_parm_levels_used;
76

77 78 79 80 81
/* A map from local variable declarations in the body of the template
   presently being instantiated to the corresponding instantiated
   local variables.  */
static htab_t local_specializations;

mrs's avatar
mrs committed
82 83 84
#define obstack_chunk_alloc xmalloc
#define obstack_chunk_free free

85 86 87 88
#define UNIFY_ALLOW_NONE 0
#define UNIFY_ALLOW_MORE_CV_QUAL 1
#define UNIFY_ALLOW_LESS_CV_QUAL 2
#define UNIFY_ALLOW_DERIVED 4
89
#define UNIFY_ALLOW_INTEGER 8
90

91 92 93 94 95 96
#define GTB_VIA_VIRTUAL 1 /* The base class we are examining is
			     virtual, or a base class of a virtual
			     base.  */
#define GTB_IGNORE_TYPE 2 /* We don't need to try to unify the current
			     type with the desired type.  */

ghazi's avatar
ghazi committed
97
static int resolve_overloaded_unification PARAMS ((tree, tree, tree, tree,
98
						 unification_kind_t, int));
ghazi's avatar
ghazi committed
99
static int try_one_overload PARAMS ((tree, tree, tree, tree, tree,
100
				   unification_kind_t, int));
ghazi's avatar
ghazi committed
101 102 103 104 105 106 107 108 109 110 111 112 113
static int unify PARAMS ((tree, tree, tree, tree, int));
static void add_pending_template PARAMS ((tree));
static int push_tinst_level PARAMS ((tree));
static tree classtype_mangled_name PARAMS ((tree));
static char *mangle_class_name_for_template PARAMS ((char *, tree, tree));
static tree tsubst_expr_values PARAMS ((tree, tree));
static int list_eq PARAMS ((tree, tree));
static tree get_class_bindings PARAMS ((tree, tree, tree));
static tree coerce_template_parms PARAMS ((tree, tree, tree, int, int));
static void tsubst_enum	PARAMS ((tree, tree, tree));
static tree add_to_template_args PARAMS ((tree, tree));
static tree add_outermost_template_args PARAMS ((tree, tree));
static void maybe_adjust_types_for_deduction PARAMS ((unification_kind_t, tree*,
114
						    tree*)); 
ghazi's avatar
ghazi committed
115
static int  type_unification_real PARAMS ((tree, tree, tree, tree,
116
					 int, unification_kind_t, int));
ghazi's avatar
ghazi committed
117 118 119 120
static void note_template_header PARAMS ((int));
static tree maybe_fold_nontype_arg PARAMS ((tree));
static tree convert_nontype_argument PARAMS ((tree, tree));
static tree convert_template_argument PARAMS ((tree, tree, tree, int,
121
					      int , tree));
ghazi's avatar
ghazi committed
122 123 124 125 126 127
static tree get_bindings_overload PARAMS ((tree, tree, tree));
static int for_each_template_parm PARAMS ((tree, tree_fn_t, void*));
static tree build_template_parm_index PARAMS ((int, int, int, tree, tree));
static int inline_needs_template_parms PARAMS ((tree));
static void push_inline_template_parms_recursive PARAMS ((tree, int));
static tree retrieve_specialization PARAMS ((tree, tree));
128
static tree retrieve_local_specialization PARAMS ((tree));
ghazi's avatar
ghazi committed
129
static tree register_specialization PARAMS ((tree, tree, tree));
130
static tree register_local_specialization PARAMS ((tree, tree));
ghazi's avatar
ghazi committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
static int unregister_specialization PARAMS ((tree, tree));
static tree reduce_template_parm_level PARAMS ((tree, tree, int));
static tree build_template_decl PARAMS ((tree, tree));
static int mark_template_parm PARAMS ((tree, void *));
static tree tsubst_friend_function PARAMS ((tree, tree));
static tree tsubst_friend_class PARAMS ((tree, tree));
static tree get_bindings_real PARAMS ((tree, tree, tree, int));
static int template_decl_level PARAMS ((tree));
static tree maybe_get_template_decl_from_type_decl PARAMS ((tree));
static int check_cv_quals_for_unify PARAMS ((int, tree, tree));
static tree tsubst_template_arg_vector PARAMS ((tree, tree, int));
static tree tsubst_template_parms PARAMS ((tree, tree, int));
static void regenerate_decl_from_template PARAMS ((tree, tree));
static tree most_specialized PARAMS ((tree, tree, tree));
static tree most_specialized_class PARAMS ((tree, tree));
static void set_mangled_name_for_template_decl PARAMS ((tree));
static int template_class_depth_real PARAMS ((tree, int));
static tree tsubst_aggr_type PARAMS ((tree, tree, int, tree, int));
static tree tsubst_decl PARAMS ((tree, tree, tree, tree));
static tree tsubst_arg_types PARAMS ((tree, tree, int, tree));
static tree tsubst_function_type PARAMS ((tree, tree, int, tree));
static void check_specialization_scope PARAMS ((void));
static tree process_partial_specialization PARAMS ((tree));
static void set_current_access_from_decl PARAMS ((tree));
static void check_default_tmpl_args PARAMS ((tree, tree, int, int));
static tree tsubst_call_declarator_parms PARAMS ((tree, tree, int, tree));
static tree get_template_base_recursive PARAMS ((tree, tree,
158
					       tree, tree, tree, int)); 
ghazi's avatar
ghazi committed
159 160 161
static tree get_template_base PARAMS ((tree, tree, tree, tree));
static tree try_class_unification PARAMS ((tree, tree, tree, tree));
static int coerce_template_template_parms PARAMS ((tree, tree, int,
162
						 tree, tree));
ghazi's avatar
ghazi committed
163 164 165 166 167
static tree determine_specialization PARAMS ((tree, tree, tree *, int));
static int template_args_equal PARAMS ((tree, tree));
static void print_template_context PARAMS ((int));
static void tsubst_default_arguments PARAMS ((tree));
static tree for_each_template_parm_r PARAMS ((tree *, int *, void *));
168
static tree instantiate_clone PARAMS ((tree, tree));
169

mmitchel's avatar
mmitchel committed
170 171 172 173 174 175 176 177 178 179
/* Called once to initialize pt.c.  */

void
init_pt ()
{
  ggc_add_tree_root (&pending_templates, 1);
  ggc_add_tree_root (&maybe_templates, 1);
  ggc_add_tree_root (&saved_trees, 1);
}

180 181 182 183 184 185
/* Do any processing required when DECL (a member template declaration
   using TEMPLATE_PARAMETERS as its innermost parameter list) is
   finished.  Returns the TEMPLATE_DECL corresponding to DECL, unless
   it is a specialization, in which case the DECL itself is returned.  */

tree
186
finish_member_template_decl (decl)
187 188
  tree decl;
{
189 190
  if (decl == NULL_TREE || decl == void_type_node)
    return NULL_TREE;
191 192 193 194
  else if (decl == error_mark_node)
    /* By returning NULL_TREE, the parser will just ignore this
       declaration.  We have already issued the error.  */
    return NULL_TREE;
195 196
  else if (TREE_CODE (decl) == TREE_LIST)
    {
jason's avatar
comment  
jason committed
197
      /* Assume that the class is the only declspec.  */
198
      decl = TREE_VALUE (decl);
199
      if (IS_AGGR_TYPE (decl) && CLASSTYPE_TEMPLATE_INFO (decl)
mmitchel's avatar
mmitchel committed
200
	  && ! CLASSTYPE_TEMPLATE_SPECIALIZATION (decl))
201 202 203 204 205
	{
	  tree tmpl = CLASSTYPE_TI_TEMPLATE (decl);
	  check_member_template (tmpl);
	  return tmpl;
	}
206
      return NULL_TREE;
207
    }
208 209
  else if (TREE_CODE (decl) == FIELD_DECL)
    cp_error ("data member `%D' cannot be a member template", decl);
210
  else if (DECL_TEMPLATE_INFO (decl))
211
    {
212 213 214 215 216 217 218 219 220
      if (!DECL_TEMPLATE_SPECIALIZATION (decl))
	{
	  check_member_template (DECL_TI_TEMPLATE (decl));
	  return DECL_TI_TEMPLATE (decl);
	}
      else
	return decl;
    } 
  else
jason's avatar
jason committed
221
    cp_error ("invalid member template declaration `%D'", decl);
222

223
  return error_mark_node;
jason's avatar
jason committed
224
}
225

jason's avatar
jason committed
226 227 228 229 230 231 232 233 234 235
/* Returns the template nesting level of the indicated class TYPE.
   
   For example, in:
     template <class T>
     struct A
     {
       template <class U>
       struct B {};
     };

236 237 238 239 240 241 242 243
   A<T>::B<U> has depth two, while A<T> has depth one.  
   Both A<T>::B<int> and A<int>::B<U> have depth one, if
   COUNT_SPECIALIZATIONS is 0 or if they are instantiations, not
   specializations.  

   This function is guaranteed to return 0 if passed NULL_TREE so
   that, for example, `template_class_depth (current_class_type)' is
   always safe.  */
jason's avatar
jason committed
244

245
static int 
246
template_class_depth_real (type, count_specializations)
jason's avatar
jason committed
247
     tree type;
248
     int count_specializations;
jason's avatar
jason committed
249
{
250
  int depth;
jason's avatar
jason committed
251

jason's avatar
jason committed
252
  for (depth = 0; 
253 254
       type && TREE_CODE (type) != NAMESPACE_DECL;
       type = (TREE_CODE (type) == FUNCTION_DECL) 
255
	 ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
256 257 258 259 260 261
    {
      if (TREE_CODE (type) != FUNCTION_DECL)
	{
	  if (CLASSTYPE_TEMPLATE_INFO (type)
	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type))
	      && ((count_specializations
mmitchel's avatar
mmitchel committed
262
		   && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
263 264 265 266 267 268 269 270 271 272 273 274 275
		  || uses_template_parms (CLASSTYPE_TI_ARGS (type))))
	    ++depth;
	}
      else 
	{
	  if (DECL_TEMPLATE_INFO (type)
	      && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (type))
	      && ((count_specializations
		   && DECL_TEMPLATE_SPECIALIZATION (type))
		  || uses_template_parms (DECL_TI_ARGS (type))))
	    ++depth;
	}
    }
jason's avatar
jason committed
276 277

  return depth;
278
}
279

280 281 282 283 284 285 286 287 288 289 290
/* Returns the template nesting level of the indicated class TYPE.
   Like template_class_depth_real, but instantiations do not count in
   the depth.  */

int 
template_class_depth (type)
     tree type;
{
  return template_class_depth_real (type, /*count_specializations=*/0);
}

291 292 293 294 295 296 297 298 299
/* Returns 1 if processing DECL as part of do_pending_inlines
   needs us to push template parms.  */

static int
inline_needs_template_parms (decl)
     tree decl;
{
  if (! DECL_TEMPLATE_INFO (decl))
    return 0;
jason's avatar
jason committed
300

301
  return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
}

/* Subroutine of maybe_begin_member_template_processing.
   Push the template parms in PARMS, starting from LEVELS steps into the
   chain, and ending at the beginning, since template parms are listed
   innermost first.  */

static void
push_inline_template_parms_recursive (parmlist, levels)
     tree parmlist;
     int levels;
{
  tree parms = TREE_VALUE (parmlist);
  int i;

  if (levels > 1)
    push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
320

321
  ++processing_template_decl;
322
  current_template_parms
323 324
    = tree_cons (build_int_2 (0, processing_template_decl),
		 parms, current_template_parms);
325 326
  TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;

327
  pushlevel (0);
328 329
  for (i = 0; i < TREE_VEC_LENGTH (parms); ++i) 
    {
330
      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
331
      my_friendly_assert (DECL_P (parm), 0);
332

333 334
      switch (TREE_CODE (parm))
	{
335
	case TYPE_DECL:
336
	case TEMPLATE_DECL:
337 338
	  pushdecl (parm);
	  break;
339 340 341

	case PARM_DECL:
	  {
342 343 344 345
	    /* Make a CONST_DECL as is done in process_template_parm.
	       It is ugly that we recreate this here; the original
	       version built in process_template_parm is no longer
	       available.  */
346 347
	    tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
				    TREE_TYPE (parm));
348
	    SET_DECL_ARTIFICIAL (decl);
349
	    DECL_INITIAL (decl) = DECL_INITIAL (parm);
350
	    SET_DECL_TEMPLATE_PARM_P (decl);
351 352
	    pushdecl (decl);
	  }
353
	  break;
354

355 356 357 358 359 360
	default:
	  my_friendly_abort (0);
	}
    }
}

361 362 363 364 365 366 367 368
/* Restore the template parameter context for a member template or
   a friend template defined in a class definition.  */

void
maybe_begin_member_template_processing (decl)
     tree decl;
{
  tree parms;
369
  int levels = 0;
370

371 372 373 374
  if (inline_needs_template_parms (decl))
    {
      parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
      levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
375

376 377 378 379 380
      if (DECL_TEMPLATE_SPECIALIZATION (decl))
	{
	  --levels;
	  parms = TREE_CHAIN (parms);
	}
381

382
      push_inline_template_parms_recursive (parms, levels);
383 384
    }

385 386 387 388 389 390 391 392
  /* Remember how many levels of template parameters we pushed so that
     we can pop them later.  */
  if (!inline_parm_levels)
    VARRAY_INT_INIT (inline_parm_levels, 4, "inline_parm_levels");
  if (inline_parm_levels_used == inline_parm_levels->num_elements)
    VARRAY_GROW (inline_parm_levels, 2 * inline_parm_levels_used);
  VARRAY_INT (inline_parm_levels, inline_parm_levels_used) = levels;
  ++inline_parm_levels_used;
393 394
}

395 396 397
/* Undo the effects of begin_member_template_processing. */

void 
ghazi's avatar
ghazi committed
398
maybe_end_member_template_processing ()
399
{
400 401 402
  int i;

  if (!inline_parm_levels_used)
403 404
    return;

405 406 407 408
  --inline_parm_levels_used;
  for (i = 0; 
       i < VARRAY_INT (inline_parm_levels, inline_parm_levels_used);
       ++i) 
409 410 411 412 413
    {
      --processing_template_decl;
      current_template_parms = TREE_CHAIN (current_template_parms);
      poplevel (0, 0, 0);
    }
414 415
}

416
/* Returns non-zero iff T is a member template function.  We must be
jason's avatar
jason committed
417
   careful as in
418 419 420 421 422 423 424 425 426 427

     template <class T> class C { void f(); }

   Here, f is a template function, and a member, but not a member
   template.  This function does not concern itself with the origin of
   T, only its present state.  So if we have 

     template <class T> class C { template <class U> void f(U); }

   then neither C<int>::f<char> nor C<T>::f<double> is considered
428 429
   to be a member template.  But, `template <class U> void
   C<int>::f(U)' is considered a member template.  */
430

431 432
int
is_member_template (t)
433 434
     tree t;
{
435
  if (!DECL_FUNCTION_TEMPLATE_P (t))
436
    /* Anything that isn't a function or a template function is
437 438 439
       certainly not a member template.  */
    return 0;

440
  /* A local class can't have member templates.  */
441
  if (decl_function_context (t))
442 443
    return 0;

444
  return (DECL_FUNCTION_MEMBER_P (DECL_TEMPLATE_RESULT (t))
jason's avatar
jason committed
445 446 447
	  /* If there are more levels of template parameters than
	     there are template classes surrounding the declaration,
	     then we have a member template.  */
448
	  && (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (t)) > 
449
	      template_class_depth (DECL_CONTEXT (t))));
jason's avatar
jason committed
450
}
451

452
#if 0 /* UNUSED */
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
/* Returns non-zero iff T is a member template class.  See
   is_member_template for a description of what precisely constitutes
   a member template.  */

int
is_member_template_class (t)
     tree t;
{
  if (!DECL_CLASS_TEMPLATE_P (t))
    /* Anything that isn't a class template, is certainly not a member
       template.  */
    return 0;

  if (!DECL_CLASS_SCOPE_P (t))
    /* Anything whose context isn't a class type is surely not a
       member template.  */
    return 0;

  /* If there are more levels of template parameters than there are
     template classes surrounding the declaration, then we have a
     member template.  */
474
  return  (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (t)) > 
475 476
	   template_class_depth (DECL_CONTEXT (t)));
}
477
#endif
478

479 480 481 482
/* Return a new template argument vector which contains all of ARGS,
   but has as its innermost set of arguments the EXTRA_ARGS.  The
   resulting vector will be built on a temporary obstack, and so must
   be explicitly copied to the permanent obstack, if required.  */
483 484

static tree
485 486 487
add_to_template_args (args, extra_args)
     tree args;
     tree extra_args;
488
{
489 490 491 492
  tree new_args;
  int extra_depth;
  int i;
  int j;
493

494
  extra_depth = TMPL_ARGS_DEPTH (extra_args);
495
  new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
496

497 498
  for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
499

500 501 502
  for (j = 1; j <= extra_depth; ++j, ++i)
    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
    
503 504 505
  return new_args;
}

506 507 508 509 510 511
/* Like add_to_template_args, but only the outermost ARGS are added to
   the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
   (EXTRA_ARGS) levels are added.  This function is used to combine
   the template arguments from a partial instantiation with the
   template arguments used to attain the full instantiation from the
   partial instantiation.  */
512

513
static tree
514
add_outermost_template_args (args, extra_args)
515 516 517 518 519
     tree args;
     tree extra_args;
{
  tree new_args;

520 521 522 523 524 525 526 527 528 529
  /* If there are more levels of EXTRA_ARGS than there are ARGS,
     something very fishy is going on.  */
  my_friendly_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args),
		      0);

  /* If *all* the new arguments will be the EXTRA_ARGS, just return
     them.  */
  if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
    return extra_args;

530 531 532 533
  /* For the moment, we make ARGS look like it contains fewer levels.  */
  TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
  
  new_args = add_to_template_args (args, extra_args);
534

535 536
  /* Now, we restore ARGS to its full dimensions.  */
  TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
537 538 539

  return new_args;
}
mrs's avatar
mrs committed
540 541 542

/* We've got a template header coming up; push to a new level for storing
   the parms.  */
mrs's avatar
mrs committed
543 544 545 546

void
begin_template_parm_list ()
{
547 548 549 550 551 552 553 554 555 556 557 558 559 560
  /* We use a non-tag-transparent scope here, which causes pushtag to
     put tags in this scope, rather than in the enclosing class or
     namespace scope.  This is the right thing, since we want
     TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
     global template class, push_template_decl handles putting the
     TEMPLATE_DECL into top-level scope.  For a nested template class,
     e.g.:

       template <class T> struct S1 {
         template <class T> struct S2 {}; 
       };

     pushtag contains special code to call pushdecl_with_scope on the
     TEMPLATE_DECL for S2.  */
561
  begin_scope (sk_template_parms);
mrs's avatar
mrs committed
562
  ++processing_template_decl;
563
  ++processing_template_parmlist;
564 565 566
  note_template_header (0);
}

567 568 569
/* This routine is called when a specialization is declared.  If it is
   illegal to declare a specialization here, an error is reported.  */

570
static void
571 572 573
check_specialization_scope ()
{
  tree scope = current_scope ();
574

575 576 577 578 579 580 581 582 583 584
  /* [temp.expl.spec] 
     
     An explicit specialization shall be declared in the namespace of
     which the template is a member, or, for member templates, in the
     namespace of which the enclosing class or enclosing class
     template is a member.  An explicit specialization of a member
     function, member class or static data member of a class template
     shall be declared in the namespace of which the class template
     is a member.  */
  if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
jason's avatar
jason committed
585
    cp_error ("explicit specialization in non-namespace scope `%D'",
586
	      scope);
587

588 589 590 591 592 593 594 595 596
  /* [temp.expl.spec] 

     In an explicit specialization declaration for a member of a class
     template or a member template that appears in namespace scope,
     the member template and some of its enclosing class templates may
     remain unspecialized, except that the declaration shall not
     explicitly specialize a class member template if its enclosing
     class templates are not explicitly specialized as well.  */
  if (current_template_parms) 
597
    cp_error ("enclosing class templates are not explicitly specialized");
598 599
}

600 601 602 603 604
/* We've just seen template <>. */

void
begin_specialization ()
{
605
  begin_scope (sk_template_spec);
606
  note_template_header (1);
607
  check_specialization_scope ();
608 609 610 611 612 613 614 615
}

/* Called at then end of processing a declaration preceeded by
   template<>.  */

void 
end_specialization ()
{
616
  finish_scope ();
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
  reset_specialization ();
}

/* Any template <>'s that we have seen thus far are not referring to a
   function specialization. */

void
reset_specialization ()
{
  processing_specialization = 0;
  template_header_count = 0;
}

/* We've just seen a template header.  If SPECIALIZATION is non-zero,
   it was of the form template <>.  */

633
static void 
634 635 636 637 638 639 640
note_template_header (specialization)
     int specialization;
{
  processing_specialization = specialization;
  template_header_count++;
}

641
/* We're beginning an explicit instantiation.  */
642

643 644
void
begin_explicit_instantiation ()
645
{
646 647
  ++processing_explicit_instantiation;
}
648 649


650 651 652 653 654 655
void
end_explicit_instantiation ()
{
  my_friendly_assert(processing_explicit_instantiation > 0, 0);
  --processing_explicit_instantiation;
}
656

657 658 659 660 661 662 663 664 665 666
/* The TYPE is being declared.  If it is a template type, that means it
   is a partial specialization.  Do appropriate error-checking.  */

void 
maybe_process_partial_specialization (type)
     tree type;
{
  if (IS_AGGR_TYPE (type) && CLASSTYPE_USE_TEMPLATE (type))
    {
      if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
nathan's avatar
gcc  
nathan committed
667
	  && !COMPLETE_TYPE_P (type))
668
	{
669 670 671 672 673 674 675
	  if (current_namespace
	      != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
	    {
	      cp_pedwarn ("specializing `%#T' in different namespace", type);
	      cp_pedwarn_at ("  from definition of `%#D'",
			     CLASSTYPE_TI_TEMPLATE (type));
	    }
mmitchel's avatar
mmitchel committed
676
	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
677 678 679 680
	  if (processing_template_decl)
	    push_template_decl (TYPE_MAIN_DECL (type));
	}
      else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
jason's avatar
jason committed
681
	cp_error ("specialization of `%T' after instantiation", type);
682
    }
683 684
  else if (processing_specialization)
    cp_error ("explicit specialization of non-template `%T'", type);
685 686
}

687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
/* Retrieve the specialization (in the sense of [temp.spec] - a
   specialization is either an instantiation or an explicit
   specialization) of TMPL for the given template ARGS.  If there is
   no such specialization, return NULL_TREE.  The ARGS are a vector of
   arguments, or a vector of vectors of arguments, in the case of
   templates with more than one level of parameters.  */
   
static tree
retrieve_specialization (tmpl, args)
     tree tmpl;
     tree args;
{
  tree s;

  my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);

703 704 705 706 707 708
  /* There should be as many levels of arguments as there are
     levels of parameters.  */
  my_friendly_assert (TMPL_ARGS_DEPTH (args) 
		      == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)),
		      0);
		      
709 710 711 712 713 714 715
  for (s = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
       s != NULL_TREE;
       s = TREE_CHAIN (s))
    if (comp_template_args (TREE_PURPOSE (s), args))
      return TREE_VALUE (s);

  return NULL_TREE;
716 717
}

718
/* Like retrieve_speciailization, but for local declarations.  */
719 720

static tree
721
retrieve_local_specialization (tmpl)
722 723
     tree tmpl;
{
724
  return (tree) htab_find (local_specializations, tmpl);
725 726
}

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
/* Returns non-zero iff DECL is a specialization of TMPL.  */

int
is_specialization_of (decl, tmpl)
     tree decl;
     tree tmpl;
{
  tree t;

  if (TREE_CODE (decl) == FUNCTION_DECL)
    {
      for (t = decl; 
	   t != NULL_TREE;
	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
	if (t == tmpl)
	  return 1;
    }
  else 
    {
      my_friendly_assert (TREE_CODE (decl) == TYPE_DECL, 0);

      for (t = TREE_TYPE (decl);
	   t != NULL_TREE;
	   t = CLASSTYPE_USE_TEMPLATE (t)
	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
752
	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
753 754
	  return 1;
    }  
755

756 757
  return 0;
}
758 759

/* Register the specialization SPEC as a specialization of TMPL with
760 761
   the indicated ARGS.  Returns SPEC, or an equivalent prior
   declaration, if available.  */
762

763
static tree
764 765 766 767 768 769 770 771 772
register_specialization (spec, tmpl, args)
     tree spec;
     tree tmpl;
     tree args;
{
  tree s;

  my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);

773 774 775 776 777 778 779 780 781 782 783 784 785 786
  if (TREE_CODE (spec) == FUNCTION_DECL 
      && uses_template_parms (DECL_TI_ARGS (spec)))
    /* This is the FUNCTION_DECL for a partial instantiation.  Don't
       register it; we want the corresponding TEMPLATE_DECL instead.
       We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
       the more obvious `uses_template_parms (spec)' to avoid problems
       with default function arguments.  In particular, given
       something like this:

          template <class T> void f(T t1, T t = T())

       the default argument expression is not substituted for in an
       instantiation unless and until it is actually needed.  */
    return spec;
787
    
788 789 790 791 792 793
  /* There should be as many levels of arguments as there are
     levels of parameters.  */
  my_friendly_assert (TMPL_ARGS_DEPTH (args) 
		      == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)),
		      0);

794 795 796
  for (s = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
       s != NULL_TREE;
       s = TREE_CHAIN (s))
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    {
      tree fn = TREE_VALUE (s);

      /* We can sometimes try to re-register a specialization that we've
	 already got.  In particular, regenerate_decl_from_template
	 calls duplicate_decls which will update the specialization
	 list.  But, we'll still get called again here anyhow.  It's
	 more convenient to simply allow this than to try to prevent it.  */
      if (fn == spec)
	return spec;
      else if (comp_template_args (TREE_PURPOSE (s), args))
	{
	  if (DECL_TEMPLATE_SPECIALIZATION (spec))
	    {
	      if (DECL_TEMPLATE_INSTANTIATION (fn))
		{
		  if (TREE_USED (fn) 
		      || DECL_EXPLICIT_INSTANTIATION (fn))
		    {
		      cp_error ("specialization of %D after instantiation",
				fn);
		      return spec;
		    }
		  else
		    {
		      /* This situation should occur only if the first
			 specialization is an implicit instantiation,
			 the second is an explicit specialization, and
			 the implicit instantiation has not yet been
			 used.  That situation can occur if we have
			 implicitly instantiated a member function and
			 then specialized it later.

			 We can also wind up here if a friend
			 declaration that looked like an instantiation
			 turns out to be a specialization:

			   template <class T> void foo(T);
			   class S { friend void foo<>(int) };
			   template <> void foo(int);  

			 We transform the existing DECL in place so that
			 any pointers to it become pointers to the
			 updated declaration.  

			 If there was a definition for the template, but
			 not for the specialization, we want this to
			 look as if there is no definition, and vice
			 versa.  */
		      DECL_INITIAL (fn) = NULL_TREE;
		      duplicate_decls (spec, fn);

		      return fn;
		    }
		}
	      else if (DECL_TEMPLATE_SPECIALIZATION (fn))
		{
		  duplicate_decls (spec, fn);
		  return fn;
		}
	    }
	}
859 860 861
      }

  DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
862
     = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887

  return spec;
}

/* Unregister the specialization SPEC as a specialization of TMPL.
   Returns nonzero if the SPEC was listed as a specialization of
   TMPL.  */

static int
unregister_specialization (spec, tmpl)
     tree spec;
     tree tmpl;
{
  tree* s;

  for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
       *s != NULL_TREE;
       s = &TREE_CHAIN (*s))
    if (TREE_VALUE (*s) == spec)
      {
	*s = TREE_CHAIN (*s);
	return 1;
      }

  return 0;
888 889
}

890 891
/* Like register_specialization, but for local declarations.  We are
   registering SPEC, an instantiation of TMPL.  */
892 893

static tree
894
register_local_specialization (spec, tmpl)
895 896 897
     tree spec;
     tree tmpl;
{
898 899 900 901
  void **slot;

  slot = htab_find_slot (local_specializations, tmpl, INSERT);
  *slot = spec;
902 903 904 905

  return spec;
}

906 907
/* Print the list of candidate FNS in an error message.  */

908
void
909 910 911 912 913
print_candidates (fns)
     tree fns;
{
  tree fn;

ghazi's avatar
ghazi committed
914
  const char *str = "candidates are:";
915 916 917

  for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
    {
918 919 920 921
      tree f;

      for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
	cp_error_at ("%s %+#D", str, OVL_CURRENT (f));
922 923 924 925
      str = "               ";
    }
}

926
/* Returns the template (one of the functions given by TEMPLATE_ID)
927
   which can be specialized to match the indicated DECL with the
928 929 930 931 932 933 934 935 936 937 938
   explicit template args given in TEMPLATE_ID.  The DECL may be
   NULL_TREE if none is available.  In that case, the functions in
   TEMPLATE_ID are non-members.

   If NEED_MEMBER_TEMPLATE is non-zero the function is known to be a
   specialization of a member template.

   The template args (those explicitly specified and those deduced)
   are output in a newly created vector *TARGS_OUT.

   If it is impossible to determine the result, an error message is
939
   issued.  The error_mark_node is returned to indicate failure.  */
940

941
static tree
942
determine_specialization (template_id, decl, targs_out, 
943
			  need_member_template)
944
     tree template_id;
945
     tree decl;
946 947 948
     tree* targs_out;
     int need_member_template;
{
949 950 951 952 953
  tree fns;
  tree targs;
  tree explicit_targs;
  tree candidates = NULL_TREE;
  tree templates = NULL_TREE;
954

955 956
  *targs_out = NULL_TREE;

957 958 959 960
  if (template_id == error_mark_node)
    return error_mark_node;

  fns = TREE_OPERAND (template_id, 0);
961
  explicit_targs = TREE_OPERAND (template_id, 1);
962

963 964 965
  if (fns == error_mark_node)
    return error_mark_node;

jason's avatar
jason committed
966
  /* Check for baselinks. */
967
  if (BASELINK_P (fns))
jason's avatar
jason committed
968
    fns = TREE_VALUE (fns);
969

970 971
  if (!is_overloaded_fn (fns))
    {
972
      cp_error ("`%D' is not a function template", fns);
973 974 975
      return error_mark_node;
    }

jason's avatar
jason committed
976
  for (; fns; fns = OVL_NEXT (fns))
977
    {
978 979
      tree tmpl;

980
      tree fn = OVL_CURRENT (fns);
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996

      if (TREE_CODE (fn) == TEMPLATE_DECL)
	/* DECL might be a specialization of FN.  */
	tmpl = fn;
      else if (need_member_template)
	/* FN is an ordinary member function, and we need a
	   specialization of a member template.  */
	continue;
      else if (TREE_CODE (fn) != FUNCTION_DECL)
	/* We can get IDENTIFIER_NODEs here in certain erroneous
	   cases.  */
	continue;
      else if (!DECL_FUNCTION_MEMBER_P (fn))
	/* This is just an ordinary non-member function.  Nothing can
	   be a specialization of that.  */
	continue;
997
      else
998 999
	{
	  tree decl_arg_types;
1000

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
	  /* This is an ordinary member function.  However, since
	     we're here, we can assume it's enclosing class is a
	     template class.  For example,
	     
	       template <typename T> struct S { void f(); };
	       template <> void S<int>::f() {}

	     Here, S<int>::f is a non-template, but S<int> is a
	     template class.  If FN has the same type as DECL, we
	     might be in business.  */
	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
			    TREE_TYPE (TREE_TYPE (fn))))
	    /* The return types differ.  */
	    continue;

	  /* Adjust the type of DECL in case FN is a static member.  */
	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
	  if (DECL_STATIC_FUNCTION_P (fn) 
	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
	    decl_arg_types = TREE_CHAIN (decl_arg_types);

	  if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)), 
			 decl_arg_types))
	    /* They match!  */
	    candidates = tree_cons (NULL_TREE, fn, candidates);

	  continue;
	}
1029

1030 1031 1032
      /* See whether this function might be a specialization of this
	 template.  */
      targs = get_bindings (tmpl, decl, explicit_targs);
1033 1034

      if (!targs)
1035
	/* We cannot deduce template arguments that when used to
1036 1037 1038 1039
	   specialize TMPL will produce DECL.  */
	continue;

      /* Save this template, and the arguments deduced.  */
1040
      templates = tree_cons (targs, tmpl, templates);
1041
    }
1042

1043
  if (templates && TREE_CHAIN (templates))
1044
    {
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
      /* We have:
	 
	   [temp.expl.spec]

	   It is possible for a specialization with a given function
	   signature to be instantiated from more than one function
	   template.  In such cases, explicit specification of the
	   template arguments must be used to uniquely identify the
	   function template specialization being specialized.

	 Note that here, there's no suggestion that we're supposed to
	 determine which of the candidate templates is most
	 specialized.  However, we, also have:

	   [temp.func.order]

	   Partial ordering of overloaded function template
	   declarations is used in the following contexts to select
	   the function template to which a function template
	   specialization refers: 

           -- when an explicit specialization refers to a function
	      template. 

	 So, we do use the partial ordering rules, at least for now.
	 This extension can only serve to make illegal programs legal,
	 so it's safe.  And, there is strong anecdotal evidence that
	 the committee intended the partial ordering rules to apply;
	 the EDG front-end has that behavior, and John Spicer claims
	 that the committee simply forgot to delete the wording in
	 [temp.expl.spec].  */
     tree tmpl = most_specialized (templates, decl, explicit_targs);
     if (tmpl && tmpl != error_mark_node)
       {
	 targs = get_bindings (tmpl, decl, explicit_targs);
1080
	 templates = tree_cons (targs, tmpl, NULL_TREE);
1081
       }
1082 1083
    }

1084
  if (templates == NULL_TREE && candidates == NULL_TREE)
1085
    {
1086 1087
      cp_error_at ("template-id `%D' for `%+D' does not match any template declaration",
		   template_id, decl);
1088
      return error_mark_node;
1089
    }
1090
  else if ((templates && TREE_CHAIN (templates))
1091 1092
	   || (candidates && TREE_CHAIN (candidates))
	   || (templates && candidates))
1093
    {
1094 1095 1096 1097
      cp_error_at ("ambiguous template specialization `%D' for `%+D'",
		   template_id, decl);
      chainon (candidates, templates);
      print_candidates (candidates);
1098
      return error_mark_node;
1099 1100 1101
    }

  /* We have one, and exactly one, match. */
1102 1103 1104 1105 1106 1107 1108 1109 1110
  if (candidates)
    {
      /* It was a specialization of an ordinary member function in a
	 template class.  */
      *targs_out = copy_node (DECL_TI_ARGS (TREE_VALUE (candidates)));
      return DECL_TI_TEMPLATE (TREE_VALUE (candidates));
    }

  /* It was a specialization of a template.  */
1111
  targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1112 1113 1114 1115 1116 1117 1118 1119 1120
  if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
    {
      *targs_out = copy_node (targs);
      SET_TMPL_ARGS_LEVEL (*targs_out, 
			   TMPL_ARGS_DEPTH (*targs_out),
			   TREE_PURPOSE (templates));
    }
  else
    *targs_out = TREE_PURPOSE (templates);
1121
  return TREE_VALUE (templates);
mrs's avatar
mrs committed
1122
}
1123
      
1124
/* Check to see if the function just declared, as indicated in
1125 1126 1127 1128
   DECLARATOR, and in DECL, is a specialization of a function
   template.  We may also discover that the declaration is an explicit
   instantiation at this point.

1129
   Returns DECL, or an equivalent declaration that should be used
1130 1131 1132
   instead if all goes well.  Issues an error message if something is
   amiss.  Returns error_mark_node if the error is not easily
   recoverable.
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
   
   FLAGS is a bitmask consisting of the following flags: 

   2: The function has a definition.
   4: The function is a friend.

   The TEMPLATE_COUNT is the number of references to qualifying
   template classes that appeared in the name of the function.  For
   example, in

     template <class T> struct S { void f(); };
     void S<int>::f();
     
   the TEMPLATE_COUNT would be 1.  However, explicitly specialized
   classes are not counted in the TEMPLATE_COUNT, so that in

     template <class T> struct S {};
     template <> struct S<int> { void f(); }
1151
     template <> void S<int>::f();
1152 1153 1154 1155 1156 1157 1158 1159

   the TEMPLATE_COUNT would be 0.  (Note that this declaration is
   illegal; there should be no template <>.)

   If the function is a specialization, it is marked as such via
   DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
   is set up correctly, and it is added to the list of specializations 
   for that template.  */
1160

1161
tree
1162
check_explicit_specialization (declarator, decl, template_count, flags)
1163 1164 1165 1166 1167
     tree declarator;
     tree decl;
     int template_count;
     int flags;
{
1168 1169 1170
  int have_def = flags & 2;
  int is_friend = flags & 4;
  int specialization = 0;
1171
  int explicit_instantiation = 0;
1172
  int member_specialization = 0;
1173 1174
  tree ctype = DECL_CLASS_CONTEXT (decl);
  tree dname = DECL_NAME (decl);
1175
  tmpl_spec_kind tsk;
1176

1177
  tsk = current_tmpl_spec_kind (template_count);
1178

1179 1180 1181 1182
  switch (tsk)
    {
    case tsk_none:
      if (processing_specialization) 
1183
	{
1184 1185
	  specialization = 1;
	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1186
	}
1187
      else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1188
	{
1189 1190
	  if (is_friend)
	    /* This could be something like:
1191

1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
	       template <class T> void f(T);
	       class S { friend void f<>(int); }  */
	    specialization = 1;
	  else
	    {
	      /* This case handles bogus declarations like template <>
		 template <class T> void f<int>(); */

	      cp_error ("template-id `%D' in declaration of primary template",
			declarator);
	      return decl;
	    }
	}
      break;

    case tsk_invalid_member_spec:
      /* The error has already been reported in
	 check_specialization_scope.  */
      return error_mark_node;

    case tsk_invalid_expl_inst:
      cp_error ("template parameter list used in explicit instantiation");

      /* Fall through.  */

    case tsk_expl_inst:
1218 1219
      if (have_def)
	cp_error ("definition provided for explicit instantiation");
1220
      
1221
      explicit_instantiation = 1;
1222
      break;
1223

1224 1225 1226 1227
    case tsk_excessive_parms:
      cp_error ("too many template parameter lists in declaration of `%D'", 
		decl);
      return error_mark_node;
1228

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
      /* Fall through.  */
    case tsk_expl_spec:
      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
      if (ctype)
	member_specialization = 1;
      else
	specialization = 1;
      break;
     
    case tsk_insufficient_parms:
1239 1240
      if (template_header_count)
	{
1241 1242
	  cp_error("too few template parameter lists in declaration of `%D'", 
		   decl);
1243
	  return decl;
1244
	}
1245 1246 1247 1248 1249 1250
      else if (ctype != NULL_TREE
	       && !TYPE_BEING_DEFINED (ctype)
	       && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype)
	       && !is_friend)
	{
	  /* For backwards compatibility, we accept:
1251

1252 1253
	       template <class T> struct S { void f(); };
	       void S<int>::f() {} // Missing template <>
1254

1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
	     That used to be legal C++.  */
	  if (pedantic)
	    cp_pedwarn
	      ("explicit specialization not preceded by `template <>'");
	  specialization = 1;
	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
	}
      break;

    case tsk_template:
      if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1266
	{
1267 1268
	  /* This case handles bogus declarations like template <>
	     template <class T> void f<int>(); */
1269

1270 1271 1272
	  cp_error ("template-id `%D' in declaration of primary template",
		    declarator);
	  return decl;
1273
	}
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289

      if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
	/* This is a specialization of a member template, without
	   specialization the containing class.  Something like:

	     template <class T> struct S {
	       template <class U> void f (U); 
             };
	     template <> template <class U> void S<int>::f(U) {}
	     
	   That's a specialization -- but of the entire template.  */
	specialization = 1;
      break;

    default:
      my_friendly_abort (20000309);
1290
    }
1291

1292 1293 1294 1295 1296 1297
  if (specialization || member_specialization)
    {
      tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
      for (; t; t = TREE_CHAIN (t))
	if (TREE_PURPOSE (t))
	  {
jason's avatar
jason committed
1298 1299
	    cp_pedwarn
	      ("default argument specified in explicit specialization");
1300 1301
	    break;
	  }
1302 1303
      if (current_lang_name == lang_name_c)
	cp_error ("template specialization with C linkage");
1304 1305
    }

1306
  if (specialization || member_specialization || explicit_instantiation)
1307 1308 1309 1310 1311
    {
      tree tmpl = NULL_TREE;
      tree targs = NULL_TREE;

      /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
1312 1313 1314 1315 1316 1317 1318
      if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
	{
	  tree fns;

	  my_friendly_assert (TREE_CODE (declarator) == IDENTIFIER_NODE, 
			      0);
	  if (!ctype)
jason's avatar
jason committed
1319
	    fns = IDENTIFIER_NAMESPACE_VALUE (dname);
1320 1321 1322
	  else
	    fns = dname;

1323 1324
	  declarator = 
	    lookup_template_function (fns, NULL_TREE);
1325 1326
	}

1327 1328 1329
      if (declarator == error_mark_node)
	return error_mark_node;

1330 1331
      if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
	{
1332
	  if (!explicit_instantiation)
1333 1334 1335 1336
	    /* A specialization in class scope.  This is illegal,
	       but the error will already have been flagged by
	       check_specialization_scope.  */
	    return error_mark_node;
1337
	  else
ghazi's avatar
ghazi committed
1338 1339 1340
	    {
	      /* It's not legal to write an explicit instantiation in
		 class scope, e.g.:
1341

ghazi's avatar
ghazi committed
1342
	           class C { template void f(); }
1343

ghazi's avatar
ghazi committed
1344 1345
		   This case is caught by the parser.  However, on
		   something like:
1346
	       
ghazi's avatar
ghazi committed
1347
		   template class C { void f(); };
1348

ghazi's avatar
ghazi committed
1349 1350 1351 1352
		   (which is illegal) we can get here.  The error will be
		   issued later.  */
	      ;
	    }
1353

1354
	  return decl;
1355
	}
1356 1357 1358 1359 1360 1361 1362 1363 1364
      else if (TREE_CODE (TREE_OPERAND (declarator, 0)) == LOOKUP_EXPR)
	{
	  /* A friend declaration.  We can't do much, because we don't
	   know what this resolves to, yet.  */
	  my_friendly_assert (is_friend != 0, 0);
	  my_friendly_assert (!explicit_instantiation, 0);
	  SET_DECL_IMPLICIT_INSTANTIATION (decl);
	  return decl;
	} 
1365 1366 1367
      else if (ctype != NULL_TREE 
	       && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
		   IDENTIFIER_NODE))
1368
	{
1369 1370 1371
	  /* Find the list of functions in ctype that have the same
	     name as the declared function.  */
	  tree name = TREE_OPERAND (declarator, 0);
1372 1373 1374
	  tree fns = NULL_TREE;
	  int idx;

1375 1376
	  if (name == constructor_name (ctype) 
	      || name == constructor_name_full (ctype))
1377
	    {
1378 1379 1380 1381 1382 1383
	      int is_constructor = DECL_CONSTRUCTOR_P (decl);
	      
	      if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
		  : !TYPE_HAS_DESTRUCTOR (ctype))
		{
		  /* From [temp.expl.spec]:
1384
		       
1385 1386 1387
		     If such an explicit specialization for the member
		     of a class template names an implicitly-declared
		     special member function (clause _special_), the
1388 1389 1390
		     program is ill-formed.  

		     Similar language is found in [temp.explicit].  */
jason's avatar
jason committed
1391
		  cp_error ("specialization of implicitly-declared special member function");
1392
		  return error_mark_node;
1393
		}
1394

1395
	      name = is_constructor ? ctor_identifier : dtor_identifier;
1396
	    }
1397

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
	  if (!IDENTIFIER_TYPENAME_P (name))
	    {
	      idx = lookup_fnfields_1 (ctype, name);
	      if (idx >= 0)
		fns = TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (ctype), idx);
	    }
	  else
	    {
	      tree methods;

	      /* For a type-conversion operator, we cannot do a
		 name-based lookup.  We might be looking for `operator
		 int' which will be a specialization of `operator T'.
		 So, we find *all* the conversion operators, and then
		 select from them.  */
	      fns = NULL_TREE;

	      methods = CLASSTYPE_METHOD_VEC (ctype);
	      if (methods)
		for (idx = 2; idx < TREE_VEC_LENGTH (methods); ++idx) 
		  {
		    tree ovl = TREE_VEC_ELT (methods, idx);

		    if (!ovl || !DECL_CONV_FN_P (OVL_CURRENT (ovl)))
		      /* There are no more conversion functions.  */
		      break;

		    /* Glue all these conversion functions together
		       with those we already have.  */
		    for (; ovl; ovl = OVL_NEXT (ovl))
		      fns = ovl_cons (OVL_CURRENT (ovl), fns);
		  }
	    }
	      
1432 1433
	  if (fns == NULL_TREE) 
	    {
1434 1435
	      cp_error ("no member function `%D' declared in `%T'",
			name, ctype);
1436
	      return error_mark_node;
1437 1438 1439 1440
	    }
	  else
	    TREE_OPERAND (declarator, 0) = fns;
	}
1441
      
1442 1443
      /* Figure out what exactly is being specialized at this point.
	 Note that for an explicit instantiation, even one for a
law's avatar
law committed
1444
	 member function, we cannot tell apriori whether the
1445
	 instantiation is for a member template, or just a member
1446 1447 1448 1449
	 function of a template class.  Even if a member template is
	 being instantiated, the member template arguments may be
	 elided if they can be deduced from the rest of the
	 declaration.  */
1450 1451
      tmpl = determine_specialization (declarator, decl,
				       &targs, 
1452
				       member_specialization);
1453
	    
1454 1455 1456 1457 1458
      if (!tmpl || tmpl == error_mark_node)
	/* We couldn't figure out what this declaration was
	   specializing.  */
	return error_mark_node;
      else
1459
	{
1460
	  tree gen_tmpl = most_general_template (tmpl);
1461

1462 1463
	  if (explicit_instantiation)
	    {
1464
	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
		 is done by do_decl_instantiation later.  */ 

	      int arg_depth = TMPL_ARGS_DEPTH (targs);
	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));

	      if (arg_depth > parm_depth)
		{
		  /* If TMPL is not the most general template (for
		     example, if TMPL is a friend template that is
		     injected into namespace scope), then there will
		     be too many levels fo TARGS.  Remove some of them
		     here.  */
		  int i;
		  tree new_targs;

1480
		  new_targs = make_tree_vec (parm_depth);
1481 1482 1483 1484 1485 1486
		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
		      = TREE_VEC_ELT (targs, i);
		  targs = new_targs;
		}
		  
1487
	      return instantiate_template (tmpl, targs);
1488
	    }
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499

	  /* If this is both a template specialization, then it's a
	     specialization of a member template of a template class.
	     In that case we want to return the TEMPLATE_DECL, not the
	     specialization of it.  */
	  if (tsk == tsk_template)
	    {
	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
	      return tmpl;
	    }

1500 1501 1502 1503 1504
	  /* If we though that the DECL was a member function, but it
	     turns out to be specializing a static member function,
	     make DECL a static member function as well.  */
	  if (DECL_STATIC_FUNCTION_P (tmpl)
	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1505
	    {
1506
	      revert_static_member_fn (decl);
1507 1508
	      last_function_parms = TREE_CHAIN (last_function_parms);
	    }
1509

1510
	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
1511
	  DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
1512

1513 1514 1515
	  /* Mangle the function name appropriately.  Note that we do
	     not mangle specializations of non-template member
	     functions of template classes, e.g. with
1516

1517
	       template <class T> struct S { void f(); }
1518

1519
	     and given the specialization 
1520

1521
	       template <> void S<int>::f() {}
1522

1523 1524
	     we do not mangle S<int>::f() here.  That's because it's
	     just an ordinary member function and doesn't need special
1525
	     treatment.  We do this here so that the ordinary,
1526
	     non-template, name-mangling algorithm will not be used
1527
	     later.  */
1528
	  if ((is_member_template (tmpl) || ctype == NULL_TREE)
1529
	      && name_mangling_version >= 1)
1530
	    set_mangled_name_for_template_decl (decl);
1531 1532

	  if (is_friend && !have_def)
1533 1534 1535
	    /* This is not really a declaration of a specialization.
	       It's just the name of an instantiation.  But, it's not
	       a request for an instantiation, either.  */
1536
	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
1537

1538 1539 1540
	  /* Register this specialization so that we can find it
	     again.  */
	  decl = register_specialization (decl, gen_tmpl, targs);
1541 1542
	}
    }
1543
  
1544
  return decl;
1545
}
1546

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
/* TYPE is being declared.  Verify that the use of template headers
   and such is reasonable.  Issue error messages if not.  */

void
maybe_check_template_type (type)
     tree type;
{
  if (template_header_count)
    {
      /* We are in the scope of some `template <...>' header.  */

      int context_depth 
	= template_class_depth_real (TYPE_CONTEXT (type),
				     /*count_specializations=*/1);

      if (template_header_count <= context_depth)
	/* This is OK; the template headers are for the context.  We
	   are actually too lenient here; like
	   check_explicit_specialization we should consider the number
	   of template types included in the actual declaration.  For
	   example, 

	     template <class T> struct S {
	       template <class U> template <class V>
	       struct I {};
	     }; 

	   is illegal, but:

	     template <class T> struct S {
	       template <class U> struct I;
	     }; 

	     template <class T> template <class U.
	     struct S<T>::I {};

	   is not.  */
	; 
      else if (template_header_count > context_depth + 1)
	/* There are two many template parameter lists.  */
jason's avatar
jason committed
1587
	cp_error ("too many template parameter lists in declaration of `%T'", type); 
1588 1589 1590
    }
}

1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
/* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
   parameters.  These are represented in the same format used for
   DECL_TEMPLATE_PARMS.  */

int comp_template_parms (parms1, parms2)
     tree parms1;
     tree parms2;
{
  tree p1;
  tree p2;

  if (parms1 == parms2)
    return 1;

  for (p1 = parms1, p2 = parms2; 
       p1 != NULL_TREE && p2 != NULL_TREE;
       p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
    {
      tree t1 = TREE_VALUE (p1);
      tree t2 = TREE_VALUE (p2);
      int i;

      my_friendly_assert (TREE_CODE (t1) == TREE_VEC, 0);
      my_friendly_assert (TREE_CODE (t2) == TREE_VEC, 0);

      if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
	return 0;

      for (i = 0; i < TREE_VEC_LENGTH (t2); ++i) 
	{
	  tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
	  tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));

	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
	    return 0;

	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM)
	    continue;
1629
	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
	    return 0;
	}
    }

  if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
    /* One set of parameters has more parameters lists than the
       other.  */
    return 0;

  return 1;
}

1642 1643 1644 1645 1646 1647 1648 1649 1650
/* Complain if DECL shadows a template parameter.

   [temp.local]: A template-parameter shall not be redeclared within its
   scope (including nested scopes).  */

void
check_template_shadow (decl)
     tree decl;
{
1651 1652
  tree olddecl;

1653 1654 1655 1656 1657 1658
  /* If we're not in a template, we can't possibly shadow a template
     parameter.  */
  if (!current_template_parms)
    return;

  /* Figure out what we're shadowing.  */
1659 1660 1661
  if (TREE_CODE (decl) == OVERLOAD)
    decl = OVL_CURRENT (decl);
  olddecl = IDENTIFIER_VALUE (DECL_NAME (decl));
1662

1663 1664 1665 1666 1667 1668 1669 1670 1671
  /* If there's no previous binding for this name, we're not shadowing
     anything, let alone a template parameter.  */
  if (!olddecl)
    return;

  /* If we're not shadowing a template parameter, we're done.  Note
     that OLDDECL might be an OVERLOAD (or perhaps even an
     ERROR_MARK), so we can't just blithely assume it to be a _DECL
     node.  */
1672
  if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
    return;

  /* We check for decl != olddecl to avoid bogus errors for using a
     name inside a class.  We check TPFI to avoid duplicate errors for
     inline member templates.  */
  if (decl == olddecl 
      || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
    return;

  cp_error_at ("declaration of `%#D'", decl);
  cp_error_at (" shadows template parm `%#D'", olddecl);
1684
}
bkoz's avatar
h  
bkoz committed
1685

1686
/* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
jason's avatar
jason committed
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
   ORIG_LEVEL, DECL, and TYPE.  */

static tree
build_template_parm_index (index, level, orig_level, decl, type)
     int index;
     int level;
     int orig_level;
     tree decl;
     tree type;
{
  tree t = make_node (TEMPLATE_PARM_INDEX);
  TEMPLATE_PARM_IDX (t) = index;
  TEMPLATE_PARM_LEVEL (t) = level;
  TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
  TEMPLATE_PARM_DECL (t) = decl;
  TREE_TYPE (t) = type;

  return t;
}

/* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
1708
   TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
jason's avatar
jason committed
1709 1710 1711 1712
   TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
   new one is created.  */

static tree 
1713
reduce_template_parm_level (index, type, levels)
jason's avatar
jason committed
1714 1715
     tree index;
     tree type;
1716
     int levels;
jason's avatar
jason committed
1717 1718 1719
{
  if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
      || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
1720
	  != TEMPLATE_PARM_LEVEL (index) - levels))
jason's avatar
jason committed
1721 1722 1723 1724 1725 1726 1727
    {
      tree decl 
	= build_decl (TREE_CODE (TEMPLATE_PARM_DECL (index)),
		      DECL_NAME (TEMPLATE_PARM_DECL (index)),
		      type);
      tree t
	= build_template_parm_index (TEMPLATE_PARM_IDX (index),
1728
				     TEMPLATE_PARM_LEVEL (index) - levels,
jason's avatar
jason committed
1729 1730 1731
				     TEMPLATE_PARM_ORIG_LEVEL (index),
				     decl, type);
      TEMPLATE_PARM_DESCENDANTS (index) = t;
1732 1733 1734 1735

      /* Template template parameters need this.  */
      DECL_TEMPLATE_PARMS (decl)
	= DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index));
jason's avatar
jason committed
1736 1737 1738 1739 1740
    }

  return TEMPLATE_PARM_DESCENDANTS (index);
}

mrs's avatar
mrs committed
1741
/* Process information from new template parameter NEXT and append it to the
mrs's avatar
mrs committed
1742
   LIST being built.  */
mrs's avatar
mrs committed
1743

mrs's avatar
mrs committed
1744 1745 1746 1747 1748 1749
tree
process_template_parm (list, next)
     tree list, next;
{
  tree parm;
  tree decl = 0;
mrs's avatar
mrs committed
1750
  tree defval;
mrs's avatar
mrs committed
1751
  int is_type, idx;
jason's avatar
jason committed
1752

mrs's avatar
mrs committed
1753 1754
  parm = next;
  my_friendly_assert (TREE_CODE (parm) == TREE_LIST, 259);
mrs's avatar
mrs committed
1755 1756 1757
  defval = TREE_PURPOSE (parm);
  parm = TREE_VALUE (parm);
  is_type = TREE_PURPOSE (parm) == class_type_node;
mrs's avatar
mrs committed
1758 1759 1760 1761 1762 1763 1764

  if (list)
    {
      tree p = TREE_VALUE (tree_last (list));

      if (TREE_CODE (p) == TYPE_DECL)
	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
1765 1766
      else if (TREE_CODE (p) == TEMPLATE_DECL)
	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (DECL_TEMPLATE_RESULT (p)));
mrs's avatar
mrs committed
1767
      else
jason's avatar
jason committed
1768
	idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
mrs's avatar
mrs committed
1769 1770 1771 1772 1773
      ++idx;
    }
  else
    idx = 0;

mrs's avatar
mrs committed
1774 1775
  if (!is_type)
    {
mrs's avatar
mrs committed
1776
      my_friendly_assert (TREE_CODE (TREE_PURPOSE (parm)) == TREE_LIST, 260);
mrs's avatar
mrs committed
1777
      /* is a const-param */
mrs's avatar
mrs committed
1778
      parm = grokdeclarator (TREE_VALUE (parm), TREE_PURPOSE (parm),
mrs's avatar
merging  
mrs committed
1779
			     PARM, 0, NULL_TREE);
1780 1781 1782 1783 1784 1785 1786

      /* [temp.param]

	 The top-level cv-qualifiers on the template-parameter are
	 ignored when determining its type.  */
      TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));

mrs's avatar
mrs committed
1787 1788
      /* A template parameter is not modifiable.  */
      TREE_READONLY (parm) = 1;
mrs's avatar
mrs committed
1789
      if (IS_AGGR_TYPE (TREE_TYPE (parm))
1790 1791
	  && TREE_CODE (TREE_TYPE (parm)) != TEMPLATE_TYPE_PARM
	  && TREE_CODE (TREE_TYPE (parm)) != TYPENAME_TYPE)
mrs's avatar
mrs committed
1792
	{
jason's avatar
jason committed
1793
	  cp_error ("`%#T' is not a valid type for a template constant parameter",
mrs's avatar
mrs committed
1794 1795
		    TREE_TYPE (parm));
	  if (DECL_NAME (parm) == NULL_TREE)
jason's avatar
jason committed
1796
	    error ("  a template type parameter must begin with `class' or `typename'");
mrs's avatar
mrs committed
1797 1798
	  TREE_TYPE (parm) = void_type_node;
	}
mrs's avatar
mrs committed
1799 1800 1801
      else if (pedantic
	       && (TREE_CODE (TREE_TYPE (parm)) == REAL_TYPE
		   || TREE_CODE (TREE_TYPE (parm)) == COMPLEX_TYPE))
jason's avatar
jason committed
1802
	cp_pedwarn ("`%T' is not a valid type for a template constant parameter",
mrs's avatar
mrs committed
1803
		    TREE_TYPE (parm));
mrs's avatar
mrs committed
1804
      decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
jason's avatar
jason committed
1805 1806 1807 1808
      DECL_INITIAL (parm) = DECL_INITIAL (decl) 
	= build_template_parm_index (idx, processing_template_decl,
				     processing_template_decl,
				     decl, TREE_TYPE (parm));
mrs's avatar
mrs committed
1809 1810 1811
    }
  else
    {
1812 1813 1814 1815 1816
      tree t;
      parm = TREE_VALUE (parm);
      
      if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
	{
rth's avatar
rth committed
1817
	  t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
1818 1819 1820 1821 1822 1823 1824 1825
	  /* This is for distinguishing between real templates and template 
	     template parameters */
	  TREE_TYPE (parm) = t;
	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
	  decl = parm;
	}
      else
	{
rth's avatar
rth committed
1826
	  t = make_aggr_type (TEMPLATE_TYPE_PARM);
1827 1828 1829 1830
	  /* parm is either IDENTIFIER_NODE or NULL_TREE */
	  decl = build_decl (TYPE_DECL, parm, t);
	}
        
mrs's avatar
mrs committed
1831 1832
      TYPE_NAME (t) = decl;
      TYPE_STUB_DECL (t) = decl;
mrs's avatar
mrs committed
1833
      parm = decl;
jason's avatar
jason committed
1834 1835 1836 1837
      TEMPLATE_TYPE_PARM_INDEX (t)
	= build_template_parm_index (idx, processing_template_decl, 
				     processing_template_decl,
				     decl, TREE_TYPE (parm));
mrs's avatar
mrs committed
1838
    }
mrs's avatar
mrs committed
1839
  SET_DECL_ARTIFICIAL (decl);
1840
  SET_DECL_TEMPLATE_PARM_P (decl);
mrs's avatar
mrs committed
1841
  pushdecl (decl);
mrs's avatar
mrs committed
1842
  parm = build_tree_list (defval, parm);
mrs's avatar
mrs committed
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
  return chainon (list, parm);
}

/* The end of a template parameter list has been reached.  Process the
   tree list into a parameter vector, converting each parameter into a more
   useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
   as PARM_DECLs.  */

tree
end_template_parm_list (parms)
     tree parms;
{
mrs's avatar
mrs committed
1855
  int nparms;
mrs's avatar
mrs committed
1856
  tree parm;
mrs's avatar
mrs committed
1857 1858 1859 1860 1861
  tree saved_parmlist = make_tree_vec (list_length (parms));

  current_template_parms
    = tree_cons (build_int_2 (0, processing_template_decl),
		 saved_parmlist, current_template_parms);
mrs's avatar
mrs committed
1862

1863 1864 1865
  for (parm = parms, nparms = 0; 
       parm; 
       parm = TREE_CHAIN (parm), nparms++)
1866
    TREE_VEC_ELT (saved_parmlist, nparms) = parm;
mrs's avatar
mrs committed
1867

1868 1869
  --processing_template_parmlist;

mrs's avatar
mrs committed
1870 1871 1872
  return saved_parmlist;
}

mrs's avatar
mrs committed
1873 1874
/* end_template_decl is called after a template declaration is seen.  */

mrs's avatar
mrs committed
1875
void
mrs's avatar
mrs committed
1876
end_template_decl ()
mrs's avatar
mrs committed
1877
{
1878 1879
  reset_specialization ();

mrs's avatar
mrs committed
1880
  if (! processing_template_decl)
mrs's avatar
mrs committed
1881 1882
    return;

mrs's avatar
mrs committed
1883
  /* This matches the pushlevel in begin_template_parm_list.  */
1884
  finish_scope ();
mrs's avatar
mrs committed
1885

mrs's avatar
mrs committed
1886 1887 1888
  --processing_template_decl;
  current_template_parms = TREE_CHAIN (current_template_parms);
}
mrs's avatar
mrs committed
1889

1890 1891
/* Given a template argument vector containing the template PARMS.
   The innermost PARMS are given first.  */
mrs's avatar
mrs committed
1892 1893 1894

tree
current_template_args ()
mrs's avatar
mrs committed
1895
{
1896
  tree header;
ghazi's avatar
ghazi committed
1897
  tree args = NULL_TREE;
1898
  int length = TMPL_PARMS_DEPTH (current_template_parms);
1899 1900
  int l = length;

1901 1902 1903 1904 1905 1906 1907
  /* If there is only one level of template parameters, we do not
     create a TREE_VEC of TREE_VECs.  Instead, we return a single
     TREE_VEC containing the arguments.  */
  if (length > 1)
    args = make_tree_vec (length);

  for (header = current_template_parms; header; header = TREE_CHAIN (header))
mrs's avatar
mrs committed
1908
    {
mrs's avatar
mrs committed
1909
      tree a = copy_node (TREE_VALUE (header));
1910 1911
      int i;

mrs's avatar
mrs committed
1912
      TREE_TYPE (a) = NULL_TREE;
1913
      for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
mrs's avatar
mrs committed
1914
	{
1915 1916
	  tree t = TREE_VEC_ELT (a, i);

1917
	  /* T will be a list if we are called from within a
1918 1919 1920 1921 1922 1923
	     begin/end_template_parm_list pair, but a vector directly
	     if within a begin/end_member_template_processing pair.  */
	  if (TREE_CODE (t) == TREE_LIST) 
	    {
	      t = TREE_VALUE (t);
	      
1924 1925
	      if (TREE_CODE (t) == TYPE_DECL 
		  || TREE_CODE (t) == TEMPLATE_DECL)
1926 1927 1928
		t = TREE_TYPE (t);
	      else
		t = DECL_INITIAL (t);
1929
	      TREE_VEC_ELT (a, i) = t;
1930
	    }
mrs's avatar
mrs committed
1931
	}
1932 1933 1934 1935 1936

      if (length > 1)
	TREE_VEC_ELT (args, --l) = a;
      else
	args = a;
mrs's avatar
mrs committed
1937 1938
    }

mrs's avatar
mrs committed
1939 1940
  return args;
}
1941

1942 1943 1944
/* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
   template PARMS.  Used by push_template_decl below.  */

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
static tree
build_template_decl (decl, parms)
     tree decl;
     tree parms;
{
  tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
  DECL_TEMPLATE_PARMS (tmpl) = parms;
  DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
  if (DECL_LANG_SPECIFIC (decl))
    {
1955
      DECL_VIRTUAL_CONTEXT (tmpl) = DECL_VIRTUAL_CONTEXT (decl);
1956 1957
      DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
      DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
1958
      DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
1959 1960 1961 1962 1963
    }

  return tmpl;
}

1964 1965
struct template_parm_data
{
1966 1967
  /* The level of the template parameters we are currently
     processing.  */
1968
  int level;
1969 1970 1971 1972 1973 1974 1975 1976

  /* The index of the specialization argument we are currently
     processing.  */
  int current_arg;

  /* An array whose size is the number of template parameters.  The
     elements are non-zero if the parameter has been used in any one
     of the arguments processed so far.  */
1977
  int* parms;
1978 1979 1980 1981 1982

  /* An array whose size is the number of template arguments.  The
     elements are non-zero if the argument makes use of template
     parameters of this level.  */
  int* arg_uses_template_parms;
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
};

/* Subroutine of push_template_decl used to see if each template
   parameter in a partial specialization is used in the explicit
   argument list.  If T is of the LEVEL given in DATA (which is
   treated as a template_parm_data*), then DATA->PARMS is marked
   appropriately.  */

static int
mark_template_parm (t, data)
     tree t;
     void* data;
{
  int level;
  int idx;
  struct template_parm_data* tpd = (struct template_parm_data*) data;

  if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
    {
      level = TEMPLATE_PARM_LEVEL (t);
      idx = TEMPLATE_PARM_IDX (t);
    }
  else
    {
      level = TEMPLATE_TYPE_LEVEL (t);
      idx = TEMPLATE_TYPE_IDX (t);
    }

  if (level == tpd->level)
2012 2013 2014 2015
    {
      tpd->parms[idx] = 1;
      tpd->arg_uses_template_parms[tpd->current_arg] = 1;
    }
2016 2017 2018 2019 2020 2021

  /* Return zero so that for_each_template_parm will continue the
     traversal of the tree; we want to mark *every* template parm.  */
  return 0;
}

2022 2023
/* Process the partial specialization DECL.  */

2024
static tree
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
process_partial_specialization (decl)
     tree decl;
{
  tree type = TREE_TYPE (decl);
  tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
  tree specargs = CLASSTYPE_TI_ARGS (type);
  tree inner_args = innermost_args (specargs);
  tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
  tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
  int nargs = TREE_VEC_LENGTH (inner_args);
  int ntparms = TREE_VEC_LENGTH (inner_parms);
  int  i;
  int did_error_intro = 0;
  struct template_parm_data tpd;
  struct template_parm_data tpd2;

  /* We check that each of the template parameters given in the
     partial specialization is used in the argument list to the
     specialization.  For example:

       template <class T> struct S;
       template <class T> struct S<T*>;

     The second declaration is OK because `T*' uses the template
     parameter T, whereas

       template <class T> struct S<int>;

     is no good.  Even trickier is:

       template <class T>
       struct S1
       {
	  template <class U>
	  struct S2;
	  template <class U>
	  struct S2<T>;
       };

     The S2<T> declaration is actually illegal; it is a
     full-specialization.  Of course, 

	  template <class U>
	  struct S2<T (*)(U)>;

     or some such would have been OK.  */
  tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
  tpd.parms = alloca (sizeof (int) * ntparms);
ghazi's avatar
ghazi committed
2073
  bzero ((PTR) tpd.parms, sizeof (int) * ntparms);
2074 2075

  tpd.arg_uses_template_parms = alloca (sizeof (int) * nargs);
ghazi's avatar
ghazi committed
2076
  bzero ((PTR) tpd.arg_uses_template_parms, sizeof (int) * nargs);
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
  for (i = 0; i < nargs; ++i)
    {
      tpd.current_arg = i;
      for_each_template_parm (TREE_VEC_ELT (inner_args, i),
			      &mark_template_parm,
			      &tpd);
    }
  for (i = 0; i < ntparms; ++i)
    if (tpd.parms[i] == 0)
      {
	/* One of the template parms was not used in the
           specialization.  */
	if (!did_error_intro)
	  {
jason's avatar
jason committed
2091
	    cp_error ("template parameters not used in partial specialization:");
2092 2093 2094
	    did_error_intro = 1;
	  }

jason's avatar
jason committed
2095
	cp_error ("        `%D'", 
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
      }

  /* [temp.class.spec]

     The argument list of the specialization shall not be identical to
     the implicit argument list of the primary template.  */
  if (comp_template_args (inner_args, 
			  innermost_args (CLASSTYPE_TI_ARGS (TREE_TYPE
							     (maintmpl)))))
jason's avatar
jason committed
2106
    cp_error ("partial specialization `%T' does not specialize any template arguments", type);
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122

  /* [temp.class.spec]

     A partially specialized non-type argument expression shall not
     involve template parameters of the partial specialization except
     when the argument expression is a simple identifier.

     The type of a template parameter corresponding to a specialized
     non-type argument shall not be dependent on a parameter of the
     specialization.  */
  my_friendly_assert (nargs == DECL_NTPARMS (maintmpl), 0);
  tpd2.parms = 0;
  for (i = 0; i < nargs; ++i)
    {
      tree arg = TREE_VEC_ELT (inner_args, i);
      if (/* These first two lines are the `non-type' bit.  */
2123
	  !TYPE_P (arg)
2124 2125 2126 2127 2128 2129 2130
	  && TREE_CODE (arg) != TEMPLATE_DECL
	  /* This next line is the `argument expression is not just a
	     simple identifier' condition and also the `specialized
	     non-type argument' bit.  */
	  && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
	{
	  if (tpd.arg_uses_template_parms[i])
jason's avatar
jason committed
2131
	    cp_error ("template argument `%E' involves template parameter(s)", arg);
2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145
	  else 
	    {
	      /* Look at the corresponding template parameter,
		 marking which template parameters its type depends
		 upon.  */
	      tree type = 
		TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (main_inner_parms, 
						     i)));

	      if (!tpd2.parms)
		{
		  /* We haven't yet initialized TPD2.  Do so now.  */
		  tpd2.arg_uses_template_parms 
		    =  (int*) alloca (sizeof (int) * nargs);
2146
		  /* The number of parameters here is the number in the
2147 2148
		     main template, which, as checked in the assertion
		     above, is NARGS.  */
2149 2150 2151 2152 2153
		  tpd2.parms = (int*) alloca (sizeof (int) * nargs);
		  tpd2.level = 
		    TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
		}

2154
	      /* Mark the template parameters.  But this time, we're
2155 2156 2157 2158
		 looking for the template parameters of the main
		 template, not in the specialization.  */
	      tpd2.current_arg = i;
	      tpd2.arg_uses_template_parms[i] = 0;
ghazi's avatar
ghazi committed
2159
	      bzero ((PTR) tpd2.parms, sizeof (int) * nargs);
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173
	      for_each_template_parm (type,
				      &mark_template_parm,
				      &tpd2);
		  
	      if (tpd2.arg_uses_template_parms [i])
		{
		  /* The type depended on some template parameters.
		     If they are fully specialized in the
		     specialization, that's OK.  */
		  int j;
		  for (j = 0; j < nargs; ++j)
		    if (tpd2.parms[j] != 0
			&& tpd.arg_uses_template_parms [j])
		      {
2174
			cp_error ("type `%T' of template argument `%E' depends on template parameter(s)", 
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187
				  type,
				  arg);
			break;
		      }
		}
	    }
	}
    }

  if (retrieve_specialization (maintmpl, specargs))
    /* We've already got this specialization.  */
    return decl;

2188
  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
2189 2190
    = tree_cons (inner_args, inner_parms,
		 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
2191 2192 2193 2194
  TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
  return decl;
}

2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
/* Check that a template declaration's use of default arguments is not
   invalid.  Here, PARMS are the template parameters.  IS_PRIMARY is
   non-zero if DECL is the thing declared by a primary template.
   IS_PARTIAL is non-zero if DECL is a partial specialization.  */

static void
check_default_tmpl_args (decl, parms, is_primary, is_partial)
     tree decl;
     tree parms;
     int is_primary;
     int is_partial;
{
ghazi's avatar
ghazi committed
2207
  const char *msg;
2208 2209
  int last_level_to_check;
  tree parm_level;
2210 2211 2212 2213 2214 2215 2216 2217

  /* [temp.param] 

     A default template-argument shall not be specified in a
     function template declaration or a function template definition, nor
     in the template-parameter-list of the definition of a member of a
     class template.  */

2218
  if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
2219 2220 2221 2222 2223
    /* You can't have a function template declaration in a local
       scope, nor you can you define a member of a class template in a
       local scope.  */
    return;

2224 2225
  if (current_class_type
      && !TYPE_BEING_DEFINED (current_class_type)
2226
      && DECL_LANG_SPECIFIC (decl)
2227 2228
      /* If this is either a friend defined in the scope of the class
	 or a member function.  */
2229 2230 2231 2232 2233
      && ((DECL_CONTEXT (decl) 
	   && same_type_p (DECL_CONTEXT (decl), current_class_type))
	  || (DECL_FRIEND_CONTEXT (decl)
	      && same_type_p (DECL_FRIEND_CONTEXT (decl), 
			      current_class_type)))
2234 2235 2236
      /* And, if it was a member function, it really was defined in
	 the scope of the class.  */
      && (!DECL_FUNCTION_MEMBER_P (decl) || DECL_DEFINED_IN_CLASS_P (decl)))
2237
    /* We already checked these parameters when the template was
2238 2239 2240
       declared, so there's no need to do it again now.  This function
       was defined in class scope, but we're processing it's body now
       that the class is complete.  */
2241 2242
    return;

2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
  /* [temp.param]
	 
     If a template-parameter has a default template-argument, all
     subsequent template-parameters shall have a default
     template-argument supplied.  */
  for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
    {
      tree inner_parms = TREE_VALUE (parm_level);
      int ntparms = TREE_VEC_LENGTH (inner_parms);
      int seen_def_arg_p = 0; 
      int i;

      for (i = 0; i < ntparms; ++i) 
	{
	  tree parm = TREE_VEC_ELT (inner_parms, i);
	  if (TREE_PURPOSE (parm))
	    seen_def_arg_p = 1;
	  else if (seen_def_arg_p)
	    {
	      cp_error ("no default argument for `%D'", TREE_VALUE (parm));
	      /* For better subsequent error-recovery, we indicate that
		 there should have been a default argument.  */
	      TREE_PURPOSE (parm) = error_mark_node;
	    }
	}
    }

2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
  if (TREE_CODE (decl) != TYPE_DECL || is_partial || !is_primary)
    /* For an ordinary class template, default template arguments are
       allowed at the innermost level, e.g.:
         template <class T = int>
	 struct S {};
       but, in a partial specialization, they're not allowed even
       there, as we have in [temp.class.spec]:
     
	 The template parameter list of a specialization shall not
	 contain default template argument values.  

       So, for a partial specialization, or for a function template,
       we look at all of them.  */
    ;
  else
    /* But, for a primary class template that is not a partial
       specialization we look at all template parameters except the
       innermost ones.  */
    parms = TREE_CHAIN (parms);

  /* Figure out what error message to issue.  */
  if (TREE_CODE (decl) == FUNCTION_DECL)
    msg = "default argument for template parameter in function template `%D'";
  else if (is_partial)
    msg = "default argument in partial specialization `%D'";
  else
    msg = "default argument for template parameter for class enclosing `%D'";

  if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
    /* If we're inside a class definition, there's no need to
2300
       examine the parameters to the class itself.  On the one
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311
       hand, they will be checked when the class is defined, and,
       on the other, default arguments are legal in things like:
         template <class T = double>
         struct S { template <class U> void f(U); };
       Here the default argument for `S' has no bearing on the
       declaration of `f'.  */
    last_level_to_check = template_class_depth (current_class_type) + 1;
  else
    /* Check everything.  */
    last_level_to_check = 0;

2312 2313 2314
  for (parm_level = parms; 
       parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check; 
       parm_level = TREE_CHAIN (parm_level))
2315
    {
2316 2317 2318
      tree inner_parms = TREE_VALUE (parm_level);
      int i;
      int ntparms;
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341

      ntparms = TREE_VEC_LENGTH (inner_parms);
      for (i = 0; i < ntparms; ++i) 
	if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
	  {
	    if (msg)
	      {
		cp_error (msg, decl);
		msg = 0;
	      }

	    /* Clear out the default argument so that we are not
	       confused later.  */
	    TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
	  }

      /* At this point, if we're still interested in issuing messages,
	 they must apply to classes surrounding the object declared.  */
      if (msg)
	msg = "default argument for template parameter for class enclosing `%D'"; 
    }
}

2342
/* Creates a TEMPLATE_DECL for the indicated DECL using the template
jason's avatar
jason committed
2343 2344
   parameters given by current_template_args, or reuses a
   previously existing one, if appropriate.  Returns the DECL, or an
2345 2346 2347
   equivalent one, if it is replaced via a call to duplicate_decls.  

   If IS_FRIEND is non-zero, DECL is a friend declaration.  */
2348 2349

tree
2350
push_template_decl_real (decl, is_friend)
mrs's avatar
mrs committed
2351
     tree decl;
2352
     int is_friend;
mrs's avatar
mrs committed
2353 2354
{
  tree tmpl;
jason's avatar
jason committed
2355
  tree args;
mrs's avatar
mrs committed
2356
  tree info;
jason's avatar
jason committed
2357 2358
  tree ctx;
  int primary;
2359
  int is_partial;
2360
  int new_template_p = 0;
2361 2362

  /* See if this is a partial specialization.  */
2363
  is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
2364
		&& TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
mmitchel's avatar
mmitchel committed
2365
		&& CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
2366 2367

  is_friend |= (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl));
jason's avatar
jason committed
2368 2369 2370 2371 2372

  if (is_friend)
    /* For a friend, we want the context of the friend function, not
       the type of which it is a friend.  */
    ctx = DECL_CONTEXT (decl);
2373 2374
  else if (CP_DECL_CONTEXT (decl)
	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
jason's avatar
jason committed
2375 2376
    /* In the case of a virtual function, we want the class in which
       it is defined.  */
2377
    ctx = CP_DECL_CONTEXT (decl);
jason's avatar
jason committed
2378 2379 2380
  else
    /* Otherwise, if we're currently definining some class, the DECL
       is assumed to be a member of the class.  */
2381
    ctx = current_scope ();
jason's avatar
jason committed
2382

jason's avatar
jason committed
2383 2384 2385 2386
  if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
    ctx = NULL_TREE;

  if (!DECL_CONTEXT (decl))
2387
    DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
jason's avatar
jason committed
2388

2389
  /* See if this is a primary template.  */
2390
  primary = template_parm_scope_p ();
mrs's avatar
mrs committed
2391

2392 2393 2394
  if (primary)
    {
      if (current_lang_name == lang_name_c)
jason's avatar
jason committed
2395
	cp_error ("template with C linkage");
2396 2397
      else if (TREE_CODE (decl) == TYPE_DECL 
	       && ANON_AGGRNAME_P (DECL_NAME (decl))) 
jason's avatar
jason committed
2398
	cp_error ("template class without a name");
2399 2400 2401 2402 2403 2404
      else if ((DECL_IMPLICIT_TYPEDEF_P (decl)
		&& CLASS_TYPE_P (TREE_TYPE (decl)))
	       || (TREE_CODE (decl) == VAR_DECL && ctx && CLASS_TYPE_P (ctx))
	       || TREE_CODE (decl) == FUNCTION_DECL)
	/* OK */;
      else
2405
	cp_error ("template declaration of `%#D'", decl);
2406 2407
    }

2408 2409 2410 2411
  /* Check to see that the rules regarding the use of default
     arguments are not being violated.  */
  check_default_tmpl_args (decl, current_template_parms, 
			   primary, is_partial);
mrs's avatar
mrs committed
2412

2413 2414
  if (is_partial)
    return process_partial_specialization (decl);
2415

mrs's avatar
mrs committed
2416 2417
  args = current_template_args ();

jason's avatar
jason committed
2418 2419 2420 2421
  if (!ctx 
      || TREE_CODE (ctx) == FUNCTION_DECL
      || TYPE_BEING_DEFINED (ctx)
      || (is_friend && !DECL_TEMPLATE_INFO (decl)))
mrs's avatar
mrs committed
2422
    {
2423
      if (DECL_LANG_SPECIFIC (decl)
jason's avatar
jason committed
2424 2425 2426
	  && DECL_TEMPLATE_INFO (decl)
	  && DECL_TI_TEMPLATE (decl))
	tmpl = DECL_TI_TEMPLATE (decl);
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
      /* If DECL is a TYPE_DECL for a class-template, then there won't
	 be DECL_LANG_SPECIFIC.  The information equivalent to
	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
      else if (DECL_IMPLICIT_TYPEDEF_P (decl) 
	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
	{
	  /* Since a template declaration already existed for this
	     class-type, we must be redeclaring it here.  Make sure
	     that the redeclaration is legal.  */
	  redeclare_class_template (TREE_TYPE (decl),
				    current_template_parms);
	  /* We don't need to create a new TEMPLATE_DECL; just use the
	     one we already had.  */
	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
	}
jason's avatar
jason committed
2443
      else
2444
	{
jason's avatar
jason committed
2445
	  tmpl = build_template_decl (decl, current_template_parms);
2446 2447
	  new_template_p = 1;

jason's avatar
jason committed
2448 2449 2450 2451 2452 2453 2454 2455 2456
	  if (DECL_LANG_SPECIFIC (decl)
	      && DECL_TEMPLATE_SPECIALIZATION (decl))
	    {
	      /* A specialization of a member template of a template
		 class. */
	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
	    }
2457
	}
mrs's avatar
mrs committed
2458 2459 2460
    }
  else
    {
2461
      tree a, t, current, parms;
2462
      int i;
mrs's avatar
mrs committed
2463

2464 2465
      if (TREE_CODE (decl) == TYPE_DECL)
	{
2466 2467 2468 2469 2470
	  if ((IS_AGGR_TYPE_CODE (TREE_CODE (TREE_TYPE (decl)))
	       || TREE_CODE (TREE_TYPE (decl)) == ENUMERAL_TYPE)
	      && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
	      && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
	    tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
2471 2472
	  else
	    {
jason's avatar
jason committed
2473
	      cp_error ("`%D' does not declare a template type", decl);
2474 2475 2476
	      return decl;
	    }
	}
mrs's avatar
mrs committed
2477
      else if (! DECL_TEMPLATE_INFO (decl))
mrs's avatar
mrs committed
2478
	{
jason's avatar
jason committed
2479
	  cp_error ("template definition of non-template `%#D'", decl);
2480
	  return decl;
mrs's avatar
mrs committed
2481
	}
mrs's avatar
mrs committed
2482
      else
mrs's avatar
mrs committed
2483
	tmpl = DECL_TI_TEMPLATE (decl);
2484
      
2485 2486 2487 2488
      if (is_member_template (tmpl)
	  && DECL_FUNCTION_TEMPLATE_P (tmpl)
	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl) 
	  && DECL_TEMPLATE_SPECIALIZATION (decl))
2489
	{
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
	  tree new_tmpl;

	  /* The declaration is a specialization of a member
	     template, declared outside the class.  Therefore, the
	     innermost template arguments will be NULL, so we
	     replace them with the arguments determined by the
	     earlier call to check_explicit_specialization.  */
	  args = DECL_TI_ARGS (decl);

	  new_tmpl 
	    = build_template_decl (decl, current_template_parms);
	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
	  DECL_TI_TEMPLATE (decl) = new_tmpl;
	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
2505 2506
	  DECL_TEMPLATE_INFO (new_tmpl) 
	    = tree_cons (tmpl, args, NULL_TREE);
2507 2508 2509

	  register_specialization (new_tmpl, tmpl, args);
	  return decl;
2510 2511
	}

2512
      /* Make sure the template headers we got make sense.  */
mrs's avatar
mrs committed
2513

2514 2515 2516
      parms = DECL_TEMPLATE_PARMS (tmpl);
      i = TMPL_PARMS_DEPTH (parms);
      if (TMPL_ARGS_DEPTH (args) != i)
2517
	{
2518 2519
	  cp_error ("expected %d levels of template parms for `%#D', got %d",
		    i, decl, TMPL_ARGS_DEPTH (args));
2520
	}
2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
      else
	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
	  {
	    a = TMPL_ARGS_LEVEL (args, i);
	    t = INNERMOST_TEMPLATE_PARMS (parms);

	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
	      {
		if (current == decl)
		  cp_error ("got %d template parameters for `%#D'",
			    TREE_VEC_LENGTH (a), decl);
		else
		  cp_error ("got %d template parameters for `%#T'",
			    TREE_VEC_LENGTH (a), current);
		cp_error ("  but %d required", TREE_VEC_LENGTH (t));
	      }
2537

2538 2539
	    /* Perhaps we should also check that the parms are used in the
               appropriate qualifying scopes in the declarator?  */
mrs's avatar
mrs committed
2540

2541 2542 2543 2544 2545
	    if (current == decl)
	      current = ctx;
	    else
	      current = TYPE_CONTEXT (current);
	  }
mrs's avatar
mrs committed
2546
    }
mrs's avatar
mrs committed
2547

mrs's avatar
mrs committed
2548 2549
  DECL_TEMPLATE_RESULT (tmpl) = decl;
  TREE_TYPE (tmpl) = TREE_TYPE (decl);
mrs's avatar
mrs committed
2550

2551 2552 2553
  /* Push template declarations for global functions and types.  Note
     that we do not try to push a global template friend declared in a
     template class; such a thing may well depend on the template
2554
     parameters of the class.  */
2555
  if (new_template_p && !ctx 
2556
      && !(is_friend && template_class_depth (current_class_type) > 0))
jason's avatar
jason committed
2557
    tmpl = pushdecl_namespace_level (tmpl);
mrs's avatar
mrs committed
2558

mrs's avatar
mrs committed
2559
  if (primary)
2560
    DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
mrs's avatar
mrs committed
2561

2562
  info = tree_cons (tmpl, args, NULL_TREE);
mrs's avatar
mrs committed
2563

2564
  if (DECL_IMPLICIT_TYPEDEF_P (decl))
mrs's avatar
mrs committed
2565
    {
2566 2567 2568
      SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
      if ((!ctx || TREE_CODE (ctx) != FUNCTION_DECL)
	  && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE)
2569
	DECL_NAME (decl) = classtype_mangled_name (TREE_TYPE (decl));
mrs's avatar
mrs committed
2570
    }
2571
  else if (DECL_LANG_SPECIFIC (decl))
mrs's avatar
mrs committed
2572
    DECL_TEMPLATE_INFO (decl) = info;
2573 2574

  return DECL_TEMPLATE_RESULT (tmpl);
mrs's avatar
mrs committed
2575 2576
}

2577 2578 2579 2580 2581 2582 2583 2584 2585
tree
push_template_decl (decl)
     tree decl;
{
  return push_template_decl_real (decl, 0);
}

/* Called when a class template TYPE is redeclared with the indicated
   template PARMS, e.g.:
2586 2587 2588 2589 2590

     template <class T> struct S;
     template <class T> struct S {};  */

void 
2591
redeclare_class_template (type, parms)
2592
     tree type;
2593
     tree parms;
2594
{
2595
  tree tmpl;
2596
  tree tmpl_parms;
2597 2598
  int i;

2599 2600 2601 2602 2603 2604 2605
  if (!TYPE_TEMPLATE_INFO (type))
    {
      cp_error ("`%T' is not a template type", type);
      return;
    }

  tmpl = TYPE_TI_TEMPLATE (type);
2606 2607 2608 2609 2610 2611
  if (!PRIMARY_TEMPLATE_P (tmpl))
    /* The type is nested in some template class.  Nothing to worry
       about here; there are no new template parameters for the nested
       type.  */
    return;

2612 2613 2614
  parms = INNERMOST_TEMPLATE_PARMS (parms);
  tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);

2615 2616
  if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
    {
jason's avatar
jason committed
2617 2618
      cp_error_at ("previous declaration `%D'", tmpl);
      cp_error ("used %d template parameter%s instead of %d",
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
		TREE_VEC_LENGTH (tmpl_parms), 
		TREE_VEC_LENGTH (tmpl_parms) == 1 ? "" : "s",
		TREE_VEC_LENGTH (parms));
      return;
    }

  for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
    {
      tree tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
      tree tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
      tree parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));

      if (TREE_CODE (tmpl_parm) != TREE_CODE (parm))
	{
jason's avatar
jason committed
2634 2635
	  cp_error_at ("template parameter `%#D'", tmpl_parm);
	  cp_error ("redeclared here as `%#D'", parm);
2636 2637 2638 2639 2640 2641 2642 2643 2644
	  return;
	}

      if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
	{
	  /* We have in [temp.param]:

	     A template-parameter may not be given default arguments
	     by two different declarations in the same scope.  */
jason's avatar
jason committed
2645 2646
	  cp_error ("redefinition of default argument for `%#D'", parm);
	  cp_error_at ("  original definition appeared here", tmpl_parm);
2647 2648 2649 2650 2651 2652 2653
	  return;
	}

      if (parm_default != NULL_TREE)
	/* Update the previous template parameters (which are the ones
	   that will really count) with the new default value.  */
	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
2654 2655 2656 2657
      else if (tmpl_default != NULL_TREE)
	/* Update the new parameters, too; they'll be used as the
	   parameters for any members.  */
	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
2658 2659
    }
}
2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671

/* Attempt to convert the non-type template parameter EXPR to the
   indicated TYPE.  If the conversion is successful, return the
   converted value.  If the conversion is unsuccesful, return
   NULL_TREE if we issued an error message, or error_mark_node if we
   did not.  We issue error messages for out-and-out bad template
   parameters, but not simply because the conversion failed, since we
   might be just trying to do argument deduction.  By the time this
   function is called, neither TYPE nor EXPR may make use of template
   parameters.  */

static tree
2672
convert_nontype_argument (type, expr)
2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
     tree type;
     tree expr;
{
  tree expr_type = TREE_TYPE (expr);

  /* A template-argument for a non-type, non-template
     template-parameter shall be one of:

     --an integral constant-expression of integral or enumeration
     type; or
     
     --the name of a non-type template-parameter; or
     
     --the name of an object or function with external linkage,
     including function templates and function template-ids but
2688
     excluding non-static class members, expressed as id-expression;
2689 2690 2691 2692 2693 2694 2695 2696 2697 2698
     or
     
     --the address of an object or function with external linkage,
     including function templates and function template-ids but
     excluding non-static class members, expressed as & id-expression
     where the & is optional if the name refers to a function or
     array; or
     
     --a pointer to member expressed as described in _expr.unary.op_.  */

2699 2700 2701 2702
  /* An integral constant-expression can include const variables or
     enumerators.  Simplify things by folding them to their values,
     unless we're about to bind the declaration to a reference
     parameter.  */
2703
  if (INTEGRAL_TYPE_P (expr_type)
2704
      && TREE_CODE (type) != REFERENCE_TYPE)
2705 2706
    expr = decl_constant_value (expr);

2707 2708 2709 2710 2711
  if (is_overloaded_fn (expr))
    /* OK for now.  We'll check that it has external linkage later.
       Check this first since if expr_type is the unknown_type_node
       we would otherwise complain below.  */
    ;
2712 2713 2714 2715 2716 2717
  else if (TYPE_PTRMEM_P (expr_type)
	   || TYPE_PTRMEMFUNC_P (expr_type))
    {
      if (TREE_CODE (expr) != PTRMEM_CST)
	goto bad_argument;
    }
2718
  else if (TYPE_PTR_P (expr_type)
2719
	   || TYPE_PTRMEM_P (expr_type)
2720 2721
	   || TREE_CODE (expr_type) == ARRAY_TYPE
	   || TREE_CODE (type) == REFERENCE_TYPE
2722 2723 2724 2725 2726
	   /* If expr is the address of an overloaded function, we
	      will get the unknown_type_node at this point.  */
	   || expr_type == unknown_type_node)
    {
      tree referent;
2727 2728
      tree e = expr;
      STRIP_NOPS (e);
2729

2730 2731 2732 2733
      if (TREE_CODE (type) == REFERENCE_TYPE
	  || TREE_CODE (expr_type) == ARRAY_TYPE)
	referent = e;
      else
2734
	{
2735 2736 2737 2738
	  if (TREE_CODE (e) != ADDR_EXPR)
	    {
	    bad_argument:
	      cp_error ("`%E' is not a valid template argument", expr);
2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
	      if (TYPE_PTR_P (expr_type))
		{
		  if (TREE_CODE (TREE_TYPE (expr_type)) == FUNCTION_TYPE)
		    cp_error ("it must be the address of a function with external linkage");
		  else
		    cp_error ("it must be the address of an object with external linkage");
		}
	      else if (TYPE_PTRMEM_P (expr_type)
		       || TYPE_PTRMEMFUNC_P (expr_type))
		cp_error ("it must be a pointer-to-member of the form `&X::Y'");

2750 2751 2752 2753 2754
	      return NULL_TREE;
	    }

	  referent = TREE_OPERAND (e, 0);
	  STRIP_NOPS (referent);
2755 2756 2757 2758
	}

      if (TREE_CODE (referent) == STRING_CST)
	{
2759
	  cp_error ("string literal %E is not a valid template argument because it is the address of an object with static linkage", 
2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770
		    referent);
	  return NULL_TREE;
	}

      if (is_overloaded_fn (referent))
	/* We'll check that it has external linkage later.  */
	;
      else if (TREE_CODE (referent) != VAR_DECL)
	goto bad_argument;
      else if (!TREE_PUBLIC (referent))
	{
jason's avatar
jason committed
2771
	  cp_error ("address of non-extern `%E' cannot be used as template argument", referent); 
2772 2773 2774
	  return error_mark_node;
	}
    }
2775 2776 2777 2778 2779 2780
  else if (INTEGRAL_TYPE_P (expr_type) 
	   || TYPE_PTRMEM_P (expr_type) 
	   || TYPE_PTRMEMFUNC_P (expr_type)
	   /* The next two are g++ extensions.  */
	   || TREE_CODE (expr_type) == REAL_TYPE
	   || TREE_CODE (expr_type) == COMPLEX_TYPE)
2781
    {
2782 2783 2784 2785 2786 2787 2788
      if (! TREE_CONSTANT (expr))
	{
	non_constant:
	  cp_error ("non-constant `%E' cannot be used as template argument",
		    expr);
	  return NULL_TREE;
	}
2789 2790 2791
    }
  else 
    {
jason's avatar
jason committed
2792
      cp_error ("object `%E' cannot be used as template argument", expr);
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
      return NULL_TREE;
    }

  switch (TREE_CODE (type))
    {
    case INTEGER_TYPE:
    case BOOLEAN_TYPE:
    case ENUMERAL_TYPE:
      /* For a non-type template-parameter of integral or enumeration
         type, integral promotions (_conv.prom_) and integral
         conversions (_conv.integral_) are applied. */
      if (!INTEGRAL_TYPE_P (expr_type))
	return error_mark_node;
      
      /* It's safe to call digest_init in this case; we know we're
	 just converting one integral constant expression to another.  */
2809
      expr = digest_init (type, expr, (tree*) 0);
2810

2811
      if (TREE_CODE (expr) != INTEGER_CST)
2812
	/* Curiously, some TREE_CONSTANT integral expressions do not
2813 2814 2815 2816 2817 2818
	   simplify to integer constants.  For example, `3 % 0',
	   remains a TRUNC_MOD_EXPR.  */
	goto non_constant;
      
      return expr;
	
2819 2820 2821 2822 2823 2824
    case REAL_TYPE:
    case COMPLEX_TYPE:
      /* These are g++ extensions.  */
      if (TREE_CODE (expr_type) != TREE_CODE (type))
	return error_mark_node;

2825 2826 2827 2828 2829 2830
      expr = digest_init (type, expr, (tree*) 0);
      
      if (TREE_CODE (expr) != REAL_CST)
	goto non_constant;

      return expr;
2831

2832 2833 2834 2835 2836
    case POINTER_TYPE:
      {
	tree type_pointed_to = TREE_TYPE (type);
 
	if (TYPE_PTRMEM_P (type))
2837 2838 2839 2840 2841 2842 2843 2844
	  {
	    tree e;

	    /* For a non-type template-parameter of type pointer to data
	       member, qualification conversions (_conv.qual_) are
	       applied.  */
	    e = perform_qualification_conversions (type, expr);
	    if (TREE_CODE (e) == NOP_EXPR)
2845 2846 2847 2848 2849 2850 2851 2852
	      /* The call to perform_qualification_conversions will
		 insert a NOP_EXPR over EXPR to do express conversion,
		 if necessary.  But, that will confuse us if we use
		 this (converted) template parameter to instantiate
		 another template; then the thing will not look like a
		 valid template argument.  So, just make a new
		 constant, of the appropriate type.  */
	      e = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
2853 2854
	    return e;
	  }
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865
	else if (TREE_CODE (type_pointed_to) == FUNCTION_TYPE)
	  { 
	    /* For a non-type template-parameter of type pointer to
	       function, only the function-to-pointer conversion
	       (_conv.func_) is applied.  If the template-argument
	       represents a set of overloaded functions (or a pointer to
	       such), the matching function is selected from the set
	       (_over.over_).  */
	    tree fns;
	    tree fn;

2866
	    if (TREE_CODE (expr) == ADDR_EXPR)
2867 2868 2869 2870
	      fns = TREE_OPERAND (expr, 0);
	    else
	      fns = expr;

jason's avatar
Revert  
jason committed
2871
	    fn = instantiate_type (type_pointed_to, fns, 0);
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885

	    if (fn == error_mark_node)
	      return error_mark_node;

	    if (!TREE_PUBLIC (fn))
	      {
		if (really_overloaded_fn (fns))
		  return error_mark_node;
		else
		  goto bad_argument;
	      }

	    expr = build_unary_op (ADDR_EXPR, fn, 0);

2886
	    my_friendly_assert (same_type_p (type, TREE_TYPE (expr)), 
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899
				0);
	    return expr;
	  }
	else 
	  {
	    /* For a non-type template-parameter of type pointer to
	       object, qualification conversions (_conv.qual_) and the
	       array-to-pointer conversion (_conv.array_) are applied.
	       [Note: In particular, neither the null pointer conversion
	       (_conv.ptr_) nor the derived-to-base conversion
	       (_conv.ptr_) are applied.  Although 0 is a valid
	       template-argument for a non-type template-parameter of
	       integral type, it is not a valid template-argument for a
2900 2901 2902 2903 2904
	       non-type template-parameter of pointer type.]  
	    
	       The call to decay_conversion performs the
	       array-to-pointer conversion, if appropriate.  */
	    expr = decay_conversion (expr);
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920

	    if (expr == error_mark_node)
	      return error_mark_node;
	    else
	      return perform_qualification_conversions (type, expr);
	  }
      }
      break;

    case REFERENCE_TYPE:
      {
	tree type_referred_to = TREE_TYPE (type);

	if (TREE_CODE (type_referred_to) == FUNCTION_TYPE)
	  {
	    /* For a non-type template-parameter of type reference to
2921 2922 2923 2924
	       function, no conversions apply.  If the
	       template-argument represents a set of overloaded
	       functions, the matching function is selected from the
	       set (_over.over_).  */
2925 2926 2927
	    tree fns = expr;
	    tree fn;

jason's avatar
Revert  
jason committed
2928
	    fn = instantiate_type (type_referred_to, fns, 0);
2929 2930 2931

	    if (fn == error_mark_node)
	      return error_mark_node;
2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943

	    if (!TREE_PUBLIC (fn))
	      {
		if (really_overloaded_fn (fns))
		  /* Don't issue an error here; we might get a different
		     function if the overloading had worked out
		     differently.  */
		  return error_mark_node;
		else
		  goto bad_argument;
	      }

2944 2945
	    my_friendly_assert (same_type_p (type_referred_to, 
					     TREE_TYPE (fn)),
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957
				0);

	    return fn;
	  }
	else
	  {
	    /* For a non-type template-parameter of type reference to
	       object, no conversions apply.  The type referred to by the
	       reference may be more cv-qualified than the (otherwise
	       identical) type of the template-argument.  The
	       template-parameter is bound directly to the
	       template-argument, which must be an lvalue.  */
2958 2959
	    if ((TYPE_MAIN_VARIANT (expr_type)
		 != TYPE_MAIN_VARIANT (type_referred_to))
2960 2961
		|| !at_least_as_qualified_p (type_referred_to,
					     expr_type)
2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
		|| !real_lvalue_p (expr))
	      return error_mark_node;
	    else
	      return expr;
	  }
      }
      break;

    case RECORD_TYPE:
      {
2972 2973 2974 2975 2976 2977 2978
	if (!TYPE_PTRMEMFUNC_P (type))
	  /* This handles templates like
	       template<class T, T t> void f();
	     when T is substituted with any class.  The second template
	     parameter becomes invalid and the template candidate is
	     rejected.  */
	  return error_mark_node;
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989

	/* For a non-type template-parameter of type pointer to member
	   function, no conversions apply.  If the template-argument
	   represents a set of overloaded member functions, the
	   matching member function is selected from the set
	   (_over.over_).  */

	if (!TYPE_PTRMEMFUNC_P (expr_type) && 
	    expr_type != unknown_type_node)
	  return error_mark_node;

2990
	if (TREE_CODE (expr) == PTRMEM_CST)
2991 2992
	  {
	    /* A ptr-to-member constant.  */
2993
	    if (!same_type_p (type, expr_type))
2994 2995 2996 2997 2998 2999 3000 3001
	      return error_mark_node;
	    else 
	      return expr;
	  }

	if (TREE_CODE (expr) != ADDR_EXPR)
	  return error_mark_node;

3002
	expr = instantiate_type (type, expr, 0);
3003
	
3004
	if (expr == error_mark_node)
3005 3006
	  return error_mark_node;

3007
	my_friendly_assert (same_type_p (type, TREE_TYPE (expr)),
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
			    0);
	return expr;
      }
      break;

    default:
      /* All non-type parameters must have one of these types.  */
      my_friendly_abort (0);
      break;
    }

  return error_mark_node;
}

3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
/* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for 
   template template parameters.  Both PARM_PARMS and ARG_PARMS are 
   vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL 
   or PARM_DECL.
   
   ARG_PARMS may contain more parameters than PARM_PARMS.  If this is 
   the case, then extra parameters must have default arguments.

   Consider the example:
     template <class T, class Allocator = allocator> class vector;
     template<template <class U> class TT> class C;

   C<vector> is a valid instantiation.  PARM_PARMS for the above code 
   contains a TYPE_DECL (for U),  ARG_PARMS contains two TYPE_DECLs (for 
   T and Allocator) and OUTER_ARGS contains the argument that is used to 
   substitute the TT parameter.  */

static int
3040 3041 3042 3043 3044
coerce_template_template_parms (parm_parms, arg_parms, complain, 
				in_decl, outer_args)
     tree parm_parms, arg_parms;
     int complain;
     tree in_decl, outer_args;
3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081
{
  int nparms, nargs, i;
  tree parm, arg;

  my_friendly_assert (TREE_CODE (parm_parms) == TREE_VEC, 0);
  my_friendly_assert (TREE_CODE (arg_parms) == TREE_VEC, 0);

  nparms = TREE_VEC_LENGTH (parm_parms);
  nargs = TREE_VEC_LENGTH (arg_parms);

  /* The rule here is opposite of coerce_template_parms.  */
  if (nargs < nparms
      || (nargs > nparms
	  && TREE_PURPOSE (TREE_VEC_ELT (arg_parms, nparms)) == NULL_TREE))
    return 0;

  for (i = 0; i < nparms; ++i)
    {
      parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
      arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));

      if (arg == NULL_TREE || arg == error_mark_node
          || parm == NULL_TREE || parm == error_mark_node)
	return 0;

      if (TREE_CODE (arg) != TREE_CODE (parm))
        return 0;

      switch (TREE_CODE (parm))
	{
	case TYPE_DECL:
	  break;

	case TEMPLATE_DECL:
	  /* We encounter instantiations of templates like
	       template <template <template <class> class> class TT>
	       class C;  */
3082 3083 3084 3085 3086
	  {
	    tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
	    tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);

	    if (!coerce_template_template_parms (parmparm, argparm, 
3087 3088
					         complain, in_decl,
						 outer_args))
3089 3090 3091
	      return 0;
	  }
	  break;
3092 3093 3094 3095 3096

	case PARM_DECL:
	  /* The tsubst call is used to handle cases such as
	       template <class T, template <T> class TT> class D;  
	     i.e. the parameter list of TT depends on earlier parameters.  */
3097 3098
	  if (!same_type_p (tsubst (TREE_TYPE (parm), outer_args, 
				    complain, in_decl),
3099
			    TREE_TYPE (arg)))
3100 3101 3102 3103 3104 3105 3106 3107 3108 3109
	    return 0;
	  break;
	  
	default:
	  my_friendly_abort (0);
	}
    }
  return 1;
}

3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
/* Convert the indicated template ARG as necessary to match the
   indicated template PARM.  Returns the converted ARG, or
   error_mark_node if the conversion was unsuccessful.  Error messages
   are issued if COMPLAIN is non-zero.  This conversion is for the Ith
   parameter in the parameter list.  ARGS is the full set of template
   arguments deduced so far.  */

static tree
convert_template_argument (parm, arg, args, complain, i, in_decl)
     tree parm;
     tree arg;
     tree args;
     int complain;
     int i;
     tree in_decl;
{
  tree val;
  tree inner_args;
  int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
  
  inner_args = innermost_args (args);

  if (TREE_CODE (arg) == TREE_LIST 
      && TREE_TYPE (arg) != NULL_TREE
      && TREE_CODE (TREE_TYPE (arg)) == OFFSET_TYPE)
    {  
      /* The template argument was the name of some
	 member function.  That's usually
	 illegal, but static members are OK.  In any
	 case, grab the underlying fields/functions
	 and issue an error later if required.  */
      arg = TREE_VALUE (arg);
      TREE_TYPE (arg) = unknown_type_node;
    }

  requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
  requires_type = (TREE_CODE (parm) == TYPE_DECL
		   || requires_tmpl_type);

  /* Check if it is a class template.  If REQUIRES_TMPL_TYPE is true,
     we also accept implicitly created TYPE_DECL as a valid argument.
     This is necessary to handle the case where we pass a template name
     to a template template parameter in a scope where we've derived from
     in instantiation of that template, so the template name refers to that
     instantiation.  We really ought to handle this better.  */
  is_tmpl_type 
    = ((TREE_CODE (arg) == TEMPLATE_DECL
	&& TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
       || (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3159
	   && !TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (arg))
3160 3161 3162 3163 3164
       || (TREE_CODE (arg) == RECORD_TYPE
	   && CLASSTYPE_TEMPLATE_INFO (arg)
	   && TREE_CODE (TYPE_NAME (arg)) == TYPE_DECL
	   && DECL_ARTIFICIAL (TYPE_NAME (arg))
	   && requires_tmpl_type
3165
	   && is_base_of_enclosing_class (arg, current_class_type)));
3166 3167 3168 3169 3170
  if (is_tmpl_type && TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
    arg = TYPE_STUB_DECL (arg);
  else if (is_tmpl_type && TREE_CODE (arg) == RECORD_TYPE)
    arg = CLASSTYPE_TI_TEMPLATE (arg);

3171
  is_type = TYPE_P (arg) || is_tmpl_type;
3172 3173 3174 3175

  if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
      && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
    {
3176
      cp_pedwarn ("to refer to a type member of a template parameter, use `typename %E'", arg);
3177 3178
      
      arg = make_typename_type (TREE_OPERAND (arg, 0),
3179 3180
				TREE_OPERAND (arg, 1),
				complain);
3181 3182 3183 3184 3185 3186 3187 3188
      is_type = 1;
    }
  if (is_type != requires_type)
    {
      if (in_decl)
	{
	  if (complain)
	    {
jason's avatar
jason committed
3189
	      cp_error ("type/value mismatch at argument %d in template parameter list for `%D'",
3190 3191
			i + 1, in_decl);
	      if (is_type)
jason's avatar
jason committed
3192
		cp_error ("  expected a constant of type `%T', got `%T'",
3193 3194 3195
			  TREE_TYPE (parm),
			  (is_tmpl_type ? DECL_NAME (arg) : arg));
	      else
jason's avatar
jason committed
3196
		cp_error ("  expected a type, got `%E'", arg);
3197 3198 3199 3200 3201 3202 3203 3204
	    }
	}
      return error_mark_node;
    }
  if (is_tmpl_type ^ requires_tmpl_type)
    {
      if (in_decl && complain)
	{
jason's avatar
jason committed
3205
	  cp_error ("type/value mismatch at argument %d in template parameter list for `%D'",
3206 3207
		    i + 1, in_decl);
	  if (is_tmpl_type)
jason's avatar
jason committed
3208
	    cp_error ("  expected a type, got `%T'", DECL_NAME (arg));
3209
	  else
jason's avatar
jason committed
3210
	    cp_error ("  expected a class template, got `%T'", arg);
3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221
	}
      return error_mark_node;
    }
      
  if (is_type)
    {
      if (requires_tmpl_type)
	{
	  tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
	  tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);

3222
	  if (coerce_template_template_parms (parmparm, argparm, complain,
3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236
					      in_decl, inner_args))
	    {
	      val = arg;
		  
	      /* TEMPLATE_TEMPLATE_PARM node is preferred over 
		 TEMPLATE_DECL.  */
	      if (val != error_mark_node 
		  && DECL_TEMPLATE_TEMPLATE_PARM_P (val))
		val = TREE_TYPE (val);
	    }
	  else
	    {
	      if (in_decl && complain)
		{
jason's avatar
jason committed
3237
		  cp_error ("type/value mismatch at argument %d in template parameter list for `%D'",
3238
			    i + 1, in_decl);
jason's avatar
jason committed
3239
		  cp_error ("  expected a template of type `%D', got `%D'", parm, arg);
3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258
		}
		  
	      val = error_mark_node;
	    }
	}
      else
	{
	  val = groktypename (arg);
	  if (! processing_template_decl)
	    {
	      /* [basic.link]: A name with no linkage (notably, the
		 name of a class or enumeration declared in a local
		 scope) shall not be used to declare an entity with
		 linkage.  This implies that names with no linkage
		 cannot be used as template arguments.  */
	      tree t = no_linkage_check (val);
	      if (t)
		{
		  if (ANON_AGGRNAME_P (TYPE_IDENTIFIER (t)))
jason's avatar
jason committed
3259 3260
		    cp_pedwarn
		      ("template-argument `%T' uses anonymous type", val);
3261
		  else
jason's avatar
jason committed
3262 3263
		    cp_error
		      ("template-argument `%T' uses local type `%T'",
3264 3265 3266 3267 3268 3269 3270 3271
		       val, t);
		  return error_mark_node;
		}
	    }
	}
    }
  else
    {
3272
      tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294

      if (processing_template_decl)
	arg = maybe_fold_nontype_arg (arg);

      if (!uses_template_parms (arg) && !uses_template_parms (t))
	/* We used to call digest_init here.  However, digest_init
	   will report errors, which we don't want when complain
	   is zero.  More importantly, digest_init will try too
	   hard to convert things: for example, `0' should not be
	   converted to pointer type at this point according to
	   the standard.  Accepting this is not merely an
	   extension, since deciding whether or not these
	   conversions can occur is part of determining which
	   function template to call, or whether a given epxlicit
	   argument specification is legal.  */
	val = convert_nontype_argument (t, arg);
      else
	val = arg;

      if (val == NULL_TREE)
	val = error_mark_node;
      else if (val == error_mark_node && complain)
jason's avatar
jason committed
3295
	cp_error ("could not convert template argument `%E' to `%T'", 
3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307
		  arg, t);
    }

  return val;
}

/* Convert all template arguments to their appropriate types, and
   return a vector containing the innermost resulting template
   arguments.  If any error occurs, return error_mark_node, and, if
   COMPLAIN is non-zero, issue an error message.  Some error messages
   are issued even if COMPLAIN is zero; for instance, if a template
   argument is composed from a local class.
3308 3309 3310 3311

   If REQUIRE_ALL_ARGUMENTS is non-zero, all arguments must be
   provided in ARGLIST, or else trailing parameters must have default
   values.  If REQUIRE_ALL_ARGUMENTS is zero, we will attempt argument
3312
   deduction for any unspecified trailing arguments.  */
3313
   
mrs's avatar
mrs committed
3314
static tree
3315
coerce_template_parms (parms, args, in_decl,
3316
		       complain,
3317
		       require_all_arguments)
3318
     tree parms, args;
mrs's avatar
mrs committed
3319
     tree in_decl;
3320 3321
     int complain;
     int require_all_arguments;
mrs's avatar
mrs committed
3322
{
mrs's avatar
mrs committed
3323
  int nparms, nargs, i, lost = 0;
3324
  tree inner_args;
3325 3326
  tree new_args;
  tree new_inner_args;
mrs's avatar
mrs committed
3327

3328
  inner_args = innermost_args (args);
3329
  nargs = NUM_TMPL_ARGS (inner_args);
mrs's avatar
mrs committed
3330 3331 3332 3333
  nparms = TREE_VEC_LENGTH (parms);

  if (nargs > nparms
      || (nargs < nparms
3334
	  && require_all_arguments
mrs's avatar
mrs committed
3335
	  && TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)) == NULL_TREE))
mrs's avatar
mrs committed
3336
    {
3337 3338
      if (complain) 
	{
jason's avatar
jason committed
3339
	  cp_error ("wrong number of template arguments (%d, should be %d)",
3340
		    nargs, nparms);
3341 3342
	  
	  if (in_decl)
jason's avatar
jason committed
3343
	    cp_error_at ("provided for `%D'", in_decl);
3344 3345
	}

mrs's avatar
mrs committed
3346 3347 3348
      return error_mark_node;
    }

3349
  new_inner_args = make_tree_vec (nparms);
3350 3351
  new_args = add_outermost_template_args (args, new_inner_args);
  for (i = 0; i < nparms; i++)
mrs's avatar
mrs committed
3352
    {
3353 3354
      tree arg;
      tree parm;
3355

3356 3357
      /* Get the Ith template parameter.  */
      parm = TREE_VEC_ELT (parms, i);
3358

3359 3360
      /* Calculate the Ith argument.  */
      if (inner_args && TREE_CODE (inner_args) == TREE_LIST)
mrs's avatar
mrs committed
3361
	{
3362 3363
	  arg = TREE_VALUE (inner_args);
	  inner_args = TREE_CHAIN (inner_args);
mrs's avatar
mrs committed
3364
	}
3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
      else if (i < nargs)
	arg = TREE_VEC_ELT (inner_args, i);
      /* If no template argument was supplied, look for a default
	 value.  */
      else if (TREE_PURPOSE (parm) == NULL_TREE)
	{
	  /* There was no default value.  */
	  my_friendly_assert (!require_all_arguments, 0);
	  break;
	}
      else if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3376
	arg = tsubst (TREE_PURPOSE (parm), new_args, complain, in_decl);
3377
      else
3378 3379
	arg = tsubst_expr (TREE_PURPOSE (parm), new_args, complain,
			   in_decl);
3380

3381
      /* Now, convert the Ith argument, as necessary.  */
3382 3383 3384 3385 3386 3387
      if (arg == NULL_TREE)
	/* We're out of arguments.  */
	{
	  my_friendly_assert (!require_all_arguments, 0);
	  break;
	}
3388
      else if (arg == error_mark_node)
3389
	{
jason's avatar
jason committed
3390
	  cp_error ("template argument %d is invalid", i + 1);
3391
	  arg = error_mark_node;
mrs's avatar
mrs committed
3392
	}
3393 3394 3395 3396 3397 3398
      else 
	arg = convert_template_argument (TREE_VALUE (parm), 
					 arg, new_args, complain, i,
					 in_decl); 
      
      if (arg == error_mark_node)
mrs's avatar
mrs committed
3399
	lost++;
3400
      TREE_VEC_ELT (new_inner_args, i) = arg;
mrs's avatar
mrs committed
3401
    }
3402

mrs's avatar
mrs committed
3403 3404
  if (lost)
    return error_mark_node;
3405 3406

  return new_inner_args;
mrs's avatar
mrs committed
3407 3408
}

3409 3410
/* Returns 1 if template args OT and NT are equivalent.  */

ghazi's avatar
ghazi committed
3411
static int
3412 3413 3414 3415 3416 3417 3418 3419 3420 3421
template_args_equal (ot, nt)
     tree ot, nt;
{
  if (nt == ot)
    return 1;
  if (TREE_CODE (nt) != TREE_CODE (ot))
    return 0;
  if (TREE_CODE (nt) == TREE_VEC)
    /* For member templates */
    return comp_template_args (ot, nt);
3422
  else if (TYPE_P (ot))
3423
    return same_type_p (ot, nt);
3424 3425 3426 3427 3428
  else
    return (cp_tree_equal (ot, nt) > 0);
}

/* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
jason's avatar
jason committed
3429 3430
   of template arguments.  Returns 0 otherwise.  */

3431
int
mrs's avatar
mrs committed
3432 3433 3434 3435 3436
comp_template_args (oldargs, newargs)
     tree oldargs, newargs;
{
  int i;

3437 3438 3439
  if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
    return 0;

mrs's avatar
mrs committed
3440 3441 3442 3443 3444
  for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
    {
      tree nt = TREE_VEC_ELT (newargs, i);
      tree ot = TREE_VEC_ELT (oldargs, i);

3445
      if (! template_args_equal (ot, nt))
3446
	return 0;
mrs's avatar
mrs committed
3447 3448 3449 3450
    }
  return 1;
}

mrs's avatar
mrs committed
3451 3452
/* Given class template name and parameter list, produce a user-friendly name
   for the instantiation.  */
mrs's avatar
mrs committed
3453

mrs's avatar
mrs committed
3454
static char *
3455
mangle_class_name_for_template (name, parms, arglist)
mrs's avatar
mrs committed
3456 3457 3458 3459 3460 3461 3462 3463
     char *name;
     tree parms, arglist;
{
  static struct obstack scratch_obstack;
  static char *scratch_firstobj;
  int i, nparms;

  if (!scratch_firstobj)
mrs's avatar
mrs committed
3464
    gcc_obstack_init (&scratch_obstack);
mrs's avatar
mrs committed
3465 3466
  else
    obstack_free (&scratch_obstack, scratch_firstobj);
mrs's avatar
mrs committed
3467
  scratch_firstobj = obstack_alloc (&scratch_obstack, 1);
mrs's avatar
mrs committed
3468 3469 3470 3471 3472 3473 3474

#define ccat(c)	obstack_1grow (&scratch_obstack, (c));
#define cat(s)	obstack_grow (&scratch_obstack, (s), strlen (s))

  cat (name);
  ccat ('<');
  nparms = TREE_VEC_LENGTH (parms);
3475
  arglist = innermost_args (arglist);
mrs's avatar
mrs committed
3476 3477 3478
  my_friendly_assert (nparms == TREE_VEC_LENGTH (arglist), 268);
  for (i = 0; i < nparms; i++)
    {
mrs's avatar
mrs committed
3479 3480
      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
      tree arg = TREE_VEC_ELT (arglist, i);
mrs's avatar
mrs committed
3481 3482 3483 3484

      if (i)
	ccat (',');

mrs's avatar
mrs committed
3485
      if (TREE_CODE (parm) == TYPE_DECL)
mrs's avatar
mrs committed
3486
	{
nathan's avatar
nathan committed
3487
	  cat (type_as_string (arg, TS_CHASE_TYPEDEFS));
mrs's avatar
mrs committed
3488 3489
	  continue;
	}
3490 3491 3492
      else if (TREE_CODE (parm) == TEMPLATE_DECL)
	{
	  if (TREE_CODE (arg) == TEMPLATE_DECL)
jason's avatar
jason committed
3493 3494 3495
	    {
	      /* Already substituted with real template.  Just output 
		 the template name here */
3496
              tree context = DECL_CONTEXT (arg);
3497 3498 3499 3500 3501 3502 3503
              if (context)
                {
                  /* The template may be defined in a namespace, or
                     may be a member template.  */
                  my_friendly_assert (TREE_CODE (context) == NAMESPACE_DECL
                                      || CLASS_TYPE_P (context), 
                                      980422);
jason's avatar
jason committed
3504 3505 3506 3507 3508
		  cat(decl_as_string (DECL_CONTEXT (arg), 0));
		  cat("::");
		}
	      cat (IDENTIFIER_POINTER (DECL_NAME (arg)));
	    }
3509 3510
	  else
	    /* Output the parameter declaration */
nathan's avatar
nathan committed
3511
	    cat (type_as_string (arg, TS_CHASE_TYPEDEFS));
3512 3513
	  continue;
	}
mrs's avatar
mrs committed
3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
      else
	my_friendly_assert (TREE_CODE (parm) == PARM_DECL, 269);

      if (TREE_CODE (arg) == TREE_LIST)
	{
	  /* New list cell was built because old chain link was in
	     use.  */
	  my_friendly_assert (TREE_PURPOSE (arg) == NULL_TREE, 270);
	  arg = TREE_VALUE (arg);
	}
      /* No need to check arglist against parmlist here; we did that
	 in coerce_template_parms, called from lookup_template_class.  */
      cat (expr_as_string (arg, 0));
    }
  {
    char *bufp = obstack_next_free (&scratch_obstack);
    int offset = 0;
    while (bufp[offset - 1] == ' ')
      offset--;
    obstack_blank_fast (&scratch_obstack, offset);

    /* B<C<char> >, not B<C<char>> */
    if (bufp[offset - 1] == '>')
      ccat (' ');
  }
  ccat ('>');
  ccat ('\0');
  return (char *) obstack_base (&scratch_obstack);
}

mrs's avatar
mrs committed
3544
static tree
mrs's avatar
mrs committed
3545 3546 3547 3548
classtype_mangled_name (t)
     tree t;
{
  if (CLASSTYPE_TEMPLATE_INFO (t)
3549 3550
      /* Specializations have already had their names set up in
	 lookup_template_class.  */
mmitchel's avatar
mmitchel committed
3551
      && !CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
3552 3553 3554
    {
      tree tmpl = most_general_template (CLASSTYPE_TI_TEMPLATE (t));

3555 3556
      /* For non-primary templates, the template parameters are
	 implicit from their surrounding context.  */
3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567
      if (PRIMARY_TEMPLATE_P (tmpl))
	{
	  tree name = DECL_NAME (tmpl);
	  char *mangled_name = mangle_class_name_for_template
	    (IDENTIFIER_POINTER (name), 
	     DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
	     CLASSTYPE_TI_ARGS (t));
	  tree id = get_identifier (mangled_name);
	  IDENTIFIER_TEMPLATE (id) = name;
	  return id;
	}
mrs's avatar
mrs committed
3568
    }
3569 3570

  return TYPE_IDENTIFIER (t);
mrs's avatar
mrs committed
3571 3572 3573 3574 3575 3576
}

static void
add_pending_template (d)
     tree d;
{
3577
  tree ti = (TYPE_P (d)) ? CLASSTYPE_TEMPLATE_INFO (d) : DECL_TEMPLATE_INFO (d);
mrs's avatar
mrs committed
3578

mrs's avatar
mrs committed
3579
  if (TI_PENDING_TEMPLATE_FLAG (ti))
mrs's avatar
mrs committed
3580 3581
    return;

3582
  *template_tail = tree_cons (build_srcloc_here (), d, NULL_TREE);
mrs's avatar
mrs committed
3583
  template_tail = &TREE_CHAIN (*template_tail);
mrs's avatar
mrs committed
3584
  TI_PENDING_TEMPLATE_FLAG (ti) = 1;
mrs's avatar
mrs committed
3585 3586
}

3587 3588 3589 3590 3591 3592 3593 3594 3595

/* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS (which
   may be either a _DECL or an overloaded function or an
   IDENTIFIER_NODE), and ARGLIST.  */

tree
lookup_template_function (fns, arglist)
     tree fns, arglist;
{
jason's avatar
jason committed
3596
  tree type;
3597

3598 3599
  if (fns == NULL_TREE)
    {
jason's avatar
jason committed
3600
      cp_error ("non-template used as template");
3601 3602 3603
      return error_mark_node;
    }

jason's avatar
jason committed
3604 3605 3606 3607
  type = TREE_TYPE (fns);
  if (TREE_CODE (fns) == OVERLOAD || !type)
    type = unknown_type_node;

3608 3609 3610 3611
  if (processing_template_decl)
    return build_min (TEMPLATE_ID_EXPR, type, fns, arglist);  
  else
    return build (TEMPLATE_ID_EXPR, type, fns, arglist);
3612 3613
}

3614 3615 3616 3617 3618 3619 3620
/* Within the scope of a template class S<T>, the name S gets bound
   (in build_self_reference) to a TYPE_DECL for the class, not a
   TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
   or one of its enclosing classes, and that type is a template,
   return the associated TEMPLATE_DECL.  Otherwise, the original
   DECL is returned.  */

3621
static tree
3622 3623 3624 3625 3626 3627
maybe_get_template_decl_from_type_decl (decl)
     tree decl;
{
  return (decl != NULL_TREE
	  && TREE_CODE (decl) == TYPE_DECL 
	  && DECL_ARTIFICIAL (decl)
jason's avatar
jason committed
3628
	  && CLASS_TYPE_P (TREE_TYPE (decl))
3629 3630 3631
	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl))) 
    ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
}
3632

mrs's avatar
mrs committed
3633 3634 3635 3636
/* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
   parameters, find the desired type.

   D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
3637 3638
   (Actually ARGLIST may be either a TREE_LIST or a TREE_VEC.  It will
   be a TREE_LIST if called directly from the parser, and a TREE_VEC
3639
   otherwise.)  Since ARGLIST is build on the temp_decl_obstack, we must
3640 3641
   copy it here to keep it from being reclaimed when the decl storage
   is reclaimed.
mrs's avatar
mrs committed
3642 3643

   IN_DECL, if non-NULL, is the template declaration we are trying to
3644 3645
   instantiate.  

3646 3647 3648
   If ENTERING_SCOPE is non-zero, we are about to enter the scope of
   the class we are looking up.

3649 3650 3651
   If the template class is really a local class in a template
   function, then the FUNCTION_CONTEXT is the function in which it is
   being instantiated.  */
mrs's avatar
mrs committed
3652

mrs's avatar
mrs committed
3653
tree
3654
lookup_template_class (d1, arglist, in_decl, context, entering_scope)
mrs's avatar
mrs committed
3655 3656
     tree d1, arglist;
     tree in_decl;
3657
     tree context;
3658
     int entering_scope;
mrs's avatar
mrs committed
3659
{
3660
  tree template = NULL_TREE, parmlist;
3661
  tree t;
mrs's avatar
mrs committed
3662 3663 3664

  if (TREE_CODE (d1) == IDENTIFIER_NODE)
    {
3665 3666 3667
      if (IDENTIFIER_VALUE (d1) 
	  && DECL_TEMPLATE_TEMPLATE_PARM_P (IDENTIFIER_VALUE (d1)))
	template = IDENTIFIER_VALUE (d1);
3668 3669
      else
	{
jason's avatar
jason committed
3670 3671
	  if (context)
	    push_decl_namespace (context);
3672 3673
	  template = lookup_name (d1, /*prefer_type=*/0);
	  template = maybe_get_template_decl_from_type_decl (template);
jason's avatar
jason committed
3674 3675
	  if (context)
	    pop_decl_namespace ();
3676
	}
3677 3678
      if (template)
	context = DECL_CONTEXT (template);
mrs's avatar
mrs committed
3679
    }
mrs's avatar
mrs committed
3680 3681
  else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
    {
3682 3683 3684 3685 3686 3687 3688 3689
      tree type = TREE_TYPE (d1);

      /* If we are declaring a constructor, say A<T>::A<T>, we will get
	 an implicit typename for the second A.  Deal with it.  */
      if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
	type = TREE_TYPE (type);
	
      if (CLASSTYPE_TEMPLATE_INFO (type))
3690
	{
3691
	  template = CLASSTYPE_TI_TEMPLATE (type);
3692 3693
	  d1 = DECL_NAME (template);
	}
mrs's avatar
mrs committed
3694
    }
3695
  else if (TREE_CODE (d1) == ENUMERAL_TYPE 
3696
	   || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
mrs's avatar
mrs committed
3697
    {
3698
      template = TYPE_TI_TEMPLATE (d1);
mrs's avatar
mrs committed
3699 3700
      d1 = DECL_NAME (template);
    }
3701
  else if (TREE_CODE (d1) == TEMPLATE_DECL
3702
	   && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
3703 3704 3705 3706 3707
    {
      template = d1;
      d1 = DECL_NAME (template);
      context = DECL_CONTEXT (template);
    }
mrs's avatar
mrs committed
3708 3709
  else
    my_friendly_abort (272);
mrs's avatar
mrs committed
3710 3711

  /* With something like `template <class T> class X class X { ... };'
3712 3713 3714 3715
     we could end up with D1 having nothing but an IDENTIFIER_VALUE.
     We don't want to do that, but we have to deal with the situation,
     so let's give them some syntax errors to chew on instead of a
     crash.  */
mrs's avatar
mrs committed
3716
  if (! template)
3717 3718 3719 3720
    {
      cp_error ("`%T' is not a template", d1);
      return error_mark_node;
    }
jason's avatar
jason committed
3721

3722 3723
  if (context == NULL_TREE)
    context = global_namespace;
jason's avatar
jason committed
3724

mrs's avatar
mrs committed
3725 3726
  if (TREE_CODE (template) != TEMPLATE_DECL)
    {
jason's avatar
jason committed
3727
      cp_error ("non-template type `%T' used as a template", d1);
mrs's avatar
mrs committed
3728
      if (in_decl)
jason's avatar
jason committed
3729
	cp_error_at ("for template declaration `%D'", in_decl);
mrs's avatar
mrs committed
3730 3731 3732
      return error_mark_node;
    }

3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743
  if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
    {
      /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
         template arguments */

      tree parm = copy_template_template_parm (TREE_TYPE (template));
      tree template2 = TYPE_STUB_DECL (parm);
      tree arglist2;

      parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);

3744
      arglist2 = coerce_template_parms (parmlist, arglist, template, 1, 1);
3745 3746 3747
      if (arglist2 == error_mark_node)
	return error_mark_node;

3748
      TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (parm)
3749
	= tree_cons (template2, arglist2, NULL_TREE);
3750 3751 3752
      TYPE_SIZE (parm) = 0;
      return parm;
    }
3753
  else 
mrs's avatar
mrs committed
3754
    {
3755
      tree template_type = TREE_TYPE (template);
3756
      tree gen_tmpl;
3757 3758 3759 3760
      tree type_decl;
      tree found = NULL_TREE;
      int arg_depth;
      int parm_depth;
3761
      int is_partial_instantiation;
3762

3763 3764
      gen_tmpl = most_general_template (template);
      parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
3765 3766 3767 3768 3769
      parm_depth = TMPL_PARMS_DEPTH (parmlist);
      arg_depth = TMPL_ARGS_DEPTH (arglist);

      if (arg_depth == 1 && parm_depth > 1)
	{
3770
	  /* We've been given an incomplete set of template arguments.
3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
	     For example, given:

	       template <class T> struct S1 {
	         template <class U> struct S2 {};
		 template <class U> struct S2<U*> {};
	        };
	     
	     we will be called with an ARGLIST of `U*', but the
	     TEMPLATE will be `template <class T> template
	     <class U> struct S1<T>::S2'.  We must fill in the missing
	     arguments.  */
3782 3783 3784
	  arglist 
	    = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
					   arglist);
3785 3786
	  arg_depth = TMPL_ARGS_DEPTH (arglist);
	}
mrs's avatar
mrs committed
3787

3788
      /* Now we should enough arguments.  */
3789 3790
      my_friendly_assert (parm_depth == arg_depth, 0);
      
3791 3792 3793 3794
      /* From here on, we're only interested in the most general
	 template.  */
      template = gen_tmpl;

3795 3796 3797 3798
      /* Calculate the BOUND_ARGS.  These will be the args that are
	 actually tsubst'd into the definition to create the
	 instantiation.  */
      if (parm_depth > 1)
3799 3800 3801
	{
	  /* We have multiple levels of arguments to coerce, at once.  */
	  int i;
3802
	  int saved_depth = TMPL_ARGS_DEPTH (arglist);
3803

3804
	  tree bound_args = make_tree_vec (parm_depth);
3805
	  
3806
	  for (i = saved_depth,
3807
		 t = DECL_TEMPLATE_PARMS (template); 
3808
	       i > 0 && t != NULL_TREE;
3809
	       --i, t = TREE_CHAIN (t))
3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824
	    {
	      tree a = coerce_template_parms (TREE_VALUE (t),
					      arglist, template, 1, 1);
	      SET_TMPL_ARGS_LEVEL (bound_args, i, a);

	      /* We temporarily reduce the length of the ARGLIST so
		 that coerce_template_parms will see only the arguments
		 corresponding to the template parameters it is
		 examining.  */
	      TREE_VEC_LENGTH (arglist)--;
	    }

	  /* Restore the ARGLIST to its full size.  */
	  TREE_VEC_LENGTH (arglist) = saved_depth;

3825
	  arglist = bound_args;
3826 3827
	}
      else
3828 3829 3830 3831 3832 3833 3834
	arglist
	  = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
				   innermost_args (arglist),
				   template, 1, 1);

      if (arglist == error_mark_node)
	/* We were unable to bind the arguments.  */
mrs's avatar
mrs committed
3835 3836
	return error_mark_node;

3837 3838 3839 3840 3841 3842 3843 3844
      /* In the scope of a template class, explicit references to the
	 template class refer to the type of the template, not any
	 instantiation of it.  For example, in:
	 
	   template <class T> class C { void f(C<T>); }

	 the `C<T>' is just the same as `C'.  Outside of the
	 class, however, such a reference is an instantiation.  */
3845
      if (comp_template_args (TYPE_TI_ARGS (template_type),
3846 3847 3848 3849 3850
			      arglist))
	{
	  found = template_type;
	  
	  if (!entering_scope && PRIMARY_TEMPLATE_P (template))
mrs's avatar
mrs committed
3851
	    {
3852 3853 3854 3855 3856 3857 3858 3859
	      tree ctx;
	      
	      /* Note that we use DECL_CONTEXT, rather than
		 CP_DECL_CONTEXT, so that the termination test is
		 always just `ctx'.  We're not interested in namepace
		 scopes.  */
	      for (ctx = current_class_type; 
		   ctx; 
3860
		   ctx = (TYPE_P (ctx)) ? TYPE_CONTEXT (ctx) : DECL_CONTEXT (ctx))
3861
		if (same_type_p (ctx, template_type))
3862 3863 3864 3865 3866 3867 3868
		  break;
	      
	      if (!ctx)
		/* We're not in the scope of the class, so the
		   TEMPLATE_TYPE is not the type we want after
		   all.  */
		found = NULL_TREE;
mrs's avatar
mrs committed
3869 3870
	    }
	}
3871 3872
      
      if (!found)
3873
	{
3874 3875 3876 3877
	  for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
	       found; found = TREE_CHAIN (found))
	    if (comp_template_args (TREE_PURPOSE (found), arglist))
	      break;
3878

3879 3880
	  if (found)
	    found = TREE_VALUE (found);
mrs's avatar
mrs committed
3881
	}
3882

3883
      if (found)
3884
	return found;
mrs's avatar
mrs committed
3885

3886
      /* This type is a "partial instantiation" if any of the template
3887 3888 3889
	 arguments still inolve template parameters.  Note that we set
	 IS_PARTIAL_INSTANTIATION for partial specializations as
	 well.  */
3890 3891
      is_partial_instantiation = uses_template_parms (arglist);

3892 3893 3894 3895 3896 3897 3898 3899 3900 3901
      if (!is_partial_instantiation 
	  && !PRIMARY_TEMPLATE_P (template)
	  && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
	{
	  found = xref_tag_from_type (TREE_TYPE (template),
				      DECL_NAME (template),
				      /*globalize=*/1);
	  return found;
	}
      
3902
      /* Create the type.  */
3903 3904
      if (TREE_CODE (template_type) == ENUMERAL_TYPE)
	{
3905
	  if (!is_partial_instantiation)
3906
	    t = start_enum (TYPE_IDENTIFIER (template_type));
3907
	  else
3908
	    /* We don't want to call start_enum for this type, since
3909 3910 3911 3912 3913 3914 3915
	       the values for the enumeration constants may involve
	       template parameters.  And, no one should be interested
	       in the enumeration constants for such a type.  */
	    t = make_node (ENUMERAL_TYPE);
	}
      else
	{
rth's avatar
rth committed
3916
	  t = make_aggr_type (TREE_CODE (template_type));
3917 3918 3919 3920
	  CLASSTYPE_DECLARED_CLASS (t) 
	    = CLASSTYPE_DECLARED_CLASS (template_type);
	  CLASSTYPE_GOT_SEMICOLON (t) = 1;
	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
bothner's avatar
(  
bothner committed
3921
	  TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
3922 3923 3924 3925

	  /* A local class.  Make sure the decl gets registered properly.  */
	  if (context == current_function_decl)
	    pushtag (DECL_NAME (template), t, 0);
3926 3927
	}

3928 3929
      /* If we called start_enum or pushtag above, this information
	 will already be set up.  */
3930 3931 3932
      if (!TYPE_NAME (t))
	{
	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
3933
	  
3934
	  type_decl = create_implicit_typedef (DECL_NAME (template), t);
3935
	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
3936
	  TYPE_STUB_DECL (t) = type_decl;
3937 3938 3939 3940 3941 3942 3943
	  DECL_SOURCE_FILE (type_decl) 
	    = DECL_SOURCE_FILE (TYPE_STUB_DECL (template_type));
	  DECL_SOURCE_LINE (type_decl) 
	    = DECL_SOURCE_LINE (TYPE_STUB_DECL (template_type));
	}
      else
	type_decl = TYPE_NAME (t);
3944

3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
      /* Set up the template information.  We have to figure out which
	 template is the immediate parent if this is a full
	 instantiation.  */
      if (parm_depth == 1 || is_partial_instantiation
	  || !PRIMARY_TEMPLATE_P (template))
	/* This case is easy; there are no member templates involved.  */
	found = template;
      else
	{
	  /* This is a full instantiation of a member template.  There
	     should be some partial instantiation of which this is an
	     instance.  */

	  for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
	       found; found = TREE_CHAIN (found))
	    {
	      int success;
	      tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));

	      /* We only want partial instantiations, here, not
		 specializations or full instantiations.  */
mmitchel's avatar
mmitchel committed
3966
	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994
		  || !uses_template_parms (TREE_VALUE (found)))
		continue;

	      /* Temporarily reduce by one the number of levels in the
		 ARGLIST and in FOUND so as to avoid comparing the
		 last set of arguments.  */
	      TREE_VEC_LENGTH (arglist)--;
	      TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;

	      /* See if the arguments match.  If they do, then TMPL is
		 the partial instantiation we want.  */
	      success = comp_template_args (TREE_PURPOSE (found), arglist);

	      /* Restore the argument vectors to their full size.  */
	      TREE_VEC_LENGTH (arglist)++;
	      TREE_VEC_LENGTH (TREE_PURPOSE (found))++;

	      if (success)
		{
		  found = tmpl;
		  break;
		}
	    }

	  if (!found)
	    my_friendly_abort (0);
	}

3995
      SET_TYPE_TEMPLATE_INFO (t,
3996
			      tree_cons (found, arglist, NULL_TREE));  
3997 3998 3999 4000 4001 4002
      DECL_TEMPLATE_INSTANTIATIONS (template) 
	= tree_cons (arglist, t, 
		     DECL_TEMPLATE_INSTANTIATIONS (template));

      if (TREE_CODE (t) == ENUMERAL_TYPE 
	  && !is_partial_instantiation)
4003 4004 4005 4006 4007 4008 4009 4010
	/* Now that the type has been registered on the instantiations
	   list, we set up the enumerators.  Because the enumeration
	   constants may involve the enumeration type itself, we make
	   sure to register the type first, and then create the
	   constants.  That way, doing tsubst_expr for the enumeration
	   constants won't result in recursive calls here; we'll find
	   the instantiation and exit above.  */
	tsubst_enum (template_type, t, arglist);
4011

4012 4013
      /* Reset the name of the type, now that CLASSTYPE_TEMPLATE_INFO
	 is set up.  */
4014 4015
      if (TREE_CODE (t) != ENUMERAL_TYPE)
	DECL_NAME (type_decl) = classtype_mangled_name (t);
4016
      DECL_ASSEMBLER_NAME (type_decl) = DECL_NAME (type_decl);
4017
      if (!is_partial_instantiation)
4018 4019 4020
	{
	  DECL_ASSEMBLER_NAME (type_decl)
	    = get_identifier (build_overload_name (t, 1, 1));
4021 4022 4023 4024 4025

	  /* For backwards compatibility; code that uses
	     -fexternal-templates expects looking up a template to
	     instantiate it.  I think DDD still relies on this.
	     (jason 8/20/1998) */
4026 4027
	  if (TREE_CODE (t) != ENUMERAL_TYPE
	      && flag_external_templates
4028 4029 4030 4031 4032
	      && CLASSTYPE_INTERFACE_KNOWN (TREE_TYPE (template))
	      && ! CLASSTYPE_INTERFACE_ONLY (TREE_TYPE (template)))
	    add_pending_template (t);
	}
      else
4033 4034 4035
	/* If the type makes use of template parameters, the
	   code that generates debugging information will crash.  */
	DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
mrs's avatar
mrs committed
4036

4037 4038
      return t;
    }
mrs's avatar
mrs committed
4039 4040
}

4041
struct pair_fn_data 
mrs's avatar
mrs committed
4042
{
4043 4044 4045 4046 4047
  tree_fn_t fn;
  void *data;
};

/* Called from for_each_template_parm via walk_tree.  */
4048

4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059
static tree
for_each_template_parm_r (tp, walk_subtrees, d)
     tree *tp;
     int *walk_subtrees;
     void *d;
{
  tree t = *tp;
  struct pair_fn_data *pfd = (struct pair_fn_data *) d;
  tree_fn_t fn = pfd->fn;
  void *data = pfd->data;
  
4060
  if (TYPE_P (t)
4061
      && for_each_template_parm (TYPE_CONTEXT (t), fn, data))
4062
    return error_mark_node;
4063

mrs's avatar
mrs committed
4064 4065 4066
  switch (TREE_CODE (t))
    {
    case RECORD_TYPE:
mrs's avatar
mrs committed
4067
      if (TYPE_PTRMEMFUNC_FLAG (t))
4068
	break;
4069 4070
      /* Fall through.  */

mrs's avatar
mrs committed
4071
    case UNION_TYPE:
4072
    case ENUMERAL_TYPE:
4073 4074 4075 4076 4077 4078 4079
      if (!TYPE_TEMPLATE_INFO (t))
	*walk_subtrees = 0;
      else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
				       fn, data))
	return error_mark_node;
      break;

4080
    case METHOD_TYPE:
4081 4082
      /* Since we're not going to walk subtrees, we have to do this
	 explicitly here.  */
4083
      if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data))
4084
	return error_mark_node;
4085 4086

    case FUNCTION_TYPE:
4087 4088 4089 4090
      /* Check the return type.  */
      if (for_each_template_parm (TREE_TYPE (t), fn, data))
	return error_mark_node;

4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101
      /* Check the parameter types.  Since default arguments are not
	 instantiated until they are needed, the TYPE_ARG_TYPES may
	 contain expressions that involve template parameters.  But,
	 no-one should be looking at them yet.  And, once they're
	 instantiated, they don't contain template parameters, so
	 there's no point in looking at them then, either.  */
      {
	tree parm;

	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
	  if (for_each_template_parm (TREE_VALUE (parm), fn, data))
4102
	    return error_mark_node;
mrs's avatar
mrs committed
4103

4104 4105 4106 4107 4108
	/* Since we've already handled the TYPE_ARG_TYPES, we don't
	   want walk_tree walking into them itself.  */
	*walk_subtrees = 0;
      }
      break;
4109

mrs's avatar
mrs committed
4110
    case FUNCTION_DECL:
mrs's avatar
mrs committed
4111 4112
    case VAR_DECL:
      if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
4113
	  && for_each_template_parm (DECL_TI_ARGS (t), fn, data))
4114 4115 4116 4117
	return error_mark_node;
      /* Fall through.  */

    case CONST_DECL:
mrs's avatar
mrs committed
4118
    case PARM_DECL:
4119 4120
      if (DECL_CONTEXT (t) 
	  && for_each_template_parm (DECL_CONTEXT (t), fn, data))
4121 4122
	return error_mark_node;
      break;
mrs's avatar
mrs committed
4123

4124
    case TEMPLATE_TEMPLATE_PARM:
4125
      /* Record template parameters such as `T' inside `TT<T>'.  */
4126 4127
      if (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t)
	  && for_each_template_parm (TYPE_TI_ARGS (t), fn, data))
4128 4129 4130
	return error_mark_node;
      /* Fall through.  */

4131
    case TEMPLATE_TYPE_PARM:
jason's avatar
jason committed
4132
    case TEMPLATE_PARM_INDEX:
4133 4134 4135 4136 4137
      if (fn && (*fn)(t, data))
	return error_mark_node;
      else if (!fn)
	return error_mark_node;
      break;
mrs's avatar
mrs committed
4138

4139 4140 4141 4142 4143
    case TEMPLATE_DECL:
      /* A template template parameter is encountered */
      if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
	  && for_each_template_parm (TREE_TYPE (t), fn, data))
	return error_mark_node;
mrs's avatar
mrs committed
4144

4145 4146 4147
      /* Already substituted template template parameter */
      *walk_subtrees = 0;
      break;
4148

4149
    case TYPENAME_TYPE:
4150 4151 4152
      if (!fn || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn, data))
	return error_mark_node;
      break;
4153

4154 4155 4156 4157 4158 4159 4160
    case CONSTRUCTOR:
      if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
	  && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
				     (TREE_TYPE (t)), fn, data))
	return error_mark_node;
      break;
      
4161 4162
    case INDIRECT_REF:
    case COMPONENT_REF:
4163
      /* If there's no type, then this thing must be some expression
4164
	 involving template parameters.  */
4165
      if (!fn && !TREE_TYPE (t))
4166 4167
	return error_mark_node;
      break;
4168

brendan's avatar
brendan committed
4169 4170 4171 4172 4173 4174 4175 4176 4177
    case MODOP_EXPR:
    case CAST_EXPR:
    case REINTERPRET_CAST_EXPR:
    case CONST_CAST_EXPR:
    case STATIC_CAST_EXPR:
    case DYNAMIC_CAST_EXPR:
    case ARROW_EXPR:
    case DOTSTAR_EXPR:
    case TYPEID_EXPR:
4178
    case LOOKUP_EXPR:
4179
    case PSEUDO_DTOR_EXPR:
4180
      if (!fn)
4181 4182
	return error_mark_node;
      break;
4183

mrs's avatar
mrs committed
4184
    default:
4185
      break;
mrs's avatar
mrs committed
4186
    }
4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213

  /* We didn't find any template parameters we liked.  */
  return NULL_TREE;
}

/* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM, or
   TEMPLATE_PARM_INDEX in T, call FN with the parameter and the DATA.
   If FN returns non-zero, the iteration is terminated, and
   for_each_template_parm returns 1.  Otherwise, the iteration
   continues.  If FN never returns a non-zero value, the value
   returned by for_each_template_parm is 0.  If FN is NULL, it is
   considered to be the function which always returns 1.  */

static int
for_each_template_parm (t, fn, data)
     tree t;
     tree_fn_t fn;
     void* data;
{
  struct pair_fn_data pfd;

  /* Set up.  */
  pfd.fn = fn;
  pfd.data = data;

  /* Walk the tree.  */
  return walk_tree (&t, for_each_template_parm_r, &pfd) != NULL_TREE;
mrs's avatar
mrs committed
4214 4215
}

4216 4217 4218 4219 4220 4221 4222
int
uses_template_parms (t)
     tree t;
{
  return for_each_template_parm (t, 0, 0);
}

4223 4224 4225
static struct tinst_level *current_tinst_level;
static struct tinst_level *free_tinst_level;
static int tinst_depth;
mrs's avatar
mrs committed
4226
extern int max_tinst_depth;
mrs's avatar
mrs committed
4227
#ifdef GATHER_STATISTICS
4228
int depth_reached;
mrs's avatar
mrs committed
4229
#endif
4230 4231
static int tinst_level_tick;
static int last_template_error_tick;
mrs's avatar
mrs committed
4232

4233
/* Print out all the template instantiations that we are currently
4234 4235
   working on.  If ERR, we are being called from cp_thing, so do
   the right thing for an error message.  */
4236

4237 4238 4239
static void
print_template_context (err)
     int err;
4240 4241 4242 4243 4244
{
  struct tinst_level *p = current_tinst_level;
  int line = lineno;
  char *file = input_filename;

4245
  if (err && p)
4246
    {
4247 4248 4249 4250 4251 4252
      if (current_function_decl != p->decl
	  && current_function_decl != NULL_TREE)
	/* We can get here during the processing of some synthesized
	   method.  Then, p->decl will be the function that's causing
	   the synthesis.  */
	;
4253 4254
      else
	{
4255 4256 4257 4258
	  if (current_function_decl == p->decl)
	    /* Avoid redundancy with the the "In function" line.  */;
	  else 
	    fprintf (stderr, "%s: In instantiation of `%s':\n",
nathan's avatar
nathan committed
4259
		     file, decl_as_string (p->decl, TS_DECL_TYPE | TS_FUNC_NORETURN));
4260
	  
4261 4262
	  line = p->line;
	  file = p->file;
4263 4264 4265 4266
	  p = p->next;
	}
    }

4267 4268
  for (; p; p = p->next)
    {
4269
      fprintf (stderr, "%s:%d:   instantiated from `%s'\n", file, line,
nathan's avatar
nathan committed
4270
	       decl_as_string (p->decl, TS_DECL_TYPE | TS_FUNC_NORETURN));
4271 4272
      line = p->line;
      file = p->file;
4273
    }
4274
  fprintf (stderr, "%s:%d:   instantiated from here\n", file, line);
4275 4276
}

4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289
/* Called from cp_thing to print the template context for an error.  */

void
maybe_print_template_context ()
{
  if (last_template_error_tick == tinst_level_tick
      || current_tinst_level == 0)
    return;

  last_template_error_tick = tinst_level_tick;
  print_template_context (1);
}

mrs's avatar
mrs committed
4290
static int
mrs's avatar
mrs committed
4291 4292
push_tinst_level (d)
     tree d;
mrs's avatar
mrs committed
4293 4294 4295
{
  struct tinst_level *new;

mrs's avatar
mrs committed
4296 4297
  if (tinst_depth >= max_tinst_depth)
    {
4298 4299 4300 4301 4302 4303
      /* If the instantiation in question still has unbound template parms,
	 we don't really care if we can't instantiate it, so just return.
         This happens with base instantiation for implicit `typename'.  */
      if (uses_template_parms (d))
	return 0;

jason's avatar
jason committed
4304
      last_template_error_tick = tinst_level_tick;
4305 4306
      cp_error ("template instantiation depth exceeds maximum of %d (use -ftemplate-depth-NN to increase the maximum) instantiating `%D'",
	     max_tinst_depth, d);
mrs's avatar
mrs committed
4307

4308
      print_template_context (0);
mrs's avatar
mrs committed
4309

mrs's avatar
mrs committed
4310 4311 4312
      return 0;
    }

mrs's avatar
mrs committed
4313 4314 4315 4316 4317 4318 4319 4320
  if (free_tinst_level)
    {
      new = free_tinst_level;
      free_tinst_level = new->next;
    }
  else
    new = (struct tinst_level *) xmalloc (sizeof (struct tinst_level));

mrs's avatar
mrs committed
4321 4322 4323
  new->decl = d;
  new->line = lineno;
  new->file = input_filename;
mrs's avatar
mrs committed
4324 4325
  new->next = current_tinst_level;
  current_tinst_level = new;
mrs's avatar
mrs committed
4326

mrs's avatar
mrs committed
4327
  ++tinst_depth;
mrs's avatar
mrs committed
4328 4329 4330 4331 4332
#ifdef GATHER_STATISTICS
  if (tinst_depth > depth_reached)
    depth_reached = tinst_depth;
#endif

4333
  ++tinst_level_tick;
mrs's avatar
mrs committed
4334
  return 1;
mrs's avatar
mrs committed
4335 4336 4337 4338 4339 4340 4341
}

void
pop_tinst_level ()
{
  struct tinst_level *old = current_tinst_level;

4342 4343 4344 4345
  /* Restore the filename and line number stashed away when we started
     this instantiation.  */
  lineno = old->line;
  input_filename = old->file;
4346
  extract_interface_info ();
4347
  
mrs's avatar
mrs committed
4348 4349 4350
  current_tinst_level = old->next;
  old->next = free_tinst_level;
  free_tinst_level = old;
mrs's avatar
mrs committed
4351
  --tinst_depth;
4352
  ++tinst_level_tick;
mrs's avatar
mrs committed
4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365
}

struct tinst_level *
tinst_for_decl ()
{
  struct tinst_level *p = current_tinst_level;

  if (p)
    for (; p->next ; p = p->next )
      ;
  return p;
}

jason's avatar
jason committed
4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376
/* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
   vector of template arguments, as for tsubst.

   Returns an appropriate tsbust'd friend declaration.  */

static tree
tsubst_friend_function (decl, args)
     tree decl;
     tree args;
{
  tree new_friend;
4377 4378 4379 4380 4381 4382
  int line = lineno;
  char *file = input_filename;

  lineno = DECL_SOURCE_LINE (decl);
  input_filename = DECL_SOURCE_FILE (decl);

jason's avatar
jason committed
4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400
  if (TREE_CODE (decl) == FUNCTION_DECL 
      && DECL_TEMPLATE_INSTANTIATION (decl)
      && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
    /* This was a friend declared with an explicit template
       argument list, e.g.:
       
       friend void f<>(T);
       
       to indicate that f was a template instantiation, not a new
       function declaration.  Now, we have to figure out what
       instantiation of what template.  */
    {
      tree template_id;
      tree new_args;
      tree tmpl;

      template_id
	= lookup_template_function (tsubst_expr (DECL_TI_TEMPLATE (decl),
4401 4402
						 args, /*complain=*/1, 
						 NULL_TREE),
jason's avatar
jason committed
4403
				    tsubst (DECL_TI_ARGS (decl),
4404 4405 4406
					    args, /*complain=*/1, 
					    NULL_TREE));
      new_friend = tsubst (decl, args, /*complain=*/1, NULL_TREE);
4407 4408
      tmpl = determine_specialization (template_id, new_friend,
				       &new_args, 
4409
				       /*need_member_template=*/0);
4410 4411
      new_friend = instantiate_template (tmpl, new_args);
      goto done;
jason's avatar
jason committed
4412
    }
4413

4414
  new_friend = tsubst (decl, args, /*complain=*/1, NULL_TREE);
jason's avatar
jason committed
4415
	
4416
  /* The NEW_FRIEND will look like an instantiation, to the
jason's avatar
jason committed
4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428
     compiler, but is not an instantiation from the point of view of
     the language.  For example, we might have had:
     
     template <class T> struct S {
       template <class U> friend void f(T, U);
     };
     
     Then, in S<int>, template <class U> void f(int, U) is not an
     instantiation of anything.  */
  DECL_USE_TEMPLATE (new_friend) = 0;
  if (TREE_CODE (decl) == TEMPLATE_DECL)
    DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444

  /* The mangled name for the NEW_FRIEND is incorrect.  The call to
     tsubst will have resulted in a call to
     set_mangled_name_for_template_decl.  But, the function is not a
     template instantiation and should not be mangled like one.
     Therefore, we remangle the function name.  We don't have to do
     this if the NEW_FRIEND is a template since
     set_mangled_name_for_template_decl doesn't do anything if the
     function declaration still uses template arguments.  */
  if (TREE_CODE (new_friend) != TEMPLATE_DECL)
    {
      set_mangled_name_for_decl (new_friend);
      DECL_RTL (new_friend) = 0;
      make_decl_rtl (new_friend, NULL_PTR, 1);
    }
      
4445
  if (DECL_NAMESPACE_SCOPE_P (new_friend))
jason's avatar
jason committed
4446
    {
4447
      tree old_decl;
4448 4449
      tree new_friend_template_info;
      tree new_friend_result_template_info;
4450
      tree ns;
4451 4452 4453 4454 4455 4456
      int  new_friend_is_defn;

      /* We must save some information from NEW_FRIEND before calling
	 duplicate decls since that function will free NEW_FRIEND if
	 possible.  */
      new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
jason's avatar
jason committed
4457
      if (TREE_CODE (new_friend) == TEMPLATE_DECL)
4458 4459 4460 4461 4462
	{
	  /* This declaration is a `primary' template.  */
	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
	  
	  new_friend_is_defn 
4463
	    = DECL_INITIAL (DECL_TEMPLATE_RESULT (new_friend)) != NULL_TREE;
4464
	  new_friend_result_template_info
4465
	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
4466 4467 4468 4469 4470 4471
	}
      else
	{
	  new_friend_is_defn = DECL_INITIAL (new_friend) != NULL_TREE;
	  new_friend_result_template_info = NULL_TREE;
	}
4472

4473 4474 4475
      /* Inside pushdecl_namespace_level, we will push into the
	 current namespace. However, the friend function should go
	 into the namespace of the template. */
4476 4477
      ns = decl_namespace_context (new_friend);
      push_nested_namespace (ns);
4478
      old_decl = pushdecl_namespace_level (new_friend);
4479
      pop_nested_namespace (ns);
4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516

      if (old_decl != new_friend)
	{
	  /* This new friend declaration matched an existing
	     declaration.  For example, given:

	       template <class T> void f(T);
	       template <class U> class C { 
		 template <class T> friend void f(T) {} 
	       };

	     the friend declaration actually provides the definition
	     of `f', once C has been instantiated for some type.  So,
	     old_decl will be the out-of-class template declaration,
	     while new_friend is the in-class definition.

	     But, if `f' was called before this point, the
	     instantiation of `f' will have DECL_TI_ARGS corresponding
	     to `T' but not to `U', references to which might appear
	     in the definition of `f'.  Previously, the most general
	     template for an instantiation of `f' was the out-of-class
	     version; now it is the in-class version.  Therefore, we
	     run through all specialization of `f', adding to their
	     DECL_TI_ARGS appropriately.  In particular, they need a
	     new set of outer arguments, corresponding to the
	     arguments for this class instantiation.  

	     The same situation can arise with something like this:

	       friend void f(int);
	       template <class T> class C { 
	         friend void f(T) {}
               };

	     when `C<int>' is instantiated.  Now, `f(int)' is defined
	     in the class.  */

4517 4518 4519 4520 4521
	  if (!new_friend_is_defn)
	    /* On the other hand, if the in-class declaration does
	       *not* provide a definition, then we don't want to alter
	       existing definitions.  We can just leave everything
	       alone.  */
4522
	    ;
4523
	  else
4524
	    {
4525 4526 4527 4528 4529 4530 4531 4532 4533
	      /* Overwrite whatever template info was there before, if
		 any, with the new template information pertaining to
		 the declaration.  */
	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;

	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
		/* duplicate_decls will take care of this case.  */
		;
	      else 
4534
		{
4535 4536 4537
		  tree t;
		  tree new_friend_args;

4538
		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl)) 
4539 4540 4541 4542 4543 4544 4545 4546
		    = new_friend_result_template_info;
		    
		  new_friend_args = TI_ARGS (new_friend_template_info);
		  for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl); 
		       t != NULL_TREE;
		       t = TREE_CHAIN (t))
		    {
		      tree spec = TREE_VALUE (t);
4547
		  
4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563
		      DECL_TI_ARGS (spec) 
			= add_outermost_template_args (new_friend_args,
						       DECL_TI_ARGS (spec));
		    }

		  /* Now, since specializations are always supposed to
		     hang off of the most general template, we must move
		     them.  */
		  t = most_general_template (old_decl);
		  if (t != old_decl)
		    {
		      DECL_TEMPLATE_SPECIALIZATIONS (t)
			= chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
				   DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
		      DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
		    }
4564 4565 4566 4567 4568 4569 4570
		}
	    }

	  /* The information from NEW_FRIEND has been merged into OLD_DECL
	     by duplicate_decls.  */
	  new_friend = old_decl;
	}
jason's avatar
jason committed
4571
    }
nathan's avatar
gcc  
nathan committed
4572
  else if (COMPLETE_TYPE_P (DECL_CONTEXT (new_friend)))
jason's avatar
jason committed
4573 4574 4575 4576 4577 4578 4579 4580 4581 4582
    {
      /* Check to see that the declaration is really present, and,
	 possibly obtain an improved declaration.  */
      tree fn = check_classfn (DECL_CONTEXT (new_friend),
			       new_friend);
      
      if (fn)
	new_friend = fn;
    }

4583 4584 4585
 done:
  lineno = line;
  input_filename = file;
jason's avatar
jason committed
4586 4587 4588
  return new_friend;
}

4589 4590
/* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
   template arguments, as for tsubst.
4591 4592 4593 4594

   Returns an appropriate tsbust'd friend type.  */

static tree
4595 4596
tsubst_friend_class (friend_tmpl, args)
     tree friend_tmpl;
4597 4598
     tree args;
{
4599
  tree friend_type;
4600
  tree tmpl;
4601

4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615
  /* First, we look for a class template.  */
  tmpl = lookup_name (DECL_NAME (friend_tmpl), /*prefer_type=*/0); 
  
  /* But, if we don't find one, it might be because we're in a
     situation like this:

       template <class T>
       struct S {
         template <class U>
	 friend struct S;
       };

     Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
     for `S<int>', not the TEMPLATE_DECL.  */
4616
  if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
4617 4618 4619 4620
    {
      tmpl = lookup_name (DECL_NAME (friend_tmpl), /*prefer_type=*/1);
      tmpl = maybe_get_template_decl_from_type_decl (tmpl);
    }
4621

4622
  if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
4623 4624
    {
      /* The friend template has already been declared.  Just
4625 4626 4627 4628 4629 4630 4631
	 check to see that the declarations match, and install any new
	 default parameters.  We must tsubst the default parameters,
	 of course.  We only need the innermost template parameters
	 because that is all that redeclare_class_template will look
	 at.  */
      tree parms 
	= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
4632
				 args, /*complain=*/1);
4633
      redeclare_class_template (TREE_TYPE (tmpl), parms);
4634 4635 4636 4637 4638 4639 4640
      friend_type = TREE_TYPE (tmpl);
    }
  else
    {
      /* The friend template has not already been declared.  In this
	 case, the instantiation of the template class will cause the
	 injection of this template into the global scope.  */
4641
      tmpl = tsubst (friend_tmpl, args, /*complain=*/1, NULL_TREE);
4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656

      /* The new TMPL is not an instantiation of anything, so we
 	 forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
	 the new type because that is supposed to be the corresponding
	 template decl, i.e., TMPL.  */
      DECL_USE_TEMPLATE (tmpl) = 0;
      DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
      CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;

      /* Inject this template into the global scope.  */
      friend_type = TREE_TYPE (pushdecl_top_level (tmpl));
    }

  return friend_type;
}
jason's avatar
jason committed
4657

mrs's avatar
mrs committed
4658
tree
mrs's avatar
mrs committed
4659 4660
instantiate_class_template (type)
     tree type;
mrs's avatar
mrs committed
4661
{
4662
  tree template, args, pattern, t;
4663
  tree typedecl;
mrs's avatar
mrs committed
4664

mrs's avatar
mrs committed
4665
  if (type == error_mark_node)
mrs's avatar
mrs committed
4666 4667
    return error_mark_node;

nathan's avatar
gcc  
nathan committed
4668
  if (TYPE_BEING_DEFINED (type) || COMPLETE_TYPE_P (type))
mrs's avatar
mrs committed
4669 4670
    return type;

4671
  /* Figure out which template is being instantiated.  */
4672
  template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
mrs's avatar
mrs committed
4673
  my_friendly_assert (TREE_CODE (template) == TEMPLATE_DECL, 279);
mrs's avatar
mrs committed
4674

4675 4676 4677
  /* Figure out which arguments are being used to do the
     instantiation.  */
  args = CLASSTYPE_TI_ARGS (type);
4678
  PARTIAL_INSTANTIATION_P (type) = uses_template_parms (args);
4679

4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696
  if (pedantic && PARTIAL_INSTANTIATION_P (type))
    /* If this is a partial instantiation, then we can't instantiate
       the type; there's no telling whether or not one of the
       template parameters might eventually be instantiated to some
       value that results in a specialization being used.  For
       example, consider:

         template <class T>
         struct S {};

         template <class U> 
         void f(S<U>);
	     
         template <> 
         struct S<int> {};

       Now, the `S<U>' in `f<int>' is the specialization, not an
4697
       instantiation of the original template.  */
4698
    return type;
4699 4700 4701 4702

  /* Determine what specialization of the original template to
     instantiate.  */
  if (PARTIAL_INSTANTIATION_P (type))
4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714
    /* There's no telling which specialization is appropriate at this
       point.  Since all peeking at the innards of this partial
       instantiation are extensions (like the "implicit typename"
       extension, which allows users to omit the keyword `typename' on
       names that are declared as types in template base classes), we
       are free to do what we please.

       Trying to figure out which partial instantiation to use can
       cause a crash.  (Some of the template arguments don't even have
       types.)  So, we just use the most general version.  */
    t = NULL_TREE;
  else
mrs's avatar
mrs committed
4715
    {
4716 4717 4718
      t = most_specialized_class (template, args);

      if (t == error_mark_node)
mrs's avatar
mrs committed
4719
	{
ghazi's avatar
ghazi committed
4720
	  const char *str = "candidates are:";
4721 4722 4723
	  cp_error ("ambiguous class template instantiation for `%#T'", type);
	  for (t = DECL_TEMPLATE_SPECIALIZATIONS (template); t; 
	       t = TREE_CHAIN (t))
mrs's avatar
mrs committed
4724
	    {
4725 4726 4727 4728 4729 4730
	      if (get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t),
				      args))
		{
		  cp_error_at ("%s %+#T", str, TREE_TYPE (t));
		  str = "               ";
		}
mrs's avatar
mrs committed
4731
	    }
4732
	  TYPE_BEING_DEFINED (type) = 1;
4733
	  return error_mark_node;
mrs's avatar
mrs committed
4734 4735
	}
    }
4736 4737

  if (t)
mrs's avatar
mrs committed
4738 4739 4740
    pattern = TREE_TYPE (t);
  else
    pattern = TREE_TYPE (template);
mrs's avatar
mrs committed
4741

4742 4743
  /* If the template we're instantiating is incomplete, then clearly
     there's nothing we can do.  */
nathan's avatar
gcc  
nathan committed
4744
  if (!COMPLETE_TYPE_P (pattern))
4745
    return type;
mrs's avatar
mrs committed
4746

4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759
  /* If this is a partial instantiation, don't tsubst anything.  We will
     only use this type for implicit typename, so the actual contents don't
     matter.  All that matters is whether a particular name is a type.  */
  if (PARTIAL_INSTANTIATION_P (type))
    {
      /* The fields set here must be kept in sync with those cleared
	 in begin_class_definition.  */
      TYPE_BINFO_BASETYPES (type) = TYPE_BINFO_BASETYPES (pattern);
      TYPE_FIELDS (type) = TYPE_FIELDS (pattern);
      TYPE_METHODS (type) = TYPE_METHODS (pattern);
      CLASSTYPE_TAGS (type) = CLASSTYPE_TAGS (pattern);
      /* Pretend that the type is complete, so that we will look
	 inside it during name lookup and such.  */
4760
      TYPE_SIZE (type) = bitsize_zero_node;
4761
      return type;
4762 4763 4764 4765
    }

  /* If we've recursively instantiated too many templates, stop.  */
  if (! push_tinst_level (type))
4766
    return type;
4767 4768 4769 4770 4771 4772 4773

  /* Now we're really doing the instantiation.  Mark the type as in
     the process of being defined.  */
  TYPE_BEING_DEFINED (type) = 1;

  maybe_push_to_top_level (uses_template_parms (type));

mrs's avatar
mrs committed
4774
  if (t)
4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800
    {
      /* This TYPE is actually a instantiation of of a partial
	 specialization.  We replace the innermost set of ARGS with
	 the arguments appropriate for substitution.  For example,
	 given:

	   template <class T> struct S {};
	   template <class T> struct S<T*> {};
	 
	 and supposing that we are instantiating S<int*>, ARGS will
	 present be {int*} but we need {int}.  */
      tree inner_args 
	= get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t),
			      args);

      /* If there were multiple levels in ARGS, replacing the
	 innermost level would alter CLASSTYPE_TI_ARGS, which we don't
	 want, so we make a copy first.  */
      if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
	{
	  args = copy_node (args);
	  SET_TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args), inner_args);
	}
      else
	args = inner_args;
    }
4801

mrs's avatar
mrs committed
4802 4803 4804 4805 4806 4807 4808
  if (flag_external_templates)
    {
      if (flag_alt_external_templates)
	{
	  CLASSTYPE_INTERFACE_ONLY (type) = interface_only;
	  SET_CLASSTYPE_INTERFACE_UNKNOWN_X (type, interface_unknown);
	  CLASSTYPE_VTABLE_NEEDS_WRITING (type)
4809 4810
	    = (! CLASSTYPE_INTERFACE_ONLY (type)
	       && CLASSTYPE_INTERFACE_KNOWN (type));
mrs's avatar
mrs committed
4811 4812 4813 4814 4815 4816 4817
	}
      else
	{
	  CLASSTYPE_INTERFACE_ONLY (type) = CLASSTYPE_INTERFACE_ONLY (pattern);
	  SET_CLASSTYPE_INTERFACE_UNKNOWN_X
	    (type, CLASSTYPE_INTERFACE_UNKNOWN (pattern));
	  CLASSTYPE_VTABLE_NEEDS_WRITING (type)
4818 4819
	    = (! CLASSTYPE_INTERFACE_ONLY (type)
	       && CLASSTYPE_INTERFACE_KNOWN (type));
mrs's avatar
mrs committed
4820 4821 4822
	}
    }
  else
mrs's avatar
mrs committed
4823
    {
mrs's avatar
mrs committed
4824 4825
      SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
      CLASSTYPE_VTABLE_NEEDS_WRITING (type) = 1;
mrs's avatar
mrs committed
4826 4827
    }

mrs's avatar
mrs committed
4828 4829 4830 4831 4832
  TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
  TYPE_HAS_DESTRUCTOR (type) = TYPE_HAS_DESTRUCTOR (pattern);
  TYPE_OVERLOADS_CALL_EXPR (type) = TYPE_OVERLOADS_CALL_EXPR (pattern);
  TYPE_OVERLOADS_ARRAY_REF (type) = TYPE_OVERLOADS_ARRAY_REF (pattern);
  TYPE_OVERLOADS_ARROW (type) = TYPE_OVERLOADS_ARROW (pattern);
4833 4834
  TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
  TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
mrs's avatar
mrs committed
4835 4836 4837 4838 4839 4840 4841 4842 4843
  TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
  TYPE_VEC_DELETE_TAKES_SIZE (type) = TYPE_VEC_DELETE_TAKES_SIZE (pattern);
  TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
  TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
  TYPE_HAS_ABSTRACT_ASSIGN_REF (type) = TYPE_HAS_ABSTRACT_ASSIGN_REF (pattern);
  TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
  TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
  TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
  TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
4844 4845
  TYPE_BASE_CONVS_MAY_REQUIRE_CODE_P (type)
    = TYPE_BASE_CONVS_MAY_REQUIRE_CODE_P (pattern);
mrs's avatar
mrs committed
4846 4847 4848 4849 4850 4851
  TYPE_USES_MULTIPLE_INHERITANCE (type)
    = TYPE_USES_MULTIPLE_INHERITANCE (pattern);
  TYPE_USES_VIRTUAL_BASECLASSES (type)
    = TYPE_USES_VIRTUAL_BASECLASSES (pattern);
  TYPE_PACKED (type) = TYPE_PACKED (pattern);
  TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
bothner's avatar
d  
bothner committed
4852
  TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
jason's avatar
jason committed
4853 4854
  if (ANON_AGGR_TYPE_P (pattern))
    SET_ANON_AGGR_TYPE_P (type);
mrs's avatar
mrs committed
4855

4856 4857 4858 4859 4860
  if (TYPE_BINFO_BASETYPES (pattern))
    {
      tree base_list = NULL_TREE;
      tree pbases = TYPE_BINFO_BASETYPES (pattern);
      int i;
mrs's avatar
mrs committed
4861

4862 4863 4864 4865 4866 4867 4868
      /* Substitute into each of the bases to determine the actual
	 basetypes.  */
      for (i = 0; i < TREE_VEC_LENGTH (pbases); ++i)
	{
	  tree base;
	  tree access;
	  tree pbase;
mrs's avatar
mrs committed
4869

4870
	  pbase = TREE_VEC_ELT (pbases, i);
4871

4872 4873 4874 4875 4876
	  /* Substitue to figure out the base class.  */
	  base = tsubst (BINFO_TYPE (pbase), args, 
			 /*complain=*/1, NULL_TREE);
	  if (base == error_mark_node)
	    continue;
4877

4878 4879 4880 4881 4882 4883 4884
	  /* Calculate the correct access node.  */
	  if (TREE_VIA_VIRTUAL (pbase)) 
	    {
	      if (TREE_VIA_PUBLIC (pbase))
		access = access_public_virtual_node;
	      else if (TREE_VIA_PROTECTED (pbase))
		access = access_protected_virtual_node;
4885
	      else 
4886 4887 4888 4889 4890 4891 4892 4893
		access = access_private_virtual_node;
	    }
	  else
	    {
	      if (TREE_VIA_PUBLIC (pbase))
		access = access_public_node;
	      else if (TREE_VIA_PROTECTED (pbase))
		access = access_protected_node;
4894
	      else 
4895 4896
		access = access_private_node;
	    }
4897

4898 4899
	  base_list = tree_cons (access, base, base_list);
	}
4900

4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913
      /* The list is now in reverse order; correct that.  */
      base_list = nreverse (base_list);

      /* Now call xref_basetypes to set up all the base-class
	 information.  */
      xref_basetypes (TREE_CODE (pattern) == RECORD_TYPE
		      ? (CLASSTYPE_DECLARED_CLASS (pattern)
			 ? class_type_node : record_type_node)
		      : union_type_node,
		      DECL_NAME (TYPE_NAME (pattern)),
		      type,
		      base_list);
    }
mrs's avatar
mrs committed
4914

4915 4916 4917 4918 4919 4920 4921
  /* Now that our base classes are set up, enter the scope of the
     class, so that name lookups into base classes, etc. will work
     corectly.  This is precisely analagous to what we do in
     begin_class_definition when defining an ordinary non-template
     class.  */
  pushclass (type, 1);

mrs's avatar
mrs committed
4922
  for (t = CLASSTYPE_TAGS (pattern); t; t = TREE_CHAIN (t))
mrs's avatar
mrs committed
4923
    {
mrs's avatar
mrs committed
4924
      tree tag = TREE_VALUE (t);
4925 4926
      tree name = TYPE_IDENTIFIER (tag);
      tree newtag;
mrs's avatar
mrs committed
4927

4928
      newtag = tsubst (tag, args, /*complain=*/1, NULL_TREE);
4929
      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
4930
	{
4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941
	  if (TYPE_LANG_SPECIFIC (tag) && CLASSTYPE_IS_TEMPLATE (tag))
	    /* Unfortunately, lookup_template_class sets
	       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
	       instantiation (i.e., for the type of a member template
	       class nested within a template class.)  This behavior is
	       required for maybe_process_partial_specialization to work
	       correctly, but is not accurate in this case; the TAG is not
	       an instantiation of anything.  (The corresponding
	       TEMPLATE_DECL is an instantiation, but the TYPE is not.) */
	    CLASSTYPE_USE_TEMPLATE (newtag) = 0;

4942 4943 4944 4945 4946 4947 4948 4949 4950
	  /* Now, we call pushtag to put this NEWTAG into the scope of
	     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
	     pushtag calling push_template_decl.  We don't have to do
	     this for enums because it will already have been done in
	     tsubst_enum.  */
	  if (name)
	    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
	  pushtag (name, newtag, /*globalize=*/0);
	}
mrs's avatar
mrs committed
4951 4952
    }

mrs's avatar
mrs committed
4953 4954
  /* Don't replace enum constants here.  */
  for (t = TYPE_FIELDS (pattern); t; t = TREE_CHAIN (t))
4955
    if (TREE_CODE (t) != CONST_DECL)
mrs's avatar
mrs committed
4956
      {
4957 4958 4959 4960 4961 4962 4963 4964
	tree r;

	/* The the file and line for this declaration, to assist in
	   error message reporting.  Since we called push_tinst_level
	   above, we don't need to restore these.  */
	lineno = DECL_SOURCE_LINE (t);
	input_filename = DECL_SOURCE_FILE (t);

4965
	r = tsubst (t, args, /*complain=*/1, NULL_TREE);
mrs's avatar
mrs committed
4966 4967
	if (TREE_CODE (r) == VAR_DECL)
	  {
4968 4969
	    tree init;

4970
	    if (DECL_DEFINED_IN_CLASS_P (r))
4971 4972 4973 4974 4975 4976 4977 4978 4979
	      init = tsubst_expr (DECL_INITIAL (t), args,
				  /*complain=*/1, NULL_TREE);
	    else
	      init = NULL_TREE;

	    finish_static_data_member_decl (r, init,
					    /*asmspec_tree=*/NULL_TREE, 
					    /*flags=*/0);

4980 4981
	    if (DECL_DEFINED_IN_CLASS_P (r))
	      check_static_variable_definition (r, TREE_TYPE (r));
mrs's avatar
mrs committed
4982
	  }
4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993
	
	/* R will have a TREE_CHAIN if and only if it has already been
	   processed by finish_member_declaration.  This can happen
	   if, for example, it is a TYPE_DECL for a class-scoped
	   ENUMERAL_TYPE; such a thing will already have been added to
	   the field list by tsubst_enum above.  */
	if (!TREE_CHAIN (r))
	  {
	    set_current_access_from_decl (r);
	    finish_member_declaration (r);
	  }
mrs's avatar
mrs committed
4994
      }
mrs's avatar
mrs committed
4995

4996 4997 4998 4999
  /* Set up the list (TYPE_METHODS) and vector (CLASSTYPE_METHOD_VEC)
     for this instantiation.  */
  for (t = TYPE_METHODS (pattern); t; t = TREE_CHAIN (t))
    {
5000
      tree r = tsubst (t, args, /*complain=*/1, NULL_TREE);
5001 5002 5003
      set_current_access_from_decl (r);
      finish_member_declaration (r);
    }
mrs's avatar
mrs committed
5004

5005 5006 5007 5008 5009
  /* Construct the DECL_FRIENDLIST for the new class type.  */
  typedecl = TYPE_MAIN_DECL (type);
  for (t = DECL_FRIENDLIST (TYPE_MAIN_DECL (pattern));
       t != NULL_TREE;
       t = TREE_CHAIN (t))
jason's avatar
jason committed
5010
    {
5011
      tree friends;
jason's avatar
jason committed
5012

5013 5014 5015
      for (friends = TREE_VALUE (t);
	   friends != NULL_TREE;
	   friends = TREE_CHAIN (friends))
5016 5017 5018 5019 5020
	if (TREE_PURPOSE (friends) == error_mark_node)
	  add_friend (type, 
		      tsubst_friend_function (TREE_VALUE (friends),
					      args));
	else
5021
	  my_friendly_abort (20000216);
5022
    }
mrs's avatar
mrs committed
5023

5024 5025 5026 5027 5028
  for (t = CLASSTYPE_FRIEND_CLASSES (pattern);
       t != NULL_TREE;
       t = TREE_CHAIN (t))
    {
      tree friend_type = TREE_VALUE (t);
5029
      tree new_friend_type;
5030

5031 5032 5033
      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
	new_friend_type = tsubst_friend_class (friend_type, args);
      else if (uses_template_parms (friend_type))
5034 5035
	new_friend_type = tsubst (friend_type, args, /*complain=*/1,
				  NULL_TREE);
5036
      else 
5037 5038
	{
	  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
5039

5040 5041 5042 5043 5044 5045 5046
	  /* The call to xref_tag_from_type does injection for friend
	     classes.  */
	  push_nested_namespace (ns);
	  new_friend_type = 
	    xref_tag_from_type (friend_type, NULL_TREE, 1);
	  pop_nested_namespace (ns);
	}
5047 5048 5049 5050 5051 5052 5053 5054 5055 5056

      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
	/* Trick make_friend_class into realizing that the friend
	   we're adding is a template, not an ordinary class.  It's
	   important that we use make_friend_class since it will
	   perform some error-checking and output cross-reference
	   information.  */
	++processing_template_decl;

      make_friend_class (type, new_friend_type);
mrs's avatar
mrs committed
5057

5058 5059
      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
	--processing_template_decl;
5060
    }
mrs's avatar
mrs committed
5061

5062 5063 5064 5065 5066 5067
  for (t = TYPE_FIELDS (type); t; t = TREE_CHAIN (t))
    if (TREE_CODE (t) == FIELD_DECL)
      {
	TREE_TYPE (t) = complete_type (TREE_TYPE (t));
	require_complete_type (t);
      }
mrs's avatar
mrs committed
5068

5069 5070 5071 5072 5073 5074 5075 5076
  /* Set the file and line number information to whatever is given for
     the class itself.  This puts error messages involving generated
     implicit functions at a predictable point, and the same point
     that would be used for non-template classes.  */
  lineno = DECL_SOURCE_LINE (typedecl);
  input_filename = DECL_SOURCE_FILE (typedecl);

  unreverse_member_declarations (type);
5077
  finish_struct_1 (type);
5078
  CLASSTYPE_GOT_SEMICOLON (type) = 1;
mrs's avatar
mrs committed
5079

5080 5081
  /* Clear this now so repo_template_used is happy.  */
  TYPE_BEING_DEFINED (type) = 0;
5082
  repo_template_used (type);
mrs's avatar
mrs committed
5083

5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095
  /* Now that the class is complete, instantiate default arguments for
     any member functions.  We don't do this earlier because the
     default arguments may reference members of the class.  */
  if (!PRIMARY_TEMPLATE_P (template))
    for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
      if (TREE_CODE (t) == FUNCTION_DECL 
	  /* Implicitly generated member functions will not have tmplate
	     information; they are not instantiations, but instead are
	     created "fresh" for each instantiation.  */
	  && DECL_TEMPLATE_INFO (t))
	tsubst_default_arguments (t);

5096
  popclass ();
mrs's avatar
mrs committed
5097 5098 5099 5100
  pop_from_top_level ();
  pop_tinst_level ();

  return type;
mrs's avatar
mrs committed
5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118
}

static int
list_eq (t1, t2)
     tree t1, t2;
{
  if (t1 == NULL_TREE)
    return t2 == NULL_TREE;
  if (t2 == NULL_TREE)
    return 0;
  /* Don't care if one declares its arg const and the other doesn't -- the
     main variant of the arg type is all that matters.  */
  if (TYPE_MAIN_VARIANT (TREE_VALUE (t1))
      != TYPE_MAIN_VARIANT (TREE_VALUE (t2)))
    return 0;
  return list_eq (TREE_CHAIN (t1), TREE_CHAIN (t2));
}

5119 5120 5121 5122 5123 5124 5125
/* If arg is a non-type template parameter that does not depend on template
   arguments, fold it like we weren't in the body of a template.  */

static tree
maybe_fold_nontype_arg (arg)
     tree arg;
{
5126 5127 5128 5129 5130
  /* If we're not in a template, ARG is already as simple as it's going to
     get, and trying to reprocess the trees will break.  */
  if (! processing_template_decl)
    return arg;

5131
  if (!TYPE_P (arg) && !uses_template_parms (arg))
5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148
    {
      /* Sometimes, one of the args was an expression involving a
	 template constant parameter, like N - 1.  Now that we've
	 tsubst'd, we might have something like 2 - 1.  This will
	 confuse lookup_template_class, so we do constant folding
	 here.  We have to unset processing_template_decl, to
	 fool build_expr_from_tree() into building an actual
	 tree.  */

      int saved_processing_template_decl = processing_template_decl; 
      processing_template_decl = 0;
      arg = fold (build_expr_from_tree (arg));
      processing_template_decl = saved_processing_template_decl; 
    }
  return arg;
}

5149
/* Return the TREE_VEC with the arguments for the innermost template header,
5150 5151
   where ARGS is either that or the VEC of VECs for all the
   arguments.  */
5152 5153

tree
5154
innermost_args (args)
5155 5156
     tree args;
{
5157
  return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
5158
}
jason's avatar
jason committed
5159

5160 5161
/* Substitute ARGS into the vector of template arguments T.  */

5162
static tree
5163
tsubst_template_arg_vector (t, args, complain)
5164 5165
     tree t;
     tree args;
5166
     int complain;
5167 5168 5169 5170 5171 5172 5173 5174 5175 5176
{
  int len = TREE_VEC_LENGTH (t), need_new = 0, i;
  tree *elts = (tree *) alloca (len * sizeof (tree));
  
  bzero ((char *) elts, len * sizeof (tree));
  
  for (i = 0; i < len; i++)
    {
      if (TREE_VEC_ELT (t, i) != NULL_TREE
	  && TREE_CODE (TREE_VEC_ELT (t, i)) == TREE_VEC)
5177 5178
	elts[i] = tsubst_template_arg_vector (TREE_VEC_ELT (t, i),
					      args, complain);
5179 5180
      else
	elts[i] = maybe_fold_nontype_arg
5181 5182
	  (tsubst_expr (TREE_VEC_ELT (t, i), args, complain,
			NULL_TREE));
5183 5184 5185 5186 5187 5188 5189 5190
      
      if (elts[i] != TREE_VEC_ELT (t, i))
	need_new = 1;
    }
  
  if (!need_new)
    return t;
  
5191
  t = make_tree_vec (len);
5192 5193 5194 5195 5196 5197
  for (i = 0; i < len; i++)
    TREE_VEC_ELT (t, i) = elts[i];
  
  return t;
}

5198 5199 5200 5201 5202 5203 5204
/* Return the result of substituting ARGS into the template parameters
   given by PARMS.  If there are m levels of ARGS and m + n levels of
   PARMS, then the result will contain n levels of PARMS.  For
   example, if PARMS is `template <class T> template <class U>
   template <T*, U, class V>' and ARGS is {{int}, {double}} then the
   result will be `template <int*, double, class V>'.  */

5205
static tree
5206
tsubst_template_parms (parms, args, complain)
5207 5208
     tree parms;
     tree args;
5209
     int complain;
5210
{
5211 5212
  tree r = NULL_TREE;
  tree* new_parms;
5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230

  for (new_parms = &r;
       TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
       new_parms = &(TREE_CHAIN (*new_parms)),
	 parms = TREE_CHAIN (parms))
    {
      tree new_vec = 
	make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
      int i;
      
      for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
	{
	  tree default_value =
	    TREE_PURPOSE (TREE_VEC_ELT (TREE_VALUE (parms), i));
	  tree parm_decl = 
	    TREE_VALUE (TREE_VEC_ELT (TREE_VALUE (parms), i));
	  
	  TREE_VEC_ELT (new_vec, i)
5231 5232 5233 5234
	    = build_tree_list (tsubst (default_value, args, complain,
				       NULL_TREE), 
			       tsubst (parm_decl, args, complain,
				       NULL_TREE));
5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245
	}
      
      *new_parms = 
	tree_cons (build_int_2 (0, (TMPL_PARMS_DEPTH (parms) 
				    - TMPL_ARGS_DEPTH (args))),
		   new_vec, NULL_TREE);
    }

  return r;
}

5246 5247 5248 5249 5250
/* Substitute the ARGS into the indicated aggregate (or enumeration)
   type T.  If T is not an aggregate or enumeration type, it is
   handled as if by tsubst.  IN_DECL is as for tsubst.  If
   ENTERING_SCOPE is non-zero, T is the context for a template which
   we are presently tsubst'ing.  Return the subsituted value.  */
5251

5252
static tree
5253
tsubst_aggr_type (t, args, complain, in_decl, entering_scope)
5254 5255
     tree t;
     tree args;
5256
     int complain;
5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268
     tree in_decl;
     int entering_scope;
{
  if (t == NULL_TREE)
    return NULL_TREE;

  switch (TREE_CODE (t))
    {
    case RECORD_TYPE:
      if (TYPE_PTRMEMFUNC_P (t))
	{
	  tree r = build_ptrmemfunc_type
5269
	    (tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl));
5270 5271
	  return cp_build_qualified_type_real (r, TYPE_QUALS (t),
					       complain);
5272 5273 5274
	}

      /* else fall through */
5275
    case ENUMERAL_TYPE:
5276
    case UNION_TYPE:
5277
      if (TYPE_TEMPLATE_INFO (t))
5278 5279 5280 5281 5282 5283 5284 5285 5286
	{
	  tree argvec;
	  tree context;
	  tree r;

	  /* First, determine the context for the type we are looking
	     up.  */
	  if (TYPE_CONTEXT (t) != NULL_TREE)
	    context = tsubst_aggr_type (TYPE_CONTEXT (t), args,
5287
					complain,
5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300
					in_decl, /*entering_scope=*/1);
	  else
	    context = NULL_TREE;

	  /* Then, figure out what arguments are appropriate for the
	     type we are trying to find.  For example, given:

	       template <class T> struct S;
	       template <class T, class U> void f(T, U) { S<U> su; }

	     and supposing that we are instantiating f<int, double>,
	     then our ARGS will be {int, double}, but, when looking up
	     S we only want {double}.  */
5301 5302
	  argvec = tsubst_template_arg_vector (TYPE_TI_ARGS (t), args,
					       complain);
5303 5304 5305 5306

  	  r = lookup_template_class (t, argvec, in_decl, context,
				     entering_scope);

5307 5308
	  return cp_build_qualified_type_real (r, TYPE_QUALS (t),
					       complain);
5309 5310 5311 5312 5313 5314
	}
      else 
	/* This is not a template type, so there's nothing to do.  */
	return t;

    default:
5315
      return tsubst (t, args, complain, in_decl);
5316 5317 5318
    }
}

5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340
/* Substitute into the default argument ARG (a default argument for
   FN), which has the indicated TYPE.  */

tree
tsubst_default_argument (fn, type, arg)
     tree fn;
     tree type;
     tree arg;
{
  /* This default argument came from a template.  Instantiate the
     default argument here, not in tsubst.  In the case of
     something like: 
     
       template <class T>
       struct S {
	 static T t();
	 void f(T = t());
       };
     
     we must be careful to do name lookup in the scope of S<T>,
     rather than in the current class.  */
  if (DECL_CLASS_SCOPE_P (fn))
5341
    pushclass (DECL_CONTEXT (fn), 2);
5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378

  arg = tsubst_expr (arg, DECL_TI_ARGS (fn), /*complain=*/1, NULL_TREE);
  
  if (DECL_CLASS_SCOPE_P (fn))
    popclass ();

  /* Make sure the default argument is reasonable.  */
  arg = check_default_argument (type, arg);

  return arg;
}

/* Substitute into all the default arguments for FN.  */

static void
tsubst_default_arguments (fn)
     tree fn;
{
  tree arg;
  tree tmpl_args;

  tmpl_args = DECL_TI_ARGS (fn);

  /* If this function is not yet instantiated, we certainly don't need
     its default arguments.  */
  if (uses_template_parms (tmpl_args))
    return;

  for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn)); 
       arg; 
       arg = TREE_CHAIN (arg))
    if (TREE_PURPOSE (arg))
      TREE_PURPOSE (arg) = tsubst_default_argument (fn, 
						    TREE_VALUE (arg),
						    TREE_PURPOSE (arg));
}

5379 5380 5381 5382
/* Substitute the ARGS into the T, which is a _DECL.  TYPE is the
   (already computed) substitution of ARGS into TREE_TYPE (T), if
   appropriate.  Return the result of the substitution.  IN_DECL is as
   for tsubst.  */
5383

5384
static tree
5385 5386 5387 5388
tsubst_decl (t, args, type, in_decl)
     tree t;
     tree args;
     tree type;
mrs's avatar
mrs committed
5389 5390
     tree in_decl;
{
5391 5392
  int saved_lineno;
  char* saved_filename;
ghazi's avatar
ghazi committed
5393
  tree r = NULL_TREE;
5394

5395 5396 5397 5398 5399
  /* Set the filename and linenumber to improve error-reporting.  */
  saved_lineno = lineno;
  saved_filename = input_filename;
  lineno = DECL_SOURCE_LINE (t);
  input_filename = DECL_SOURCE_FILE (t);
mrs's avatar
mrs committed
5400

mrs's avatar
mrs committed
5401 5402
  switch (TREE_CODE (t))
    {
5403 5404 5405 5406 5407
    case TEMPLATE_DECL:
      {
	/* We can get here when processing a member template function
	   of a template class.  */
	tree decl = DECL_TEMPLATE_RESULT (t);
5408
	tree spec;
5409
	int is_template_template_parm = DECL_TEMPLATE_TEMPLATE_PARM_P (t);
5410

5411 5412
	if (!is_template_template_parm)
	  {
5413 5414 5415 5416 5417 5418
	    /* We might already have an instance of this template.
	       The ARGS are for the surrounding class type, so the
	       full args contain the tsubst'd args for the context,
	       plus the innermost args from the template decl.  */
	    tree tmpl_args = DECL_CLASS_TEMPLATE_P (t) 
	      ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
5419
	      : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
5420 5421
	    tree full_args;
	    
5422 5423
	    full_args = tsubst_template_arg_vector (tmpl_args, args,
						    /*complain=*/1);
5424 5425 5426 5427 5428 5429 5430

	    /* tsubst_template_arg_vector doesn't copy the vector if
	       nothing changed.  But, *something* should have
	       changed.  */
	    my_friendly_assert (full_args != tmpl_args, 0);

	    spec = retrieve_specialization (t, full_args);
5431
	    if (spec != NULL_TREE)
5432 5433 5434 5435
	      {
		r = spec;
		break;
	      }
5436
	  }
5437 5438 5439 5440 5441 5442

	/* Make a new template decl.  It will be similar to the
	   original, but will record the current template arguments. 
	   We also create a new function declaration, which is just
	   like the old one, but points to this new template, rather
	   than the old one.  */
5443
	r = copy_decl (t);
5444 5445
	my_friendly_assert (DECL_LANG_SPECIFIC (r) != 0, 0);
	TREE_CHAIN (r) = NULL_TREE;
5446 5447 5448

	if (is_template_template_parm)
	  {
5449
	    tree new_decl = tsubst (decl, args, /*complain=*/1, in_decl);
5450
	    DECL_TEMPLATE_RESULT (r) = new_decl;
5451 5452
	    TREE_TYPE (r) = TREE_TYPE (new_decl);
	    break;
5453 5454
	  }

5455
	DECL_CONTEXT (r) 
5456
	  = tsubst_aggr_type (DECL_CONTEXT (t), args, 
5457 5458
			      /*complain=*/1, in_decl, 
			      /*entering_scope=*/1); 
5459 5460 5461 5462
	DECL_VIRTUAL_CONTEXT (r) 
	  = tsubst_aggr_type (DECL_VIRTUAL_CONTEXT (t), args, 
			      /*complain=*/1, in_decl, 
			      /*entering_scope=*/1);
5463
	DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
5464 5465 5466

	if (TREE_CODE (decl) == TYPE_DECL)
	  {
5467 5468
	    tree new_type = tsubst (TREE_TYPE (t), args,
				    /*complain=*/1, in_decl);
5469 5470
	    TREE_TYPE (r) = new_type;
	    CLASSTYPE_TI_TEMPLATE (new_type) = r;
5471
	    DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
5472
	    DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
5473 5474 5475
	  }
	else
	  {
5476
	    tree new_decl = tsubst (decl, args, /*complain=*/1, in_decl);
5477 5478

	    DECL_TEMPLATE_RESULT (r) = new_decl;
5479 5480 5481
	    DECL_TI_TEMPLATE (new_decl) = r;
	    TREE_TYPE (r) = TREE_TYPE (new_decl);
	    DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
5482 5483
	  }

5484 5485 5486
	SET_DECL_IMPLICIT_INSTANTIATION (r);
	DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
	DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
5487 5488 5489 5490

	/* The template parameters for this new template are all the
	   template parameters for the old template, except the
	   outermost level of parameters. */
5491
	DECL_TEMPLATE_PARMS (r) 
5492 5493
	  = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
				   /*complain=*/1);
5494

5495
	if (PRIMARY_TEMPLATE_P (t))
5496
	  DECL_PRIMARY_TEMPLATE (r) = r;
5497

5498
	/* We don't partially instantiate partial specializations.  */
5499
	if (TREE_CODE (decl) == TYPE_DECL)
5500
	  break;
5501

5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541
	for (spec = DECL_TEMPLATE_SPECIALIZATIONS (t);
	     spec != NULL_TREE;
	     spec = TREE_CHAIN (spec))
	  {
	    /* It helps to consider example here.  Consider:

	       template <class T>
	       struct S {
	         template <class U>
		 void f(U u);

		 template <>
		 void f(T* t) {}
	       };
	       
	       Now, for example, we are instantiating S<int>::f(U u).  
	       We want to make a template:

	       template <class U>
	       void S<int>::f(U);

	       It will have a specialization, for the case U = int*, of
	       the form:

	       template <>
	       void S<int>::f<int*>(int*);

	       This specialization will be an instantiation of
	       the specialization given in the declaration of S, with
	       argument list int*.  */

	    tree fn = TREE_VALUE (spec);
	    tree spec_args;
	    tree new_fn;

	    if (!DECL_TEMPLATE_SPECIALIZATION (fn))
	      /* Instantiations are on the same list, but they're of
		 no concern to us.  */
	      continue;

5542 5543 5544 5545 5546
	    if (TREE_CODE (fn) != TEMPLATE_DECL)
	      /* A full specialization.  There's no need to record
		 that here.  */
	      continue;

5547 5548
	    spec_args = tsubst (DECL_TI_ARGS (fn), args,
				/*complain=*/1, in_decl); 
5549 5550 5551
	    new_fn
	      = tsubst (DECL_TEMPLATE_RESULT (most_general_template (fn)), 
			spec_args, /*complain=*/1, in_decl); 
5552
	    DECL_TI_TEMPLATE (new_fn) = fn;
5553
	    register_specialization (new_fn, r, 
5554
				     innermost_args (spec_args));
5555 5556 5557
	  }

	/* Record this partial instantiation.  */
5558
	register_specialization (r, t, 
5559
				 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)));
5560

5561
      }
5562
      break;
mrs's avatar
mrs committed
5563 5564 5565

    case FUNCTION_DECL:
      {
5566
	tree ctx;
ghazi's avatar
ghazi committed
5567
	tree argvec = NULL_TREE;
5568
	tree *friends;
5569
	tree gen_tmpl;
mrs's avatar
mrs committed
5570
	int member;
5571 5572
	int args_depth;
	int parms_depth;
mrs's avatar
mrs committed
5573

5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584
	/* Nobody should be tsubst'ing into non-template functions.  */
	my_friendly_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE, 0);

	if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
	  {
	    tree spec;

	    /* Calculate the most general template of which R is a
	       specialization, and the complete set of arguments used to
	       specialize R.  */
	    gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
5585 5586 5587
	    argvec 
	      = tsubst_template_arg_vector (DECL_TI_ARGS 
					    (DECL_TEMPLATE_RESULT (gen_tmpl)),
5588
					    args, /*complain=*/1); 
5589 5590 5591

	    /* Check to see if we already have this specialization.  */
	    spec = retrieve_specialization (gen_tmpl, argvec);
5592

5593
	    if (spec)
5594 5595 5596 5597
	      {
		r = spec;
		break;
	      }
5598 5599 5600 5601 5602 5603

	    /* Here, we deal with the peculiar case:

		 template <class T> struct S { 
		   template <class U> friend void f();
		 };
5604
		 template <class U> void f() {}
5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630
		 template S<int>;
		 template void f<double>();

	       Here, the ARGS for the instantiation of will be {int,
	       double}.  But, we only need as many ARGS as there are
	       levels of template parameters in CODE_PATTERN.  We are
	       careful not to get fooled into reducing the ARGS in
	       situations like:

		 template <class T> struct S { template <class U> void f(U); }
		 template <class T> template <> void S<T>::f(int) {}

	       which we can spot because the pattern will be a
	       specialization in this case.  */
	    args_depth = TMPL_ARGS_DEPTH (args);
	    parms_depth = 
	      TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t))); 
	    if (args_depth > parms_depth
		&& !DECL_TEMPLATE_SPECIALIZATION (t))
	      {
		my_friendly_assert (DECL_FRIEND_P (t), 0);

		if (parms_depth > 1)
		  {
		    int i;

5631
		    args = make_tree_vec (parms_depth);
5632 5633 5634 5635 5636 5637 5638
		    for (i = 0; i < parms_depth; ++i)
		      TREE_VEC_ELT (args, i) = 
			TREE_VEC_ELT (args, i + (args_depth - parms_depth));
		  }
		else
		  args = TREE_VEC_ELT (args, args_depth - parms_depth);
	      }
5639 5640 5641 5642 5643 5644 5645 5646 5647 5648
	  }
	else
	  {
	    /* This special case arises when we have something like this:

	         template <class T> struct S { 
		   friend void f<int>(int, double); 
		 };

	       Here, the DECL_TI_TEMPLATE for the friend declaration
5649 5650 5651 5652 5653 5654 5655 5656
	       will be a LOOKUP_EXPR or an IDENTIFIER_NODE.  We are
	       being called from tsubst_friend_function, and we want
	       only to create a new decl (R) with appropriate types so
	       that we can call determine_specialization.  */
	    my_friendly_assert ((TREE_CODE (DECL_TI_TEMPLATE (t)) 
				 == LOOKUP_EXPR)
				|| (TREE_CODE (DECL_TI_TEMPLATE (t))
				    == IDENTIFIER_NODE), 0);
5657 5658 5659
	    gen_tmpl = NULL_TREE;
	  }

5660
	if (DECL_CLASS_SCOPE_P (t))
mrs's avatar
mrs committed
5661
	  {
mrs's avatar
mrs committed
5662 5663 5664 5665
	    if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
	      member = 2;
	    else
	      member = 1;
5666
	    ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, 
5667
				    /*complain=*/1, t, 
5668
				    /*entering_scope=*/1);
mrs's avatar
mrs committed
5669 5670 5671 5672
	  }
	else
	  {
	    member = 0;
5673
	    ctx = DECL_CONTEXT (t);
mrs's avatar
mrs committed
5674
	  }
5675
	type = tsubst (type, args, /*complain=*/1, in_decl);
5676 5677
	if (type == error_mark_node)
	  return error_mark_node;
mrs's avatar
mrs committed
5678

mrs's avatar
mrs committed
5679 5680 5681
	/* We do NOT check for matching decls pushed separately at this
           point, as they may not represent instantiations of this
           template, and in any case are considered separate under the
mrs's avatar
mrs committed
5682
           discrete model.  Instead, see add_maybe_template.  */
5683
	r = copy_decl (t);
5684
	DECL_USE_TEMPLATE (r) = 0;
mrs's avatar
mrs committed
5685 5686
	TREE_TYPE (r) = type;

5687 5688 5689 5690
	DECL_CONTEXT (r) = ctx;
	DECL_VIRTUAL_CONTEXT (r)
	  = tsubst_aggr_type (DECL_VIRTUAL_CONTEXT (t), args, 
			      /*complain=*/1, t,
5691
			      /*entering_scope=*/1);
mrs's avatar
mrs committed
5692

5693
	if (member && IDENTIFIER_TYPENAME_P (DECL_NAME (r)))
5694 5695 5696
	  /* Type-conversion operator.  Reconstruct the name, in
	     case it's the name of one of the template's parameters.  */
	  DECL_NAME (r) = build_typename_overload (TREE_TYPE (type));
mrs's avatar
mrs committed
5697

5698 5699
	DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
				     /*complain=*/1, t);
5700
	DECL_TEMPLATE_RESULT (r) = NULL_TREE;
5701 5702 5703 5704 5705 5706 5707 5708

	TREE_STATIC (r) = 0;
	TREE_PUBLIC (r) = TREE_PUBLIC (t);
	DECL_EXTERNAL (r) = 1;
	DECL_INTERFACE_KNOWN (r) = 0;
	DECL_DEFER_OUTPUT (r) = 0;
	TREE_CHAIN (r) = NULL_TREE;
	DECL_PENDING_INLINE_INFO (r) = 0;
5709
	DECL_PENDING_INLINE_P (r) = 0;
5710
	TREE_USED (r) = 0;
5711 5712 5713 5714 5715 5716 5717
	if (DECL_CLONED_FUNCTION (r))
	  {
	    DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
					       args, /*complain=*/1, t);
	    TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
	    TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
	  }
5718

5719 5720 5721 5722
	/* Set up the DECL_TEMPLATE_INFO for R and compute its mangled
	   name.  There's no need to do this in the special friend
	   case mentioned above where GEN_TMPL is NULL.  */
	if (gen_tmpl)
5723
	  {
5724
	    DECL_TEMPLATE_INFO (r) 
5725
	      = tree_cons (gen_tmpl, argvec, NULL_TREE);
5726 5727 5728 5729 5730 5731 5732
	    SET_DECL_IMPLICIT_INSTANTIATION (r);
	    register_specialization (r, gen_tmpl, argvec);

	    /* Set the mangled name for R.  */
	    if (DECL_DESTRUCTOR_P (t))
	      DECL_ASSEMBLER_NAME (r) = build_destructor_name (ctx);
	    else 
5733
	      {
5734 5735 5736 5737
		/* Instantiations of template functions must be mangled
		   specially, in order to conform to 14.5.5.1
		   [temp.over.link].  */
		tree tmpl = DECL_TI_TEMPLATE (t);
5738
		
5739 5740 5741 5742 5743 5744 5745
		/* TMPL will be NULL if this is a specialization of a
		   member function of a template class.  */
		if (name_mangling_version < 1
		    || tmpl == NULL_TREE
		    || (member && !is_member_template (tmpl)
			&& !DECL_TEMPLATE_INFO (tmpl)))
		  set_mangled_name_for_decl (r);
5746
		else
5747
		  set_mangled_name_for_template_decl (r);
5748
	      }
5749 5750 5751 5752 5753 5754 5755 5756
	    
	    DECL_RTL (r) = 0;
	    make_decl_rtl (r, NULL_PTR, 1);
	    
	    /* Like grokfndecl.  If we don't do this, pushdecl will
	       mess up our TREE_CHAIN because it doesn't find a
	       previous decl.  Sigh.  */
	    if (member
5757
		&& ! uses_template_parms (r)
5758 5759 5760
		&& (IDENTIFIER_GLOBAL_VALUE (DECL_ASSEMBLER_NAME (r)) 
		    == NULL_TREE))
	      SET_IDENTIFIER_GLOBAL_VALUE (DECL_ASSEMBLER_NAME (r), r);
5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776

	    /* We're not supposed to instantiate default arguments
	       until they are called, for a template.  But, for a
	       declaration like:

	         template <class T> void f () 
                 { extern void g(int i = T()); }
		 
	       we should do the substitution when the template is
	       instantiated.  We handle the member function case in
	       instantiate_class_template since the default arguments
	       might refer to other members of the class.  */
	    if (!member
		&& !PRIMARY_TEMPLATE_P (gen_tmpl)
		&& !uses_template_parms (argvec))
	      tsubst_default_arguments (r);
5777
	  }
5778

5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789
	/* Copy the list of befriending classes.  */
	for (friends = &DECL_BEFRIENDING_CLASSES (r);
	     *friends;
	     friends = &TREE_CHAIN (*friends)) 
	  {
	    *friends = copy_node (*friends);
	    TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
					    args, /*complain=*/1, 
					    in_decl);
	  }

5790 5791 5792 5793 5794
	if (DECL_CONSTRUCTOR_P (r))
	  {
	    maybe_retrofit_in_chrg (r);
	    grok_ctor_properties (ctx, r);
	  }
5795
	else if (DECL_OVERLOADED_OPERATOR_P (r))
5796
	  grok_op_properties (r, DECL_VIRTUAL_P (r), DECL_FRIEND_P (r));
mrs's avatar
mrs committed
5797
      }
5798
      break;
mrs's avatar
mrs committed
5799 5800 5801

    case PARM_DECL:
      {
5802
	r = copy_node (t);
mrs's avatar
mrs committed
5803
	TREE_TYPE (r) = type;
5804 5805
	c_apply_type_quals_to_decl (CP_TYPE_QUALS (type), r);

5806 5807 5808
	if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
	  DECL_INITIAL (r) = TREE_TYPE (r);
	else
5809 5810
	  DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
				     /*complain=*/1, in_decl);
5811

mrs's avatar
mrs committed
5812
	DECL_CONTEXT (r) = NULL_TREE;
rth's avatar
rth committed
5813 5814 5815
	if (PROMOTE_PROTOTYPES
	    && (TREE_CODE (type) == INTEGER_TYPE
		|| TREE_CODE (type) == ENUMERAL_TYPE)
kenner's avatar
kenner committed
5816 5817
	    && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))
	  DECL_ARG_TYPE (r) = integer_type_node;
mrs's avatar
mrs committed
5818
	if (TREE_CHAIN (t))
5819 5820
	  TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
				   /*complain=*/1, TREE_CHAIN (t));
mrs's avatar
mrs committed
5821
      }
5822
      break;
mrs's avatar
mrs committed
5823

mrs's avatar
mrs committed
5824 5825
    case FIELD_DECL:
      {
5826
	r = copy_decl (t);
5827 5828 5829 5830 5831
	TREE_TYPE (r) = type;
	c_apply_type_quals_to_decl (CP_TYPE_QUALS (type), r);

	/* We don't have to set DECL_CONTEXT here; it is set by
	   finish_member_declaration.  */
5832 5833
	DECL_INITIAL (r) = tsubst_expr (DECL_INITIAL (t), args,
					/*complain=*/1, in_decl);
mrs's avatar
mrs committed
5834
	TREE_CHAIN (r) = NULL_TREE;
5835
	if (TREE_CODE (type) == VOID_TYPE) 
jason's avatar
jason committed
5836
	  cp_error_at ("instantiation of `%D' as type void", r);
mrs's avatar
mrs committed
5837
      }
5838
      break;
mrs's avatar
mrs committed
5839 5840 5841

    case USING_DECL:
      {
5842
	r = copy_node (t);
mrs's avatar
mrs committed
5843
	DECL_INITIAL (r)
5844
	  = tsubst_copy (DECL_INITIAL (t), args, /*complain=*/1, in_decl);
mrs's avatar
mrs committed
5845 5846
	TREE_CHAIN (r) = NULL_TREE;
      }
5847
      break;
mrs's avatar
mrs committed
5848

5849 5850 5851 5852 5853 5854 5855 5856 5857 5858
    case TYPE_DECL:
      if (DECL_IMPLICIT_TYPEDEF_P (t))
	{
	  /* For an implicit typedef, we just want the implicit
	     typedef for the tsubst'd type.  We've already got the
	     tsubst'd type, as TYPE, so we just need it's associated
	     declaration.  */
	  r = TYPE_NAME (type);
	  break;
	}
5859 5860
      else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
	       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
5861 5862 5863
	{
	  /* For a template type parameter, we don't have to do
	     anything special.  */
5864
	  r = TYPE_NAME (type);
5865 5866 5867 5868 5869
	  break;
	}

      /* Fall through.  */

mrs's avatar
mrs committed
5870 5871
    case VAR_DECL:
      {
5872 5873 5874 5875
	tree argvec;
	tree gen_tmpl;
	tree spec;
	tree tmpl;
5876
	tree ctx;
5877
	int local_p;
5878

5879 5880
	/* Assume this is a non-local variable.  */
	local_p = 0;
mrs's avatar
mrs committed
5881

mmitchel's avatar
mmitchel committed
5882
	if (TYPE_P (CP_DECL_CONTEXT (t)))
5883 5884 5885 5886
	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, 
				  /*complain=*/1,
				  in_decl, /*entering_scope=*/1);
	else
5887 5888 5889 5890 5891 5892
	  {
	    /* Subsequent calls to pushdecl will fill this in.  */
	    ctx = NULL_TREE;
	    if (!DECL_NAMESPACE_SCOPE_P (t))
	      local_p = 1;
	  }
5893

5894
	/* Check to see if we already have this specialization.  */
5895 5896 5897 5898 5899 5900 5901
	if (!local_p)
	  {
	    tmpl = DECL_TI_TEMPLATE (t);
	    gen_tmpl = most_general_template (tmpl);
	    argvec = tsubst (DECL_TI_ARGS (t), args, /*complain=*/1, in_decl);
	    spec = retrieve_specialization (gen_tmpl, argvec);
	  }
5902
	else
5903
	  spec = retrieve_local_specialization (t);
5904

5905
	if (spec)
5906 5907 5908 5909
	  {
	    r = spec;
	    break;
	  }
mrs's avatar
mrs committed
5910

5911
	r = copy_decl (t);
mrs's avatar
mrs committed
5912
	TREE_TYPE (r) = type;
5913
	c_apply_type_quals_to_decl (CP_TYPE_QUALS (type), r);
mrs's avatar
mrs committed
5914
	DECL_CONTEXT (r) = ctx;
mrs's avatar
mrs committed
5915 5916 5917 5918

	/* Don't try to expand the initializer until someone tries to use
	   this variable; otherwise we run into circular dependencies.  */
	DECL_INITIAL (r) = NULL_TREE;
mrs's avatar
mrs committed
5919
	DECL_RTL (r) = 0;
5920
	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
mrs's avatar
mrs committed
5921

5922 5923 5924 5925 5926 5927 5928 5929 5930 5931
	/* For __PRETTY_FUNCTION__ we have to adjust the initializer.  */
	if (DECL_PRETTY_FUNCTION_P (r))
	  {
	    DECL_INITIAL (r) = tsubst (DECL_INITIAL (t),
				       args,
				       /*complain=*/1,
				       NULL_TREE);
	    TREE_TYPE (r) = TREE_TYPE (DECL_INITIAL (r));
	  }

5932 5933 5934 5935 5936
	/* Even if the original location is out of scope, the newly
	   substituted one is not.  */
	if (TREE_CODE (r) == VAR_DECL)
	  DECL_DEAD_FOR_LOCAL (r) = 0;

5937 5938 5939 5940 5941 5942 5943
	if (!local_p)
	  {
	    /* A static data member declaration is always marked
	       external when it is declared in-class, even if an
	       initializer is present.  We mimic the non-template
	       processing here.  */
	    DECL_EXTERNAL (r) = 1;
5944

5945 5946 5947 5948
	    register_specialization (r, gen_tmpl, argvec);
	    DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
	    SET_DECL_IMPLICIT_INSTANTIATION (r);
	  }
5949
	else
5950
	  register_local_specialization (r, t);
mrs's avatar
mrs committed
5951 5952

	TREE_CHAIN (r) = NULL_TREE;
5953
	if (TREE_CODE (r) == VAR_DECL && TREE_CODE (type) == VOID_TYPE)
jason's avatar
jason committed
5954
	  cp_error_at ("instantiation of `%D' as type void", r);
mrs's avatar
mrs committed
5955
      }
5956
      break;
mrs's avatar
mrs committed
5957

5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968
    default:
      my_friendly_abort (0);
    } 

  /* Restore the file and line information.  */
  lineno = saved_lineno;
  input_filename = saved_filename;

  return r;
}

5969 5970
/* Substitue into the ARG_TYPES of a function type.  */

5971
static tree
5972
tsubst_arg_types (arg_types, args, complain, in_decl)
5973 5974
     tree arg_types;
     tree args;
5975
     int complain;
5976 5977 5978 5979 5980 5981 5982 5983 5984
     tree in_decl;
{
  tree remaining_arg_types;
  tree type;

  if (!arg_types || arg_types == void_list_node)
    return arg_types;
  
  remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
5985 5986 5987 5988 5989 5990 5991
					  args, complain, in_decl);
  if (remaining_arg_types == error_mark_node)
    return error_mark_node;

  type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
  if (type == error_mark_node)
    return error_mark_node;
5992

5993 5994 5995
  /* Do array-to-pointer, function-to-pointer conversion, and ignore
     top-level qualifiers as required.  */
  type = TYPE_MAIN_VARIANT (type_decays_to (type));
5996 5997 5998 5999

  /* Note that we do not substitute into default arguments here.  The
     standard mandates that they be instantiated only when needed,
     which is done in build_over_call.  */
6000 6001
  return hash_tree_cons (TREE_PURPOSE (arg_types), type,
			 remaining_arg_types);
6002 6003 6004
			 
}

6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032
/* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
   *not* handle the exception-specification for FNTYPE, because the
   initial substitution of explicitly provided template parameters
   during argument deduction forbids substitution into the
   exception-specification:

     [temp.deduct]

     All references in the function type of the function template to  the
     corresponding template parameters are replaced by the specified tem-
     plate argument values.  If a substitution in a template parameter or
     in  the function type of the function template results in an invalid
     type, type deduction fails.  [Note: The equivalent  substitution  in
     exception specifications is done only when the function is instanti-
     ated, at which point a program is  ill-formed  if  the  substitution
     results in an invalid type.]  */

static tree
tsubst_function_type (t, args, complain, in_decl)
     tree t;
     tree args;
     int complain;
     tree in_decl;
{
  tree return_type;
  tree arg_types;
  tree fntype;

6033
  /* The TYPE_CONTEXT is not used for function/method types.  */
6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071
  my_friendly_assert (TYPE_CONTEXT (t) == NULL_TREE, 0);

  /* Substitue the return type.  */
  return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
  if (return_type == error_mark_node)
    return error_mark_node;

  /* Substitue the argument types.  */
  arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
				complain, in_decl); 
  if (arg_types == error_mark_node)
    return error_mark_node;
  
  /* Construct a new type node and return it.  */
  if (TREE_CODE (t) == FUNCTION_TYPE)
    fntype = build_function_type (return_type, arg_types);
  else
    {
      tree r = TREE_TYPE (TREE_VALUE (arg_types));
      if (! IS_AGGR_TYPE (r))
	{
	  /* [temp.deduct]
	     
	     Type deduction may fail for any of the following
	     reasons:
	     
	     -- Attempting to create "pointer to member of T" when T
	     is not a class type.  */
	  if (complain)
	    cp_error ("creating pointer to member function of non-class type `%T'",
		      r);
	  return error_mark_node;
	}
      
      fntype = build_cplus_method_type (r, return_type, TREE_CHAIN
					(arg_types));
    }
  fntype = build_qualified_type (fntype, TYPE_QUALS (t));
6072
  fntype = build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
6073 6074 6075 6076
  
  return fntype;  
}

6077 6078
/* Substitute into the PARMS of a call-declarator.  */

6079
static tree
6080
tsubst_call_declarator_parms (parms, args, complain, in_decl)
6081 6082
     tree parms;
     tree args;
6083
     int complain;
6084 6085 6086 6087 6088 6089 6090 6091 6092 6093
     tree in_decl;
{
  tree new_parms;
  tree type;
  tree defarg;

  if (!parms || parms == void_list_node)
    return parms;
  
  new_parms = tsubst_call_declarator_parms (TREE_CHAIN (parms),
6094
					    args, complain, in_decl);
6095 6096

  /* Figure out the type of this parameter.  */
6097
  type = tsubst (TREE_VALUE (parms), args, complain, in_decl);
6098 6099
  
  /* Figure out the default argument as well.  Note that we use
6100 6101
     tsubst_expr since the default argument is really an expression.  */
  defarg = tsubst_expr (TREE_PURPOSE (parms), args, complain, in_decl);
6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113

  /* Chain this parameter on to the front of those we have already
     processed.  We don't use hash_tree_cons because that function
     doesn't check TREE_PARMLIST.  */
  new_parms = tree_cons (defarg, type, new_parms);

  /* And note that these are parameters.  */
  TREE_PARMLIST (new_parms) = 1;
  
  return new_parms;
}

6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128
/* Take the tree structure T and replace template parameters used
   therein with the argument vector ARGS.  IN_DECL is an associated
   decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
   An appropriate error message is issued only if COMPLAIN is
   non-zero.  Note that we must be relatively non-tolerant of
   extensions here, in order to preserve conformance; if we allow
   substitutions that should not be allowed, we may allow argument
   deductions that should not succeed, and therefore report ambiguous
   overload situations where there are none.  In theory, we could
   allow the substitution, but indicate that it should have failed,
   and allow our caller to make sure that the right thing happens, but
   we don't try to do this yet.

   This function is used for dealing with types, decls and the like;
   for expressions, use tsubst_expr or tsubst_copy.  */
6129 6130

tree
6131
tsubst (t, args, complain, in_decl)
6132
     tree t, args;
6133
     int complain;
6134 6135
     tree in_decl;
{
6136
  tree type, r;
6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154

  if (t == NULL_TREE || t == error_mark_node
      || t == integer_type_node
      || t == void_type_node
      || t == char_type_node
      || TREE_CODE (t) == NAMESPACE_DECL)
    return t;

  if (TREE_CODE (t) == IDENTIFIER_NODE)
    type = IDENTIFIER_TYPE_VALUE (t);
  else
    type = TREE_TYPE (t);
  if (type == unknown_type_node)
    my_friendly_abort (42);

  if (type && TREE_CODE (t) != FUNCTION_DECL
      && TREE_CODE (t) != TYPENAME_TYPE
      && TREE_CODE (t) != TEMPLATE_DECL
6155 6156 6157 6158 6159 6160
      && TREE_CODE (t) != IDENTIFIER_NODE
      && TREE_CODE (t) != FUNCTION_TYPE
      && TREE_CODE (t) != METHOD_TYPE)
    type = tsubst (type, args, complain, in_decl);
  if (type == error_mark_node)
    return error_mark_node;
6161

6162
  if (DECL_P (t))
6163 6164 6165 6166 6167 6168 6169
    return tsubst_decl (t, args, type, in_decl);

  switch (TREE_CODE (t))
    {
    case RECORD_TYPE:
    case UNION_TYPE:
    case ENUMERAL_TYPE:
6170 6171
      return tsubst_aggr_type (t, args, complain, in_decl,
			       /*entering_scope=*/0);
6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191

    case ERROR_MARK:
    case IDENTIFIER_NODE:
    case OP_IDENTIFIER:
    case VOID_TYPE:
    case REAL_TYPE:
    case COMPLEX_TYPE:
    case BOOLEAN_TYPE:
    case INTEGER_CST:
    case REAL_CST:
    case STRING_CST:
      return t;

    case INTEGER_TYPE:
      if (t == integer_type_node)
	return t;

      if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
	  && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
	return t;
mrs's avatar
mrs committed
6192

mrs's avatar
mrs committed
6193
      {
6194
	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
6195

6196
	max = tsubst_expr (omax, args, complain, in_decl);
6197 6198 6199
	if (max == error_mark_node)
	  return error_mark_node;

6200 6201
	/* See if we can reduce this expression to something simpler.  */
	max = maybe_fold_nontype_arg (max);
6202
	if (!processing_template_decl)
6203 6204
	  max = decl_constant_value (max);

6205 6206 6207 6208
	if (processing_template_decl 
	    /* When providing explicit arguments to a template
	       function, but leaving some arguments for subsequent
	       deduction, MAX may be template-dependent even if we're
6209 6210 6211 6212 6213
	       not PROCESSING_TEMPLATE_DECL.  We still need to check for
	       template parms, though; MAX won't be an INTEGER_CST for
	       dynamic arrays, either.  */
	    || (TREE_CODE (max) != INTEGER_CST
		&& uses_template_parms (max)))
6214
	  {
6215 6216 6217 6218 6219
	    tree itype = make_node (INTEGER_TYPE);
	    TYPE_MIN_VALUE (itype) = size_zero_node;
	    TYPE_MAX_VALUE (itype) = build_min (MINUS_EXPR, sizetype, max,
						integer_one_node);
	    return itype;
6220 6221
	  }

6222 6223 6224 6225 6226 6227
	if (integer_zerop (omax))
	  {
	    /* Still allow an explicit array of size zero.  */
	    if (pedantic)
	      pedwarn ("creating array with size zero");
	  }
6228 6229 6230
	else if (integer_zerop (max) 
		 || (TREE_CODE (max) == INTEGER_CST 
		     && INT_CST_LT (max, integer_zero_node)))
6231
	  {
6232 6233 6234 6235 6236
	    /* [temp.deduct]

	       Type deduction may fail for any of the following
	       reasons:  

6237 6238
		 Attempting to create an array with a size that is
		 zero or negative.  */
6239
	    if (complain)
6240
	      cp_error ("creating array with size zero (`%E')", max);
6241 6242

	    return error_mark_node;
6243 6244
	  }

6245
	return compute_array_index_type (NULL_TREE, max);
6246 6247 6248 6249 6250 6251 6252 6253 6254
      }

    case TEMPLATE_TYPE_PARM:
    case TEMPLATE_TEMPLATE_PARM:
    case TEMPLATE_PARM_INDEX:
      {
	int idx;
	int level;
	int levels;
6255 6256

	r = NULL_TREE;
6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277

	if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
	    || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
	  {
	    idx = TEMPLATE_TYPE_IDX (t);
	    level = TEMPLATE_TYPE_LEVEL (t);
	  }
	else
	  {
	    idx = TEMPLATE_PARM_IDX (t);
	    level = TEMPLATE_PARM_LEVEL (t);
	  }

	if (TREE_VEC_LENGTH (args) > 0)
	  {
	    tree arg = NULL_TREE;

	    levels = TMPL_ARGS_DEPTH (args);
	    if (level <= levels)
	      arg = TMPL_ARG (args, level, idx);

6278 6279 6280
	    if (arg == error_mark_node)
	      return error_mark_node;
	    else if (arg != NULL_TREE)
6281 6282 6283
	      {
		if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
		  {
6284
		    my_friendly_assert (TYPE_P (arg), 0);
6285 6286 6287
		    return cp_build_qualified_type_real
		      (arg, CP_TYPE_QUALS (arg) | CP_TYPE_QUALS (t),
		       complain);
6288 6289 6290
		  }
		else if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM)
		  {
6291
		    if (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t))
6292 6293 6294
		      {
			/* We are processing a type constructed from
			   a template template parameter */
6295
			tree argvec = tsubst (TYPE_TI_ARGS (t),
6296 6297 6298 6299
					      args, complain, in_decl);
			if (argvec == error_mark_node)
			  return error_mark_node;
			
6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311
			/* We can get a TEMPLATE_TEMPLATE_PARM here when 
			   we are resolving nested-types in the signature of 
			   a member function templates.
			   Otherwise ARG is a TEMPLATE_DECL and is the real 
			   template to be instantiated.  */
			if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
			  arg = TYPE_NAME (arg);

			r = lookup_template_class (DECL_NAME (arg), 
						   argvec, in_decl, 
						   DECL_CONTEXT (arg),
						   /*entering_scope=*/0);
6312 6313 6314
			return cp_build_qualified_type_real (r, 
							     TYPE_QUALS (t),
							     complain);
6315 6316 6317 6318 6319 6320 6321 6322 6323
		      }
		    else
		      /* We are processing a template argument list.  */ 
		      return arg;
		  }
		else
		  return arg;
	      }
	  }
6324 6325
	else
	  my_friendly_abort (981018);
6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349

	if (level == 1)
	  /* This can happen during the attempted tsubst'ing in
	     unify.  This means that we don't yet have any information
	     about the template parameter in question.  */
	  return t;

	/* If we get here, we must have been looking at a parm for a
	   more deeply nested template.  Make a new version of this
	   template parameter, but with a lower level.  */
	switch (TREE_CODE (t))
	  {
	  case TEMPLATE_TYPE_PARM:
	  case TEMPLATE_TEMPLATE_PARM:
	    r = copy_node (t);
	    TEMPLATE_TYPE_PARM_INDEX (r)
	      = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
					    r, levels);
	    TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
	    TYPE_MAIN_VARIANT (r) = r;
	    TYPE_POINTER_TO (r) = NULL_TREE;
	    TYPE_REFERENCE_TO (r) = NULL_TREE;

	    if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
6350
		&& TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t))
6351
	      {
6352 6353 6354 6355 6356
		tree argvec = tsubst (TYPE_TI_ARGS (t), args,
				      complain, in_decl); 
		if (argvec == error_mark_node)
		  return error_mark_node;

6357
		TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
6358
		  = tree_cons (TYPE_NAME (t), argvec, NULL_TREE);
6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369
	      }
	    break;

	  case TEMPLATE_PARM_INDEX:
	    r = reduce_template_parm_level (t, type, levels);
	    break;
	   
	  default:
	    my_friendly_abort (0);
	  }

mrs's avatar
mrs committed
6370
	return r;
6371
      }
mrs's avatar
mrs committed
6372

mrs's avatar
mrs committed
6373 6374 6375 6376 6377 6378 6379 6380 6381
    case TREE_LIST:
      {
	tree purpose, value, chain, result;

	if (t == void_list_node)
	  return t;

	purpose = TREE_PURPOSE (t);
	if (purpose)
6382 6383 6384 6385 6386
	  {
	    purpose = tsubst (purpose, args, complain, in_decl);
	    if (purpose == error_mark_node)
	      return error_mark_node;
	  }
mrs's avatar
mrs committed
6387 6388
	value = TREE_VALUE (t);
	if (value)
6389 6390 6391 6392 6393
	  {
	    value = tsubst (value, args, complain, in_decl);
	    if (value == error_mark_node)
	      return error_mark_node;
	  }
mrs's avatar
mrs committed
6394 6395
	chain = TREE_CHAIN (t);
	if (chain && chain != void_type_node)
6396 6397 6398 6399 6400
	  {
	    chain = tsubst (chain, args, complain, in_decl);
	    if (chain == error_mark_node)
	      return error_mark_node;
	  }
mrs's avatar
mrs committed
6401 6402 6403 6404
	if (purpose == TREE_PURPOSE (t)
	    && value == TREE_VALUE (t)
	    && chain == TREE_CHAIN (t))
	  return t;
6405
	result = hash_tree_cons (purpose, value, chain);
mrs's avatar
mrs committed
6406 6407 6408 6409
	TREE_PARMLIST (result) = TREE_PARMLIST (t);
	return result;
      }
    case TREE_VEC:
mrs's avatar
mrs committed
6410 6411
      if (type != NULL_TREE)
	{
6412 6413
	  /* A binfo node.  We always need to make a copy, of the node
	     itself and of its BINFO_BASETYPES.  */
6414

mrs's avatar
mrs committed
6415 6416
	  t = copy_node (t);

6417 6418 6419
	  /* Make sure type isn't a typedef copy.  */
	  type = BINFO_TYPE (TYPE_BINFO (type));

mrs's avatar
mrs committed
6420
	  TREE_TYPE (t) = complete_type (type);
mrs's avatar
mrs committed
6421 6422 6423 6424 6425 6426 6427
	  if (IS_AGGR_TYPE (type))
	    {
	      BINFO_VTABLE (t) = TYPE_BINFO_VTABLE (type);
	      BINFO_VIRTUALS (t) = TYPE_BINFO_VIRTUALS (type);
	      if (TYPE_BINFO_BASETYPES (type) != NULL_TREE)
		BINFO_BASETYPES (t) = copy_node (TYPE_BINFO_BASETYPES (type));
	    }
mrs's avatar
mrs committed
6428 6429
	  return t;
	}
6430 6431

      /* Otherwise, a vector of template arguments.  */
6432
      return tsubst_template_arg_vector (t, args, complain);
mrs's avatar
mrs committed
6433 6434 6435 6436 6437

    case POINTER_TYPE:
    case REFERENCE_TYPE:
      {
	enum tree_code code;
6438

mrs's avatar
mrs committed
6439 6440 6441 6442
	if (type == TREE_TYPE (t))
	  return t;

	code = TREE_CODE (t);
6443 6444 6445 6446 6447 6448 6449 6450 6451 6452


	/* [temp.deduct]
	   
	   Type deduction may fail for any of the following
	   reasons:  

	   -- Attempting to create a pointer to reference type.
	   -- Attempting to create a reference to a reference type or
	      a reference to void.  */
6453 6454
	if (TREE_CODE (type) == REFERENCE_TYPE
	    || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
6455 6456 6457 6458 6459 6460 6461
	  {
	    static int   last_line = 0;
	    static char* last_file = 0;

	    /* We keep track of the last time we issued this error
	       message to avoid spewing a ton of messages during a
	       single bad template instantiation.  */
6462 6463
	    if (complain && (last_line != lineno ||
			     last_file != input_filename))
6464
	      {
6465 6466 6467 6468 6469 6470
		if (TREE_CODE (type) == VOID_TYPE)
		  cp_error ("forming reference to void");
		else
		  cp_error ("forming %s to reference type `%T'",
			    (code == POINTER_TYPE) ? "pointer" : "reference",
			    type);
6471 6472 6473 6474
		last_line = lineno;
		last_file = input_filename;
	      }

6475
	    return error_mark_node;
6476 6477
	  }
	else if (code == POINTER_TYPE)
mrs's avatar
mrs committed
6478 6479 6480
	  r = build_pointer_type (type);
	else
	  r = build_reference_type (type);
6481
	r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
6482

mrs's avatar
mrs committed
6483 6484 6485 6486
	/* Will this ever be needed for TYPE_..._TO values?  */
	layout_type (r);
	return r;
      }
mrs's avatar
mrs committed
6487
    case OFFSET_TYPE:
6488
      {
6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503
	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
	if (r == error_mark_node || !IS_AGGR_TYPE (r))
	  {
	    /* [temp.deduct]

	       Type deduction may fail for any of the following
	       reasons:
	       
	       -- Attempting to create "pointer to member of T" when T
	          is not a class type.  */
	    if (complain)
	      cp_error ("creating pointer to member of non-class type `%T'", 
			r);
	    return error_mark_node;
	  }
6504 6505
	return build_offset_type (r, type);
      }
mrs's avatar
mrs committed
6506 6507 6508
    case FUNCTION_TYPE:
    case METHOD_TYPE:
      {
mrs's avatar
merging  
mrs committed
6509
	tree fntype;
6510
	tree raises;
mrs's avatar
mrs committed
6511

6512 6513 6514
	fntype = tsubst_function_type (t, args, complain, in_decl);
	if (fntype == error_mark_node)
	  return error_mark_node;
6515 6516 6517

	/* Substitue the exception specification. */
	raises = TYPE_RAISES_EXCEPTIONS (t);
mrs's avatar
merging  
mrs committed
6518 6519
	if (raises)
	  {
6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534
	    tree   list = NULL_TREE;
	    
	    if (! TREE_VALUE (raises))
	      list = raises;
	    else
	      for (; raises != NULL_TREE; raises = TREE_CHAIN (raises))
	        {
	          tree spec = TREE_VALUE (raises);
	          
	          spec = tsubst (spec, args, complain, in_decl);
	          if (spec == error_mark_node)
	            return spec;
	          list = add_exception_specifier (list, spec, complain);
	        }
	    fntype = build_exception_variant (fntype, list);
mrs's avatar
merging  
mrs committed
6535 6536
	  }
	return fntype;
mrs's avatar
mrs committed
6537 6538 6539
      }
    case ARRAY_TYPE:
      {
6540 6541 6542 6543 6544 6545
	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
	if (domain == error_mark_node)
	  return error_mark_node;

	/* As an optimization, we avoid regenerating the array type if
	   it will obviously be the same as T.  */
mrs's avatar
mrs committed
6546 6547
	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
	  return t;
6548

6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559
	/* These checks should match the ones in grokdeclarator.  

	   [temp.deduct] 
	
	   The deduction may fail for any of the following reasons: 

	   -- Attempting to create an array with an element type that
	      is void, a function type, or a reference type.  */
	if (TREE_CODE (type) == VOID_TYPE 
	    || TREE_CODE (type) == FUNCTION_TYPE
	    || TREE_CODE (type) == REFERENCE_TYPE)
6560
	  {
6561 6562 6563
	    if (complain)
	      cp_error ("creating array of `%T'", type);
	    return error_mark_node;
6564 6565
	  }

mrs's avatar
mrs committed
6566 6567 6568 6569 6570
	r = build_cplus_array_type (type, domain);
	return r;
      }

    case PLUS_EXPR:
mrs's avatar
mrs committed
6571
    case MINUS_EXPR:
6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582
      {
	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain,
			  in_decl);
	tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain,
			  in_decl);

	if (e1 == error_mark_node || e2 == error_mark_node)
	  return error_mark_node;

	return fold (build (TREE_CODE (t), TREE_TYPE (t), e1, e2));
      }
mrs's avatar
mrs committed
6583 6584 6585

    case NEGATE_EXPR:
    case NOP_EXPR:
6586 6587 6588 6589 6590 6591 6592 6593
      {
	tree e = tsubst (TREE_OPERAND (t, 0), args, complain,
			  in_decl);
	if (e == error_mark_node)
	  return error_mark_node;

	return fold (build (TREE_CODE (t), TREE_TYPE (t), e));
      }
mrs's avatar
mrs committed
6594

mrs's avatar
mrs committed
6595 6596
    case TYPENAME_TYPE:
      {
6597 6598 6599 6600 6601 6602 6603
	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
				     in_decl, /*entering_scope=*/1);
	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
			      complain, in_decl); 

	if (ctx == error_mark_node || f == error_mark_node)
	  return error_mark_node;
6604

6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615
	if (!IS_AGGR_TYPE (ctx))
	  {
	    if (complain)
	      cp_error ("`%T' is not a class, struct, or union type",
			ctx);
	    return error_mark_node;
	  }
	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
	  {
	    /* Normally, make_typename_type does not require that the CTX
	       have complete type in order to allow things like:
6616
	     
6617
	         template <class T> struct S { typename S<T>::X Y; };
6618

6619 6620 6621
	       But, such constructs have already been resolved by this
	       point, so here CTX really should have complete type, unless
	       it's a partial instantiation.  */
6622
	    ctx = complete_type (ctx);
nathan's avatar
gcc  
nathan committed
6623
	    if (!COMPLETE_TYPE_P (ctx))
6624 6625 6626 6627 6628 6629
	      {
		if (complain)
		  incomplete_type_error (NULL_TREE, ctx);
		return error_mark_node;
	      }
	  }
6630

6631
	f = make_typename_type (ctx, f, complain);
6632 6633
	if (f == error_mark_node)
	  return f;
6634 6635 6636 6637
	return cp_build_qualified_type_real (f, 
					     CP_TYPE_QUALS (f) 
					     | CP_TYPE_QUALS (t),
					     complain);
mrs's avatar
mrs committed
6638 6639 6640
      }

    case INDIRECT_REF:
6641 6642 6643 6644 6645 6646 6647 6648
      {
	tree e = tsubst (TREE_OPERAND (t, 0), args, complain,
			 in_decl);
	if (e == error_mark_node)
	  return error_mark_node;
	return make_pointer_declarator (type, e);
      }

mrs's avatar
mrs committed
6649
    case ADDR_EXPR:
6650 6651 6652 6653 6654 6655 6656
      {
	tree e = tsubst (TREE_OPERAND (t, 0), args, complain,
			 in_decl);
	if (e == error_mark_node)
	  return error_mark_node;
	return make_reference_declarator (type, e);
      }
mrs's avatar
mrs committed
6657 6658

    case ARRAY_REF:
6659 6660 6661
      {
	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain,
			  in_decl);
6662 6663
	tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain,
			       in_decl);
6664 6665 6666 6667 6668
	if (e1 == error_mark_node || e2 == error_mark_node)
	  return error_mark_node;

	return build_parse_node (ARRAY_REF, e1, e2, tsubst_expr);
      }
mrs's avatar
mrs committed
6669 6670

    case CALL_EXPR:
6671 6672 6673
      {
	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain,
			  in_decl);
6674 6675 6676 6677
	tree e2 = (tsubst_call_declarator_parms
		   (CALL_DECLARATOR_PARMS (t), args, complain, in_decl));
	tree e3 = tsubst (CALL_DECLARATOR_EXCEPTION_SPEC (t), args,
			  complain, in_decl);
6678 6679 6680 6681 6682

	if (e1 == error_mark_node || e2 == error_mark_node 
	    || e3 == error_mark_node)
	  return error_mark_node;

6683
	return make_call_declarator (e1, e2, CALL_DECLARATOR_QUALS (t), e3);
6684
      }
mrs's avatar
mrs committed
6685

mrs's avatar
mrs committed
6686
    case SCOPE_REF:
6687 6688 6689 6690 6691 6692 6693 6694 6695
      {
	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain,
				  in_decl);
	tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
	if (e1 == error_mark_node || e2 == error_mark_node)
	  return error_mark_node;

	return build_parse_node (TREE_CODE (t), e1, e2);
      }
mrs's avatar
mrs committed
6696

6697
    case TYPEOF_TYPE:
6698 6699 6700 6701 6702 6703 6704 6705
      {
	tree e1 = tsubst_expr (TYPE_FIELDS (t), args, complain,
			       in_decl);
	if (e1 == error_mark_node)
	  return error_mark_node;

	return TREE_TYPE (e1); 
      }
6706

6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724
    case FUNCTION_NAME:
      {
	const char *name;
	int len;
	tree type;
	tree str;

	/* This code should match declare_hidden_char_array in
	   c-common.c.  */
	name = (*decl_printable_name) (current_function_decl, 2);
	len = strlen (name) + 1;
	type =  build_array_type (char_type_node,
				  build_index_type (build_int_2 (len, 0)));
	str = build_string (len, name);
	TREE_TYPE (str) = type;
	return str;
      }

mrs's avatar
mrs committed
6725
    default:
mrs's avatar
mrs committed
6726
      sorry ("use of `%s' in template",
mrs's avatar
mrs committed
6727 6728 6729 6730 6731
	     tree_code_name [(int) TREE_CODE (t)]);
      return error_mark_node;
    }
}

6732 6733 6734 6735
/* Like tsubst, but deals with expressions.  This function just replaces
   template parms; to finish processing the resultant expression, use
   tsubst_expr.  */

mrs's avatar
mrs committed
6736
tree
6737
tsubst_copy (t, args, complain, in_decl)
6738
     tree t, args;
6739
     int complain;
mrs's avatar
mrs committed
6740 6741 6742
     tree in_decl;
{
  enum tree_code code;
6743
  tree r;
mrs's avatar
mrs committed
6744

mrs's avatar
mrs committed
6745 6746 6747 6748
  if (t == NULL_TREE || t == error_mark_node)
    return t;

  code = TREE_CODE (t);
mrs's avatar
mrs committed
6749

mrs's avatar
mrs committed
6750 6751 6752
  switch (code)
    {
    case PARM_DECL:
6753
      return do_identifier (DECL_NAME (t), 0, NULL_TREE);
mrs's avatar
mrs committed
6754 6755

    case CONST_DECL:
6756 6757 6758 6759 6760 6761 6762 6763 6764
      {
	tree enum_type;
	tree v;

	if (!DECL_CONTEXT (t))
	  /* This is a global enumeration constant.  */
	  return t;

	/* Unfortunately, we cannot just call lookup_name here.
6765 6766 6767 6768 6769 6770 6771 6772 6773
	   Consider:
	   
	     template <int I> int f() {
	     enum E { a = I };
	     struct S { void g() { E e = a; } };
	     };
	   
	   When we instantiate f<7>::S::g(), say, lookup_name is not
	   clever enough to find f<7>::a.  */
6774
	enum_type 
6775
	  = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl, 
6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788
			      /*entering_scope=*/0);

	for (v = TYPE_VALUES (enum_type); 
	     v != NULL_TREE; 
	     v = TREE_CHAIN (v))
	  if (TREE_PURPOSE (v) == DECL_NAME (t))
	    return TREE_VALUE (v);

	  /* We didn't find the name.  That should never happen; if
	     name-lookup found it during preliminary parsing, we
	     should find it again here during instantiation.  */
	my_friendly_abort (0);
      }
jason's avatar
jason committed
6789
      return t;
6790

mrs's avatar
mrs committed
6791 6792 6793
    case FIELD_DECL:
      if (DECL_CONTEXT (t))
	{
6794 6795
	  tree ctx;

6796
	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
6797
				  /*entering_scope=*/1);
6798
	  if (ctx != DECL_CONTEXT (t))
mrs's avatar
mrs committed
6799 6800 6801 6802 6803 6804 6805
	    return lookup_field (ctx, DECL_NAME (t), 0, 0);
	}
      return t;

    case VAR_DECL:
    case FUNCTION_DECL:
      if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
6806
	t = tsubst (t, args, complain, in_decl);
mrs's avatar
mrs committed
6807 6808 6809
      mark_used (t);
      return t;

6810 6811
    case TEMPLATE_DECL:
      if (is_member_template (t))
6812
	return tsubst (t, args, complain, in_decl);
6813 6814 6815
      else
	return t;

6816 6817 6818 6819 6820 6821 6822
    case LOOKUP_EXPR:
      {
	/* We must tsbust into a LOOKUP_EXPR in case the names to
	   which it refers is a conversion operator; in that case the
	   name will change.  We avoid making unnecessary copies,
	   however.  */
	
6823
	tree id = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
6824 6825 6826

	if (id != TREE_OPERAND (t, 0))
	  {
6827
	    r = build_nt (LOOKUP_EXPR, id);
6828 6829 6830 6831 6832 6833 6834
	    LOOKUP_EXPR_GLOBAL (r) = LOOKUP_EXPR_GLOBAL (t);
	    t = r;
	  }

	return t;
      }

mrs's avatar
mrs committed
6835 6836
    case CAST_EXPR:
    case REINTERPRET_CAST_EXPR:
mrs's avatar
mrs committed
6837 6838 6839
    case CONST_CAST_EXPR:
    case STATIC_CAST_EXPR:
    case DYNAMIC_CAST_EXPR:
6840
    case NOP_EXPR:
mrs's avatar
mrs committed
6841
      return build1
6842 6843
	(code, tsubst (TREE_TYPE (t), args, complain, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
mrs's avatar
mrs committed
6844 6845 6846 6847 6848 6849 6850 6851

    case INDIRECT_REF:
    case PREDECREMENT_EXPR:
    case PREINCREMENT_EXPR:
    case POSTDECREMENT_EXPR:
    case POSTINCREMENT_EXPR:
    case NEGATE_EXPR:
    case TRUTH_NOT_EXPR:
mrs's avatar
mrs committed
6852
    case BIT_NOT_EXPR:
mrs's avatar
mrs committed
6853 6854 6855
    case ADDR_EXPR:
    case CONVERT_EXPR:      /* Unary + */
    case SIZEOF_EXPR:
6856
    case ALIGNOF_EXPR:
mrs's avatar
mrs committed
6857
    case ARROW_EXPR:
mrs's avatar
mrs committed
6858
    case THROW_EXPR:
mrs's avatar
mrs committed
6859
    case TYPEID_EXPR:
6860 6861
    case REALPART_EXPR:
    case IMAGPART_EXPR:
mrs's avatar
mrs committed
6862
      return build1
6863
	(code, tsubst (TREE_TYPE (t), args, complain, in_decl),
6864
	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
mrs's avatar
mrs committed
6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902

    case PLUS_EXPR:
    case MINUS_EXPR:
    case MULT_EXPR:
    case TRUNC_DIV_EXPR:
    case CEIL_DIV_EXPR:
    case FLOOR_DIV_EXPR:
    case ROUND_DIV_EXPR:
    case EXACT_DIV_EXPR:
    case BIT_AND_EXPR:
    case BIT_ANDTC_EXPR:
    case BIT_IOR_EXPR:
    case BIT_XOR_EXPR:
    case TRUNC_MOD_EXPR:
    case FLOOR_MOD_EXPR:
    case TRUTH_ANDIF_EXPR:
    case TRUTH_ORIF_EXPR:
    case TRUTH_AND_EXPR:
    case TRUTH_OR_EXPR:
    case RSHIFT_EXPR:
    case LSHIFT_EXPR:
    case RROTATE_EXPR:
    case LROTATE_EXPR:
    case EQ_EXPR:
    case NE_EXPR:
    case MAX_EXPR:
    case MIN_EXPR:
    case LE_EXPR:
    case GE_EXPR:
    case LT_EXPR:
    case GT_EXPR:
    case COMPONENT_REF:
    case ARRAY_REF:
    case COMPOUND_EXPR:
    case SCOPE_REF:
    case DOTSTAR_EXPR:
    case MEMBER_REF:
      return build_nt
6903 6904
	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
mrs's avatar
mrs committed
6905 6906 6907 6908

    case CALL_EXPR:
      {
	tree fn = TREE_OPERAND (t, 0);
jason's avatar
jason committed
6909
	if (is_overloaded_fn (fn))
6910
	  fn = tsubst_copy (get_first_fn (fn), args, complain, in_decl);
mrs's avatar
mrs committed
6911
	else
jason's avatar
jason committed
6912
	  /* Sometimes FN is a LOOKUP_EXPR.  */
6913
	  fn = tsubst_copy (fn, args, complain, in_decl);
mrs's avatar
mrs committed
6914
	return build_nt
6915 6916
	  (code, fn, tsubst_copy (TREE_OPERAND (t, 1), args, complain,
				  in_decl),
mrs's avatar
mrs committed
6917 6918 6919 6920 6921 6922 6923 6924
	   NULL_TREE);
      }

    case METHOD_CALL_EXPR:
      {
	tree name = TREE_OPERAND (t, 0);
	if (TREE_CODE (name) == BIT_NOT_EXPR)
	  {
6925 6926
	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
				complain, in_decl);
6927
	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
mrs's avatar
mrs committed
6928 6929 6930 6931
	  }
	else if (TREE_CODE (name) == SCOPE_REF
		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
	  {
6932 6933
	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
				     complain, in_decl);
mrs's avatar
mrs committed
6934
	    name = TREE_OPERAND (name, 1);
6935 6936
	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
				complain, in_decl);
6937
	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
mrs's avatar
mrs committed
6938 6939 6940
	    name = build_nt (SCOPE_REF, base, name);
	  }
	else
6941
	  name = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
mrs's avatar
mrs committed
6942
	return build_nt
6943 6944 6945
	  (code, name, tsubst_copy (TREE_OPERAND (t, 1), args,
				    complain, in_decl),
	   tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl),
mrs's avatar
mrs committed
6946 6947 6948
	   NULL_TREE);
      }

6949 6950 6951 6952 6953 6954 6955 6956
    case STMT_EXPR:
      /* This processing should really occur in tsubst_expr, However,
	 tsubst_expr does not recurse into expressions, since it
	 assumes that there aren't any statements inside them.
	 Instead, it simply calls build_expr_from_tree.  So, we need
	 to expand the STMT_EXPR here.  */
      if (!processing_template_decl)
	{
6957
	  tree stmt_expr = begin_stmt_expr ();
6958 6959
	  tsubst_expr (STMT_EXPR_STMT (t), args,
		       complain, in_decl);
6960
	  return finish_stmt_expr (stmt_expr);
6961
	}
6962 6963
      
      return t;
6964

mrs's avatar
mrs committed
6965 6966
    case COND_EXPR:
    case MODOP_EXPR:
6967
    case PSEUDO_DTOR_EXPR:
6968
      {
6969
	r = build_nt
6970 6971 6972
	  (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
	   tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
	   tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
6973 6974
	return r;
      }
mrs's avatar
mrs committed
6975 6976 6977

    case NEW_EXPR:
      {
6978
	r = build_nt
6979 6980 6981
	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
mrs's avatar
mrs committed
6982 6983 6984 6985 6986 6987
	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
	return r;
      }

    case DELETE_EXPR:
      {
6988
	r = build_nt
6989 6990
	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
mrs's avatar
mrs committed
6991 6992 6993 6994 6995
	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
	return r;
      }

6996 6997
    case TEMPLATE_ID_EXPR:
      {
6998
        /* Substituted template arguments */
6999 7000
	tree targs = tsubst_copy (TREE_OPERAND (t, 1), args, complain,
				  in_decl);
7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014

	if (targs && TREE_CODE (targs) == TREE_LIST)
	  {
	    tree chain;
	    for (chain = targs; chain; chain = TREE_CHAIN (chain))
	      TREE_VALUE (chain) = maybe_fold_nontype_arg (TREE_VALUE (chain));
	  }
	else if (targs)
	  {
	    int i;
	    for (i = 0; i < TREE_VEC_LENGTH (targs); ++i)
	      TREE_VEC_ELT (targs, i) 
		= maybe_fold_nontype_arg (TREE_VEC_ELT (targs, i));
	  }
7015 7016

	return lookup_template_function
7017
	  (tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl), targs);
7018 7019
      }

mrs's avatar
mrs committed
7020 7021 7022 7023 7024 7025 7026 7027 7028
    case TREE_LIST:
      {
	tree purpose, value, chain;

	if (t == void_list_node)
	  return t;

	purpose = TREE_PURPOSE (t);
	if (purpose)
7029
	  purpose = tsubst_copy (purpose, args, complain, in_decl);
mrs's avatar
mrs committed
7030 7031
	value = TREE_VALUE (t);
	if (value)
7032
	  value = tsubst_copy (value, args, complain, in_decl);
mrs's avatar
mrs committed
7033 7034
	chain = TREE_CHAIN (t);
	if (chain && chain != void_type_node)
7035
	  chain = tsubst_copy (chain, args, complain, in_decl);
mrs's avatar
mrs committed
7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047
	if (purpose == TREE_PURPOSE (t)
	    && value == TREE_VALUE (t)
	    && chain == TREE_CHAIN (t))
	  return t;
	return tree_cons (purpose, value, chain);
      }

    case RECORD_TYPE:
    case UNION_TYPE:
    case ENUMERAL_TYPE:
    case INTEGER_TYPE:
    case TEMPLATE_TYPE_PARM:
7048
    case TEMPLATE_TEMPLATE_PARM:
jason's avatar
jason committed
7049
    case TEMPLATE_PARM_INDEX:
mrs's avatar
mrs committed
7050 7051 7052 7053 7054 7055 7056
    case POINTER_TYPE:
    case REFERENCE_TYPE:
    case OFFSET_TYPE:
    case FUNCTION_TYPE:
    case METHOD_TYPE:
    case ARRAY_TYPE:
    case TYPENAME_TYPE:
jason's avatar
jason committed
7057
    case TYPE_DECL:
7058
      return tsubst (t, args, complain, in_decl);
mrs's avatar
mrs committed
7059

mrs's avatar
mrs committed
7060
    case IDENTIFIER_NODE:
7061 7062 7063 7064
      if (IDENTIFIER_TYPENAME_P (t)
	  /* Make sure it's not just a variable named `__opr', for instance,
	     which can occur in some existing code.  */
	  && TREE_TYPE (t))
mrs's avatar
mrs committed
7065
	return build_typename_overload
7066
	  (tsubst (TREE_TYPE (t), args, complain, in_decl));
mrs's avatar
mrs committed
7067 7068 7069
      else
	return t;

mrs's avatar
mrs committed
7070
    case CONSTRUCTOR:
7071 7072
      {
	r = build
7073 7074 7075
	  (CONSTRUCTOR, tsubst (TREE_TYPE (t), args, complain, in_decl), 
	   NULL_TREE, tsubst_copy (CONSTRUCTOR_ELTS (t), args,
				   complain, in_decl));
7076 7077 7078
	TREE_HAS_CONSTRUCTOR (r) = TREE_HAS_CONSTRUCTOR (t);
	return r;
      }
mrs's avatar
mrs committed
7079

7080 7081 7082 7083
    case VA_ARG_EXPR:
      return build_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
					in_decl),
			   tsubst (TREE_TYPE (t), args, complain, in_decl));
7084 7085 7086 7087

    case FUNCTION_NAME:
      return tsubst (t, args, complain, in_decl);

mrs's avatar
mrs committed
7088 7089 7090 7091 7092
    default:
      return t;
    }
}

7093
/* Like tsubst_copy, but also does semantic processing.  */
7094

mrs's avatar
mrs committed
7095
tree
7096
tsubst_expr (t, args, complain, in_decl)
7097
     tree t, args;
7098
     int complain;
mrs's avatar
mrs committed
7099 7100
     tree in_decl;
{
7101 7102
  tree stmt;

mrs's avatar
mrs committed
7103 7104 7105
  if (t == NULL_TREE || t == error_mark_node)
    return t;

mrs's avatar
mrs committed
7106
  if (processing_template_decl)
7107
    return tsubst_copy (t, args, complain, in_decl);
mrs's avatar
mrs committed
7108 7109

  switch (TREE_CODE (t))
mrs's avatar
mrs committed
7110
    {
7111
    case RETURN_INIT:
7112
      prep_stmt (t);
7113 7114 7115 7116 7117 7118 7119
      finish_named_return_value
	(TREE_OPERAND (t, 0),
	 tsubst_expr (TREE_OPERAND (t, 1), args, /*complain=*/1, in_decl));
      tsubst_expr (TREE_CHAIN (t), args, complain, in_decl);
      break;

    case CTOR_INITIALIZER:
7120
      prep_stmt (t);
7121 7122 7123 7124 7125 7126 7127 7128
      current_member_init_list
	= tsubst_expr_values (TREE_OPERAND (t, 0), args);
      current_base_init_list
	= tsubst_expr_values (TREE_OPERAND (t, 1), args);
      setup_vtbl_ptr ();
      tsubst_expr (TREE_CHAIN (t), args, complain, in_decl);
      break;

mrs's avatar
mrs committed
7129
    case RETURN_STMT:
7130
      prep_stmt (t);
7131
      finish_return_stmt (tsubst_expr (RETURN_EXPR (t),
7132
				       args, complain, in_decl));
mrs's avatar
mrs committed
7133 7134 7135
      break;

    case EXPR_STMT:
7136
      prep_stmt (t);
7137
      finish_expr_stmt (tsubst_expr (EXPR_STMT_EXPR (t),
7138
				     args, complain, in_decl));
mrs's avatar
mrs committed
7139 7140 7141 7142
      break;

    case DECL_STMT:
      {
7143 7144
	tree decl;
	tree init;
mrs's avatar
mrs committed
7145

7146
	prep_stmt (t);
7147
	decl = DECL_STMT_DECL (t);
7148 7149 7150 7151 7152 7153 7154
	if (TREE_CODE (decl) == LABEL_DECL)
	  finish_label_decl (DECL_NAME (decl));
	else
	  {
	    init = DECL_INITIAL (decl);
	    decl = tsubst (decl, args, complain, in_decl);
	    init = tsubst_expr (init, args, complain, in_decl);
7155 7156
	    if (init)
	      DECL_INITIAL (decl) = error_mark_node;
7157 7158 7159 7160 7161
	    /* By marking the declaration as instantiated, we avoid
	       trying to instantiate it.  Since instantiate_decl can't
	       handle local variables, and since we've already done
	       all that needs to be done, that's the right thing to
	       do.  */
7162 7163 7164
	    if (TREE_CODE (decl) == VAR_DECL)
	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
	    maybe_push_decl (decl);
7165
	    cp_finish_decl (decl, init, NULL_TREE, 0);
7166
	  }
7167
	return decl;
mrs's avatar
mrs committed
7168
      }
mrs's avatar
mrs committed
7169

mrs's avatar
mrs committed
7170 7171 7172
    case FOR_STMT:
      {
	tree tmp;
7173
	prep_stmt (t);
mrs's avatar
mrs committed
7174

7175
	stmt = begin_for_stmt ();
7176
	for (tmp = FOR_INIT_STMT (t); tmp; tmp = TREE_CHAIN (tmp))
7177
	  tsubst_expr (tmp, args, complain, in_decl);
7178
	finish_for_init_stmt (stmt);
7179
	finish_for_cond (tsubst_expr (FOR_COND (t), args,
7180
				      complain, in_decl),
7181
			 stmt);
7182
	tmp = tsubst_expr (FOR_EXPR (t), args, complain, in_decl);
7183
	finish_for_expr (tmp, stmt);
7184
	tsubst_expr (FOR_BODY (t), args, complain, in_decl);
7185
	finish_for_stmt (tmp, stmt);
mrs's avatar
mrs committed
7186 7187
      }
      break;
mrs's avatar
mrs committed
7188

mrs's avatar
mrs committed
7189 7190
    case WHILE_STMT:
      {
7191
	prep_stmt (t);
7192
	stmt = begin_while_stmt ();
7193
	finish_while_stmt_cond (tsubst_expr (WHILE_COND (t),
7194
					     args, complain, in_decl),
7195
				stmt);
7196
	tsubst_expr (WHILE_BODY (t), args, complain, in_decl);
7197
	finish_while_stmt (stmt);
mrs's avatar
mrs committed
7198 7199
      }
      break;
mrs's avatar
mrs committed
7200

mrs's avatar
mrs committed
7201 7202
    case DO_STMT:
      {
7203
	prep_stmt (t);
7204
	stmt = begin_do_stmt ();
7205
	tsubst_expr (DO_BODY (t), args, complain, in_decl);
7206
	finish_do_body (stmt);
7207
	finish_do_stmt (tsubst_expr (DO_COND (t), args,
7208
				     complain, in_decl),
7209
			stmt);
mrs's avatar
mrs committed
7210 7211
      }
      break;
mrs's avatar
mrs committed
7212

mrs's avatar
mrs committed
7213
    case IF_STMT:
mrs's avatar
mrs committed
7214
      {
mrs's avatar
mrs committed
7215 7216
	tree tmp;

7217
	prep_stmt (t);
7218
	stmt = begin_if_stmt ();
7219
	finish_if_stmt_cond (tsubst_expr (IF_COND (t),
7220
					  args, complain, in_decl),
7221
			     stmt);
mrs's avatar
mrs committed
7222

7223
	if (tmp = THEN_CLAUSE (t), tmp)
mrs's avatar
mrs committed
7224
	  {
7225
	    tsubst_expr (tmp, args, complain, in_decl);
7226
	    finish_then_clause (stmt);
mrs's avatar
mrs committed
7227 7228
	  }

7229 7230 7231
	if (tmp = ELSE_CLAUSE (t), tmp)
	  {
	    begin_else_clause ();
7232
	    tsubst_expr (tmp, args, complain, in_decl);
7233
	    finish_else_clause (stmt);
7234
	  }
mrs's avatar
mrs committed
7235

7236
	finish_if_stmt ();
mrs's avatar
mrs committed
7237
      }
mrs's avatar
mrs committed
7238
      break;
mrs's avatar
mrs committed
7239

mrs's avatar
mrs committed
7240 7241
    case COMPOUND_STMT:
      {
7242
	tree substmt;
mrs's avatar
mrs committed
7243

7244
	prep_stmt (t);
7245
	stmt = begin_compound_stmt (COMPOUND_STMT_NO_SCOPE (t));
7246 7247 7248
	for (substmt = COMPOUND_BODY (t); 
	     substmt != NULL_TREE;
	     substmt = TREE_CHAIN (substmt))
7249
	  tsubst_expr (substmt, args, complain, in_decl);
7250
	return finish_compound_stmt (COMPOUND_STMT_NO_SCOPE (t), stmt);
mrs's avatar
mrs committed
7251 7252
      }
      break;
mrs's avatar
mrs committed
7253

mrs's avatar
mrs committed
7254
    case BREAK_STMT:
7255
      prep_stmt (t);
7256
      finish_break_stmt ();
mrs's avatar
mrs committed
7257
      break;
mrs's avatar
mrs committed
7258

mrs's avatar
mrs committed
7259
    case CONTINUE_STMT:
7260
      prep_stmt (t);
7261
      finish_continue_stmt ();
mrs's avatar
mrs committed
7262 7263
      break;

mrs's avatar
mrs committed
7264 7265
    case SWITCH_STMT:
      {
7266
	tree val;
mrs's avatar
mrs committed
7267

7268
	prep_stmt (t);
7269
	stmt = begin_switch_stmt ();
7270
	val = tsubst_expr (SWITCH_COND (t), args, complain, in_decl);
7271
	finish_switch_cond (val, stmt);
7272 7273
	tsubst_expr (SWITCH_BODY (t), args, complain, in_decl);
	finish_switch_stmt (val, stmt);
mrs's avatar
mrs committed
7274 7275 7276 7277
      }
      break;

    case CASE_LABEL:
7278
      prep_stmt (t);
7279 7280
      finish_case_label (tsubst_expr (CASE_LOW (t), args, complain, in_decl),
			 tsubst_expr (CASE_HIGH (t), args, complain, in_decl));
mrs's avatar
mrs committed
7281 7282
      break;

7283 7284 7285
    case LABEL_STMT:
      lineno = STMT_LINENO (t);
      finish_label_stmt (DECL_NAME (LABEL_STMT_LABEL (t)));
mrs's avatar
mrs committed
7286 7287 7288
      break;

    case GOTO_STMT:
7289
      prep_stmt (t);
mmitchel's avatar
 
mmitchel committed
7290
      t = GOTO_DESTINATION (t);
7291
      if (TREE_CODE (t) != LABEL_DECL)
mmitchel's avatar
 
mmitchel committed
7292 7293 7294
	/* Computed goto's must be tsubst'd into.  On the other hand,
	   non-computed gotos must not be; the identifier in question
	   will have no binding.  */
7295
	t = tsubst_expr (t, args, complain, in_decl);
7296 7297
      else
	t = DECL_NAME (t);
mmitchel's avatar
 
mmitchel committed
7298
      finish_goto_stmt (t);
7299 7300 7301
      break;

    case ASM_STMT:
7302
      prep_stmt (t);
7303
      finish_asm_stmt (ASM_CV_QUAL (t),
7304 7305 7306 7307 7308
		       tsubst_expr (ASM_STRING (t), args, complain, in_decl),
		       tsubst_expr (ASM_OUTPUTS (t), args, complain, in_decl),
		       tsubst_expr (ASM_INPUTS (t), args, complain, in_decl), 
		       tsubst_expr (ASM_CLOBBERS (t), args, complain,
				    in_decl));
mrs's avatar
mrs committed
7309
      break;
mrs's avatar
mrs committed
7310 7311

    case TRY_BLOCK:
7312
      prep_stmt (t);
7313
      if (CLEANUP_P (t))
7314
	{
7315
	  stmt = begin_try_block ();
7316 7317 7318 7319 7320 7321
	  tsubst_expr (TRY_STMTS (t), args, complain, in_decl);
	  finish_cleanup_try_block (stmt);
	  finish_cleanup (tsubst_expr (TRY_HANDLERS (t), args,
				       complain, in_decl),
			  stmt);
	}
7322 7323
      else
	{
7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338
	  tree handler;

	  if (FN_TRY_BLOCK_P (t))
	    stmt = begin_function_try_block ();
	  else
	    stmt = begin_try_block ();

	  tsubst_expr (TRY_STMTS (t), args, complain, in_decl);

	  if (FN_TRY_BLOCK_P (t))
	    finish_function_try_block (stmt);
	  else
	    finish_try_block (stmt);

	  handler = TRY_HANDLERS (t);
7339 7340
	  for (; handler; handler = TREE_CHAIN (handler))
	    tsubst_expr (handler, args, complain, in_decl);
7341 7342 7343 7344
	  if (FN_TRY_BLOCK_P (t))
	    finish_function_handler_sequence (stmt);
	  else
	    finish_handler_sequence (stmt);
7345
	}
mrs's avatar
mrs committed
7346
      break;
7347
      
mrs's avatar
mrs committed
7348
    case HANDLER:
7349 7350 7351 7352 7353 7354 7355 7356 7357 7358
      {
	tree decl;
	tree blocks;

	prep_stmt (t);
	stmt = begin_handler ();
	if (HANDLER_PARMS (t))
	  {
	    decl = DECL_STMT_DECL (HANDLER_PARMS (t));
	    decl = tsubst (decl, args, complain, in_decl);
7359 7360 7361 7362
	    /* Prevent instantiate_decl from trying to instantiate
	       this variable.  We've already done all that needs to be
	       done.  */
	    DECL_TEMPLATE_INSTANTIATED (decl) = 1;
7363 7364 7365 7366 7367 7368 7369
	  }
	else
	  decl = NULL_TREE;
	blocks = finish_handler_parms (decl, stmt);
	tsubst_expr (HANDLER_BODY (t), args, complain, in_decl);
	finish_handler (blocks, stmt);
      }
mrs's avatar
mrs committed
7370 7371
      break;

mrs's avatar
mrs committed
7372
    case TAG_DEFN:
7373
      prep_stmt (t);
mrs's avatar
mrs committed
7374
      t = TREE_TYPE (t);
7375
      tsubst (t, args, complain, NULL_TREE);
mrs's avatar
mrs committed
7376 7377
      break;

mrs's avatar
mrs committed
7378
    default:
7379
      return build_expr_from_tree (tsubst_copy (t, args, complain, in_decl));
mrs's avatar
mrs committed
7380 7381
    }
  return NULL_TREE;
mrs's avatar
mrs committed
7382 7383
}

7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420
/* TMPL is a TEMPLATE_DECL for a cloned constructor or destructor.
   Instantiate it with the ARGS.  */

static tree
instantiate_clone (tmpl, args)
     tree tmpl;
     tree args;
{
  tree spec;
  tree clone;

  /* Instantiated the cloned function, rather than the clone.  */
  spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), args);

  /* Then, see if we've already cloned the instantiation.  */
  for (clone = TREE_CHAIN (spec);
       clone && DECL_CLONED_FUNCTION_P (clone);
       clone = TREE_CHAIN (clone))
    if (DECL_NAME (clone) == DECL_NAME (tmpl))
      return clone;

  /* If we haven't, do so know.  */
  if (!clone)
    clone_function_decl (spec, /*update_method_vec_p=*/0);

  /* Look again.  */
  for (clone = TREE_CHAIN (spec);
       clone && DECL_CLONED_FUNCTION_P (clone);
       clone = TREE_CHAIN (clone))
    if (DECL_NAME (clone) == DECL_NAME (tmpl))
      return clone;

  /* We should always have found the clone by now.  */
  my_friendly_abort (20000411);
  return NULL_TREE;
}

7421
/* Instantiate the indicated variable or function template TMPL with
7422 7423
   the template arguments in TARG_PTR.  */

mrs's avatar
mrs committed
7424 7425
tree
instantiate_template (tmpl, targ_ptr)
7426
     tree tmpl, targ_ptr;
mrs's avatar
mrs committed
7427
{
mrs's avatar
mrs committed
7428
  tree fndecl;
7429 7430
  tree gen_tmpl;
  tree spec;
mrs's avatar
mrs committed
7431
  int i, len;
7432
  tree inner_args;
mrs's avatar
mrs committed
7433

7434 7435 7436
  if (tmpl == error_mark_node)
    return error_mark_node;

7437 7438
  my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 283);

7439 7440 7441 7442
  /* If this function is a clone, handle it specially.  */
  if (DECL_CLONED_FUNCTION_P (tmpl))
    return instantiate_clone (tmpl, targ_ptr);

7443 7444 7445 7446 7447
  /* Check to see if we already have this specialization.  */
  spec = retrieve_specialization (tmpl, targ_ptr);
  if (spec != NULL_TREE)
    return spec;

7448
  if (DECL_TEMPLATE_INFO (tmpl) && !DECL_TEMPLATE_SPECIALIZATION (tmpl))
7449
    {
7450 7451 7452 7453 7454 7455 7456 7457 7458
      /* The TMPL is a partial instantiation.  To get a full set of
	 arguments we must add the arguments used to perform the
	 partial instantiation.  */
      targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
					      targ_ptr);
      gen_tmpl = most_general_template (tmpl);

      /* Check to see if we already have this specialization.  */
      spec = retrieve_specialization (gen_tmpl, targ_ptr);
7459 7460
      if (spec != NULL_TREE)
	return spec;
7461
    }
7462 7463
  else
    gen_tmpl = tmpl;
7464

7465 7466
  len = DECL_NTPARMS (gen_tmpl);
  inner_args = innermost_args (targ_ptr);
mrs's avatar
mrs committed
7467 7468
  i = len;
  while (i--)
mrs's avatar
mrs committed
7469
    {
7470
      tree t = TREE_VEC_ELT (inner_args, i);
7471
      if (TYPE_P (t))
mrs's avatar
mrs committed
7472 7473
	{
	  tree nt = target_type (t);
mrs's avatar
mrs committed
7474
	  if (IS_AGGR_TYPE (nt) && decl_function_context (TYPE_MAIN_DECL (nt)))
mrs's avatar
mrs committed
7475
	    {
jason's avatar
jason committed
7476 7477
	      cp_error ("type `%T' composed from a local class is not a valid template-argument", t);
	      cp_error ("  trying to instantiate `%D'", gen_tmpl);
7478
	      return error_mark_node;
mrs's avatar
mrs committed
7479 7480
	    }
	}
mrs's avatar
mrs committed
7481 7482
    }

mrs's avatar
mrs committed
7483
  /* substitute template parameters */
7484 7485
  fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
		   targ_ptr, /*complain=*/1, gen_tmpl);
7486 7487 7488
  /* The DECL_TI_TEMPLATE should always be the immediate parent
     template, not the most general template.  */
  DECL_TI_TEMPLATE (fndecl) = tmpl;
mrs's avatar
mrs committed
7489

mrs's avatar
mrs committed
7490 7491 7492
  if (flag_external_templates)
    add_pending_template (fndecl);

mrs's avatar
mrs committed
7493
  return fndecl;
mrs's avatar
mrs committed
7494
}
mrs's avatar
mrs committed
7495 7496

/* Push the name of the class template into the scope of the instantiation.  */
mrs's avatar
mrs committed
7497 7498

void
mrs's avatar
mrs committed
7499 7500
overload_template_name (type)
     tree type;
mrs's avatar
mrs committed
7501
{
mrs's avatar
mrs committed
7502 7503
  tree id = DECL_NAME (CLASSTYPE_TI_TEMPLATE (type));
  tree decl;
mrs's avatar
mrs committed
7504

mrs's avatar
mrs committed
7505 7506 7507
  if (IDENTIFIER_CLASS_VALUE (id)
      && TREE_TYPE (IDENTIFIER_CLASS_VALUE (id)) == type)
    return;
mrs's avatar
mrs committed
7508

mrs's avatar
mrs committed
7509 7510 7511
  decl = build_decl (TYPE_DECL, id, type);
  SET_DECL_ARTIFICIAL (decl);
  pushdecl_class_level (decl);
mrs's avatar
mrs committed
7512 7513
}

7514 7515 7516
/* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
   arguments that are being used when calling it.  TARGS is a vector
   into which the deduced template arguments are placed.  
mrs's avatar
mrs committed
7517 7518 7519 7520 7521

   Return zero for success, 2 for an incomplete match that doesn't resolve
   all the types, and 1 for complete failure.  An error message will be
   printed only for an incomplete match.

7522 7523
   If FN is a conversion operator, RETURN_TYPE is the type desired as
   the result of the conversion operator.
mrs's avatar
mrs committed
7524

7525
   TPARMS is a vector of template parameters.
7526 7527 7528

   The EXPLICIT_TARGS are explicit template arguments provided via a
   template-id.
mrs's avatar
mrs committed
7529

7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544
   The parameter STRICT is one of:

   DEDUCE_CALL: 
     We are deducing arguments for a function call, as in
     [temp.deduct.call].

   DEDUCE_CONV:
     We are deducing arguments for a conversion function, as in 
     [temp.deduct.conv].

   DEDUCE_EXACT:
     We are deducing arguments when calculating the partial
     ordering between specializations of function or class
     templates, as in [temp.func.order] and [temp.class.order],
     when doing an explicit instantiation as in [temp.explicit],
7545
     when determining an explicit specialization as in
7546
     [temp.expl.spec], or when taking the address of a function
7547 7548 7549
     template, as in [temp.deduct.funcaddr]. 

   The other arguments are as for type_unification.  */
mrs's avatar
mrs committed
7550 7551

int
7552
fn_type_unification (fn, explicit_targs, targs, args, return_type,
7553
		     strict)
7554
     tree fn, explicit_targs, targs, args, return_type;
7555
     unification_kind_t strict;
7556
{
7557 7558
  tree parms;
  tree fntype;
7559
  int result;
7560

7561 7562 7563 7564
  my_friendly_assert (TREE_CODE (fn) == TEMPLATE_DECL, 0);
  
  fntype = TREE_TYPE (fn);
  if (explicit_targs)
7565
    {
7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584
      /* [temp.deduct]
	  
	 The specified template arguments must match the template
	 parameters in kind (i.e., type, nontype, template), and there
	 must not be more arguments than there are parameters;
	 otherwise type deduction fails.

	 Nontype arguments must match the types of the corresponding
	 nontype template parameters, or must be convertible to the
	 types of the corresponding nontype parameters as specified in
	 _temp.arg.nontype_, otherwise type deduction fails.

	 All references in the function type of the function template
	 to the corresponding template parameters are replaced by the
	 specified template argument values.  If a substitution in a
	 template parameter or in the function type of the function
	 template results in an invalid type, type deduction fails.  */
      int i;
      tree converted_args;
7585

7586 7587 7588 7589 7590
      converted_args
	= (coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn), 
				  explicit_targs, NULL_TREE, /*complain=*/0, 
				  /*require_all_arguments=*/0));
      if (converted_args == error_mark_node)
7591
	return 1;
7592

7593 7594 7595
      fntype = tsubst (fntype, converted_args, /*complain=*/0, NULL_TREE);
      if (fntype == error_mark_node)
	return 1;
7596

7597 7598 7599
      /* Place the explicitly specified arguments in TARGS.  */
      for (i = 0; i < TREE_VEC_LENGTH (targs); i++)
	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
7600
    }
7601 7602
     
  parms = TYPE_ARG_TYPES (fntype);
7603

7604 7605
  if (DECL_CONV_FN_P (fn))
    {
7606
      /* This is a template conversion operator.  Remove `this', since
7607
         we could be comparing conversions from different classes.  */
7608 7609 7610 7611 7612 7613 7614 7615 7616 7617
      parms = TREE_CHAIN (parms);
      args = TREE_CHAIN (args);
      my_friendly_assert (return_type != NULL_TREE, 20000227);
    }
  
  if (return_type)
    {
      /* We've been given a return type to match, prepend it.  */
      parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
      args = tree_cons (NULL_TREE, return_type, args);
7618 7619 7620 7621 7622 7623
    }

  /* We allow incomplete unification without an error message here
     because the standard doesn't seem to explicitly prohibit it.  Our
     callers must be ready to deal with unification failures in any
     event.  */
7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642
  result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn), 
				  targs, parms, args, /*subr=*/0,
				  strict, /*allow_incomplete*/1);

  if (result == 0) 
    /* All is well so far.  Now, check:
       
       [temp.deduct] 
       
       When all template arguments have been deduced, all uses of
       template parameters in nondeduced contexts are replaced with
       the corresponding deduced argument values.  If the
       substitution results in an invalid type, as described above,
       type deduction fails.  */
    if (tsubst (TREE_TYPE (fn), targs, /*complain=*/0, NULL_TREE)
	== error_mark_node)
      return 1;

  return result;
7643 7644 7645 7646
}

/* Adjust types before performing type deduction, as described in
   [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
mmitchel's avatar
mmitchel committed
7647 7648 7649 7650
   sections are symmetric.  PARM is the type of a function parameter
   or the return type of the conversion function.  ARG is the type of
   the argument passed to the call, or the type of the value
   intialized with the result of the conversion function.  */
7651

7652
static void
7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664
maybe_adjust_types_for_deduction (strict, parm, arg)
     unification_kind_t strict;
     tree* parm;
     tree* arg;
{
  switch (strict)
    {
    case DEDUCE_CALL:
      break;

    case DEDUCE_CONV:
      {
mmitchel's avatar
mmitchel committed
7665 7666 7667
	/* Swap PARM and ARG throughout the remainder of this
	   function; the handling is precisely symmetric since PARM
	   will initialize ARG rather than vice versa.  */
7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701
	tree* temp = parm;
	parm = arg;
	arg = temp;
	break;
      }

    case DEDUCE_EXACT:
      /* There is nothing to do in this case.  */
      return;

    default:
      my_friendly_abort (0);
    }

  if (TREE_CODE (*parm) != REFERENCE_TYPE)
    {
      /* [temp.deduct.call]
	 
	 If P is not a reference type:
	 
	 --If A is an array type, the pointer type produced by the
	 array-to-pointer standard conversion (_conv.array_) is
	 used in place of A for type deduction; otherwise,
	 
	 --If A is a function type, the pointer type produced by
	 the function-to-pointer standard conversion
	 (_conv.func_) is used in place of A for type deduction;
	 otherwise,
	 
	 --If A is a cv-qualified type, the top level
	 cv-qualifiers of A's type are ignored for type
	 deduction.  */
      if (TREE_CODE (*arg) == ARRAY_TYPE)
	*arg = build_pointer_type (TREE_TYPE (*arg));
7702
      else if (TREE_CODE (*arg) == FUNCTION_TYPE)
7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716
	*arg = build_pointer_type (*arg);
      else
	*arg = TYPE_MAIN_VARIANT (*arg);
    }
  
  /* [temp.deduct.call]
     
     If P is a cv-qualified type, the top level cv-qualifiers
     of P's type are ignored for type deduction.  If P is a
     reference type, the type referred to by P is used for
     type deduction.  */
  *parm = TYPE_MAIN_VARIANT (*parm);
  if (TREE_CODE (*parm) == REFERENCE_TYPE)
    *parm = TREE_TYPE (*parm);
7717 7718
}

7719
/* Like type_unfication.
7720 7721 7722 7723

   If SUBR is 1, we're being called recursively (to unify the
   arguments of a function or method parameter of a function
   template).  */
7724

7725
static int
7726
type_unification_real (tparms, targs, parms, args, subr,
7727
		       strict, allow_incomplete)
7728
     tree tparms, targs, parms, args;
7729 7730 7731
     int subr;
     unification_kind_t strict;
     int allow_incomplete;
mrs's avatar
mrs committed
7732 7733 7734 7735
{
  tree parm, arg;
  int i;
  int ntparms = TREE_VEC_LENGTH (tparms);
7736
  int sub_strict;
mrs's avatar
mrs committed
7737 7738

  my_friendly_assert (TREE_CODE (tparms) == TREE_VEC, 289);
7739 7740
  my_friendly_assert (parms == NULL_TREE 
		      || TREE_CODE (parms) == TREE_LIST, 290);
mrs's avatar
mrs committed
7741
  /* ARGS could be NULL (via a call from parse.y to
mrs's avatar
mrs committed
7742 7743 7744 7745 7746
     build_x_function_call).  */
  if (args)
    my_friendly_assert (TREE_CODE (args) == TREE_LIST, 291);
  my_friendly_assert (ntparms > 0, 292);

7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764
  switch (strict)
    {
    case DEDUCE_CALL:
      sub_strict = UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_DERIVED;
      break;
      
    case DEDUCE_CONV:
      sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
      break;

    case DEDUCE_EXACT:
      sub_strict = UNIFY_ALLOW_NONE;
      break;
      
    default:
      my_friendly_abort (0);
    }

mrs's avatar
mrs committed
7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777
  while (parms
	 && parms != void_list_node
	 && args
	 && args != void_list_node)
    {
      parm = TREE_VALUE (parms);
      parms = TREE_CHAIN (parms);
      arg = TREE_VALUE (args);
      args = TREE_CHAIN (args);

      if (arg == error_mark_node)
	return 1;
      if (arg == unknown_type_node)
7778 7779 7780
	/* We can't deduce anything from this, but we might get all the
	   template args from other function args.  */
	continue;
mrs's avatar
mrs committed
7781

7782 7783 7784 7785 7786
      /* Conversions will be performed on a function argument that
	 corresponds with a function parameter that contains only
	 non-deducible template parameters and explicitly specified
	 template parameters.  */
      if (! uses_template_parms (parm))
mrs's avatar
mrs committed
7787
	{
7788 7789
	  tree type;

7790
	  if (!TYPE_P (arg))
7791 7792 7793 7794 7795 7796 7797
	    type = TREE_TYPE (arg);
	  else
	    {
	      type = arg;
	      arg = NULL_TREE;
	    }

7798
	  if (strict == DEDUCE_EXACT)
7799
	    {
7800
	      if (same_type_p (parm, type))
7801 7802 7803
		continue;
	    }
	  else
7804 7805 7806 7807
	    /* It might work; we shouldn't check now, because we might
	       get into infinite recursion.  Overload resolution will
	       handle it.  */
	    continue;
7808

mrs's avatar
mrs committed
7809 7810 7811
	  return 1;
	}
	
7812
      if (!TYPE_P (arg))
mrs's avatar
mrs committed
7813 7814
	{
	  my_friendly_assert (TREE_TYPE (arg) != NULL_TREE, 293);
7815
	  if (type_unknown_p (arg))
mrs's avatar
mrs committed
7816
	    {
7817 7818 7819 7820 7821 7822 7823
	      /* [temp.deduct.type] A template-argument can be deduced from
		 a pointer to function or pointer to member function
		 argument if the set of overloaded functions does not
		 contain function templates and at most one of a set of
		 overloaded functions provides a unique match.  */

	      if (resolve_overloaded_unification
7824
		  (tparms, targs, parm, arg, strict, sub_strict)
7825 7826 7827
		  != 0)
		return 1;
	      continue;
mrs's avatar
mrs committed
7828
	    }
mrs's avatar
mrs committed
7829 7830
	  arg = TREE_TYPE (arg);
	}
7831

7832 7833
      if (!subr)
	maybe_adjust_types_for_deduction (strict, &parm, &arg);
mrs's avatar
mrs committed
7834

7835
      switch (unify (tparms, targs, parm, arg, sub_strict))
mrs's avatar
mrs committed
7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853
	{
	case 0:
	  break;
	case 1:
	  return 1;
	}
    }
  /* Fail if we've reached the end of the parm list, and more args
     are present, and the parm list isn't variadic.  */
  if (args && args != void_list_node && parms == void_list_node)
    return 1;
  /* Fail if parms are left and they don't have default values.	 */
  if (parms
      && parms != void_list_node
      && TREE_PURPOSE (parms) == NULL_TREE)
    return 1;
  if (!subr)
    for (i = 0; i < ntparms; i++)
7854
      if (TREE_VEC_ELT (targs, i) == NULL_TREE)
mrs's avatar
mrs committed
7855
	{
7856
	  if (!allow_incomplete)
jason's avatar
jason committed
7857
	    error ("incomplete type unification");
mrs's avatar
mrs committed
7858 7859 7860 7861 7862
	  return 2;
	}
  return 0;
}

7863 7864 7865 7866 7867 7868 7869
/* Subroutine of type_unification_real.  Args are like the variables at the
   call site.  ARG is an overloaded function (or template-id); we try
   deducing template args from each of the overloads, and if only one
   succeeds, we go with that.  Modifies TARGS and returns 0 on success.  */

static int
resolve_overloaded_unification (tparms, targs, parm, arg, strict,
7870
				sub_strict)
7871 7872 7873 7874 7875 7876 7877 7878 7879
     tree tparms, targs, parm, arg;
     unification_kind_t strict;
     int sub_strict;
{
  tree tempargs = copy_node (targs);
  int good = 0;

  if (TREE_CODE (arg) == ADDR_EXPR)
    arg = TREE_OPERAND (arg, 0);
7880

7881 7882 7883 7884 7885
  if (TREE_CODE (arg) == COMPONENT_REF)
    /* Handle `&x' where `x' is some static or non-static member
       function name.  */
    arg = TREE_OPERAND (arg, 1);

7886 7887 7888
  if (TREE_CODE (arg) == OFFSET_REF)
    arg = TREE_OPERAND (arg, 1);

7889 7890 7891 7892
  /* Strip baselink information.  */
  while (TREE_CODE (arg) == TREE_LIST)
    arg = TREE_VALUE (arg);

7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909
  if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
    {
      /* If we got some explicit template args, we need to plug them into
	 the affected templates before we try to unify, in case the
	 explicit args will completely resolve the templates in question.  */

      tree expl_subargs = TREE_OPERAND (arg, 1);
      arg = TREE_OPERAND (arg, 0);

      for (; arg; arg = OVL_NEXT (arg))
	{
	  tree fn = OVL_CURRENT (arg);
	  tree subargs, elem;

	  if (TREE_CODE (fn) != TEMPLATE_DECL)
	    continue;

7910 7911
	  subargs = get_bindings_overload (fn, DECL_TEMPLATE_RESULT (fn),
					   expl_subargs);
7912 7913
	  if (subargs)
	    {
7914 7915
	      elem = tsubst (TREE_TYPE (fn), subargs, /*complain=*/0,
			     NULL_TREE);
7916 7917
	      if (TREE_CODE (elem) == METHOD_TYPE)
		elem = build_ptrmemfunc_type (build_pointer_type (elem));
7918
	      good += try_one_overload (tparms, targs, tempargs, parm, elem,
7919
					strict, sub_strict);
7920 7921 7922 7923 7924 7925
	    }
	}
    }
  else if (TREE_CODE (arg) == OVERLOAD)
    {
      for (; arg; arg = OVL_NEXT (arg))
7926 7927 7928 7929 7930 7931
	{
	  tree type = TREE_TYPE (OVL_CURRENT (arg));
	  if (TREE_CODE (type) == METHOD_TYPE)
	    type = build_ptrmemfunc_type (build_pointer_type (type));
	  good += try_one_overload (tparms, targs, tempargs, parm,
				    type,
7932
				    strict, sub_strict);
7933
	}
7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964
    }
  else
    my_friendly_abort (981006);

  /* [temp.deduct.type] A template-argument can be deduced from a pointer
     to function or pointer to member function argument if the set of
     overloaded functions does not contain function templates and at most
     one of a set of overloaded functions provides a unique match.

     So if we found multiple possibilities, we return success but don't
     deduce anything.  */

  if (good == 1)
    {
      int i = TREE_VEC_LENGTH (targs);
      for (; i--; )
	if (TREE_VEC_ELT (tempargs, i))
	  TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
    }
  if (good)
    return 0;

  return 1;
}

/* Subroutine of resolve_overloaded_unification; does deduction for a single
   overload.  Fills TARGS with any deduced arguments, or error_mark_node if
   different overloads deduce different arguments for a given parm.
   Returns 1 on success.  */

static int
7965
try_one_overload (tparms, orig_targs, targs, parm, arg, strict,
7966
		  sub_strict)
7967
     tree tparms, orig_targs, targs, parm, arg;
7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991
     unification_kind_t strict;
     int sub_strict;
{
  int nargs;
  tree tempargs;
  int i;

  /* [temp.deduct.type] A template-argument can be deduced from a pointer
     to function or pointer to member function argument if the set of
     overloaded functions does not contain function templates and at most
     one of a set of overloaded functions provides a unique match.

     So if this is a template, just return success.  */

  if (uses_template_parms (arg))
    return 1;

  maybe_adjust_types_for_deduction (strict, &parm, &arg);

  /* We don't copy orig_targs for this because if we have already deduced
     some template args from previous args, unify would complain when we
     try to deduce a template parameter for the same argument, even though
     there isn't really a conflict.  */
  nargs = TREE_VEC_LENGTH (targs);
7992
  tempargs = make_tree_vec (nargs);
7993

7994
  if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
7995 7996 7997
    return 0;

  /* First make sure we didn't deduce anything that conflicts with
7998
     explicitly specified args.  */
7999 8000 8001
  for (i = nargs; i--; )
    {
      tree elt = TREE_VEC_ELT (tempargs, i);
8002
      tree oldelt = TREE_VEC_ELT (orig_targs, i);
8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028

      if (elt == NULL_TREE)
	continue;
      else if (uses_template_parms (elt))
	{
	  /* Since we're unifying against ourselves, we will fill in template
	     args used in the function parm list with our own template parms.
	     Discard them.  */
	  TREE_VEC_ELT (tempargs, i) = NULL_TREE;
	  continue;
	}
      else if (oldelt && ! template_args_equal (oldelt, elt))
	return 0;
    }

  for (i = nargs; i--; )
    {
      tree elt = TREE_VEC_ELT (tempargs, i);

      if (elt)
	TREE_VEC_ELT (targs, i) = elt;
    }

  return 1;
}

8029 8030 8031 8032
/* PARM is a template class (perhaps with unbound template
   parameters).  ARG is a fully instantiated type.  If ARG can be
   bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
   TARGS are as for unify.  */
8033 8034

static tree
8035
try_class_unification (tparms, targs, parm, arg)
8036 8037
     tree tparms;
     tree targs;
8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077
     tree parm;
     tree arg;
{
  int i;
  tree copy_of_targs;

  if (!CLASSTYPE_TEMPLATE_INFO (arg)
      || CLASSTYPE_TI_TEMPLATE (arg) != CLASSTYPE_TI_TEMPLATE (parm))
    return NULL_TREE;

  /* We need to make a new template argument vector for the call to
     unify.  If we used TARGS, we'd clutter it up with the result of
     the attempted unification, even if this class didn't work out.
     We also don't want to commit ourselves to all the unifications
     we've already done, since unification is supposed to be done on
     an argument-by-argument basis.  In other words, consider the
     following pathological case:

       template <int I, int J, int K>
       struct S {};
       
       template <int I, int J>
       struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
       
       template <int I, int J, int K>
       void f(S<I, J, K>, S<I, I, I>);
       
       void g() {
         S<0, 0, 0> s0;
         S<0, 1, 2> s2;
       
         f(s0, s2);
       }

     Now, by the time we consider the unification involving `s2', we
     already know that we must have `f<0, 0, 0>'.  But, even though
     `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is not legal
     because there are two ways to unify base classes of S<0, 1, 2>
     with S<I, I, I>.  If we kept the already deduced knowledge, we
     would reject the possibility I=1.  */
8078
  copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098
  i = unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE);
  
  /* If unification failed, we're done.  */
  if (i != 0)
    return NULL_TREE;
  else
    return arg;
}

/* Subroutine of get_template_base.  RVAL, if non-NULL, is a base we
   have alreay discovered to be satisfactory.  ARG_BINFO is the binfo
   for the base class of ARG that we are currently examining.  */

static tree
get_template_base_recursive (tparms, targs, parm,
			     arg_binfo, rval, flags)
     tree tparms;
     tree targs;
     tree arg_binfo;
8099
     tree rval;
8100 8101
     tree parm;
     int flags;
8102 8103 8104
{
  tree binfos;
  int i, n_baselinks;
8105
  tree arg = BINFO_TYPE (arg_binfo);
8106

8107
  if (!(flags & GTB_IGNORE_TYPE))
8108
    {
8109 8110
      tree r = try_class_unification (tparms, targs,
				      parm, arg);
8111

8112
      /* If there is more than one satisfactory baseclass, then:
8113

8114 8115 8116 8117 8118 8119 8120 8121 8122 8123
	   [temp.deduct.call]

	   If they yield more than one possible deduced A, the type
	   deduction fails.

	   applies.  */
      if (r && rval && !same_type_p (r, rval))
	return error_mark_node;
      else if (r)
	rval = r;
8124 8125
    }

8126
  binfos = BINFO_BASETYPES (arg_binfo);
8127 8128 8129 8130 8131 8132
  n_baselinks = binfos ? TREE_VEC_LENGTH (binfos) : 0;

  /* Process base types.  */
  for (i = 0; i < n_baselinks; i++)
    {
      tree base_binfo = TREE_VEC_ELT (binfos, i);
8133
      int this_virtual;
8134

8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156
      /* Skip this base, if we've already seen it.  */
      if (BINFO_MARKED (base_binfo))
	continue;

      this_virtual = 
	(flags & GTB_VIA_VIRTUAL) || TREE_VIA_VIRTUAL (base_binfo);
      
      /* When searching for a non-virtual, we cannot mark virtually
	 found binfos.  */
      if (! this_virtual)
	SET_BINFO_MARKED (base_binfo);
      
      rval = get_template_base_recursive (tparms, targs,
					  parm,
					  base_binfo, 
					  rval,
					  GTB_VIA_VIRTUAL * this_virtual);
      
      /* If we discovered more than one matching base class, we can
	 stop now.  */
      if (rval == error_mark_node)
	return error_mark_node;
8157 8158 8159 8160 8161
    }

  return rval;
}

8162 8163 8164 8165 8166 8167
/* Given a template type PARM and a class type ARG, find the unique
   base type in ARG that is an instance of PARM.  We do not examine
   ARG itself; only its base-classes.  If there is no appropriate base
   class, return NULL_TREE.  If there is more than one, return
   error_mark_node.  PARM may be the type of a partial specialization,
   as well as a plain template type.  Used by unify.  */
8168 8169

static tree
8170
get_template_base (tparms, targs, parm, arg)
8171 8172
     tree tparms;
     tree targs;
8173 8174
     tree parm;
     tree arg;
8175
{
8176 8177
  tree rval;
  tree arg_binfo;
8178

8179 8180 8181 8182 8183 8184 8185
  my_friendly_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)), 92);
  
  arg_binfo = TYPE_BINFO (complete_type (arg));
  rval = get_template_base_recursive (tparms, targs,
				      parm, arg_binfo, 
				      NULL_TREE,
				      GTB_IGNORE_TYPE);
8186

8187 8188
  /* Since get_template_base_recursive marks the bases classes, we
     must unmark them here.  */
8189
  dfs_walk (arg_binfo, dfs_unmark, markedp, 0);
8190 8191 8192 8193

  return rval;
}

8194 8195
/* Returns the level of DECL, which declares a template parameter.  */

8196
static int
8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210
template_decl_level (decl)
     tree decl;
{
  switch (TREE_CODE (decl))
    {
    case TYPE_DECL:
    case TEMPLATE_DECL:
      return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));

    case PARM_DECL:
      return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));

    default:
      my_friendly_abort (0);
8211
      return 0;
8212 8213 8214
    }
}

8215 8216 8217
/* Decide whether ARG can be unified with PARM, considering only the
   cv-qualifiers of each type, given STRICT as documented for unify.
   Returns non-zero iff the unification is OK on that basis.*/
mrs's avatar
mrs committed
8218

8219
static int
8220 8221 8222 8223 8224
check_cv_quals_for_unify (strict, arg, parm)
     int strict;
     tree arg;
     tree parm;
{
8225 8226 8227 8228 8229 8230 8231 8232 8233
  if (!(strict & UNIFY_ALLOW_MORE_CV_QUAL)
      && !at_least_as_qualified_p (arg, parm))
    return 0;

  if (!(strict & UNIFY_ALLOW_LESS_CV_QUAL)
      && !at_least_as_qualified_p (parm, arg))
    return 0;

  return 1;
8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248
}

/* Takes parameters as for type_unification.  Returns 0 if the
   type deduction suceeds, 1 otherwise.  The parameter STRICT is a
   bitwise or of the following flags:

     UNIFY_ALLOW_NONE:
       Require an exact match between PARM and ARG.
     UNIFY_ALLOW_MORE_CV_QUAL:
       Allow the deduced ARG to be more cv-qualified than ARG.
     UNIFY_ALLOW_LESS_CV_QUAL:
       Allow the deduced ARG to be less cv-qualified than ARG.
     UNIFY_ALLOW_DERIVED:
       Allow the deduced ARG to be a template base class of ARG,
       or a pointer to a template base class of the type pointed to by
8249 8250 8251 8252
       ARG.
     UNIFY_ALLOW_INTEGER:
       Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
       case for more information.  */
8253

8254
static int
8255
unify (tparms, targs, parm, arg, strict)
8256
     tree tparms, targs, parm, arg;
8257
     int strict;
mrs's avatar
mrs committed
8258 8259
{
  int idx;
8260
  tree targ;
8261
  tree tparm;
mrs's avatar
mrs committed
8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272

  /* I don't think this will do the right thing with respect to types.
     But the only case I've seen it in so far has been array bounds, where
     signedness is the only information lost, and I think that will be
     okay.  */
  while (TREE_CODE (parm) == NOP_EXPR)
    parm = TREE_OPERAND (parm, 0);

  if (arg == error_mark_node)
    return 1;
  if (arg == unknown_type_node)
8273 8274 8275 8276
    /* We can't deduce anything from this, but we might get all the
       template args from other function args.  */
    return 0;

8277
  /* If PARM uses template parameters, then we can't bail out here,
8278
     even if ARG == PARM, since we won't record unifications for the
8279 8280 8281
     template parameters.  We might need them if we're trying to
     figure out which of two things is more specialized.  */
  if (arg == parm && !uses_template_parms (parm))
mrs's avatar
mrs committed
8282 8283
    return 0;

8284 8285 8286
  /* Immediately reject some pairs that won't unify because of
     cv-qualification mismatches.  */
  if (TREE_CODE (arg) == TREE_CODE (parm)
8287
      && TYPE_P (arg)
8288 8289 8290 8291 8292 8293
      /* We check the cv-qualifiers when unifying with template type
	 parameters below.  We want to allow ARG `const T' to unify with
	 PARM `T' for example, when computing which of two templates
	 is more specialized, for example.  */
      && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
      && !check_cv_quals_for_unify (strict, arg, parm))
8294 8295
    return 1;

mrs's avatar
mrs committed
8296 8297
  switch (TREE_CODE (parm))
    {
8298 8299 8300 8301 8302 8303
    case TYPENAME_TYPE:
      /* In a type which contains a nested-name-specifier, template
	 argument values cannot be deduced for template parameters used
	 within the nested-name-specifier.  */
      return 0;

mrs's avatar
mrs committed
8304
    case TEMPLATE_TYPE_PARM:
8305
    case TEMPLATE_TEMPLATE_PARM:
8306 8307 8308 8309 8310 8311 8312
      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));

      if (TEMPLATE_TYPE_LEVEL (parm)
	  != template_decl_level (tparm))
	/* The PARM is not one we're trying to unify.  Just check
	   to see if it matches ARG.  */
	return (TREE_CODE (arg) == TREE_CODE (parm)
8313
		&& same_type_p (parm, arg)) ? 0 : 1;
8314
      idx = TEMPLATE_TYPE_IDX (parm);
8315
      targ = TREE_VEC_ELT (targs, idx);
8316
      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
8317

8318
      /* Check for mixed types and values.  */
8319 8320 8321 8322
      if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
	   && TREE_CODE (tparm) != TYPE_DECL)
	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM 
	      && TREE_CODE (tparm) != TEMPLATE_DECL))
8323 8324
	return 1;

8325
      if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
8326
	{
8327
	  if (TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (parm))
8328 8329 8330
	    {
	      /* We arrive here when PARM does not involve template 
		 specialization.  */
8331

8332 8333 8334
	      /* ARG must be constructed from a template class.  */
	      if (TREE_CODE (arg) != RECORD_TYPE || !CLASSTYPE_TEMPLATE_INFO (arg))
		return 1;
8335

8336
	      {
8337 8338
		tree parmtmpl = TYPE_TI_TEMPLATE (parm);
		tree parmvec = TYPE_TI_ARGS (parm);
8339 8340 8341 8342 8343 8344 8345 8346 8347
		tree argvec = CLASSTYPE_TI_ARGS (arg);
		tree argtmplvec
		  = DECL_INNERMOST_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (arg));
		int i;

		/* The parameter and argument roles have to be switched here 
		   in order to handle default arguments properly.  For example, 
		   template<template <class> class TT> void f(TT<int>) 
		   should be able to accept vector<int> which comes from 
8348
		   template <class T, class Allocator = allocator> 
8349 8350
		   class vector.  */

8351
		if (coerce_template_parms (argtmplvec, parmvec, parmtmpl, 0, 1)
8352 8353
		    == error_mark_node)
		  return 1;
8354
	  
8355 8356 8357 8358 8359
		/* Deduce arguments T, i from TT<T> or TT<i>.  
		   We check each element of PARMVEC and ARGVEC individually
		   rather than the whole TREE_VEC since they can have
		   different number of elements.  */

8360 8361 8362
		for (i = 0; i < TREE_VEC_LENGTH (parmvec); ++i)
		  {
		    tree t = TREE_VEC_ELT (parmvec, i);
8363

8364 8365
		    if (unify (tparms, targs, t, 
			       TREE_VEC_ELT (argvec, i), 
8366
			       UNIFY_ALLOW_NONE))
8367 8368
		      return 1;
		  }
8369
	      }
8370 8371 8372 8373 8374
	      arg = CLASSTYPE_TI_TEMPLATE (arg);
	    }
	}
      else
	{
8375 8376 8377 8378 8379 8380
	  /* If PARM is `const T' and ARG is only `int', we don't have
	     a match unless we are allowing additional qualification.
	     If ARG is `const int' and PARM is just `T' that's OK;
	     that binds `const int' to `T'.  */
	  if (!check_cv_quals_for_unify (strict | UNIFY_ALLOW_LESS_CV_QUAL, 
					 arg, parm))
8381 8382
	    return 1;

8383 8384 8385
	  /* Consider the case where ARG is `const volatile int' and
	     PARM is `const T'.  Then, T should be `volatile int'.  */
	  arg = 
8386 8387 8388 8389 8390 8391
	    cp_build_qualified_type_real (arg,
					  CP_TYPE_QUALS (arg) 
					  & ~CP_TYPE_QUALS (parm),
					  /*complain=*/0);
	  if (arg == error_mark_node)
	    return 1;
8392 8393 8394
	}

      /* Simple cases: Value already set, does match or doesn't.  */
8395
      if (targ != NULL_TREE && same_type_p (targ, arg))
8396
	return 0;
8397
      else if (targ)
8398
	return 1;
8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412

      /* Make sure that ARG is not a variable-sized array.  (Note that
	 were talking about variable-sized arrays (like `int[n]'),
	 rather than arrays of unknown size (like `int[]').)  We'll
	 get very confused by such a type since the bound of the array
	 will not be computable in an instantiation.  Besides, such
	 types are not allowed in ISO C++, so we can do as we please
	 here.  */
      if (TREE_CODE (arg) == ARRAY_TYPE 
	  && !uses_template_parms (arg)
	  && (TREE_CODE (TYPE_MAX_VALUE (TYPE_DOMAIN (arg)))
	      != INTEGER_CST))
	return 1;

8413
      TREE_VEC_ELT (targs, idx) = arg;
8414 8415
      return 0;

jason's avatar
jason committed
8416
    case TEMPLATE_PARM_INDEX:
8417 8418 8419 8420 8421 8422 8423
      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));

      if (TEMPLATE_PARM_LEVEL (parm) 
	  != template_decl_level (tparm))
	/* The PARM is not one we're trying to unify.  Just check
	   to see if it matches ARG.  */
	return (TREE_CODE (arg) == TREE_CODE (parm)
8424
		&& cp_tree_equal (parm, arg) > 0) ? 0 : 1;
8425

jason's avatar
jason committed
8426
      idx = TEMPLATE_PARM_IDX (parm);
8427
      targ = TREE_VEC_ELT (targs, idx);
8428

8429
      if (targ)
mrs's avatar
mrs committed
8430
	{
8431
	  int i = (cp_tree_equal (targ, arg) > 0);
mrs's avatar
mrs committed
8432 8433 8434 8435 8436 8437
	  if (i == 1)
	    return 0;
	  else if (i == 0)
	    return 1;
	  else
	    my_friendly_abort (42);
mrs's avatar
mrs committed
8438 8439
	}

8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455
      /* [temp.deduct.type] If, in the declaration of a function template
	 with a non-type template-parameter, the non-type
	 template-parameter is used in an expression in the function
	 parameter-list and, if the corresponding template-argument is
	 deduced, the template-argument type shall match the type of the
	 template-parameter exactly, except that a template-argument
	 deduced from an array bound may be of any integral type.  */
      if (same_type_p (TREE_TYPE (arg), TREE_TYPE (parm)))
	/* OK */;
      else if ((strict & UNIFY_ALLOW_INTEGER)
	       && (TREE_CODE (TREE_TYPE (parm)) == INTEGER_TYPE
		   || TREE_CODE (TREE_TYPE (parm)) == BOOLEAN_TYPE))
	/* OK */;
      else
	return 1;

8456
      TREE_VEC_ELT (targs, idx) = arg;
mrs's avatar
mrs committed
8457 8458 8459
      return 0;

    case POINTER_TYPE:
8460 8461
      {
	int sub_strict;
mrs's avatar
mrs committed
8462

8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481
	if (TREE_CODE (arg) != POINTER_TYPE)
	  return 1;
	
	/* [temp.deduct.call]

	   A can be another pointer or pointer to member type that can
	   be converted to the deduced A via a qualification
	   conversion (_conv.qual_).

	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
	   This will allow for additional cv-qualification of the
	   pointed-to types if appropriate.  In general, this is a bit
	   too generous; we are only supposed to allow qualification
	   conversions and this method will allow an ARG of char** and
	   a deduced ARG of const char**.  However, overload
	   resolution will subsequently invalidate the candidate, so
	   this is probably OK.  */
	sub_strict = strict;
	
8482
	if (TREE_CODE (TREE_TYPE (arg)) != RECORD_TYPE)
8483 8484 8485 8486
	  /* The derived-to-base conversion only persists through one
	     level of pointers.  */
	  sub_strict &= ~UNIFY_ALLOW_DERIVED;

8487 8488
	return unify (tparms, targs, TREE_TYPE (parm), 
		      TREE_TYPE (arg), sub_strict);
8489
      }
mrs's avatar
mrs committed
8490 8491

    case REFERENCE_TYPE:
8492 8493 8494
      if (TREE_CODE (arg) != REFERENCE_TYPE)
	return 1;
      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
8495
		    UNIFY_ALLOW_NONE);
mrs's avatar
mrs committed
8496 8497 8498 8499

    case ARRAY_TYPE:
      if (TREE_CODE (arg) != ARRAY_TYPE)
	return 1;
8500 8501 8502 8503
      if ((TYPE_DOMAIN (parm) == NULL_TREE)
	  != (TYPE_DOMAIN (arg) == NULL_TREE))
	return 1;
      if (TYPE_DOMAIN (parm) != NULL_TREE
8504
	  && unify (tparms, targs, TYPE_DOMAIN (parm),
8505
		    TYPE_DOMAIN (arg), UNIFY_ALLOW_NONE) != 0)
mrs's avatar
mrs committed
8506
	return 1;
8507
      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
8508
		    UNIFY_ALLOW_NONE);
mrs's avatar
mrs committed
8509 8510

    case REAL_TYPE:
mrs's avatar
mrs committed
8511
    case COMPLEX_TYPE:
mrs's avatar
mrs committed
8512
    case INTEGER_TYPE:
brendan's avatar
brendan committed
8513
    case BOOLEAN_TYPE:
8514
    case VOID_TYPE:
mrs's avatar
mrs committed
8515 8516 8517
      if (TREE_CODE (arg) != TREE_CODE (parm))
	return 1;

8518 8519
      if (TREE_CODE (parm) == INTEGER_TYPE
	  && TREE_CODE (TYPE_MAX_VALUE (parm)) != INTEGER_CST)
mrs's avatar
mrs committed
8520 8521
	{
	  if (TYPE_MIN_VALUE (parm) && TYPE_MIN_VALUE (arg)
8522
	      && unify (tparms, targs, TYPE_MIN_VALUE (parm),
8523
			TYPE_MIN_VALUE (arg), UNIFY_ALLOW_INTEGER))
mrs's avatar
mrs committed
8524 8525
	    return 1;
	  if (TYPE_MAX_VALUE (parm) && TYPE_MAX_VALUE (arg)
8526
	      && unify (tparms, targs, TYPE_MAX_VALUE (parm),
8527
			TYPE_MAX_VALUE (arg), UNIFY_ALLOW_INTEGER))
mrs's avatar
mrs committed
8528 8529
	    return 1;
	}
8530
      /* We have already checked cv-qualification at the top of the
8531
	 function.  */
8532
      else if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
8533 8534
	return 1;

mrs's avatar
mrs committed
8535 8536 8537 8538 8539
      /* As far as unification is concerned, this wins.	 Later checks
	 will invalidate it if necessary.  */
      return 0;

      /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
mrs's avatar
mrs committed
8540
      /* Type INTEGER_CST can come from ordinary constant template args.  */
mrs's avatar
mrs committed
8541
    case INTEGER_CST:
mrs's avatar
mrs committed
8542 8543 8544
      while (TREE_CODE (arg) == NOP_EXPR)
	arg = TREE_OPERAND (arg, 0);

mrs's avatar
mrs committed
8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556
      if (TREE_CODE (arg) != INTEGER_CST)
	return 1;
      return !tree_int_cst_equal (parm, arg);

    case TREE_VEC:
      {
	int i;
	if (TREE_CODE (arg) != TREE_VEC)
	  return 1;
	if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
	  return 1;
	for (i = TREE_VEC_LENGTH (parm) - 1; i >= 0; i--)
8557
	  if (unify (tparms, targs,
mrs's avatar
mrs committed
8558
		     TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
8559
		     UNIFY_ALLOW_NONE))
mrs's avatar
mrs committed
8560 8561 8562 8563 8564
	    return 1;
	return 0;
      }

    case RECORD_TYPE:
8565 8566
    case UNION_TYPE:
      if (TREE_CODE (arg) != TREE_CODE (parm))
mrs's avatar
mrs committed
8567
	return 1;
8568
  
8569 8570 8571 8572 8573 8574 8575 8576 8577 8578 8579
      if (TYPE_PTRMEMFUNC_P (parm))
	{
	  if (!TYPE_PTRMEMFUNC_P (arg))
	    return 1;

	  return unify (tparms, targs, 
			TYPE_PTRMEMFUNC_FN_TYPE (parm),
			TYPE_PTRMEMFUNC_FN_TYPE (arg),
			strict);
	}

8580
      if (CLASSTYPE_TEMPLATE_INFO (parm))
mrs's avatar
mrs committed
8581
	{
mrs's avatar
mrs committed
8582
	  tree t = NULL_TREE;
8583

8584
	  if (strict & UNIFY_ALLOW_DERIVED)
8585 8586 8587 8588 8589 8590 8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602 8603 8604 8605 8606 8607
	    {
	      /* First, we try to unify the PARM and ARG directly.  */
	      t = try_class_unification (tparms, targs,
					 parm, arg);

	      if (!t)
		{
		  /* Fallback to the special case allowed in
		     [temp.deduct.call]:
		     
		       If P is a class, and P has the form
		       template-id, then A can be a derived class of
		       the deduced A.  Likewise, if P is a pointer to
		       a class of the form template-id, A can be a
		       pointer to a derived class pointed to by the
		       deduced A.  */
		  t = get_template_base (tparms, targs,
					 parm, arg);

		  if (! t || t == error_mark_node)
		    return 1;
		}
	    }
8608
	  else if (CLASSTYPE_TEMPLATE_INFO (arg) 
8609 8610
		   && (CLASSTYPE_TI_TEMPLATE (parm) 
		       == CLASSTYPE_TI_TEMPLATE (arg)))
8611 8612
	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
	       Then, we should unify `int' and `U'.  */
mrs's avatar
mrs committed
8613
	    t = arg;
8614 8615
	  else
	    /* There's no chance of unication succeeding.  */
mrs's avatar
mrs committed
8616
	    return 1;
mrs's avatar
mrs committed
8617

8618
	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
8619
			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
mrs's avatar
mrs committed
8620
	}
8621
      else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
mrs's avatar
mrs committed
8622
	return 1;
mrs's avatar
mrs committed
8623
      return 0;
mrs's avatar
mrs committed
8624 8625 8626

    case METHOD_TYPE:
    case FUNCTION_TYPE:
8627
      if (TREE_CODE (arg) != TREE_CODE (parm))
mrs's avatar
mrs committed
8628
	return 1;
8629 8630

      if (unify (tparms, targs, TREE_TYPE (parm),
8631
		 TREE_TYPE (arg), UNIFY_ALLOW_NONE))
mrs's avatar
mrs committed
8632
	return 1;
8633
      return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
8634
				    TYPE_ARG_TYPES (arg), 1, 
8635
				    DEDUCE_EXACT, 0);
mrs's avatar
mrs committed
8636 8637 8638 8639

    case OFFSET_TYPE:
      if (TREE_CODE (arg) != OFFSET_TYPE)
	return 1;
8640
      if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
8641
		 TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
mrs's avatar
mrs committed
8642
	return 1;
8643
      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
8644
		    strict);
mrs's avatar
mrs committed
8645

jason's avatar
merge  
jason committed
8646
    case CONST_DECL:
8647
      if (arg != decl_constant_value (parm)) 
jason's avatar
merge  
jason committed
8648 8649 8650
	return 1;
      return 0;

8651 8652 8653 8654
    case TEMPLATE_DECL:
      /* Matched cases are handled by the ARG == PARM test above.  */
      return 1;

8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668
    case MINUS_EXPR:
      if (TREE_CODE (TREE_OPERAND (parm, 1)) == INTEGER_CST)
	{
	  /* We handle this case specially, since it comes up with
	     arrays.  In particular, something like:

	     template <int N> void f(int (&x)[N]);

	     Here, we are trying to unify the range type, which
	     looks like [0 ... (N - 1)].  */
	  tree t, t1, t2;
	  t1 = TREE_OPERAND (parm, 0);
	  t2 = TREE_OPERAND (parm, 1);

8669
	  t = fold (build (PLUS_EXPR, integer_type_node, arg, t2));
8670

8671
	  return unify (tparms, targs, t1, t, strict);
8672 8673 8674
	}
      /* else fall through */

mrs's avatar
mrs committed
8675
    default:
8676
      if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (TREE_CODE (parm))))
8677 8678 8679 8680 8681
	/* We're looking at an expression.  This can happen with
	   something like: 
	   
	     template <int I>
	     void foo(S<I>, S<I + 2>);
8682

8683
	   This is a "nondeduced context":
8684

8685 8686 8687
	     [deduct.type]
	   
	     The nondeduced contexts are:
8688

8689 8690 8691
	     --A type that is a template-id in which one or more of
	       the template-arguments is an expression that references
	       a template-parameter.  
8692

8693 8694 8695
	   In these cases, we assume deduction succeeded, but don't
	   actually infer any unifications.  */
	return 0;
8696
      else
8697 8698
	sorry ("use of `%s' in template type unification",
	       tree_code_name [(int) TREE_CODE (parm)]);
8699

mrs's avatar
mrs committed
8700 8701 8702 8703
      return 1;
    }
}

8704 8705 8706 8707
/* Called if RESULT is explicitly instantiated, or is a member of an
   explicitly instantiated class, or if using -frepo and the
   instantiation of RESULT has been assigned to this file.  */

mrs's avatar
mrs committed
8708
void
mrs's avatar
mrs committed
8709
mark_decl_instantiated (result, extern_p)
mrs's avatar
mrs committed
8710 8711 8712
     tree result;
     int extern_p;
{
8713 8714 8715 8716
  if (TREE_CODE (result) != FUNCTION_DECL)
    /* The TREE_PUBLIC flag for function declarations will have been
       set correctly by tsubst.  */
    TREE_PUBLIC (result) = 1;
mrs's avatar
mrs committed
8717 8718 8719 8720 8721

  if (! extern_p)
    {
      DECL_INTERFACE_KNOWN (result) = 1;
      DECL_NOT_REALLY_EXTERN (result) = 1;
8722

8723 8724 8725
      /* Always make artificials weak.  */
      if (DECL_ARTIFICIAL (result) && flag_weak)
	comdat_linkage (result);
8726 8727
      /* For WIN32 we also want to put explicit instantiations in
	 linkonce sections.  */
8728
      else if (TREE_PUBLIC (result))
8729
	maybe_make_one_only (result);
mrs's avatar
mrs committed
8730
    }
mrs's avatar
mrs committed
8731
  else if (TREE_CODE (result) == FUNCTION_DECL)
8732
    defer_fn (result);
mrs's avatar
mrs committed
8733 8734
}

8735 8736
/* Given two function templates PAT1 and PAT2, and explicit template
   arguments EXPLICIT_ARGS return:
mrs's avatar
mrs committed
8737 8738 8739 8740 8741 8742

   1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
   -1 if PAT2 is more specialized than PAT1.
   0 if neither is more specialized.  */
   
int
8743 8744
more_specialized (pat1, pat2, explicit_args)
     tree pat1, pat2, explicit_args;
mrs's avatar
mrs committed
8745
{
8746
  tree targs;
mrs's avatar
mrs committed
8747
  int winner = 0;
mrs's avatar
mrs committed
8748

8749 8750
  targs
    = get_bindings_overload (pat1, DECL_TEMPLATE_RESULT (pat2), explicit_args);
mrs's avatar
mrs committed
8751
  if (targs)
8752
    --winner;
mrs's avatar
mrs committed
8753

8754 8755
  targs
    = get_bindings_overload (pat2, DECL_TEMPLATE_RESULT (pat1), explicit_args);
mrs's avatar
mrs committed
8756
  if (targs)
8757
    ++winner;
mrs's avatar
mrs committed
8758

mrs's avatar
mrs committed
8759 8760
  return winner;
}
mrs's avatar
mrs committed
8761

mrs's avatar
mrs committed
8762
/* Given two class template specialization list nodes PAT1 and PAT2, return:
mrs's avatar
mrs committed
8763

mrs's avatar
mrs committed
8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774
   1 if PAT1 is more specialized than PAT2 as described in [temp.class.order].
   -1 if PAT2 is more specialized than PAT1.
   0 if neither is more specialized.  */
   
int
more_specialized_class (pat1, pat2)
     tree pat1, pat2;
{
  tree targs;
  int winner = 0;

8775 8776
  targs = get_class_bindings (TREE_VALUE (pat1), TREE_PURPOSE (pat1),
			      TREE_PURPOSE (pat2));
mrs's avatar
mrs committed
8777 8778 8779
  if (targs)
    --winner;

8780 8781
  targs = get_class_bindings (TREE_VALUE (pat2), TREE_PURPOSE (pat2),
			      TREE_PURPOSE (pat1));
mrs's avatar
mrs committed
8782
  if (targs)
mrs's avatar
mrs committed
8783 8784 8785 8786
    ++winner;

  return winner;
}
mrs's avatar
mrs committed
8787 8788

/* Return the template arguments that will produce the function signature
8789
   DECL from the function template FN, with the explicit template
8790
   arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is 1, the return type must
8791 8792
   also match.  Return NULL_TREE if no satisfactory arguments could be
   found.  */
mrs's avatar
mrs committed
8793

8794 8795
static tree
get_bindings_real (fn, decl, explicit_args, check_rettype)
8796
     tree fn, decl, explicit_args;
8797
     int check_rettype;
mrs's avatar
mrs committed
8798
{
8799
  int ntparms = DECL_NTPARMS (fn);
8800
  tree targs = make_tree_vec (ntparms);
8801
  tree decl_type;
8802
  tree decl_arg_types;
8803 8804
  int i;

8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833
  /* Substitute the explicit template arguments into the type of DECL.
     The call to fn_type_unification will handle substitution into the
     FN.  */
  decl_type = TREE_TYPE (decl);
  if (explicit_args && uses_template_parms (decl_type))
    {
      tree tmpl;
      tree converted_args;

      if (DECL_TEMPLATE_INFO (decl))
	tmpl = DECL_TI_TEMPLATE (decl);
      else
	/* We can get here for some illegal specializations.  */
	return NULL_TREE;

      converted_args
	= (coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
				  explicit_args, NULL_TREE,
				  /*complain=*/0, 
				  /*require_all_arguments=*/0));
      if (converted_args == error_mark_node)
	return NULL_TREE;
      
      decl_type = tsubst (decl_type, converted_args, /*complain=*/0, 
			  NULL_TREE); 
      if (decl_type == error_mark_node)
	return NULL_TREE;
    }

8834 8835
  /* If FN is a static member function, adjust the type of DECL
     appropriately.  */
8836
  decl_arg_types = TYPE_ARG_TYPES (decl_type);
8837 8838
  if (DECL_STATIC_FUNCTION_P (fn) 
      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
8839
    decl_arg_types = TREE_CHAIN (decl_arg_types);
8840

8841
  i = fn_type_unification (fn, explicit_args, targs, 
8842
			   decl_arg_types,
8843 8844
			   (check_rettype || DECL_CONV_FN_P (fn)
	                    ? TREE_TYPE (decl_type) : NULL_TREE),
8845
			   DEDUCE_EXACT);
8846

8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857 8858 8859 8860 8861 8862 8863 8864 8865 8866 8867 8868
  if (i != 0)
    return NULL_TREE;

  return targs;
}

/* For most uses, we want to check the return type.  */

tree 
get_bindings (fn, decl, explicit_args)
     tree fn, decl, explicit_args;
{
  return get_bindings_real (fn, decl, explicit_args, 1);
}

/* But for more_specialized, we only care about the parameter types.  */

static tree
get_bindings_overload (fn, decl, explicit_args)
     tree fn, decl, explicit_args;
{
  return get_bindings_real (fn, decl, explicit_args, 0);
mrs's avatar
mrs committed
8869 8870
}

8871 8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885
/* Return the innermost template arguments that, when applied to a
   template specialization whose innermost template parameters are
   TPARMS, and whose specialization arguments are ARGS, yield the
   ARGS.  

   For example, suppose we have:

     template <class T, class U> struct S {};
     template <class T> struct S<T*, int> {};

   Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
   {T}, the PARMS will be {T*, int} and the ARGS will be {double*,
   int}.  The resulting vector will be {double}, indicating that `T'
   is bound to `double'.  */

mrs's avatar
mrs committed
8886
static tree
8887 8888
get_class_bindings (tparms, parms, args)
     tree tparms, parms, args;
mrs's avatar
mrs committed
8889
{
8890
  int i, ntparms = TREE_VEC_LENGTH (tparms);
8891
  tree vec = make_tree_vec (ntparms);
mrs's avatar
mrs committed
8892

8893
  args = innermost_args (args);
8894

8895
  if (unify (tparms, vec, parms, args, UNIFY_ALLOW_NONE))
8896
    return NULL_TREE;
mrs's avatar
mrs committed
8897 8898 8899 8900 8901 8902 8903 8904

  for (i =  0; i < ntparms; ++i)
    if (! TREE_VEC_ELT (vec, i))
      return NULL_TREE;

  return vec;
}

8905 8906 8907 8908 8909
/* In INSTANTIATIONS is a list of <INSTANTIATION, TEMPLATE> pairs.
   Pick the most specialized template, and return the corresponding
   instantiation, or if there is no corresponding instantiation, the
   template itself.  EXPLICIT_ARGS is any template arguments explicity
   mentioned in a template-id.  If there is no most specialized
jason's avatar
typo  
jason committed
8910
   template, error_mark_node is returned.  If there are no templates
8911
   at all, NULL_TREE is returned.  */
mrs's avatar
mrs committed
8912 8913

tree
8914 8915 8916
most_specialized_instantiation (instantiations, explicit_args)
     tree instantiations;
     tree explicit_args;
mrs's avatar
mrs committed
8917
{
8918
  tree fn, champ;
mrs's avatar
mrs committed
8919 8920
  int fate;

8921
  if (!instantiations)
mrs's avatar
mrs committed
8922 8923
    return NULL_TREE;

8924 8925
  champ = instantiations;
  for (fn = TREE_CHAIN (instantiations); fn; fn = TREE_CHAIN (fn))
mrs's avatar
mrs committed
8926
    {
8927 8928
      fate = more_specialized (TREE_VALUE (champ), 
			       TREE_VALUE (fn), explicit_args);
mrs's avatar
mrs committed
8929 8930 8931 8932 8933 8934 8935 8936 8937 8938
      if (fate == 1)
	;
      else
	{
	  if (fate == 0)
	    {
	      fn = TREE_CHAIN (fn);
	      if (! fn)
		return error_mark_node;
	    }
8939
	  champ = fn;
mrs's avatar
mrs committed
8940 8941 8942
	}
    }

8943
  for (fn = instantiations; fn && fn != champ; fn = TREE_CHAIN (fn))
mrs's avatar
mrs committed
8944
    {
8945 8946
      fate = more_specialized (TREE_VALUE (champ), 
			       TREE_VALUE (fn), explicit_args);
mrs's avatar
mrs committed
8947 8948 8949 8950
      if (fate != 1)
	return error_mark_node;
    }

8951 8952 8953 8954 8955 8956 8957
  return TREE_PURPOSE (champ) ? TREE_PURPOSE (champ) : TREE_VALUE (champ);
}

/* Return the most specialized of the list of templates in FNS that can
   produce an instantiation matching DECL, given the explicit template
   arguments EXPLICIT_ARGS.  */

8958
static tree
8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970
most_specialized (fns, decl, explicit_args)
     tree fns, decl, explicit_args;
{
  tree candidates = NULL_TREE;
  tree fn, args;

  for (fn = fns; fn; fn = TREE_CHAIN (fn))
    {
      tree candidate = TREE_VALUE (fn);

      args = get_bindings (candidate, decl, explicit_args);
      if (args)
8971
	candidates = tree_cons (NULL_TREE, candidate, candidates);
8972 8973 8974
    }

  return most_specialized_instantiation (candidates, explicit_args);
mrs's avatar
mrs committed
8975 8976
}

8977 8978 8979 8980 8981 8982 8983 8984 8985 8986 8987 8988 8989
/* If DECL is a specialization of some template, return the most
   general such template.  For example, given:

     template <class T> struct S { template <class U> void f(U); };

   if TMPL is `template <class U> void S<int>::f(U)' this will return
   the full template.  This function will not trace past partial
   specializations, however.  For example, given in addition:

     template <class T> struct S<T*> { template <class U> void f(U); };

   if TMPL is `template <class U> void S<int*>::f(U)' this will return
   `template <class T> template <class U> S<T*>::f(U)'.  */
mrs's avatar
mrs committed
8990

8991
tree
8992 8993
most_general_template (decl)
     tree decl;
mrs's avatar
mrs committed
8994
{
8995
  while (DECL_TEMPLATE_INFO (decl)
8996 8997
	 && !(TREE_CODE (decl) == TEMPLATE_DECL
	      && DECL_TEMPLATE_SPECIALIZATION (decl))
8998 8999 9000 9001
	 /* The DECL_TI_TEMPLATE can be a LOOKUP_EXPR or
	    IDENTIFIER_NODE in some cases.  (See cp-tree.h for
	    details.)  */
	 && TREE_CODE (DECL_TI_TEMPLATE (decl)) == TEMPLATE_DECL)
9002 9003 9004 9005 9006 9007 9008 9009 9010
    decl = DECL_TI_TEMPLATE (decl);

  return decl;
}

/* Return the most specialized of the class template specializations
   of TMPL which can produce an instantiation matching ARGS, or
   error_mark_node if the choice is ambiguous.  */

9011
static tree
9012 9013 9014 9015 9016 9017 9018
most_specialized_class (tmpl, args)
     tree tmpl;
     tree args;
{
  tree list = NULL_TREE;
  tree t;
  tree champ;
mrs's avatar
mrs committed
9019 9020
  int fate;

9021 9022
  tmpl = most_general_template (tmpl);
  for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
mrs's avatar
mrs committed
9023
    {
9024 9025 9026
      tree spec_args 
	= get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t), args);
      if (spec_args)
mrs's avatar
mrs committed
9027 9028 9029 9030 9031 9032 9033 9034 9035 9036 9037 9038 9039 9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057
	{
	  list = decl_tree_cons (TREE_PURPOSE (t), TREE_VALUE (t), list);
	  TREE_TYPE (list) = TREE_TYPE (t);
	}
    }

  if (! list)
    return NULL_TREE;

  t = list;
  champ = t;
  t = TREE_CHAIN (t);
  for (; t; t = TREE_CHAIN (t))
    {
      fate = more_specialized_class (champ, t);
      if (fate == 1)
	;
      else
	{
	  if (fate == 0)
	    {
	      t = TREE_CHAIN (t);
	      if (! t)
		return error_mark_node;
	    }
	  champ = t;
	}
    }

  for (t = list; t && t != champ; t = TREE_CHAIN (t))
    {
9058
      fate = more_specialized_class (champ, t);
mrs's avatar
mrs committed
9059 9060 9061 9062 9063 9064 9065
      if (fate != 1)
	return error_mark_node;
    }

  return champ;
}

mrs's avatar
mrs committed
9066
/* called from the parser.  */
mrs's avatar
mrs committed
9067

mrs's avatar
mrs committed
9068
void
mrs's avatar
mrs committed
9069
do_decl_instantiation (declspecs, declarator, storage)
mrs's avatar
mrs committed
9070
     tree declspecs, declarator, storage;
mrs's avatar
mrs committed
9071
{
mrs's avatar
merging  
mrs committed
9072
  tree decl = grokdeclarator (declarator, declspecs, NORMAL, 0, NULL_TREE);
mrs's avatar
mrs committed
9073
  tree result = NULL_TREE;
mrs's avatar
mrs committed
9074
  int extern_p = 0;
mrs's avatar
mrs committed
9075

9076 9077 9078 9079 9080
  if (!decl)
    /* An error ocurred, for which grokdeclarator has already issued
       an appropriate message.  */
    return;
  else if (! DECL_LANG_SPECIFIC (decl))
mrs's avatar
mrs committed
9081
    {
jason's avatar
jason committed
9082
      cp_error ("explicit instantiation of non-template `%#D'", decl);
mrs's avatar
mrs committed
9083 9084
      return;
    }
9085
  else if (TREE_CODE (decl) == VAR_DECL)
mrs's avatar
mrs committed
9086
    {
9087 9088 9089 9090 9091 9092 9093 9094
      /* There is an asymmetry here in the way VAR_DECLs and
	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
	 the latter, the DECL we get back will be marked as a
	 template instantiation, and the appropriate
	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
	 should handle VAR_DECLs as it currently handles
	 FUNCTION_DECLs.  */
mrs's avatar
mrs committed
9095 9096
      result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, 0);
      if (result && TREE_CODE (result) != VAR_DECL)
9097
	{
jason's avatar
jason committed
9098
	  cp_error ("no matching template for `%D' found", result);
9099 9100
	  return;
	}
mrs's avatar
mrs committed
9101 9102 9103
    }
  else if (TREE_CODE (decl) != FUNCTION_DECL)
    {
jason's avatar
jason committed
9104
      cp_error ("explicit instantiation of `%#D'", decl);
mrs's avatar
mrs committed
9105 9106
      return;
    }
9107 9108
  else
    result = decl;
9109

9110 9111 9112 9113 9114 9115
  /* Check for various error cases.  Note that if the explicit
     instantiation is legal the RESULT will currently be marked as an
     *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
     until we get here.  */

  if (DECL_TEMPLATE_SPECIALIZATION (result))
9116
    {
9117 9118 9119 9120
      /* [temp.spec]

	 No program shall both explicitly instantiate and explicitly
	 specialize a template.  */
9121 9122
      cp_pedwarn ("explicit instantiation of `%#D' after", result);
      cp_pedwarn_at ("explicit specialization here", result);
9123 9124
      return;
    }
9125 9126 9127
  else if (DECL_EXPLICIT_INSTANTIATION (result))
    {
      /* [temp.spec]
9128

9129 9130 9131
	 No program shall explicitly instantiate any template more
	 than once.  

9132 9133 9134 9135 9136
	 We check DECL_INTERFACE_KNOWN so as not to complain when the first
	 instantiation was `extern' and the second is not, and EXTERN_P for
	 the opposite case.  If -frepo, chances are we already got marked
	 as an explicit instantion because of the repo file.  */
      if (DECL_INTERFACE_KNOWN (result) && !extern_p && !flag_use_repository)
9137
	cp_pedwarn ("duplicate explicit instantiation of `%#D'", result);
9138 9139 9140 9141 9142 9143

      /* If we've already instantiated the template, just return now.  */
      if (DECL_INTERFACE_KNOWN (result))
	return;
    }
  else if (!DECL_IMPLICIT_INSTANTIATION (result))
mrs's avatar
mrs committed
9144
    {
jason's avatar
jason committed
9145
      cp_error ("no matching template for `%D' found", result);
mrs's avatar
mrs committed
9146 9147
      return;
    }
9148
  else if (!DECL_TEMPLATE_INFO (result))
mrs's avatar
mrs committed
9149
    {
jason's avatar
jason committed
9150
      cp_pedwarn ("explicit instantiation of non-template `%#D'", result);
mrs's avatar
mrs committed
9151 9152 9153
      return;
    }

mrs's avatar
mrs committed
9154 9155 9156
  if (flag_external_templates)
    return;

mrs's avatar
mrs committed
9157
  if (storage == NULL_TREE)
mrs's avatar
mrs committed
9158
    ;
mrs's avatar
mrs committed
9159
  else if (storage == ridpointers[(int) RID_EXTERN])
9160 9161
    {
      if (pedantic)
9162
	cp_pedwarn ("ISO C++ forbids the use of `extern' on explicit instantiations");
9163 9164
      extern_p = 1;
    }
mrs's avatar
mrs committed
9165
  else
jason's avatar
jason committed
9166
    cp_error ("storage class `%D' applied to template instantiation",
mrs's avatar
mrs committed
9167
	      storage);
mrs's avatar
mrs committed
9168

9169
  SET_DECL_EXPLICIT_INSTANTIATION (result);
mrs's avatar
mrs committed
9170
  mark_decl_instantiated (result, extern_p);
mrs's avatar
mrs committed
9171
  repo_template_instantiated (result, extern_p);
mrs's avatar
mrs committed
9172
  if (! extern_p)
9173
    instantiate_decl (result, /*defer_ok=*/1);
mrs's avatar
mrs committed
9174 9175
}

mrs's avatar
mrs committed
9176 9177 9178 9179 9180 9181
void
mark_class_instantiated (t, extern_p)
     tree t;
     int extern_p;
{
  SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
9182 9183
  SET_CLASSTYPE_INTERFACE_KNOWN (t);
  CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
mrs's avatar
mrs committed
9184 9185 9186 9187 9188 9189 9190 9191
  CLASSTYPE_VTABLE_NEEDS_WRITING (t) = ! extern_p;
  TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
  if (! extern_p)
    {
      CLASSTYPE_DEBUG_REQUESTED (t) = 1;
      rest_of_type_compilation (t, 1);
    }
}     
mrs's avatar
mrs committed
9192

mrs's avatar
mrs committed
9193
void
9194 9195
do_type_instantiation (t, storage)
     tree t, storage;
mrs's avatar
mrs committed
9196
{
mrs's avatar
mrs committed
9197 9198
  int extern_p = 0;
  int nomem_p = 0;
mrs's avatar
mrs committed
9199 9200
  int static_p = 0;

9201 9202 9203
  if (TREE_CODE (t) == TYPE_DECL)
    t = TREE_TYPE (t);

9204
  if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
9205
    {
jason's avatar
jason committed
9206
      cp_error ("explicit instantiation of non-template type `%T'", t);
9207 9208 9209
      return;
    }

mrs's avatar
mrs committed
9210
  complete_type (t);
mrs's avatar
mrs committed
9211

mrs's avatar
mrs committed
9212 9213
  /* With -fexternal-templates, explicit instantiations are treated the same
     as implicit ones.  */
mrs's avatar
mrs committed
9214 9215 9216
  if (flag_external_templates)
    return;

nathan's avatar
gcc  
nathan committed
9217
  if (!COMPLETE_TYPE_P (t))
mrs's avatar
mrs committed
9218
    {
jason's avatar
jason committed
9219
      cp_error ("explicit instantiation of `%#T' before definition of template",
mrs's avatar
mrs committed
9220 9221 9222 9223
		t);
      return;
    }

9224
  if (storage != NULL_TREE)
mrs's avatar
mrs committed
9225
    {
9226
      if (pedantic)
9227
	cp_pedwarn("ISO C++ forbids the use of `%s' on explicit instantiations", 
jason's avatar
jason committed
9228
		   IDENTIFIER_POINTER (storage));
9229 9230 9231 9232 9233 9234 9235 9236 9237

      if (storage == ridpointers[(int) RID_INLINE])
	nomem_p = 1;
      else if (storage == ridpointers[(int) RID_EXTERN])
	extern_p = 1;
      else if (storage == ridpointers[(int) RID_STATIC])
	static_p = 1;
      else
	{
jason's avatar
jason committed
9238
	  cp_error ("storage class `%D' applied to template instantiation",
9239 9240 9241
		    storage);
	  extern_p = 0;
	}
mrs's avatar
mrs committed
9242 9243
    }

mmitchel's avatar
mmitchel committed
9244
  if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
9245 9246
    {
      /* [temp.spec]
mrs's avatar
mrs committed
9247

9248 9249
	 No program shall both explicitly instantiate and explicitly
	 specialize a template.  */
jason's avatar
jason committed
9250 9251
      cp_error ("explicit instantiation of `%#T' after", t);
      cp_error_at ("explicit specialization here", t);
9252 9253 9254
      return;
    }
  else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
mrs's avatar
mrs committed
9255
    {
9256 9257 9258 9259 9260
      /* [temp.spec]

	 No program shall explicitly instantiate any template more
	 than once.  

9261 9262 9263 9264 9265 9266
         If CLASSTYPE_INTERFACE_ONLY, then the first explicit instantiation
	 was `extern'.  If EXTERN_P then the second is.  If -frepo, chances
	 are we already got marked as an explicit instantion because of the
	 repo file.  All these cases are OK.  */
      if (!CLASSTYPE_INTERFACE_ONLY (t) && !extern_p && !flag_use_repository)
	cp_pedwarn ("duplicate explicit instantiation of `%#T'", t);
9267 9268 9269 9270
      
      /* If we've already instantiated the template, just return now.  */
      if (!CLASSTYPE_INTERFACE_ONLY (t))
	return;
mrs's avatar
mrs committed
9271
    }
mrs's avatar
mrs committed
9272

9273 9274 9275
  mark_class_instantiated (t, extern_p);
  repo_template_instantiated (t, extern_p);

mrs's avatar
mrs committed
9276 9277 9278
  if (nomem_p)
    return;

mrs's avatar
mrs committed
9279
  {
mrs's avatar
mrs committed
9280
    tree tmp;
mrs's avatar
mrs committed
9281

9282 9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300
    /* In contrast to implicit instantiation, where only the
       declarations, and not the definitions, of members are
       instantiated, we have here:

         [temp.explicit]

	 The explicit instantiation of a class template specialization
	 implies the instantiation of all of its members not
	 previously explicitly specialized in the translation unit
	 containing the explicit instantiation.  

       Of course, we can't instantiate member template classes, since
       we don't have any arguments for them.  Note that the standard
       is unclear on whether the instatiation of the members are
       *explicit* instantiations or not.  We choose to be generous,
       and not set DECL_EXPLICIT_INSTANTIATION.  Therefore, we allow
       the explicit instantiation of a class where some of the members
       have no definition in the current translation unit.  */

mrs's avatar
mrs committed
9301 9302
    if (! static_p)
      for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
9303
	if (TREE_CODE (tmp) == FUNCTION_DECL
9304
	    && DECL_TEMPLATE_INSTANTIATION (tmp))
mrs's avatar
mrs committed
9305 9306 9307 9308
	  {
	    mark_decl_instantiated (tmp, extern_p);
	    repo_template_instantiated (tmp, extern_p);
	    if (! extern_p)
9309
	      instantiate_decl (tmp, /*defer_ok=*/1);
mrs's avatar
mrs committed
9310 9311 9312 9313
	  }

    for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
      if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
mrs's avatar
mrs committed
9314
	{
mrs's avatar
mrs committed
9315
	  mark_decl_instantiated (tmp, extern_p);
mrs's avatar
mrs committed
9316
	  repo_template_instantiated (tmp, extern_p);
mrs's avatar
mrs committed
9317
	  if (! extern_p)
9318
	    instantiate_decl (tmp, /*defer_ok=*/1);
mrs's avatar
mrs committed
9319
	}
mrs's avatar
mrs committed
9320

mrs's avatar
mrs committed
9321
    for (tmp = CLASSTYPE_TAGS (t); tmp; tmp = TREE_CHAIN (tmp))
9322 9323
      if (IS_AGGR_TYPE (TREE_VALUE (tmp))
	  && !uses_template_parms (CLASSTYPE_TI_ARGS (TREE_VALUE (tmp))))
mrs's avatar
mrs committed
9324
	do_type_instantiation (TYPE_MAIN_DECL (TREE_VALUE (tmp)), storage);
mrs's avatar
mrs committed
9325
  }
mrs's avatar
mrs committed
9326
}
mrs's avatar
mrs committed
9327

9328 9329 9330 9331
/* Given a function DECL, which is a specialization of TMPL, modify
   DECL to be a re-instantiation of TMPL with the same template
   arguments.  TMPL should be the template into which tsubst'ing
   should occur for DECL, not the most general template.
9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343 9344 9345 9346 9347

   One reason for doing this is a scenario like this:

     template <class T>
     void f(const T&, int i);

     void g() { f(3, 7); }

     template <class T>
     void f(const T& t, const int i) { }

   Note that when the template is first instantiated, with
   instantiate_template, the resulting DECL will have no name for the
   first parameter, and the wrong type for the second.  So, when we go
   to instantiate the DECL, we regenerate it.  */

9348
static void
9349 9350 9351 9352 9353 9354 9355
regenerate_decl_from_template (decl, tmpl)
     tree decl;
     tree tmpl;
{
  tree args;
  tree code_pattern;
  tree new_decl;
9356 9357
  tree gen_tmpl;
  int unregistered;
9358 9359 9360 9361

  args = DECL_TI_ARGS (decl);
  code_pattern = DECL_TEMPLATE_RESULT (tmpl);

jason's avatar
jason committed
9362 9363 9364 9365 9366
  /* Unregister the specialization so that when we tsubst we will not
     just return DECL.  We don't have to unregister DECL from TMPL
     because if would only be registered there if it were a partial
     instantiation of a specialization, which it isn't: it's a full
     instantiation.  */
9367 9368 9369 9370 9371 9372 9373 9374
  gen_tmpl = most_general_template (tmpl);
  unregistered = unregister_specialization (decl, gen_tmpl);

  /* If the DECL was not unregistered then something peculiar is
     happening: we created a specialization but did not call
     register_specialization for it.  */
  my_friendly_assert (unregistered, 0);

9375 9376 9377 9378 9379 9380
  if (TREE_CODE (decl) == VAR_DECL)
    /* Make sure that we can see identifiers, and compute access
       correctly, for the class members used in the declaration of
       this static variable.  */
    pushclass (DECL_CONTEXT (decl), 2);

9381
  /* Do the substitution to get the new declaration.  */
9382
  new_decl = tsubst (code_pattern, args, /*complain=*/1, NULL_TREE);
9383 9384 9385 9386 9387

  if (TREE_CODE (decl) == VAR_DECL)
    {
      /* Set up DECL_INITIAL, since tsubst doesn't.  */
      DECL_INITIAL (new_decl) = 
9388
	tsubst_expr (DECL_INITIAL (code_pattern), args, 
9389
		     /*complain=*/1, DECL_TI_TEMPLATE (decl));
9390
      /* Pop the class context we pushed above.  */
9391
      popclass ();
9392
    }
9393
  else if (TREE_CODE (decl) == FUNCTION_DECL)
9394 9395 9396 9397 9398 9399 9400
    {
      /* Convince duplicate_decls to use the DECL_ARGUMENTS from the
	 new decl.  */ 
      DECL_INITIAL (new_decl) = error_mark_node;
      /* And don't complain about a duplicate definition.  */
      DECL_INITIAL (decl) = NULL_TREE;
    }
9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413

  /* The immediate parent of the new template is still whatever it was
     before, even though tsubst sets DECL_TI_TEMPLATE up as the most
     general template.  We also reset the DECL_ASSEMBLER_NAME since
     tsubst always calculates the name as if the function in question
     were really a template instance, and sometimes, with friend
     functions, this is not so.  See tsubst_friend_function for
     details.  */
  DECL_TI_TEMPLATE (new_decl) = DECL_TI_TEMPLATE (decl);
  DECL_ASSEMBLER_NAME (new_decl) = DECL_ASSEMBLER_NAME (decl);
  DECL_RTL (new_decl) = DECL_RTL (decl);

  /* Call duplicate decls to merge the old and new declarations.  */
9414 9415
  duplicate_decls (new_decl, decl);

9416 9417
  /* Now, re-register the specialization.  */
  register_specialization (decl, gen_tmpl, args);
9418 9419
}

9420 9421 9422
/* Produce the definition of D, a _DECL generated from a template.  If
   DEFER_OK is non-zero, then we don't have to actually do the
   instantiation now; we just have to do it sometime.  */
jason's avatar
jason committed
9423

mrs's avatar
mrs committed
9424
tree
9425
instantiate_decl (d, defer_ok)
mrs's avatar
mrs committed
9426
     tree d;
9427
     int defer_ok;
mrs's avatar
mrs committed
9428
{
9429 9430
  tree tmpl = DECL_TI_TEMPLATE (d);
  tree args = DECL_TI_ARGS (d);
9431
  tree td;
9432 9433 9434
  tree code_pattern;
  tree spec;
  tree gen_tmpl;
mrs's avatar
mrs committed
9435
  int pattern_defined;
9436 9437
  int line = lineno;
  char *file = input_filename;
mrs's avatar
mrs committed
9438

9439 9440 9441 9442 9443
  /* This function should only be used to instantiate templates for
     functions and static member variables.  */
  my_friendly_assert (TREE_CODE (d) == FUNCTION_DECL
		      || TREE_CODE (d) == VAR_DECL, 0);

9444 9445 9446 9447 9448
  /* Don't instantiate cloned functions.  Instead, instantiate the
     functions they cloned.  */
  if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
    d = DECL_CLONED_FUNCTION (d);

9449
  if (DECL_TEMPLATE_INSTANTIATED (d))
9450 9451 9452 9453 9454
    /* D has already been instantiated.  It might seem reasonable to
       check whether or not D is an explict instantiation, and, if so,
       stop here.  But when an explicit instantiation is deferred
       until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
       is set, even though we still need to do the instantiation.  */
9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470
    return d;

  /* If we already have a specialization of this declaration, then
     there's no reason to instantiate it.  Note that
     retrieve_specialization gives us both instantiations and
     specializations, so we must explicitly check
     DECL_TEMPLATE_SPECIALIZATION.  */
  gen_tmpl = most_general_template (tmpl);
  spec = retrieve_specialization (gen_tmpl, args);
  if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
    return spec;

  /* This needs to happen before any tsubsting.  */
  if (! push_tinst_level (d))
    return d;

9471 9472 9473 9474 9475 9476 9477 9478 9479 9480 9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504
  /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
     for the instantiation.  This is not always the most general
     template.  Consider, for example:

        template <class T>
	struct S { template <class U> void f();
	           template <> void f<int>(); };

     and an instantiation of S<double>::f<int>.  We want TD to be the
     specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
  td = tmpl;
  for (td = tmpl;
       /* An instantiation cannot have a definition, so we need a
	  more general template.  */
       DECL_TEMPLATE_INSTANTIATION (td)
	 /* We must also deal with friend templates.  Given:

	      template <class T> struct S { 
		template <class U> friend void f() {};
	      };
	 
	    S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
	    so far as the language is concerned, but that's still
	    where we get the pattern for the instantiation from.  On
	    ther hand, if the definition comes outside the class, say:

 	      template <class T> struct S { 
	        template <class U> friend void f();
              };
	      template <class U> friend void f() {}

	    we don't need to look any further.  That's what the check for
	    DECL_INITIAL is for.  */
	|| (TREE_CODE (d) == FUNCTION_DECL
9505
	    && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (td)
9506
	    && !DECL_INITIAL (DECL_TEMPLATE_RESULT (td)));
jason's avatar
jason committed
9507
       )
9508 9509 9510 9511 9512 9513 9514 9515 9516 9517 9518 9519 9520
    {
      /* The present template, TD, should not be a definition.  If it
	 were a definition, we should be using it!  Note that we
	 cannot restructure the loop to just keep going until we find
	 a template with a definition, since that might go too far if
	 a specialization was declared, but not defined.  */
      my_friendly_assert (!(TREE_CODE (d) == VAR_DECL
			    && !DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (td))), 
			  0); 
      
      /* Fetch the more general template.  */
      td = DECL_TI_TEMPLATE (td);
    }
9521

jason's avatar
jason committed
9522
  code_pattern = DECL_TEMPLATE_RESULT (td);
9523

mrs's avatar
mrs committed
9524
  if (TREE_CODE (d) == FUNCTION_DECL)
9525
    pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
mrs's avatar
mrs committed
9526
  else
9527
    pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
mrs's avatar
mrs committed
9528 9529 9530 9531 9532 9533

  push_to_top_level ();
  lineno = DECL_SOURCE_LINE (d);
  input_filename = DECL_SOURCE_FILE (d);

  if (pattern_defined)
mrs's avatar
mrs committed
9534 9535 9536 9537 9538 9539 9540 9541 9542 9543
    {
      repo_template_used (d);

      if (flag_external_templates && ! DECL_INTERFACE_KNOWN (d))
	{
	  if (flag_alt_external_templates)
	    {
	      if (interface_unknown)
		warn_if_unknown_interface (d);
	    }
jason's avatar
jason committed
9544
	  else if (DECL_INTERFACE_KNOWN (code_pattern))
mrs's avatar
mrs committed
9545 9546
	    {
	      DECL_INTERFACE_KNOWN (d) = 1;
jason's avatar
jason committed
9547
	      DECL_NOT_REALLY_EXTERN (d) = ! DECL_EXTERNAL (code_pattern);
mrs's avatar
mrs committed
9548 9549
	    }
	  else
jason's avatar
jason committed
9550
	    warn_if_unknown_interface (code_pattern);
mrs's avatar
mrs committed
9551 9552
	}

mrs's avatar
mrs committed
9553
      if (at_eof)
mrs's avatar
mrs committed
9554 9555 9556
	import_export_decl (d);
    }

9557 9558 9559 9560 9561 9562
  /* Reject all external templates except inline functions.  */
  if (DECL_INTERFACE_KNOWN (d)
      && ! DECL_NOT_REALLY_EXTERN (d)
      && ! (TREE_CODE (d) == FUNCTION_DECL && DECL_INLINE (d)))
    goto out;

9563 9564
  /* We need to set up DECL_INITIAL regardless of pattern_defined if
     the variable is a static const initialized in the class body.  */
9565
  if (TREE_CODE (d) == VAR_DECL 
9566
      && TREE_READONLY (d)
9567 9568
      && DECL_INITIAL (d) == NULL_TREE
      && DECL_INITIAL (code_pattern) != NULL_TREE)
9569 9570 9571 9572 9573 9574
    ;
  /* Defer all other templates, unless we have been explicitly
     forbidden from doing so.  We restore the source position here
     because it's used by add_pending_template.  */
  else if (! pattern_defined || defer_ok)
    {
9575 9576 9577
      lineno = line;
      input_filename = file;

9578 9579 9580 9581 9582 9583 9584 9585 9586
      if (at_eof && !pattern_defined 
	  && DECL_EXPLICIT_INSTANTIATION (d))
	/* [temp.explicit]

	   The definition of a non-exported function template, a
	   non-exported member function template, or a non-exported
	   member function or static data member of a class template
	   shall be present in every translation unit in which it is
	   explicitly instantiated.  */
jason's avatar
jason committed
9587
	cp_error ("explicit instantiation of `%D' but no definition available",
9588 9589
		  d);

mrs's avatar
mrs committed
9590
      add_pending_template (d);
mrs's avatar
mrs committed
9591
      goto out;
mrs's avatar
mrs committed
9592 9593
    }

9594 9595 9596
  /* We're now committed to instantiating this template.  Mark it as
     instantiated so that recursive calls to instantiate_decl do not
     try to instantiate it again.  */
9597
  DECL_TEMPLATE_INSTANTIATED (d) = 1;
9598

9599 9600 9601 9602
  /* Regenerate the declaration in case the template has been modified
     by a subsequent redeclaration.  */
  regenerate_decl_from_template (d, td);

9603 9604
  /* We already set the file and line above.  Reset them now in case
     they changed as a result of calling regenerate_decl_from_template.  */
mrs's avatar
mrs committed
9605 9606 9607
  lineno = DECL_SOURCE_LINE (d);
  input_filename = DECL_SOURCE_FILE (d);

mrs's avatar
mrs committed
9608 9609 9610 9611 9612 9613 9614 9615 9616 9617
  if (TREE_CODE (d) == VAR_DECL)
    {
      DECL_IN_AGGR_P (d) = 0;
      if (DECL_INTERFACE_KNOWN (d))
	DECL_EXTERNAL (d) = ! DECL_NOT_REALLY_EXTERN (d);
      else
	{
	  DECL_EXTERNAL (d) = 1;
	  DECL_NOT_REALLY_EXTERN (d) = 1;
	}
9618
      cp_finish_decl (d, DECL_INITIAL (d), NULL_TREE, 0);
mrs's avatar
mrs committed
9619 9620 9621
    }
  else if (TREE_CODE (d) == FUNCTION_DECL)
    {
9622 9623 9624 9625 9626 9627 9628
      /* Set up the list of local specializations.  */
      my_friendly_assert (local_specializations == NULL, 20000422);
      local_specializations = htab_create (37, 
					   htab_hash_pointer,
					   htab_eq_pointer,
					   NULL);

9629
      /* Set up context.  */
mmitchel's avatar
mmitchel committed
9630
      start_function (NULL_TREE, d, NULL_TREE, SF_PRE_PARSED);
mrs's avatar
mrs committed
9631 9632
      store_parm_decls ();

9633 9634 9635 9636
      /* We already set up __FUNCTION__, etc., so we don't want to do
	 it again now.  */
      current_function_name_declared = 1;

9637 9638 9639 9640
      /* Substitute into the body of the function.  */
      tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
		   /*complain=*/1, tmpl);

9641 9642 9643 9644
      /* We don't need the local specializations any more.  */
      htab_delete (local_specializations);
      local_specializations = NULL;

9645
      /* Finish the function.  */
9646
      expand_body (finish_function (0));
mrs's avatar
mrs committed
9647 9648
    }

9649 9650 9651
  /* We're not deferring instantiation any more.  */
  TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;

mrs's avatar
mrs committed
9652
out:
9653 9654 9655
  lineno = line;
  input_filename = file;

mrs's avatar
mrs committed
9656 9657
  pop_from_top_level ();
  pop_tinst_level ();
mrs's avatar
mrs committed
9658 9659 9660

  return d;
}
mrs's avatar
mrs committed
9661

9662 9663 9664 9665 9666 9667 9668 9669 9670 9671 9672 9673 9674 9675 9676 9677 9678 9679 9680 9681 9682 9683 9684
/* Run through the list of templates that we wish we could
   instantiate, and instantiate any we can.  */

int
instantiate_pending_templates ()
{
  tree *t;
  int instantiated_something = 0;
  int reconsider;
  
  do 
    {
      reconsider = 0;

      t = &pending_templates;
      while (*t)
	{
	  tree srcloc = TREE_PURPOSE (*t);
	  tree instantiation = TREE_VALUE (*t);

	  input_filename = SRCLOC_FILE (srcloc);
	  lineno = SRCLOC_LINE (srcloc);

9685
	  if (TYPE_P (instantiation))
9686 9687 9688
	    {
	      tree fn;

nathan's avatar
gcc  
nathan committed
9689
	      if (!COMPLETE_TYPE_P (instantiation))
9690 9691 9692 9693 9694 9695 9696
		{
		  instantiate_class_template (instantiation);
		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
		    for (fn = TYPE_METHODS (instantiation); 
			 fn;
			 fn = TREE_CHAIN (fn))
		      if (! DECL_ARTIFICIAL (fn))
9697
			instantiate_decl (fn, /*defer_ok=*/0);
nathan's avatar
gcc  
nathan committed
9698
		  if (COMPLETE_TYPE_P (instantiation))
9699 9700 9701 9702 9703 9704
		    {
		      instantiated_something = 1;
		      reconsider = 1;
		    }
		}

nathan's avatar
gcc  
nathan committed
9705
	      if (COMPLETE_TYPE_P (instantiation))
9706 9707 9708 9709 9710 9711 9712 9713
		/* If INSTANTIATION has been instantiated, then we don't
		   need to consider it again in the future.  */
		*t = TREE_CHAIN (*t);
	      else 
		t = &TREE_CHAIN (*t);
	    }
	  else
	    {
9714
	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
9715 9716
		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
		{
9717 9718
		  instantiation = instantiate_decl (instantiation,
						    /*defer_ok=*/0);
9719 9720 9721 9722 9723 9724 9725
		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
		    {
		      instantiated_something = 1;
		      reconsider = 1;
		    }
		}

9726
	      if (DECL_TEMPLATE_SPECIALIZATION (instantiation)
9727 9728 9729 9730 9731 9732 9733 9734 9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754 9755 9756 9757
		  || DECL_TEMPLATE_INSTANTIATED (instantiation))
		/* If INSTANTIATION has been instantiated, then we don't
		   need to consider it again in the future.  */
		*t = TREE_CHAIN (*t);
	      else 
		t = &TREE_CHAIN (*t);
	    }
	}
      template_tail = t;

      /* Go through the things that are template instantiations if we are
	 using guiding declarations.  */
      t = &maybe_templates;
      while (*t)
	{
	  tree template;
	  tree fn;
	  tree args;

	  fn = TREE_VALUE (*t);

	  if (DECL_INITIAL (fn))
	    /* If the FN is already defined, then it was either already
	       instantiated or, even though guiding declarations were
	       allowed, a non-template definition was provided.  */
	    ;
	  else
	    {
	      template = TREE_PURPOSE (*t);
	      args = get_bindings (template, fn, NULL_TREE);
	      fn = instantiate_template (template, args);
9758
	      instantiate_decl (fn, /*defer_ok=*/0);
9759 9760 9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771
	      reconsider = 1;
	    }
	
	  /* Remove this entry from the chain.  */
	  *t = TREE_CHAIN (*t);
	}
      maybe_template_tail = t;
    } 
  while (reconsider);

  return instantiated_something;
}

9772 9773 9774 9775
/* Substitute ARGVEC into T, which is a TREE_LIST.  In particular, it
   is an initializer list: the TREE_PURPOSEs are DECLs, and the
   TREE_VALUEs are initializer values.  Used by instantiate_decl.  */

mrs's avatar
mrs committed
9776
static tree
mrs's avatar
mrs committed
9777 9778 9779 9780 9781 9782 9783 9784
tsubst_expr_values (t, argvec)
     tree t, argvec;
{
  tree first = NULL_TREE;
  tree *p = &first;

  for (; t; t = TREE_CHAIN (t))
    {
9785 9786 9787 9788
      tree pur = tsubst_copy (TREE_PURPOSE (t), argvec,
			      /*complain=*/1, NULL_TREE);
      tree val = tsubst_expr (TREE_VALUE (t), argvec, /*complain=*/1, 
			      NULL_TREE);
mrs's avatar
mrs committed
9789 9790 9791 9792 9793 9794
      *p = build_tree_list (pur, val);
      p = &TREE_CHAIN (*p);
    }
  return first;
}

mrs's avatar
mrs committed
9795 9796 9797 9798 9799 9800 9801 9802 9803 9804 9805 9806 9807 9808
/* D is an undefined function declaration in the presence of templates with
   the same name, listed in FNS.  If one of them can produce D as an
   instantiation, remember this so we can instantiate it at EOF if D has
   not been defined by that time.  */

void
add_maybe_template (d, fns)
     tree d, fns;
{
  tree t;

  if (DECL_MAYBE_TEMPLATE (d))
    return;

9809
  t = most_specialized (fns, d, NULL_TREE);
mrs's avatar
mrs committed
9810 9811 9812 9813
  if (! t)
    return;
  if (t == error_mark_node)
    {
jason's avatar
jason committed
9814
      cp_error ("ambiguous template instantiation for `%D'", d);
mrs's avatar
mrs committed
9815 9816 9817
      return;
    }

9818
  *maybe_template_tail = tree_cons (t, d, NULL_TREE);
mrs's avatar
mrs committed
9819 9820 9821
  maybe_template_tail = &TREE_CHAIN (*maybe_template_tail);
  DECL_MAYBE_TEMPLATE (d) = 1;
}
mrs's avatar
mrs committed
9822

9823 9824 9825 9826 9827 9828 9829 9830 9831 9832 9833 9834 9835 9836
/* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */

static void
set_current_access_from_decl (decl)
     tree decl;
{
  if (TREE_PRIVATE (decl))
    current_access_specifier = access_private_node;
  else if (TREE_PROTECTED (decl))
    current_access_specifier = access_protected_node;
  else
    current_access_specifier = access_public_node;
}

9837 9838 9839
/* Instantiate an enumerated type.  TAG is the template type, NEWTAG
   is the instantiation (which should have been created with
   start_enum) and ARGS are the template arguments to use.  */
mrs's avatar
mrs committed
9840

9841 9842 9843 9844 9845
static void
tsubst_enum (tag, newtag, args)
     tree tag;
     tree newtag;
     tree args;
mrs's avatar
mrs committed
9846
{
9847
  tree e;
mrs's avatar
mrs committed
9848 9849 9850

  for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
    {
9851
      tree value;
9852
      
9853 9854 9855
      /* Note that in a template enum, the TREE_VALUE is the
	 CONST_DECL, not the corresponding INTEGER_CST.  */
      value = tsubst_expr (DECL_INITIAL (TREE_VALUE (e)), 
9856 9857
			   args, /*complain=*/1,
			   NULL_TREE);
9858 9859 9860 9861 9862

      /* Give this enumeration constant the correct access.  */
      set_current_access_from_decl (TREE_VALUE (e));

      /* Actually build the enumerator itself.  */
9863
      build_enumerator (TREE_PURPOSE (e), value, newtag); 
9864
    }
9865

9866
  finish_enum (newtag);
mrs's avatar
mrs committed
9867
}
9868 9869 9870 9871 9872 9873 9874 9875 9876 9877

/* Set the DECL_ASSEMBLER_NAME for DECL, which is a FUNCTION_DECL that
   is either an instantiation or specialization of a template
   function.  */

static void
set_mangled_name_for_template_decl (decl)
     tree decl;
{
  tree saved_namespace;
ghazi's avatar
ghazi committed
9878
  tree context = NULL_TREE;
9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889 9890 9891 9892 9893 9894 9895 9896 9897 9898 9899 9900 9901 9902 9903 9904 9905 9906 9907 9908 9909 9910 9911 9912 9913 9914 9915 9916 9917 9918 9919 9920 9921 9922 9923 9924 9925 9926 9927 9928 9929 9930 9931 9932
  tree fn_type;
  tree ret_type;
  tree parm_types;
  tree tparms;
  tree targs;
  tree tmpl;
  int parm_depth;

  my_friendly_assert (TREE_CODE (decl) == FUNCTION_DECL, 0);
  my_friendly_assert (DECL_TEMPLATE_INFO (decl) != NULL_TREE, 0);

  /* The names of template functions must be mangled so as to indicate
     what template is being specialized with what template arguments.
     For example, each of the following three functions must get
     different mangled names:

       void f(int);                  
       template <> void f<7>(int);
       template <> void f<8>(int);  */

  targs = DECL_TI_ARGS (decl);
  if (uses_template_parms (targs))
    /* This DECL is for a partial instantiation.  There's no need to
       mangle the name of such an entity.  */
    return;

  tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
  tparms = DECL_TEMPLATE_PARMS (tmpl);
  parm_depth = TMPL_PARMS_DEPTH (tparms);

  /* There should be as many levels of arguments as there are levels
     of parameters.  */
  my_friendly_assert (parm_depth == TMPL_ARGS_DEPTH (targs), 0);

  /* We now compute the PARMS and RET_TYPE to give to
     build_decl_overload_real.  The PARMS and RET_TYPE are the
     parameter and return types of the template, after all but the
     innermost template arguments have been substituted, not the
     parameter and return types of the function DECL.  For example,
     given:

       template <class T> T f(T);

     both PARMS and RET_TYPE should be `T' even if DECL is `int f(int)'.  
     A more subtle example is:

       template <class T> struct S { template <class U> void f(T, U); }

     Here, if DECL is `void S<int>::f(int, double)', PARMS should be
     {int, U}.  Thus, the args that we want to subsitute into the
     return and parameter type for the function are those in TARGS,
     with the innermost level omitted.  */
  fn_type = TREE_TYPE (tmpl);
  if (DECL_STATIC_FUNCTION_P (decl))
9933
    context = DECL_CONTEXT (decl);
9934 9935 9936 9937 9938 9939 9940 9941 9942 9943 9944

  if (parm_depth == 1)
    /* No substitution is necessary.  */
    ;
  else
    {
      int i;
      tree partial_args;

      /* Replace the innermost level of the TARGS with NULL_TREEs to
	 let tsubst know not to subsitute for those parameters.  */
9945
      partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
9946 9947 9948 9949 9950
      for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
	SET_TMPL_ARGS_LEVEL (partial_args, i,
			     TMPL_ARGS_LEVEL (targs, i));
      SET_TMPL_ARGS_LEVEL (partial_args,
			   TMPL_ARGS_DEPTH (targs),
9951
			   make_tree_vec (DECL_NTPARMS (tmpl)));
9952 9953 9954

      /* Now, do the (partial) substitution to figure out the
	 appropriate function type.  */
9955
      fn_type = tsubst (fn_type, partial_args, /*complain=*/1, NULL_TREE);
9956
      if (DECL_STATIC_FUNCTION_P (decl))
9957
	context = tsubst (context, partial_args, /*complain=*/1, NULL_TREE);
9958 9959 9960 9961 9962 9963

      /* Substitute into the template parameters to obtain the real
	 innermost set of parameters.  This step is important if the
	 innermost set of template parameters contains value
	 parameters whose types depend on outer template parameters.  */
      TREE_VEC_LENGTH (partial_args)--;
9964
      tparms = tsubst_template_parms (tparms, partial_args, /*complain=*/1);
9965 9966 9967 9968 9969 9970 9971 9972 9973 9974 9975 9976 9977 9978 9979 9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994 9995 9996
    }

  /* Now, get the innermost parameters and arguments, and figure out
     the parameter and return types.  */
  tparms = INNERMOST_TEMPLATE_PARMS (tparms);
  targs = innermost_args (targs);
  ret_type = TREE_TYPE (fn_type);
  parm_types = TYPE_ARG_TYPES (fn_type);

  /* For a static member function, we generate a fake `this' pointer,
     for the purposes of mangling.  This indicates of which class the
     function is a member.  Because of:

       [class.static] 

       There shall not be a static and a nonstatic member function
       with the same name and the same parameter types

     we don't have to worry that this will result in a clash with a
     non-static member function.  */
  if (DECL_STATIC_FUNCTION_P (decl))
    parm_types = hash_tree_chain (build_pointer_type (context), parm_types);

  /* There should be the same number of template parameters as
     template arguments.  */
  my_friendly_assert (TREE_VEC_LENGTH (tparms) == TREE_VEC_LENGTH (targs),
		      0);

  /* If the template is in a namespace, we need to put that into the
     mangled name. Unfortunately, build_decl_overload_real does not
     get the decl to mangle, so it relies on the current
     namespace. Therefore, we set that here temporarily. */
9997
  my_friendly_assert (DECL_P (decl), 980702);
9998 9999 10000 10001 10002 10003 10004 10005
  saved_namespace = current_namespace;
  current_namespace = CP_DECL_CONTEXT (decl);  

  /* Actually set the DCL_ASSEMBLER_NAME.  */
  DECL_ASSEMBLER_NAME (decl)
    = build_decl_overload_real (DECL_NAME (decl), parm_types, ret_type,
				tparms, targs, 
				DECL_FUNCTION_MEMBER_P (decl) 
10006
				+ DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (decl));
10007 10008 10009 10010

  /* Restore the previously active namespace.  */
  current_namespace = saved_namespace;
}