SemaTemplateInstantiate.cpp revision 21d18f2893c38398e147708d48ceb5d4c9c1290f
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/ 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7//===----------------------------------------------------------------------===/ 8// 9// This file implements C++ template instantiation. 10// 11//===----------------------------------------------------------------------===/ 12 13#include "Sema.h" 14#include "TreeTransform.h" 15#include "clang/AST/ASTConsumer.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/Expr.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/Parse/DeclSpec.h" 20#include "clang/Basic/LangOptions.h" 21#include "llvm/Support/Compiler.h" 22 23using namespace clang; 24 25//===----------------------------------------------------------------------===/ 26// Template Instantiation Support 27//===----------------------------------------------------------------------===/ 28 29/// \brief Retrieve the template argument list(s) that should be used to 30/// instantiate the definition of the given declaration. 31MultiLevelTemplateArgumentList 32Sema::getTemplateInstantiationArgs(NamedDecl *D) { 33 // Accumulate the set of template argument lists in this structure. 34 MultiLevelTemplateArgumentList Result; 35 36 DeclContext *Ctx = dyn_cast<DeclContext>(D); 37 if (!Ctx) 38 Ctx = D->getDeclContext(); 39 40 while (!Ctx->isFileContext()) { 41 // Add template arguments from a class template instantiation. 42 if (ClassTemplateSpecializationDecl *Spec 43 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) { 44 // We're done when we hit an explicit specialization. 45 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization) 46 break; 47 48 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs()); 49 } 50 51 // Add template arguments from a function template specialization. 52 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) { 53 // FIXME: Check whether this is an explicit specialization. 54 if (const TemplateArgumentList *TemplateArgs 55 = Function->getTemplateSpecializationArgs()) 56 Result.addOuterTemplateArguments(TemplateArgs); 57 58 // If this is a friend declaration and it declares an entity at 59 // namespace scope, take arguments from its lexical parent 60 // instead of its semantic parent. 61 if (Function->getFriendObjectKind() && 62 Function->getDeclContext()->isFileContext()) { 63 Ctx = Function->getLexicalDeclContext(); 64 continue; 65 } 66 } 67 68 Ctx = Ctx->getParent(); 69 } 70 71 return Result; 72} 73 74Sema::InstantiatingTemplate:: 75InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 76 Decl *Entity, 77 SourceRange InstantiationRange) 78 : SemaRef(SemaRef) { 79 80 Invalid = CheckInstantiationDepth(PointOfInstantiation, 81 InstantiationRange); 82 if (!Invalid) { 83 ActiveTemplateInstantiation Inst; 84 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation; 85 Inst.PointOfInstantiation = PointOfInstantiation; 86 Inst.Entity = reinterpret_cast<uintptr_t>(Entity); 87 Inst.TemplateArgs = 0; 88 Inst.NumTemplateArgs = 0; 89 Inst.InstantiationRange = InstantiationRange; 90 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 91 Invalid = false; 92 } 93} 94 95Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 96 SourceLocation PointOfInstantiation, 97 TemplateDecl *Template, 98 const TemplateArgument *TemplateArgs, 99 unsigned NumTemplateArgs, 100 SourceRange InstantiationRange) 101 : SemaRef(SemaRef) { 102 103 Invalid = CheckInstantiationDepth(PointOfInstantiation, 104 InstantiationRange); 105 if (!Invalid) { 106 ActiveTemplateInstantiation Inst; 107 Inst.Kind 108 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation; 109 Inst.PointOfInstantiation = PointOfInstantiation; 110 Inst.Entity = reinterpret_cast<uintptr_t>(Template); 111 Inst.TemplateArgs = TemplateArgs; 112 Inst.NumTemplateArgs = NumTemplateArgs; 113 Inst.InstantiationRange = InstantiationRange; 114 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 115 Invalid = false; 116 } 117} 118 119Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 120 SourceLocation PointOfInstantiation, 121 FunctionTemplateDecl *FunctionTemplate, 122 const TemplateArgument *TemplateArgs, 123 unsigned NumTemplateArgs, 124 ActiveTemplateInstantiation::InstantiationKind Kind, 125 SourceRange InstantiationRange) 126: SemaRef(SemaRef) { 127 128 Invalid = CheckInstantiationDepth(PointOfInstantiation, 129 InstantiationRange); 130 if (!Invalid) { 131 ActiveTemplateInstantiation Inst; 132 Inst.Kind = Kind; 133 Inst.PointOfInstantiation = PointOfInstantiation; 134 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate); 135 Inst.TemplateArgs = TemplateArgs; 136 Inst.NumTemplateArgs = NumTemplateArgs; 137 Inst.InstantiationRange = InstantiationRange; 138 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 139 Invalid = false; 140 } 141} 142 143Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 144 SourceLocation PointOfInstantiation, 145 ClassTemplatePartialSpecializationDecl *PartialSpec, 146 const TemplateArgument *TemplateArgs, 147 unsigned NumTemplateArgs, 148 SourceRange InstantiationRange) 149 : SemaRef(SemaRef) { 150 151 Invalid = CheckInstantiationDepth(PointOfInstantiation, 152 InstantiationRange); 153 if (!Invalid) { 154 ActiveTemplateInstantiation Inst; 155 Inst.Kind 156 = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution; 157 Inst.PointOfInstantiation = PointOfInstantiation; 158 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec); 159 Inst.TemplateArgs = TemplateArgs; 160 Inst.NumTemplateArgs = NumTemplateArgs; 161 Inst.InstantiationRange = InstantiationRange; 162 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 163 Invalid = false; 164 } 165} 166 167Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef, 168 SourceLocation PointOfInstantation, 169 ParmVarDecl *Param, 170 const TemplateArgument *TemplateArgs, 171 unsigned NumTemplateArgs, 172 SourceRange InstantiationRange) 173 : SemaRef(SemaRef) { 174 175 Invalid = CheckInstantiationDepth(PointOfInstantation, InstantiationRange); 176 177 if (!Invalid) { 178 ActiveTemplateInstantiation Inst; 179 Inst.Kind 180 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation; 181 Inst.PointOfInstantiation = PointOfInstantation; 182 Inst.Entity = reinterpret_cast<uintptr_t>(Param); 183 Inst.TemplateArgs = TemplateArgs; 184 Inst.NumTemplateArgs = NumTemplateArgs; 185 Inst.InstantiationRange = InstantiationRange; 186 SemaRef.ActiveTemplateInstantiations.push_back(Inst); 187 Invalid = false; 188 } 189} 190 191void Sema::InstantiatingTemplate::Clear() { 192 if (!Invalid) { 193 SemaRef.ActiveTemplateInstantiations.pop_back(); 194 Invalid = true; 195 } 196} 197 198bool Sema::InstantiatingTemplate::CheckInstantiationDepth( 199 SourceLocation PointOfInstantiation, 200 SourceRange InstantiationRange) { 201 if (SemaRef.ActiveTemplateInstantiations.size() 202 <= SemaRef.getLangOptions().InstantiationDepth) 203 return false; 204 205 SemaRef.Diag(PointOfInstantiation, 206 diag::err_template_recursion_depth_exceeded) 207 << SemaRef.getLangOptions().InstantiationDepth 208 << InstantiationRange; 209 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) 210 << SemaRef.getLangOptions().InstantiationDepth; 211 return true; 212} 213 214/// \brief Prints the current instantiation stack through a series of 215/// notes. 216void Sema::PrintInstantiationStack() { 217 // FIXME: In all of these cases, we need to show the template arguments 218 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator 219 Active = ActiveTemplateInstantiations.rbegin(), 220 ActiveEnd = ActiveTemplateInstantiations.rend(); 221 Active != ActiveEnd; 222 ++Active) { 223 switch (Active->Kind) { 224 case ActiveTemplateInstantiation::TemplateInstantiation: { 225 Decl *D = reinterpret_cast<Decl *>(Active->Entity); 226 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 227 unsigned DiagID = diag::note_template_member_class_here; 228 if (isa<ClassTemplateSpecializationDecl>(Record)) 229 DiagID = diag::note_template_class_instantiation_here; 230 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 231 DiagID) 232 << Context.getTypeDeclType(Record) 233 << Active->InstantiationRange; 234 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 235 unsigned DiagID; 236 if (Function->getPrimaryTemplate()) 237 DiagID = diag::note_function_template_spec_here; 238 else 239 DiagID = diag::note_template_member_function_here; 240 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 241 DiagID) 242 << Function 243 << Active->InstantiationRange; 244 } else { 245 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 246 diag::note_template_static_data_member_def_here) 247 << cast<VarDecl>(D) 248 << Active->InstantiationRange; 249 } 250 break; 251 } 252 253 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: { 254 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity); 255 std::string TemplateArgsStr 256 = TemplateSpecializationType::PrintTemplateArgumentList( 257 Active->TemplateArgs, 258 Active->NumTemplateArgs, 259 Context.PrintingPolicy); 260 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 261 diag::note_default_arg_instantiation_here) 262 << (Template->getNameAsString() + TemplateArgsStr) 263 << Active->InstantiationRange; 264 break; 265 } 266 267 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: { 268 FunctionTemplateDecl *FnTmpl 269 = cast<FunctionTemplateDecl>((Decl *)Active->Entity); 270 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 271 diag::note_explicit_template_arg_substitution_here) 272 << FnTmpl << Active->InstantiationRange; 273 break; 274 } 275 276 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 277 if (ClassTemplatePartialSpecializationDecl *PartialSpec 278 = dyn_cast<ClassTemplatePartialSpecializationDecl>( 279 (Decl *)Active->Entity)) { 280 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 281 diag::note_partial_spec_deduct_instantiation_here) 282 << Context.getTypeDeclType(PartialSpec) 283 << Active->InstantiationRange; 284 } else { 285 FunctionTemplateDecl *FnTmpl 286 = cast<FunctionTemplateDecl>((Decl *)Active->Entity); 287 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 288 diag::note_function_template_deduction_instantiation_here) 289 << FnTmpl << Active->InstantiationRange; 290 } 291 break; 292 293 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: { 294 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity); 295 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); 296 TemplateDecl *Template = FD->getPrimaryTemplate(); 297 298 std::string TemplateArgsStr 299 = TemplateSpecializationType::PrintTemplateArgumentList( 300 Active->TemplateArgs, 301 Active->NumTemplateArgs, 302 Context.PrintingPolicy); 303 Diags.Report(FullSourceLoc(Active->PointOfInstantiation, SourceMgr), 304 diag::note_default_function_arg_instantiation_here) 305 << (Template->getNameAsString() + TemplateArgsStr) 306 << Active->InstantiationRange; 307 break; 308 } 309 310 } 311 } 312} 313 314bool Sema::isSFINAEContext() const { 315 using llvm::SmallVector; 316 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator 317 Active = ActiveTemplateInstantiations.rbegin(), 318 ActiveEnd = ActiveTemplateInstantiations.rend(); 319 Active != ActiveEnd; 320 ++Active) { 321 322 switch(Active->Kind) { 323 case ActiveTemplateInstantiation::TemplateInstantiation: 324 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: 325 326 // This is a template instantiation, so there is no SFINAE. 327 return false; 328 329 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: 330 // A default template argument instantiation may or may not be a 331 // SFINAE context; look further up the stack. 332 break; 333 334 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: 335 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: 336 // We're either substitution explicitly-specified template arguments 337 // or deduced template arguments, so SFINAE applies. 338 return true; 339 } 340 } 341 342 return false; 343} 344 345//===----------------------------------------------------------------------===/ 346// Template Instantiation for Types 347//===----------------------------------------------------------------------===/ 348namespace { 349 class VISIBILITY_HIDDEN TemplateInstantiator 350 : public TreeTransform<TemplateInstantiator> 351 { 352 const MultiLevelTemplateArgumentList &TemplateArgs; 353 SourceLocation Loc; 354 DeclarationName Entity; 355 356 public: 357 typedef TreeTransform<TemplateInstantiator> inherited; 358 359 TemplateInstantiator(Sema &SemaRef, 360 const MultiLevelTemplateArgumentList &TemplateArgs, 361 SourceLocation Loc, 362 DeclarationName Entity) 363 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), 364 Entity(Entity) { } 365 366 /// \brief Determine whether the given type \p T has already been 367 /// transformed. 368 /// 369 /// For the purposes of template instantiation, a type has already been 370 /// transformed if it is NULL or if it is not dependent. 371 bool AlreadyTransformed(QualType T) { 372 return T.isNull() || !T->isDependentType(); 373 } 374 375 /// \brief Returns the location of the entity being instantiated, if known. 376 SourceLocation getBaseLocation() { return Loc; } 377 378 /// \brief Returns the name of the entity being instantiated, if any. 379 DeclarationName getBaseEntity() { return Entity; } 380 381 /// \brief Transform the given declaration by instantiating a reference to 382 /// this declaration. 383 Decl *TransformDecl(Decl *D); 384 385 /// \brief Transform the definition of the given declaration by 386 /// instantiating it. 387 Decl *TransformDefinition(Decl *D); 388 389 /// \brief Rebuild the exception declaration and register the declaration 390 /// as an instantiated local. 391 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, QualType T, 392 DeclaratorInfo *Declarator, 393 IdentifierInfo *Name, 394 SourceLocation Loc, SourceRange TypeRange); 395 396 Sema::OwningExprResult TransformDeclRefExpr(DeclRefExpr *E); 397 398 /// \brief Transforms a template type parameter type by performing 399 /// substitution of the corresponding template type argument. 400 QualType TransformTemplateTypeParmType(const TemplateTypeParmType *T); 401 }; 402} 403 404Decl *TemplateInstantiator::TransformDecl(Decl *D) { 405 if (!D) 406 return 0; 407 408 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) { 409 if (TTP->getDepth() < TemplateArgs.getNumLevels()) { 410 assert(TemplateArgs(TTP->getDepth(), TTP->getPosition()).getAsDecl() && 411 "Wrong kind of template template argument"); 412 return cast<TemplateDecl>(TemplateArgs(TTP->getDepth(), 413 TTP->getPosition()).getAsDecl()); 414 } 415 416 // If the corresponding template argument is NULL or non-existent, it's 417 // because we are performing instantiation from explicitly-specified 418 // template arguments in a function template, but there were some 419 // arguments left unspecified. 420 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(), 421 TTP->getPosition())) 422 return D; 423 424 // FIXME: Implement depth reduction of template template parameters 425 assert(false && 426 "Reducing depth of template template parameters is not yet implemented"); 427 } 428 429 return SemaRef.FindInstantiatedDecl(cast<NamedDecl>(D)); 430} 431 432Decl *TemplateInstantiator::TransformDefinition(Decl *D) { 433 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs); 434 if (!Inst) 435 return 0; 436 437 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); 438 return Inst; 439} 440 441VarDecl * 442TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, 443 QualType T, 444 DeclaratorInfo *Declarator, 445 IdentifierInfo *Name, 446 SourceLocation Loc, 447 SourceRange TypeRange) { 448 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, T, Declarator, 449 Name, Loc, TypeRange); 450 if (Var && !Var->isInvalidDecl()) 451 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); 452 return Var; 453} 454 455Sema::OwningExprResult 456TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { 457 // FIXME: Clean this up a bit 458 NamedDecl *D = E->getDecl(); 459 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) { 460 if (NTTP->getDepth() >= TemplateArgs.getNumLevels()) { 461 assert(false && "Cannot reduce non-type template parameter depth yet"); 462 return getSema().ExprError(); 463 } 464 465 // If the corresponding template argument is NULL or non-existent, it's 466 // because we are performing instantiation from explicitly-specified 467 // template arguments in a function template, but there were some 468 // arguments left unspecified. 469 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(), 470 NTTP->getPosition())) 471 return SemaRef.Owned(E->Retain()); 472 473 const TemplateArgument &Arg = TemplateArgs(NTTP->getDepth(), 474 NTTP->getPosition()); 475 476 // The template argument itself might be an expression, in which 477 // case we just return that expression. 478 if (Arg.getKind() == TemplateArgument::Expression) 479 return SemaRef.Owned(Arg.getAsExpr()->Retain()); 480 481 if (Arg.getKind() == TemplateArgument::Declaration) { 482 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl()); 483 484 VD = cast_or_null<ValueDecl>(getSema().FindInstantiatedDecl(VD)); 485 if (!VD) 486 return SemaRef.ExprError(); 487 488 return SemaRef.BuildDeclRefExpr(VD, VD->getType(), E->getLocation(), 489 /*FIXME:*/false, /*FIXME:*/false); 490 } 491 492 assert(Arg.getKind() == TemplateArgument::Integral); 493 QualType T = Arg.getIntegralType(); 494 if (T->isCharType() || T->isWideCharType()) 495 return SemaRef.Owned(new (SemaRef.Context) CharacterLiteral( 496 Arg.getAsIntegral()->getZExtValue(), 497 T->isWideCharType(), 498 T, 499 E->getSourceRange().getBegin())); 500 if (T->isBooleanType()) 501 return SemaRef.Owned(new (SemaRef.Context) CXXBoolLiteralExpr( 502 Arg.getAsIntegral()->getBoolValue(), 503 T, 504 E->getSourceRange().getBegin())); 505 506 assert(Arg.getAsIntegral()->getBitWidth() == SemaRef.Context.getIntWidth(T)); 507 return SemaRef.Owned(new (SemaRef.Context) IntegerLiteral( 508 *Arg.getAsIntegral(), 509 T, 510 E->getSourceRange().getBegin())); 511 } 512 513 NamedDecl *InstD = SemaRef.FindInstantiatedDecl(D); 514 if (!InstD) 515 return SemaRef.ExprError(); 516 517 // If we instantiated an UnresolvedUsingDecl and got back an UsingDecl, 518 // we need to get the underlying decl. 519 // FIXME: Is this correct? Maybe FindInstantiatedDecl should do this? 520 InstD = InstD->getUnderlyingDecl(); 521 522 // FIXME: nested-name-specifier for QualifiedDeclRefExpr 523 return SemaRef.BuildDeclarationNameExpr(E->getLocation(), InstD, 524 /*FIXME:*/false, 525 /*FIXME:*/0, 526 /*FIXME:*/false); 527} 528 529QualType 530TemplateInstantiator::TransformTemplateTypeParmType( 531 const TemplateTypeParmType *T) { 532 if (T->getDepth() < TemplateArgs.getNumLevels()) { 533 // Replace the template type parameter with its corresponding 534 // template argument. 535 536 // If the corresponding template argument is NULL or doesn't exist, it's 537 // because we are performing instantiation from explicitly-specified 538 // template arguments in a function template class, but there were some 539 // arguments left unspecified. 540 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) 541 return QualType(T, 0); 542 543 assert(TemplateArgs(T->getDepth(), T->getIndex()).getKind() 544 == TemplateArgument::Type && 545 "Template argument kind mismatch"); 546 547 return TemplateArgs(T->getDepth(), T->getIndex()).getAsType(); 548 } 549 550 // The template type parameter comes from an inner template (e.g., 551 // the template parameter list of a member template inside the 552 // template we are instantiating). Create a new template type 553 // parameter with the template "level" reduced by one. 554 return getSema().Context.getTemplateTypeParmType( 555 T->getDepth() - TemplateArgs.getNumLevels(), 556 T->getIndex(), 557 T->isParameterPack(), 558 T->getName()); 559} 560 561/// \brief Perform substitution on the type T with a given set of template 562/// arguments. 563/// 564/// This routine substitutes the given template arguments into the 565/// type T and produces the instantiated type. 566/// 567/// \param T the type into which the template arguments will be 568/// substituted. If this type is not dependent, it will be returned 569/// immediately. 570/// 571/// \param TemplateArgs the template arguments that will be 572/// substituted for the top-level template parameters within T. 573/// 574/// \param Loc the location in the source code where this substitution 575/// is being performed. It will typically be the location of the 576/// declarator (if we're instantiating the type of some declaration) 577/// or the location of the type in the source code (if, e.g., we're 578/// instantiating the type of a cast expression). 579/// 580/// \param Entity the name of the entity associated with a declaration 581/// being instantiated (if any). May be empty to indicate that there 582/// is no such entity (if, e.g., this is a type that occurs as part of 583/// a cast expression) or that the entity has no name (e.g., an 584/// unnamed function parameter). 585/// 586/// \returns If the instantiation succeeds, the instantiated 587/// type. Otherwise, produces diagnostics and returns a NULL type. 588QualType Sema::SubstType(QualType T, 589 const MultiLevelTemplateArgumentList &TemplateArgs, 590 SourceLocation Loc, DeclarationName Entity) { 591 assert(!ActiveTemplateInstantiations.empty() && 592 "Cannot perform an instantiation without some context on the " 593 "instantiation stack"); 594 595 // If T is not a dependent type, there is nothing to do. 596 if (!T->isDependentType()) 597 return T; 598 599 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); 600 return Instantiator.TransformType(T); 601} 602 603/// \brief Perform substitution on the base class specifiers of the 604/// given class template specialization. 605/// 606/// Produces a diagnostic and returns true on error, returns false and 607/// attaches the instantiated base classes to the class template 608/// specialization if successful. 609bool 610Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 611 CXXRecordDecl *Pattern, 612 const MultiLevelTemplateArgumentList &TemplateArgs) { 613 bool Invalid = false; 614 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; 615 for (ClassTemplateSpecializationDecl::base_class_iterator 616 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end(); 617 Base != BaseEnd; ++Base) { 618 if (!Base->getType()->isDependentType()) { 619 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base)); 620 continue; 621 } 622 623 QualType BaseType = SubstType(Base->getType(), 624 TemplateArgs, 625 Base->getSourceRange().getBegin(), 626 DeclarationName()); 627 if (BaseType.isNull()) { 628 Invalid = true; 629 continue; 630 } 631 632 if (CXXBaseSpecifier *InstantiatedBase 633 = CheckBaseSpecifier(Instantiation, 634 Base->getSourceRange(), 635 Base->isVirtual(), 636 Base->getAccessSpecifierAsWritten(), 637 BaseType, 638 /*FIXME: Not totally accurate */ 639 Base->getSourceRange().getBegin())) 640 InstantiatedBases.push_back(InstantiatedBase); 641 else 642 Invalid = true; 643 } 644 645 if (!Invalid && 646 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(), 647 InstantiatedBases.size())) 648 Invalid = true; 649 650 return Invalid; 651} 652 653/// \brief Instantiate the definition of a class from a given pattern. 654/// 655/// \param PointOfInstantiation The point of instantiation within the 656/// source code. 657/// 658/// \param Instantiation is the declaration whose definition is being 659/// instantiated. This will be either a class template specialization 660/// or a member class of a class template specialization. 661/// 662/// \param Pattern is the pattern from which the instantiation 663/// occurs. This will be either the declaration of a class template or 664/// the declaration of a member class of a class template. 665/// 666/// \param TemplateArgs The template arguments to be substituted into 667/// the pattern. 668/// 669/// \param TSK the kind of implicit or explicit instantiation to perform. 670/// 671/// \param Complain whether to complain if the class cannot be instantiated due 672/// to the lack of a definition. 673/// 674/// \returns true if an error occurred, false otherwise. 675bool 676Sema::InstantiateClass(SourceLocation PointOfInstantiation, 677 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 678 const MultiLevelTemplateArgumentList &TemplateArgs, 679 TemplateSpecializationKind TSK, 680 bool Complain) { 681 bool Invalid = false; 682 683 CXXRecordDecl *PatternDef 684 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context)); 685 if (!PatternDef) { 686 if (!Complain) { 687 // Say nothing 688 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) { 689 Diag(PointOfInstantiation, 690 diag::err_implicit_instantiate_member_undefined) 691 << Context.getTypeDeclType(Instantiation); 692 Diag(Pattern->getLocation(), diag::note_member_of_template_here); 693 } else { 694 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 695 << (TSK != TSK_ImplicitInstantiation) 696 << Context.getTypeDeclType(Instantiation); 697 Diag(Pattern->getLocation(), diag::note_template_decl_here); 698 } 699 return true; 700 } 701 Pattern = PatternDef; 702 703 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); 704 if (Inst) 705 return true; 706 707 // Enter the scope of this instantiation. We don't use 708 // PushDeclContext because we don't have a scope. 709 DeclContext *PreviousContext = CurContext; 710 CurContext = Instantiation; 711 712 // Start the definition of this instantiation. 713 Instantiation->startDefinition(); 714 715 // Do substitution on the base class specifiers. 716 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) 717 Invalid = true; 718 719 llvm::SmallVector<DeclPtrTy, 4> Fields; 720 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(), 721 MemberEnd = Pattern->decls_end(); 722 Member != MemberEnd; ++Member) { 723 Decl *NewMember = SubstDecl(*Member, Instantiation, TemplateArgs); 724 if (NewMember) { 725 if (NewMember->isInvalidDecl()) 726 Invalid = true; 727 else if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) 728 Fields.push_back(DeclPtrTy::make(Field)); 729 else if (UsingDecl *UD = dyn_cast<UsingDecl>(NewMember)) 730 Instantiation->addDecl(UD); 731 } else { 732 // FIXME: Eventually, a NULL return will mean that one of the 733 // instantiations was a semantic disaster, and we'll want to set Invalid = 734 // true. For now, we expect to skip some members that we can't yet handle. 735 } 736 } 737 738 // Finish checking fields. 739 ActOnFields(0, Instantiation->getLocation(), DeclPtrTy::make(Instantiation), 740 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(), 741 0); 742 743 // Add any implicitly-declared members that we might need. 744 AddImplicitlyDeclaredMembersToClass(Instantiation); 745 746 // Exit the scope of this instantiation. 747 CurContext = PreviousContext; 748 749 if (!Invalid) 750 Consumer.HandleTagDeclDefinition(Instantiation); 751 752 // If this is an explicit instantiation, instantiate our members, too. 753 if (!Invalid && TSK != TSK_ImplicitInstantiation) { 754 Inst.Clear(); 755 InstantiateClassMembers(PointOfInstantiation, Instantiation, TemplateArgs, 756 TSK); 757 } 758 759 return Invalid; 760} 761 762bool 763Sema::InstantiateClassTemplateSpecialization( 764 ClassTemplateSpecializationDecl *ClassTemplateSpec, 765 TemplateSpecializationKind TSK, 766 bool Complain) { 767 // Perform the actual instantiation on the canonical declaration. 768 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( 769 ClassTemplateSpec->getCanonicalDecl()); 770 771 // We can only instantiate something that hasn't already been 772 // instantiated or specialized. Fail without any diagnostics: our 773 // caller will provide an error message. 774 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) 775 return true; 776 777 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); 778 CXXRecordDecl *Pattern = 0; 779 780 // C++ [temp.class.spec.match]p1: 781 // When a class template is used in a context that requires an 782 // instantiation of the class, it is necessary to determine 783 // whether the instantiation is to be generated using the primary 784 // template or one of the partial specializations. This is done by 785 // matching the template arguments of the class template 786 // specialization with the template argument lists of the partial 787 // specializations. 788 typedef std::pair<ClassTemplatePartialSpecializationDecl *, 789 TemplateArgumentList *> MatchResult; 790 llvm::SmallVector<MatchResult, 4> Matched; 791 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 792 Partial = Template->getPartialSpecializations().begin(), 793 PartialEnd = Template->getPartialSpecializations().end(); 794 Partial != PartialEnd; 795 ++Partial) { 796 TemplateDeductionInfo Info(Context); 797 if (TemplateDeductionResult Result 798 = DeduceTemplateArguments(&*Partial, 799 ClassTemplateSpec->getTemplateArgs(), 800 Info)) { 801 // FIXME: Store the failed-deduction information for use in 802 // diagnostics, later. 803 (void)Result; 804 } else { 805 Matched.push_back(std::make_pair(&*Partial, Info.take())); 806 } 807 } 808 809 if (Matched.size() == 1) { 810 // -- If exactly one matching specialization is found, the 811 // instantiation is generated from that specialization. 812 Pattern = Matched[0].first; 813 ClassTemplateSpec->setInstantiationOf(Matched[0].first, Matched[0].second); 814 } else if (Matched.size() > 1) { 815 // -- If more than one matching specialization is found, the 816 // partial order rules (14.5.4.2) are used to determine 817 // whether one of the specializations is more specialized 818 // than the others. If none of the specializations is more 819 // specialized than all of the other matching 820 // specializations, then the use of the class template is 821 // ambiguous and the program is ill-formed. 822 // FIXME: Implement partial ordering of class template partial 823 // specializations. 824 Diag(ClassTemplateSpec->getLocation(), 825 diag::unsup_template_partial_spec_ordering); 826 827 // FIXME: Temporary hack to fall back to the primary template 828 ClassTemplateDecl *OrigTemplate = Template; 829 while (OrigTemplate->getInstantiatedFromMemberTemplate()) 830 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate(); 831 832 Pattern = OrigTemplate->getTemplatedDecl(); 833 } else { 834 // -- If no matches are found, the instantiation is generated 835 // from the primary template. 836 ClassTemplateDecl *OrigTemplate = Template; 837 while (OrigTemplate->getInstantiatedFromMemberTemplate()) 838 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate(); 839 840 Pattern = OrigTemplate->getTemplatedDecl(); 841 } 842 843 // Note that this is an instantiation. 844 ClassTemplateSpec->setSpecializationKind(TSK); 845 846 bool Result = InstantiateClass(ClassTemplateSpec->getLocation(), 847 ClassTemplateSpec, Pattern, 848 getTemplateInstantiationArgs(ClassTemplateSpec), 849 TSK, 850 Complain); 851 852 for (unsigned I = 0, N = Matched.size(); I != N; ++I) { 853 // FIXME: Implement TemplateArgumentList::Destroy! 854 // if (Matched[I].first != Pattern) 855 // Matched[I].second->Destroy(Context); 856 } 857 858 return Result; 859} 860 861/// \brief Instantiates the definitions of all of the member 862/// of the given class, which is an instantiation of a class template 863/// or a member class of a template. 864void 865Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, 866 CXXRecordDecl *Instantiation, 867 const MultiLevelTemplateArgumentList &TemplateArgs, 868 TemplateSpecializationKind TSK) { 869 // FIXME: extern templates 870 for (DeclContext::decl_iterator D = Instantiation->decls_begin(), 871 DEnd = Instantiation->decls_end(); 872 D != DEnd; ++D) { 873 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) { 874 if (!Function->getBody()) 875 InstantiateFunctionDefinition(PointOfInstantiation, Function); 876 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) { 877 if (Var->isStaticDataMember()) 878 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var); 879 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) { 880 if (!Record->isInjectedClassName() && !Record->getDefinition(Context)) { 881 assert(Record->getInstantiatedFromMemberClass() && 882 "Missing instantiated-from-template information"); 883 InstantiateClass(PointOfInstantiation, Record, 884 Record->getInstantiatedFromMemberClass(), 885 TemplateArgs, 886 TSK); 887 } 888 } 889 } 890} 891 892/// \brief Instantiate the definitions of all of the members of the 893/// given class template specialization, which was named as part of an 894/// explicit instantiation. 895void 896Sema::InstantiateClassTemplateSpecializationMembers( 897 SourceLocation PointOfInstantiation, 898 ClassTemplateSpecializationDecl *ClassTemplateSpec, 899 TemplateSpecializationKind TSK) { 900 // C++0x [temp.explicit]p7: 901 // An explicit instantiation that names a class template 902 // specialization is an explicit instantion of the same kind 903 // (declaration or definition) of each of its members (not 904 // including members inherited from base classes) that has not 905 // been previously explicitly specialized in the translation unit 906 // containing the explicit instantiation, except as described 907 // below. 908 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec, 909 getTemplateInstantiationArgs(ClassTemplateSpec), 910 TSK); 911} 912 913Sema::OwningStmtResult 914Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { 915 if (!S) 916 return Owned(S); 917 918 TemplateInstantiator Instantiator(*this, TemplateArgs, 919 SourceLocation(), 920 DeclarationName()); 921 return Instantiator.TransformStmt(S); 922} 923 924Sema::OwningExprResult 925Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { 926 if (!E) 927 return Owned(E); 928 929 TemplateInstantiator Instantiator(*this, TemplateArgs, 930 SourceLocation(), 931 DeclarationName()); 932 return Instantiator.TransformExpr(E); 933} 934 935/// \brief Do template substitution on a nested-name-specifier. 936NestedNameSpecifier * 937Sema::SubstNestedNameSpecifier(NestedNameSpecifier *NNS, 938 SourceRange Range, 939 const MultiLevelTemplateArgumentList &TemplateArgs) { 940 TemplateInstantiator Instantiator(*this, TemplateArgs, Range.getBegin(), 941 DeclarationName()); 942 return Instantiator.TransformNestedNameSpecifier(NNS, Range); 943} 944 945TemplateName 946Sema::SubstTemplateName(TemplateName Name, SourceLocation Loc, 947 const MultiLevelTemplateArgumentList &TemplateArgs) { 948 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, 949 DeclarationName()); 950 return Instantiator.TransformTemplateName(Name); 951} 952 953TemplateArgument Sema::Subst(TemplateArgument Arg, 954 const MultiLevelTemplateArgumentList &TemplateArgs) { 955 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), 956 DeclarationName()); 957 return Instantiator.TransformTemplateArgument(Arg); 958} 959