SemaTemplateInstantiateDecl.cpp revision 659107b190503e2588bec81f92af1d5f745f9580
1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations. 10// 11//===----------------------------------------------------------------------===/ 12#include "Sema.h" 13#include "Lookup.h" 14#include "clang/AST/ASTConsumer.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/DeclTemplate.h" 17#include "clang/AST/DeclVisitor.h" 18#include "clang/AST/DependentDiagnostic.h" 19#include "clang/AST/Expr.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/AST/TypeLoc.h" 22#include "clang/Basic/PrettyStackTrace.h" 23#include "clang/Lex/Preprocessor.h" 24 25using namespace clang; 26 27namespace { 28 class TemplateDeclInstantiator 29 : public DeclVisitor<TemplateDeclInstantiator, Decl *> { 30 Sema &SemaRef; 31 DeclContext *Owner; 32 const MultiLevelTemplateArgumentList &TemplateArgs; 33 34 void InstantiateAttrs(Decl *Tmpl, Decl *New); 35 36 public: 37 typedef Sema::OwningExprResult OwningExprResult; 38 39 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, 40 const MultiLevelTemplateArgumentList &TemplateArgs) 41 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { } 42 43 // FIXME: Once we get closer to completion, replace these manually-written 44 // declarations with automatically-generated ones from 45 // clang/AST/DeclNodes.def. 46 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); 47 Decl *VisitNamespaceDecl(NamespaceDecl *D); 48 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 49 Decl *VisitTypedefDecl(TypedefDecl *D); 50 Decl *VisitVarDecl(VarDecl *D); 51 Decl *VisitFieldDecl(FieldDecl *D); 52 Decl *VisitStaticAssertDecl(StaticAssertDecl *D); 53 Decl *VisitEnumDecl(EnumDecl *D); 54 Decl *VisitEnumConstantDecl(EnumConstantDecl *D); 55 Decl *VisitFriendDecl(FriendDecl *D); 56 Decl *VisitFunctionDecl(FunctionDecl *D, 57 TemplateParameterList *TemplateParams = 0); 58 Decl *VisitCXXRecordDecl(CXXRecordDecl *D); 59 Decl *VisitCXXMethodDecl(CXXMethodDecl *D, 60 TemplateParameterList *TemplateParams = 0); 61 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 62 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 63 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 64 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 65 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D); 66 Decl *VisitClassTemplatePartialSpecializationDecl( 67 ClassTemplatePartialSpecializationDecl *D); 68 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 69 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 70 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 71 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 72 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 73 Decl *VisitUsingDecl(UsingDecl *D); 74 Decl *VisitUsingShadowDecl(UsingShadowDecl *D); 75 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 76 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 77 78 // Base case. FIXME: Remove once we can instantiate everything. 79 Decl *VisitDecl(Decl *D) { 80 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 81 Diagnostic::Error, 82 "cannot instantiate %0 yet"); 83 SemaRef.Diag(D->getLocation(), DiagID) 84 << D->getDeclKindName(); 85 86 return 0; 87 } 88 89 const LangOptions &getLangOptions() { 90 return SemaRef.getLangOptions(); 91 } 92 93 // Helper functions for instantiating methods. 94 TypeSourceInfo *SubstFunctionType(FunctionDecl *D, 95 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 96 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl); 97 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 98 99 TemplateParameterList * 100 SubstTemplateParams(TemplateParameterList *List); 101 102 bool SubstQualifier(const DeclaratorDecl *OldDecl, 103 DeclaratorDecl *NewDecl); 104 bool SubstQualifier(const TagDecl *OldDecl, 105 TagDecl *NewDecl); 106 107 bool InstantiateClassTemplatePartialSpecialization( 108 ClassTemplateDecl *ClassTemplate, 109 ClassTemplatePartialSpecializationDecl *PartialSpec); 110 }; 111} 112 113bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 114 DeclaratorDecl *NewDecl) { 115 NestedNameSpecifier *OldQual = OldDecl->getQualifier(); 116 if (!OldQual) return false; 117 118 SourceRange QualRange = OldDecl->getQualifierRange(); 119 120 NestedNameSpecifier *NewQual 121 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs); 122 if (!NewQual) 123 return true; 124 125 NewDecl->setQualifierInfo(NewQual, QualRange); 126 return false; 127} 128 129bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 130 TagDecl *NewDecl) { 131 NestedNameSpecifier *OldQual = OldDecl->getQualifier(); 132 if (!OldQual) return false; 133 134 SourceRange QualRange = OldDecl->getQualifierRange(); 135 136 NestedNameSpecifier *NewQual 137 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs); 138 if (!NewQual) 139 return true; 140 141 NewDecl->setQualifierInfo(NewQual, QualRange); 142 return false; 143} 144 145// FIXME: Is this too simple? 146void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) { 147 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr; 148 TmplAttr = TmplAttr->getNext()) { 149 150 // FIXME: Is cloning correct for all attributes? 151 Attr *NewAttr = TmplAttr->clone(SemaRef.Context); 152 153 New->addAttr(NewAttr); 154 } 155} 156 157Decl * 158TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 159 assert(false && "Translation units cannot be instantiated"); 160 return D; 161} 162 163Decl * 164TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 165 assert(false && "Namespaces cannot be instantiated"); 166 return D; 167} 168 169Decl * 170TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 171 NamespaceAliasDecl *Inst 172 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 173 D->getNamespaceLoc(), 174 D->getAliasLoc(), 175 D->getNamespace()->getIdentifier(), 176 D->getQualifierRange(), 177 D->getQualifier(), 178 D->getTargetNameLoc(), 179 D->getNamespace()); 180 Owner->addDecl(Inst); 181 return Inst; 182} 183 184Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 185 bool Invalid = false; 186 TypeSourceInfo *DI = D->getTypeSourceInfo(); 187 if (DI->getType()->isDependentType()) { 188 DI = SemaRef.SubstType(DI, TemplateArgs, 189 D->getLocation(), D->getDeclName()); 190 if (!DI) { 191 Invalid = true; 192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 193 } 194 } else { 195 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 196 } 197 198 // Create the new typedef 199 TypedefDecl *Typedef 200 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 201 D->getIdentifier(), DI); 202 if (Invalid) 203 Typedef->setInvalidDecl(); 204 205 if (const TagType *TT = DI->getType()->getAs<TagType>()) { 206 TagDecl *TD = TT->getDecl(); 207 208 // If the TagDecl that the TypedefDecl points to is an anonymous decl 209 // keep track of the TypedefDecl. 210 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl()) 211 TD->setTypedefForAnonDecl(Typedef); 212 } 213 214 if (TypedefDecl *Prev = D->getPreviousDeclaration()) { 215 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 216 TemplateArgs); 217 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev)); 218 } 219 220 InstantiateAttrs(D, Typedef); 221 222 Typedef->setAccess(D->getAccess()); 223 Owner->addDecl(Typedef); 224 225 return Typedef; 226} 227 228/// \brief Instantiate the arguments provided as part of initialization. 229/// 230/// \returns true if an error occurred, false otherwise. 231static bool InstantiateInitializationArguments(Sema &SemaRef, 232 Expr **Args, unsigned NumArgs, 233 const MultiLevelTemplateArgumentList &TemplateArgs, 234 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs, 235 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) { 236 for (unsigned I = 0; I != NumArgs; ++I) { 237 // When we hit the first defaulted argument, break out of the loop: 238 // we don't pass those default arguments on. 239 if (Args[I]->isDefaultArgument()) 240 break; 241 242 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs); 243 if (Arg.isInvalid()) 244 return true; 245 246 Expr *ArgExpr = (Expr *)Arg.get(); 247 InitArgs.push_back(Arg.release()); 248 249 // FIXME: We're faking all of the comma locations. Do we need them? 250 FakeCommaLocs.push_back( 251 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd())); 252 } 253 254 return false; 255} 256 257/// \brief Instantiate an initializer, breaking it into separate 258/// initialization arguments. 259/// 260/// \param S The semantic analysis object. 261/// 262/// \param Init The initializer to instantiate. 263/// 264/// \param TemplateArgs Template arguments to be substituted into the 265/// initializer. 266/// 267/// \param NewArgs Will be filled in with the instantiation arguments. 268/// 269/// \returns true if an error occurred, false otherwise 270static bool InstantiateInitializer(Sema &S, Expr *Init, 271 const MultiLevelTemplateArgumentList &TemplateArgs, 272 SourceLocation &LParenLoc, 273 llvm::SmallVector<SourceLocation, 4> &CommaLocs, 274 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs, 275 SourceLocation &RParenLoc) { 276 NewArgs.clear(); 277 LParenLoc = SourceLocation(); 278 RParenLoc = SourceLocation(); 279 280 if (!Init) 281 return false; 282 283 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init)) 284 Init = ExprTemp->getSubExpr(); 285 286 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init)) 287 Init = Binder->getSubExpr(); 288 289 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init)) 290 Init = ICE->getSubExprAsWritten(); 291 292 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 293 LParenLoc = ParenList->getLParenLoc(); 294 RParenLoc = ParenList->getRParenLoc(); 295 return InstantiateInitializationArguments(S, ParenList->getExprs(), 296 ParenList->getNumExprs(), 297 TemplateArgs, CommaLocs, 298 NewArgs); 299 } 300 301 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) { 302 if (!isa<CXXTemporaryObjectExpr>(Construct)) { 303 if (InstantiateInitializationArguments(S, 304 Construct->getArgs(), 305 Construct->getNumArgs(), 306 TemplateArgs, 307 CommaLocs, NewArgs)) 308 return true; 309 310 // FIXME: Fake locations! 311 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart()); 312 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back(); 313 return false; 314 } 315 } 316 317 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs); 318 if (Result.isInvalid()) 319 return true; 320 321 NewArgs.push_back(Result.takeAs<Expr>()); 322 return false; 323} 324 325Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 326 // If this is the variable for an anonymous struct or union, 327 // instantiate the anonymous struct/union type first. 328 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 329 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 330 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 331 return 0; 332 333 // Do substitution on the type of the declaration 334 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 335 TemplateArgs, 336 D->getTypeSpecStartLoc(), 337 D->getDeclName()); 338 if (!DI) 339 return 0; 340 341 // Build the instantiated declaration 342 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 343 D->getLocation(), D->getIdentifier(), 344 DI->getType(), DI, 345 D->getStorageClass(), 346 D->getStorageClassAsWritten()); 347 Var->setThreadSpecified(D->isThreadSpecified()); 348 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 349 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 350 351 // Substitute the nested name specifier, if any. 352 if (SubstQualifier(D, Var)) 353 return 0; 354 355 // If we are instantiating a static data member defined 356 // out-of-line, the instantiation will have the same lexical 357 // context (which will be a namespace scope) as the template. 358 if (D->isOutOfLine()) 359 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 360 361 Var->setAccess(D->getAccess()); 362 Var->setUsed(D->isUsed()); 363 364 // FIXME: In theory, we could have a previous declaration for variables that 365 // are not static data members. 366 bool Redeclaration = false; 367 // FIXME: having to fake up a LookupResult is dumb. 368 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(), 369 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 370 if (D->isStaticDataMember()) 371 SemaRef.LookupQualifiedName(Previous, Owner, false); 372 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration); 373 374 if (D->isOutOfLine()) { 375 D->getLexicalDeclContext()->addDecl(Var); 376 Owner->makeDeclVisibleInContext(Var); 377 } else { 378 Owner->addDecl(Var); 379 380 if (Owner->isFunctionOrMethod()) 381 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var); 382 } 383 384 // Link instantiations of static data members back to the template from 385 // which they were instantiated. 386 if (Var->isStaticDataMember()) 387 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 388 TSK_ImplicitInstantiation); 389 390 if (Var->getAnyInitializer()) { 391 // We already have an initializer in the class. 392 } else if (D->getInit()) { 393 if (Var->isStaticDataMember() && !D->isOutOfLine()) 394 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated); 395 else 396 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 397 398 // Instantiate the initializer. 399 SourceLocation LParenLoc, RParenLoc; 400 llvm::SmallVector<SourceLocation, 4> CommaLocs; 401 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef); 402 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc, 403 CommaLocs, InitArgs, RParenLoc)) { 404 // Attach the initializer to the declaration. 405 if (D->hasCXXDirectInitializer()) { 406 // Add the direct initializer to the declaration. 407 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var), 408 LParenLoc, 409 move_arg(InitArgs), 410 CommaLocs.data(), 411 RParenLoc); 412 } else if (InitArgs.size() == 1) { 413 Expr *Init = (Expr*)(InitArgs.take()[0]); 414 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), 415 SemaRef.Owned(Init), 416 false); 417 } else { 418 assert(InitArgs.size() == 0); 419 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 420 } 421 } else { 422 // FIXME: Not too happy about invalidating the declaration 423 // because of a bogus initializer. 424 Var->setInvalidDecl(); 425 } 426 427 SemaRef.PopExpressionEvaluationContext(); 428 } else if (!Var->isStaticDataMember() || Var->isOutOfLine()) 429 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 430 431 // Diagnose unused local variables. 432 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed()) 433 SemaRef.DiagnoseUnusedDecl(Var); 434 435 return Var; 436} 437 438Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 439 bool Invalid = false; 440 TypeSourceInfo *DI = D->getTypeSourceInfo(); 441 if (DI->getType()->isDependentType()) { 442 DI = SemaRef.SubstType(DI, TemplateArgs, 443 D->getLocation(), D->getDeclName()); 444 if (!DI) { 445 DI = D->getTypeSourceInfo(); 446 Invalid = true; 447 } else if (DI->getType()->isFunctionType()) { 448 // C++ [temp.arg.type]p3: 449 // If a declaration acquires a function type through a type 450 // dependent on a template-parameter and this causes a 451 // declaration that does not use the syntactic form of a 452 // function declarator to have function type, the program is 453 // ill-formed. 454 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 455 << DI->getType(); 456 Invalid = true; 457 } 458 } else { 459 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 460 } 461 462 Expr *BitWidth = D->getBitWidth(); 463 if (Invalid) 464 BitWidth = 0; 465 else if (BitWidth) { 466 // The bit-width expression is not potentially evaluated. 467 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 468 469 OwningExprResult InstantiatedBitWidth 470 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 471 if (InstantiatedBitWidth.isInvalid()) { 472 Invalid = true; 473 BitWidth = 0; 474 } else 475 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 476 } 477 478 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 479 DI->getType(), DI, 480 cast<RecordDecl>(Owner), 481 D->getLocation(), 482 D->isMutable(), 483 BitWidth, 484 D->getTypeSpecStartLoc(), 485 D->getAccess(), 486 0); 487 if (!Field) { 488 cast<Decl>(Owner)->setInvalidDecl(); 489 return 0; 490 } 491 492 InstantiateAttrs(D, Field); 493 494 if (Invalid) 495 Field->setInvalidDecl(); 496 497 if (!Field->getDeclName()) { 498 // Keep track of where this decl came from. 499 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 500 } 501 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 502 if (Parent->isAnonymousStructOrUnion() && 503 Parent->getLookupContext()->isFunctionOrMethod()) 504 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 505 } 506 507 Field->setImplicit(D->isImplicit()); 508 Field->setAccess(D->getAccess()); 509 Owner->addDecl(Field); 510 511 return Field; 512} 513 514Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 515 // Handle friend type expressions by simply substituting template 516 // parameters into the pattern type and checking the result. 517 if (TypeSourceInfo *Ty = D->getFriendType()) { 518 TypeSourceInfo *InstTy = 519 SemaRef.SubstType(Ty, TemplateArgs, 520 D->getLocation(), DeclarationName()); 521 if (!InstTy) 522 return 0; 523 524 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy); 525 if (!FD) 526 return 0; 527 528 FD->setAccess(AS_public); 529 Owner->addDecl(FD); 530 return FD; 531 } 532 533 NamedDecl *ND = D->getFriendDecl(); 534 assert(ND && "friend decl must be a decl or a type!"); 535 536 // All of the Visit implementations for the various potential friend 537 // declarations have to be carefully written to work for friend 538 // objects, with the most important detail being that the target 539 // decl should almost certainly not be placed in Owner. 540 Decl *NewND = Visit(ND); 541 if (!NewND) return 0; 542 543 FriendDecl *FD = 544 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 545 cast<NamedDecl>(NewND), D->getFriendLoc()); 546 FD->setAccess(AS_public); 547 Owner->addDecl(FD); 548 return FD; 549} 550 551Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 552 Expr *AssertExpr = D->getAssertExpr(); 553 554 // The expression in a static assertion is not potentially evaluated. 555 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 556 557 OwningExprResult InstantiatedAssertExpr 558 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 559 if (InstantiatedAssertExpr.isInvalid()) 560 return 0; 561 562 OwningExprResult Message(SemaRef, D->getMessage()); 563 D->getMessage()->Retain(); 564 Decl *StaticAssert 565 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 566 move(InstantiatedAssertExpr), 567 move(Message)).getAs<Decl>(); 568 return StaticAssert; 569} 570 571Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 572 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 573 D->getLocation(), D->getIdentifier(), 574 D->getTagKeywordLoc(), 575 /*PrevDecl=*/0); 576 Enum->setInstantiationOfMemberEnum(D); 577 Enum->setAccess(D->getAccess()); 578 if (SubstQualifier(D, Enum)) return 0; 579 Owner->addDecl(Enum); 580 Enum->startDefinition(); 581 582 if (D->getDeclContext()->isFunctionOrMethod()) 583 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 584 585 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators; 586 587 EnumConstantDecl *LastEnumConst = 0; 588 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 589 ECEnd = D->enumerator_end(); 590 EC != ECEnd; ++EC) { 591 // The specified value for the enumerator. 592 OwningExprResult Value = SemaRef.Owned((Expr *)0); 593 if (Expr *UninstValue = EC->getInitExpr()) { 594 // The enumerator's value expression is not potentially evaluated. 595 EnterExpressionEvaluationContext Unevaluated(SemaRef, 596 Action::Unevaluated); 597 598 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 599 } 600 601 // Drop the initial value and continue. 602 bool isInvalid = false; 603 if (Value.isInvalid()) { 604 Value = SemaRef.Owned((Expr *)0); 605 isInvalid = true; 606 } 607 608 EnumConstantDecl *EnumConst 609 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 610 EC->getLocation(), EC->getIdentifier(), 611 move(Value)); 612 613 if (isInvalid) { 614 if (EnumConst) 615 EnumConst->setInvalidDecl(); 616 Enum->setInvalidDecl(); 617 } 618 619 if (EnumConst) { 620 EnumConst->setAccess(Enum->getAccess()); 621 Enum->addDecl(EnumConst); 622 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 623 LastEnumConst = EnumConst; 624 625 if (D->getDeclContext()->isFunctionOrMethod()) { 626 // If the enumeration is within a function or method, record the enum 627 // constant as a local. 628 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst); 629 } 630 } 631 } 632 633 // FIXME: Fixup LBraceLoc and RBraceLoc 634 // FIXME: Empty Scope and AttributeList (required to handle attribute packed). 635 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 636 Sema::DeclPtrTy::make(Enum), 637 &Enumerators[0], Enumerators.size(), 638 0, 0); 639 640 return Enum; 641} 642 643Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 644 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 645 return 0; 646} 647 648Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 649 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 650 651 // Create a local instantiation scope for this class template, which 652 // will contain the instantiations of the template parameters. 653 Sema::LocalInstantiationScope Scope(SemaRef); 654 TemplateParameterList *TempParams = D->getTemplateParameters(); 655 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 656 if (!InstParams) 657 return NULL; 658 659 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 660 661 // Instantiate the qualifier. We have to do this first in case 662 // we're a friend declaration, because if we are then we need to put 663 // the new declaration in the appropriate context. 664 NestedNameSpecifier *Qualifier = Pattern->getQualifier(); 665 if (Qualifier) { 666 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 667 Pattern->getQualifierRange(), 668 TemplateArgs); 669 if (!Qualifier) return 0; 670 } 671 672 CXXRecordDecl *PrevDecl = 0; 673 ClassTemplateDecl *PrevClassTemplate = 0; 674 675 // If this isn't a friend, then it's a member template, in which 676 // case we just want to build the instantiation in the 677 // specialization. If it is a friend, we want to build it in 678 // the appropriate context. 679 DeclContext *DC = Owner; 680 if (isFriend) { 681 if (Qualifier) { 682 CXXScopeSpec SS; 683 SS.setScopeRep(Qualifier); 684 SS.setRange(Pattern->getQualifierRange()); 685 DC = SemaRef.computeDeclContext(SS); 686 if (!DC) return 0; 687 } else { 688 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 689 Pattern->getDeclContext(), 690 TemplateArgs); 691 } 692 693 // Look for a previous declaration of the template in the owning 694 // context. 695 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 696 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 697 SemaRef.LookupQualifiedName(R, DC); 698 699 if (R.isSingleResult()) { 700 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 701 if (PrevClassTemplate) 702 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 703 } 704 705 if (!PrevClassTemplate && Qualifier) { 706 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 707 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 708 << Pattern->getQualifierRange(); 709 return 0; 710 } 711 712 bool AdoptedPreviousTemplateParams = false; 713 if (PrevClassTemplate) { 714 bool Complain = true; 715 716 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 717 // template for struct std::tr1::__detail::_Map_base, where the 718 // template parameters of the friend declaration don't match the 719 // template parameters of the original declaration. In this one 720 // case, we don't complain about the ill-formed friend 721 // declaration. 722 if (isFriend && Pattern->getIdentifier() && 723 Pattern->getIdentifier()->isStr("_Map_base") && 724 DC->isNamespace() && 725 cast<NamespaceDecl>(DC)->getIdentifier() && 726 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 727 DeclContext *DCParent = DC->getParent(); 728 if (DCParent->isNamespace() && 729 cast<NamespaceDecl>(DCParent)->getIdentifier() && 730 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 731 DeclContext *DCParent2 = DCParent->getParent(); 732 if (DCParent2->isNamespace() && 733 cast<NamespaceDecl>(DCParent2)->getIdentifier() && 734 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") && 735 DCParent2->getParent()->isTranslationUnit()) 736 Complain = false; 737 } 738 } 739 740 TemplateParameterList *PrevParams 741 = PrevClassTemplate->getTemplateParameters(); 742 743 // Make sure the parameter lists match. 744 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 745 Complain, 746 Sema::TPL_TemplateMatch)) { 747 if (Complain) 748 return 0; 749 750 AdoptedPreviousTemplateParams = true; 751 InstParams = PrevParams; 752 } 753 754 // Do some additional validation, then merge default arguments 755 // from the existing declarations. 756 if (!AdoptedPreviousTemplateParams && 757 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 758 Sema::TPC_ClassTemplate)) 759 return 0; 760 } 761 } 762 763 CXXRecordDecl *RecordInst 764 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 765 Pattern->getLocation(), Pattern->getIdentifier(), 766 Pattern->getTagKeywordLoc(), PrevDecl, 767 /*DelayTypeCreation=*/true); 768 769 if (Qualifier) 770 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange()); 771 772 ClassTemplateDecl *Inst 773 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 774 D->getIdentifier(), InstParams, RecordInst, 775 PrevClassTemplate); 776 RecordInst->setDescribedClassTemplate(Inst); 777 778 if (isFriend) { 779 if (PrevClassTemplate) 780 Inst->setAccess(PrevClassTemplate->getAccess()); 781 else 782 Inst->setAccess(D->getAccess()); 783 784 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0); 785 // TODO: do we want to track the instantiation progeny of this 786 // friend target decl? 787 } else { 788 Inst->setAccess(D->getAccess()); 789 Inst->setInstantiatedFromMemberTemplate(D); 790 } 791 792 // Trigger creation of the type for the instantiation. 793 SemaRef.Context.getInjectedClassNameType(RecordInst, 794 Inst->getInjectedClassNameSpecialization(SemaRef.Context)); 795 796 // Finish handling of friends. 797 if (isFriend) { 798 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false); 799 return Inst; 800 } 801 802 Owner->addDecl(Inst); 803 804 // Instantiate all of the partial specializations of this member class 805 // template. 806 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 807 D->getPartialSpecializations(PartialSpecs); 808 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 809 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]); 810 811 return Inst; 812} 813 814Decl * 815TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 816 ClassTemplatePartialSpecializationDecl *D) { 817 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 818 819 // Lookup the already-instantiated declaration in the instantiation 820 // of the class template and return that. 821 DeclContext::lookup_result Found 822 = Owner->lookup(ClassTemplate->getDeclName()); 823 if (Found.first == Found.second) 824 return 0; 825 826 ClassTemplateDecl *InstClassTemplate 827 = dyn_cast<ClassTemplateDecl>(*Found.first); 828 if (!InstClassTemplate) 829 return 0; 830 831 Decl *DCanon = D->getCanonicalDecl(); 832 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 833 P = InstClassTemplate->getPartialSpecializations().begin(), 834 PEnd = InstClassTemplate->getPartialSpecializations().end(); 835 P != PEnd; ++P) { 836 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon) 837 return &*P; 838 } 839 840 return 0; 841} 842 843Decl * 844TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 845 // Create a local instantiation scope for this function template, which 846 // will contain the instantiations of the template parameters and then get 847 // merged with the local instantiation scope for the function template 848 // itself. 849 Sema::LocalInstantiationScope Scope(SemaRef); 850 851 TemplateParameterList *TempParams = D->getTemplateParameters(); 852 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 853 if (!InstParams) 854 return NULL; 855 856 FunctionDecl *Instantiated = 0; 857 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 858 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 859 InstParams)); 860 else 861 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 862 D->getTemplatedDecl(), 863 InstParams)); 864 865 if (!Instantiated) 866 return 0; 867 868 Instantiated->setAccess(D->getAccess()); 869 870 // Link the instantiated function template declaration to the function 871 // template from which it was instantiated. 872 FunctionTemplateDecl *InstTemplate 873 = Instantiated->getDescribedFunctionTemplate(); 874 InstTemplate->setAccess(D->getAccess()); 875 assert(InstTemplate && 876 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 877 878 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 879 880 // Link the instantiation back to the pattern *unless* this is a 881 // non-definition friend declaration. 882 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 883 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 884 InstTemplate->setInstantiatedFromMemberTemplate(D); 885 886 // Make declarations visible in the appropriate context. 887 if (!isFriend) 888 Owner->addDecl(InstTemplate); 889 890 return InstTemplate; 891} 892 893Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 894 CXXRecordDecl *PrevDecl = 0; 895 if (D->isInjectedClassName()) 896 PrevDecl = cast<CXXRecordDecl>(Owner); 897 else if (D->getPreviousDeclaration()) { 898 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 899 D->getPreviousDeclaration(), 900 TemplateArgs); 901 if (!Prev) return 0; 902 PrevDecl = cast<CXXRecordDecl>(Prev); 903 } 904 905 CXXRecordDecl *Record 906 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 907 D->getLocation(), D->getIdentifier(), 908 D->getTagKeywordLoc(), PrevDecl); 909 910 // Substitute the nested name specifier, if any. 911 if (SubstQualifier(D, Record)) 912 return 0; 913 914 Record->setImplicit(D->isImplicit()); 915 // FIXME: Check against AS_none is an ugly hack to work around the issue that 916 // the tag decls introduced by friend class declarations don't have an access 917 // specifier. Remove once this area of the code gets sorted out. 918 if (D->getAccess() != AS_none) 919 Record->setAccess(D->getAccess()); 920 if (!D->isInjectedClassName()) 921 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 922 923 // If the original function was part of a friend declaration, 924 // inherit its namespace state. 925 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 926 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 927 928 // Make sure that anonymous structs and unions are recorded. 929 if (D->isAnonymousStructOrUnion()) { 930 Record->setAnonymousStructOrUnion(true); 931 if (Record->getDeclContext()->getLookupContext()->isFunctionOrMethod()) 932 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 933 } 934 935 Owner->addDecl(Record); 936 return Record; 937} 938 939/// Normal class members are of more specific types and therefore 940/// don't make it here. This function serves two purposes: 941/// 1) instantiating function templates 942/// 2) substituting friend declarations 943/// FIXME: preserve function definitions in case #2 944Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 945 TemplateParameterList *TemplateParams) { 946 // Check whether there is already a function template specialization for 947 // this declaration. 948 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 949 void *InsertPos = 0; 950 if (FunctionTemplate && !TemplateParams) { 951 llvm::FoldingSetNodeID ID; 952 FunctionTemplateSpecializationInfo::Profile(ID, 953 TemplateArgs.getInnermost().getFlatArgumentList(), 954 TemplateArgs.getInnermost().flat_size(), 955 SemaRef.Context); 956 957 FunctionTemplateSpecializationInfo *Info 958 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 959 InsertPos); 960 961 // If we already have a function template specialization, return it. 962 if (Info) 963 return Info->Function; 964 } 965 966 bool isFriend; 967 if (FunctionTemplate) 968 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 969 else 970 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 971 972 bool MergeWithParentScope = (TemplateParams != 0) || 973 !(isa<Decl>(Owner) && 974 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 975 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 976 977 llvm::SmallVector<ParmVarDecl *, 4> Params; 978 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 979 TInfo = SubstFunctionType(D, Params); 980 if (!TInfo) 981 return 0; 982 QualType T = TInfo->getType(); 983 984 NestedNameSpecifier *Qualifier = D->getQualifier(); 985 if (Qualifier) { 986 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 987 D->getQualifierRange(), 988 TemplateArgs); 989 if (!Qualifier) return 0; 990 } 991 992 // If we're instantiating a local function declaration, put the result 993 // in the owner; otherwise we need to find the instantiated context. 994 DeclContext *DC; 995 if (D->getDeclContext()->isFunctionOrMethod()) 996 DC = Owner; 997 else if (isFriend && Qualifier) { 998 CXXScopeSpec SS; 999 SS.setScopeRep(Qualifier); 1000 SS.setRange(D->getQualifierRange()); 1001 DC = SemaRef.computeDeclContext(SS); 1002 if (!DC) return 0; 1003 } else { 1004 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 1005 TemplateArgs); 1006 } 1007 1008 FunctionDecl *Function = 1009 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(), 1010 D->getDeclName(), T, TInfo, 1011 D->getStorageClass(), D->getStorageClassAsWritten(), 1012 D->isInlineSpecified(), D->hasWrittenPrototype()); 1013 1014 if (Qualifier) 1015 Function->setQualifierInfo(Qualifier, D->getQualifierRange()); 1016 1017 DeclContext *LexicalDC = Owner; 1018 if (!isFriend && D->isOutOfLine()) { 1019 assert(D->getDeclContext()->isFileContext()); 1020 LexicalDC = D->getDeclContext(); 1021 } 1022 1023 Function->setLexicalDeclContext(LexicalDC); 1024 1025 // Attach the parameters 1026 for (unsigned P = 0; P < Params.size(); ++P) 1027 Params[P]->setOwningFunction(Function); 1028 Function->setParams(Params.data(), Params.size()); 1029 1030 SourceLocation InstantiateAtPOI; 1031 if (TemplateParams) { 1032 // Our resulting instantiation is actually a function template, since we 1033 // are substituting only the outer template parameters. For example, given 1034 // 1035 // template<typename T> 1036 // struct X { 1037 // template<typename U> friend void f(T, U); 1038 // }; 1039 // 1040 // X<int> x; 1041 // 1042 // We are instantiating the friend function template "f" within X<int>, 1043 // which means substituting int for T, but leaving "f" as a friend function 1044 // template. 1045 // Build the function template itself. 1046 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1047 Function->getLocation(), 1048 Function->getDeclName(), 1049 TemplateParams, Function); 1050 Function->setDescribedFunctionTemplate(FunctionTemplate); 1051 1052 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1053 1054 if (isFriend && D->isThisDeclarationADefinition()) { 1055 // TODO: should we remember this connection regardless of whether 1056 // the friend declaration provided a body? 1057 FunctionTemplate->setInstantiatedFromMemberTemplate( 1058 D->getDescribedFunctionTemplate()); 1059 } 1060 } else if (FunctionTemplate) { 1061 // Record this function template specialization. 1062 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1063 &TemplateArgs.getInnermost(), 1064 InsertPos); 1065 } else if (isFriend && D->isThisDeclarationADefinition()) { 1066 // TODO: should we remember this connection regardless of whether 1067 // the friend declaration provided a body? 1068 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1069 } 1070 1071 if (InitFunctionInstantiation(Function, D)) 1072 Function->setInvalidDecl(); 1073 1074 bool Redeclaration = false; 1075 bool OverloadableAttrRequired = false; 1076 bool isExplicitSpecialization = false; 1077 1078 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(), 1079 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 1080 1081 if (DependentFunctionTemplateSpecializationInfo *Info 1082 = D->getDependentSpecializationInfo()) { 1083 assert(isFriend && "non-friend has dependent specialization info?"); 1084 1085 // This needs to be set now for future sanity. 1086 Function->setObjectOfFriendDecl(/*HasPrevious*/ true); 1087 1088 // Instantiate the explicit template arguments. 1089 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1090 Info->getRAngleLoc()); 1091 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) { 1092 TemplateArgumentLoc Loc; 1093 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs)) 1094 return 0; 1095 1096 ExplicitArgs.addArgument(Loc); 1097 } 1098 1099 // Map the candidate templates to their instantiations. 1100 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1101 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1102 Info->getTemplate(I), 1103 TemplateArgs); 1104 if (!Temp) return 0; 1105 1106 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1107 } 1108 1109 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1110 &ExplicitArgs, 1111 Previous)) 1112 Function->setInvalidDecl(); 1113 1114 isExplicitSpecialization = true; 1115 1116 } else if (TemplateParams || !FunctionTemplate) { 1117 // Look only into the namespace where the friend would be declared to 1118 // find a previous declaration. This is the innermost enclosing namespace, 1119 // as described in ActOnFriendFunctionDecl. 1120 SemaRef.LookupQualifiedName(Previous, DC); 1121 1122 // In C++, the previous declaration we find might be a tag type 1123 // (class or enum). In this case, the new declaration will hide the 1124 // tag type. Note that this does does not apply if we're declaring a 1125 // typedef (C++ [dcl.typedef]p4). 1126 if (Previous.isSingleTagDecl()) 1127 Previous.clear(); 1128 } 1129 1130 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 1131 isExplicitSpecialization, Redeclaration, 1132 /*FIXME:*/OverloadableAttrRequired); 1133 1134 NamedDecl *PrincipalDecl = (TemplateParams 1135 ? cast<NamedDecl>(FunctionTemplate) 1136 : Function); 1137 1138 // If the original function was part of a friend declaration, 1139 // inherit its namespace state and add it to the owner. 1140 if (isFriend) { 1141 NamedDecl *PrevDecl; 1142 if (TemplateParams) 1143 PrevDecl = FunctionTemplate->getPreviousDeclaration(); 1144 else 1145 PrevDecl = Function->getPreviousDeclaration(); 1146 1147 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0); 1148 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false); 1149 1150 if (!SemaRef.getLangOptions().CPlusPlus0x && 1151 D->isThisDeclarationADefinition()) { 1152 // Check for a function body. 1153 const FunctionDecl *Definition = 0; 1154 if (Function->getBody(Definition) && 1155 Definition->getTemplateSpecializationKind() == TSK_Undeclared) { 1156 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 1157 << Function->getDeclName(); 1158 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition); 1159 Function->setInvalidDecl(); 1160 } 1161 // Check for redefinitions due to other instantiations of this or 1162 // a similar friend function. 1163 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(), 1164 REnd = Function->redecls_end(); 1165 R != REnd; ++R) { 1166 if (*R != Function && 1167 ((*R)->getFriendObjectKind() != Decl::FOK_None)) { 1168 if (const FunctionDecl *RPattern 1169 = (*R)->getTemplateInstantiationPattern()) 1170 if (RPattern->getBody(RPattern)) { 1171 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 1172 << Function->getDeclName(); 1173 SemaRef.Diag((*R)->getLocation(), diag::note_previous_definition); 1174 Function->setInvalidDecl(); 1175 break; 1176 } 1177 } 1178 } 1179 } 1180 1181 } 1182 1183 if (Function->isOverloadedOperator() && !DC->isRecord() && 1184 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1185 PrincipalDecl->setNonMemberOperator(); 1186 1187 return Function; 1188} 1189 1190Decl * 1191TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 1192 TemplateParameterList *TemplateParams) { 1193 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1194 void *InsertPos = 0; 1195 if (FunctionTemplate && !TemplateParams) { 1196 // We are creating a function template specialization from a function 1197 // template. Check whether there is already a function template 1198 // specialization for this particular set of template arguments. 1199 llvm::FoldingSetNodeID ID; 1200 FunctionTemplateSpecializationInfo::Profile(ID, 1201 TemplateArgs.getInnermost().getFlatArgumentList(), 1202 TemplateArgs.getInnermost().flat_size(), 1203 SemaRef.Context); 1204 1205 FunctionTemplateSpecializationInfo *Info 1206 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 1207 InsertPos); 1208 1209 // If we already have a function template specialization, return it. 1210 if (Info) 1211 return Info->Function; 1212 } 1213 1214 bool isFriend; 1215 if (FunctionTemplate) 1216 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1217 else 1218 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1219 1220 bool MergeWithParentScope = (TemplateParams != 0) || 1221 !(isa<Decl>(Owner) && 1222 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1223 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1224 1225 llvm::SmallVector<ParmVarDecl *, 4> Params; 1226 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 1227 TInfo = SubstFunctionType(D, Params); 1228 if (!TInfo) 1229 return 0; 1230 QualType T = TInfo->getType(); 1231 1232 // \brief If the type of this function is not *directly* a function 1233 // type, then we're instantiating the a function that was declared 1234 // via a typedef, e.g., 1235 // 1236 // typedef int functype(int, int); 1237 // functype func; 1238 // 1239 // In this case, we'll just go instantiate the ParmVarDecls that we 1240 // synthesized in the method declaration. 1241 if (!isa<FunctionProtoType>(T)) { 1242 assert(!Params.size() && "Instantiating type could not yield parameters"); 1243 for (unsigned I = 0, N = D->getNumParams(); I != N; ++I) { 1244 ParmVarDecl *P = SemaRef.SubstParmVarDecl(D->getParamDecl(I), 1245 TemplateArgs); 1246 if (!P) 1247 return 0; 1248 1249 Params.push_back(P); 1250 } 1251 } 1252 1253 NestedNameSpecifier *Qualifier = D->getQualifier(); 1254 if (Qualifier) { 1255 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier, 1256 D->getQualifierRange(), 1257 TemplateArgs); 1258 if (!Qualifier) return 0; 1259 } 1260 1261 DeclContext *DC = Owner; 1262 if (isFriend) { 1263 if (Qualifier) { 1264 CXXScopeSpec SS; 1265 SS.setScopeRep(Qualifier); 1266 SS.setRange(D->getQualifierRange()); 1267 DC = SemaRef.computeDeclContext(SS); 1268 } else { 1269 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 1270 D->getDeclContext(), 1271 TemplateArgs); 1272 } 1273 if (!DC) return 0; 1274 } 1275 1276 // Build the instantiated method declaration. 1277 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1278 CXXMethodDecl *Method = 0; 1279 1280 DeclarationName Name = D->getDeclName(); 1281 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1282 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 1283 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName( 1284 SemaRef.Context.getCanonicalType(ClassTy)); 1285 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 1286 Constructor->getLocation(), 1287 Name, T, TInfo, 1288 Constructor->isExplicit(), 1289 Constructor->isInlineSpecified(), 1290 false); 1291 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 1292 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 1293 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName( 1294 SemaRef.Context.getCanonicalType(ClassTy)); 1295 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 1296 Destructor->getLocation(), Name, 1297 T, Destructor->isInlineSpecified(), 1298 false); 1299 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 1300 CanQualType ConvTy 1301 = SemaRef.Context.getCanonicalType( 1302 T->getAs<FunctionType>()->getResultType()); 1303 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName( 1304 ConvTy); 1305 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 1306 Conversion->getLocation(), Name, 1307 T, TInfo, 1308 Conversion->isInlineSpecified(), 1309 Conversion->isExplicit()); 1310 } else { 1311 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 1312 D->getDeclName(), T, TInfo, 1313 D->isStatic(), 1314 D->getStorageClassAsWritten(), 1315 D->isInlineSpecified()); 1316 } 1317 1318 if (Qualifier) 1319 Method->setQualifierInfo(Qualifier, D->getQualifierRange()); 1320 1321 if (TemplateParams) { 1322 // Our resulting instantiation is actually a function template, since we 1323 // are substituting only the outer template parameters. For example, given 1324 // 1325 // template<typename T> 1326 // struct X { 1327 // template<typename U> void f(T, U); 1328 // }; 1329 // 1330 // X<int> x; 1331 // 1332 // We are instantiating the member template "f" within X<int>, which means 1333 // substituting int for T, but leaving "f" as a member function template. 1334 // Build the function template itself. 1335 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 1336 Method->getLocation(), 1337 Method->getDeclName(), 1338 TemplateParams, Method); 1339 if (isFriend) { 1340 FunctionTemplate->setLexicalDeclContext(Owner); 1341 FunctionTemplate->setObjectOfFriendDecl(true); 1342 } else if (D->isOutOfLine()) 1343 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 1344 Method->setDescribedFunctionTemplate(FunctionTemplate); 1345 } else if (FunctionTemplate) { 1346 // Record this function template specialization. 1347 Method->setFunctionTemplateSpecialization(FunctionTemplate, 1348 &TemplateArgs.getInnermost(), 1349 InsertPos); 1350 } else if (!isFriend) { 1351 // Record that this is an instantiation of a member function. 1352 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1353 } 1354 1355 // If we are instantiating a member function defined 1356 // out-of-line, the instantiation will have the same lexical 1357 // context (which will be a namespace scope) as the template. 1358 if (isFriend) { 1359 Method->setLexicalDeclContext(Owner); 1360 Method->setObjectOfFriendDecl(true); 1361 } else if (D->isOutOfLine()) 1362 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 1363 1364 // Attach the parameters 1365 for (unsigned P = 0; P < Params.size(); ++P) 1366 Params[P]->setOwningFunction(Method); 1367 Method->setParams(Params.data(), Params.size()); 1368 1369 if (InitMethodInstantiation(Method, D)) 1370 Method->setInvalidDecl(); 1371 1372 LookupResult Previous(SemaRef, Name, SourceLocation(), 1373 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 1374 1375 if (!FunctionTemplate || TemplateParams || isFriend) { 1376 SemaRef.LookupQualifiedName(Previous, Record); 1377 1378 // In C++, the previous declaration we find might be a tag type 1379 // (class or enum). In this case, the new declaration will hide the 1380 // tag type. Note that this does does not apply if we're declaring a 1381 // typedef (C++ [dcl.typedef]p4). 1382 if (Previous.isSingleTagDecl()) 1383 Previous.clear(); 1384 } 1385 1386 bool Redeclaration = false; 1387 bool OverloadableAttrRequired = false; 1388 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration, 1389 /*FIXME:*/OverloadableAttrRequired); 1390 1391 if (D->isPure()) 1392 SemaRef.CheckPureMethod(Method, SourceRange()); 1393 1394 Method->setAccess(D->getAccess()); 1395 1396 if (FunctionTemplate) { 1397 // If there's a function template, let our caller handle it. 1398 } else if (Method->isInvalidDecl() && !Previous.empty()) { 1399 // Don't hide a (potentially) valid declaration with an invalid one. 1400 } else { 1401 NamedDecl *DeclToAdd = (TemplateParams 1402 ? cast<NamedDecl>(FunctionTemplate) 1403 : Method); 1404 if (isFriend) 1405 Record->makeDeclVisibleInContext(DeclToAdd); 1406 else 1407 Owner->addDecl(DeclToAdd); 1408 } 1409 1410 return Method; 1411} 1412 1413Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1414 return VisitCXXMethodDecl(D); 1415} 1416 1417Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1418 return VisitCXXMethodDecl(D); 1419} 1420 1421Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 1422 return VisitCXXMethodDecl(D); 1423} 1424 1425ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 1426 return SemaRef.SubstParmVarDecl(D, TemplateArgs); 1427} 1428 1429Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1430 TemplateTypeParmDecl *D) { 1431 // TODO: don't always clone when decls are refcounted. 1432 const Type* T = D->getTypeForDecl(); 1433 assert(T->isTemplateTypeParmType()); 1434 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>(); 1435 1436 TemplateTypeParmDecl *Inst = 1437 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1438 TTPT->getDepth() - 1, TTPT->getIndex(), 1439 TTPT->getName(), 1440 D->wasDeclaredWithTypename(), 1441 D->isParameterPack()); 1442 1443 if (D->hasDefaultArgument()) 1444 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 1445 1446 // Introduce this template parameter's instantiation into the instantiation 1447 // scope. 1448 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1449 1450 return Inst; 1451} 1452 1453Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1454 NonTypeTemplateParmDecl *D) { 1455 // Substitute into the type of the non-type template parameter. 1456 QualType T; 1457 TypeSourceInfo *DI = D->getTypeSourceInfo(); 1458 if (DI) { 1459 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 1460 D->getDeclName()); 1461 if (DI) T = DI->getType(); 1462 } else { 1463 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 1464 D->getDeclName()); 1465 DI = 0; 1466 } 1467 if (T.isNull()) 1468 return 0; 1469 1470 // Check that this type is acceptable for a non-type template parameter. 1471 bool Invalid = false; 1472 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation()); 1473 if (T.isNull()) { 1474 T = SemaRef.Context.IntTy; 1475 Invalid = true; 1476 } 1477 1478 NonTypeTemplateParmDecl *Param 1479 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1480 D->getDepth() - 1, D->getPosition(), 1481 D->getIdentifier(), T, DI); 1482 if (Invalid) 1483 Param->setInvalidDecl(); 1484 1485 Param->setDefaultArgument(D->getDefaultArgument()); 1486 1487 // Introduce this template parameter's instantiation into the instantiation 1488 // scope. 1489 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1490 return Param; 1491} 1492 1493Decl * 1494TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1495 TemplateTemplateParmDecl *D) { 1496 // Instantiate the template parameter list of the template template parameter. 1497 TemplateParameterList *TempParams = D->getTemplateParameters(); 1498 TemplateParameterList *InstParams; 1499 { 1500 // Perform the actual substitution of template parameters within a new, 1501 // local instantiation scope. 1502 Sema::LocalInstantiationScope Scope(SemaRef); 1503 InstParams = SubstTemplateParams(TempParams); 1504 if (!InstParams) 1505 return NULL; 1506 } 1507 1508 // Build the template template parameter. 1509 TemplateTemplateParmDecl *Param 1510 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1511 D->getDepth() - 1, D->getPosition(), 1512 D->getIdentifier(), InstParams); 1513 Param->setDefaultArgument(D->getDefaultArgument()); 1514 1515 // Introduce this template parameter's instantiation into the instantiation 1516 // scope. 1517 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1518 1519 return Param; 1520} 1521 1522Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1523 // Using directives are never dependent, so they require no explicit 1524 1525 UsingDirectiveDecl *Inst 1526 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1527 D->getNamespaceKeyLocation(), 1528 D->getQualifierRange(), D->getQualifier(), 1529 D->getIdentLocation(), 1530 D->getNominatedNamespace(), 1531 D->getCommonAncestor()); 1532 Owner->addDecl(Inst); 1533 return Inst; 1534} 1535 1536Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 1537 // The nested name specifier is non-dependent, so no transformation 1538 // is required. 1539 1540 // We only need to do redeclaration lookups if we're in a class 1541 // scope (in fact, it's not really even possible in non-class 1542 // scopes). 1543 bool CheckRedeclaration = Owner->isRecord(); 1544 1545 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(), 1546 Sema::LookupUsingDeclName, Sema::ForRedeclaration); 1547 1548 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 1549 D->getLocation(), 1550 D->getNestedNameRange(), 1551 D->getUsingLocation(), 1552 D->getTargetNestedNameDecl(), 1553 D->getDeclName(), 1554 D->isTypeName()); 1555 1556 CXXScopeSpec SS; 1557 SS.setScopeRep(D->getTargetNestedNameDecl()); 1558 SS.setRange(D->getNestedNameRange()); 1559 1560 if (CheckRedeclaration) { 1561 Prev.setHideTags(false); 1562 SemaRef.LookupQualifiedName(Prev, Owner); 1563 1564 // Check for invalid redeclarations. 1565 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(), 1566 D->isTypeName(), SS, 1567 D->getLocation(), Prev)) 1568 NewUD->setInvalidDecl(); 1569 1570 } 1571 1572 if (!NewUD->isInvalidDecl() && 1573 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS, 1574 D->getLocation())) 1575 NewUD->setInvalidDecl(); 1576 1577 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 1578 NewUD->setAccess(D->getAccess()); 1579 Owner->addDecl(NewUD); 1580 1581 // Don't process the shadow decls for an invalid decl. 1582 if (NewUD->isInvalidDecl()) 1583 return NewUD; 1584 1585 bool isFunctionScope = Owner->isFunctionOrMethod(); 1586 1587 // Process the shadow decls. 1588 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 1589 I != E; ++I) { 1590 UsingShadowDecl *Shadow = *I; 1591 NamedDecl *InstTarget = 1592 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(), 1593 Shadow->getTargetDecl(), 1594 TemplateArgs)); 1595 1596 if (CheckRedeclaration && 1597 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev)) 1598 continue; 1599 1600 UsingShadowDecl *InstShadow 1601 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget); 1602 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 1603 1604 if (isFunctionScope) 1605 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 1606 } 1607 1608 return NewUD; 1609} 1610 1611Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 1612 // Ignore these; we handle them in bulk when processing the UsingDecl. 1613 return 0; 1614} 1615 1616Decl * TemplateDeclInstantiator 1617 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 1618 NestedNameSpecifier *NNS = 1619 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1620 D->getTargetNestedNameRange(), 1621 TemplateArgs); 1622 if (!NNS) 1623 return 0; 1624 1625 CXXScopeSpec SS; 1626 SS.setRange(D->getTargetNestedNameRange()); 1627 SS.setScopeRep(NNS); 1628 1629 NamedDecl *UD = 1630 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1631 D->getUsingLoc(), SS, D->getLocation(), 1632 D->getDeclName(), 0, 1633 /*instantiation*/ true, 1634 /*typename*/ true, D->getTypenameLoc()); 1635 if (UD) 1636 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1637 1638 return UD; 1639} 1640 1641Decl * TemplateDeclInstantiator 1642 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1643 NestedNameSpecifier *NNS = 1644 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1645 D->getTargetNestedNameRange(), 1646 TemplateArgs); 1647 if (!NNS) 1648 return 0; 1649 1650 CXXScopeSpec SS; 1651 SS.setRange(D->getTargetNestedNameRange()); 1652 SS.setScopeRep(NNS); 1653 1654 NamedDecl *UD = 1655 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1656 D->getUsingLoc(), SS, D->getLocation(), 1657 D->getDeclName(), 0, 1658 /*instantiation*/ true, 1659 /*typename*/ false, SourceLocation()); 1660 if (UD) 1661 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1662 1663 return UD; 1664} 1665 1666Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 1667 const MultiLevelTemplateArgumentList &TemplateArgs) { 1668 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 1669 if (D->isInvalidDecl()) 1670 return 0; 1671 1672 return Instantiator.Visit(D); 1673} 1674 1675/// \brief Instantiates a nested template parameter list in the current 1676/// instantiation context. 1677/// 1678/// \param L The parameter list to instantiate 1679/// 1680/// \returns NULL if there was an error 1681TemplateParameterList * 1682TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 1683 // Get errors for all the parameters before bailing out. 1684 bool Invalid = false; 1685 1686 unsigned N = L->size(); 1687 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector; 1688 ParamVector Params; 1689 Params.reserve(N); 1690 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 1691 PI != PE; ++PI) { 1692 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 1693 Params.push_back(D); 1694 Invalid = Invalid || !D || D->isInvalidDecl(); 1695 } 1696 1697 // Clean up if we had an error. 1698 if (Invalid) { 1699 for (ParamVector::iterator PI = Params.begin(), PE = Params.end(); 1700 PI != PE; ++PI) 1701 if (*PI) 1702 (*PI)->Destroy(SemaRef.Context); 1703 return NULL; 1704 } 1705 1706 TemplateParameterList *InstL 1707 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 1708 L->getLAngleLoc(), &Params.front(), N, 1709 L->getRAngleLoc()); 1710 return InstL; 1711} 1712 1713/// \brief Instantiate the declaration of a class template partial 1714/// specialization. 1715/// 1716/// \param ClassTemplate the (instantiated) class template that is partially 1717// specialized by the instantiation of \p PartialSpec. 1718/// 1719/// \param PartialSpec the (uninstantiated) class template partial 1720/// specialization that we are instantiating. 1721/// 1722/// \returns true if there was an error, false otherwise. 1723bool 1724TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 1725 ClassTemplateDecl *ClassTemplate, 1726 ClassTemplatePartialSpecializationDecl *PartialSpec) { 1727 // Create a local instantiation scope for this class template partial 1728 // specialization, which will contain the instantiations of the template 1729 // parameters. 1730 Sema::LocalInstantiationScope Scope(SemaRef); 1731 1732 // Substitute into the template parameters of the class template partial 1733 // specialization. 1734 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 1735 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1736 if (!InstParams) 1737 return true; 1738 1739 // Substitute into the template arguments of the class template partial 1740 // specialization. 1741 const TemplateArgumentLoc *PartialSpecTemplateArgs 1742 = PartialSpec->getTemplateArgsAsWritten(); 1743 unsigned N = PartialSpec->getNumTemplateArgsAsWritten(); 1744 1745 TemplateArgumentListInfo InstTemplateArgs; // no angle locations 1746 for (unsigned I = 0; I != N; ++I) { 1747 TemplateArgumentLoc Loc; 1748 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs)) 1749 return true; 1750 InstTemplateArgs.addArgument(Loc); 1751 } 1752 1753 1754 // Check that the template argument list is well-formed for this 1755 // class template. 1756 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 1757 InstTemplateArgs.size()); 1758 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 1759 PartialSpec->getLocation(), 1760 InstTemplateArgs, 1761 false, 1762 Converted)) 1763 return true; 1764 1765 // Figure out where to insert this class template partial specialization 1766 // in the member template's set of class template partial specializations. 1767 llvm::FoldingSetNodeID ID; 1768 ClassTemplatePartialSpecializationDecl::Profile(ID, 1769 Converted.getFlatArguments(), 1770 Converted.flatSize(), 1771 SemaRef.Context); 1772 void *InsertPos = 0; 1773 ClassTemplateSpecializationDecl *PrevDecl 1774 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 1775 InsertPos); 1776 1777 // Build the canonical type that describes the converted template 1778 // arguments of the class template partial specialization. 1779 QualType CanonType 1780 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1781 Converted.getFlatArguments(), 1782 Converted.flatSize()); 1783 1784 // Build the fully-sugared type for this class template 1785 // specialization as the user wrote in the specialization 1786 // itself. This means that we'll pretty-print the type retrieved 1787 // from the specialization's declaration the way that the user 1788 // actually wrote the specialization, rather than formatting the 1789 // name based on the "canonical" representation used to store the 1790 // template arguments in the specialization. 1791 TypeSourceInfo *WrittenTy 1792 = SemaRef.Context.getTemplateSpecializationTypeInfo( 1793 TemplateName(ClassTemplate), 1794 PartialSpec->getLocation(), 1795 InstTemplateArgs, 1796 CanonType); 1797 1798 if (PrevDecl) { 1799 // We've already seen a partial specialization with the same template 1800 // parameters and template arguments. This can happen, for example, when 1801 // substituting the outer template arguments ends up causing two 1802 // class template partial specializations of a member class template 1803 // to have identical forms, e.g., 1804 // 1805 // template<typename T, typename U> 1806 // struct Outer { 1807 // template<typename X, typename Y> struct Inner; 1808 // template<typename Y> struct Inner<T, Y>; 1809 // template<typename Y> struct Inner<U, Y>; 1810 // }; 1811 // 1812 // Outer<int, int> outer; // error: the partial specializations of Inner 1813 // // have the same signature. 1814 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 1815 << WrittenTy; 1816 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 1817 << SemaRef.Context.getTypeDeclType(PrevDecl); 1818 return true; 1819 } 1820 1821 1822 // Create the class template partial specialization declaration. 1823 ClassTemplatePartialSpecializationDecl *InstPartialSpec 1824 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, 1825 PartialSpec->getTagKind(), 1826 Owner, 1827 PartialSpec->getLocation(), 1828 InstParams, 1829 ClassTemplate, 1830 Converted, 1831 InstTemplateArgs, 1832 CanonType, 1833 0, 1834 ClassTemplate->getPartialSpecializations().size()); 1835 // Substitute the nested name specifier, if any. 1836 if (SubstQualifier(PartialSpec, InstPartialSpec)) 1837 return 0; 1838 1839 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 1840 InstPartialSpec->setTypeAsWritten(WrittenTy); 1841 1842 // Add this partial specialization to the set of class template partial 1843 // specializations. 1844 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec, 1845 InsertPos); 1846 return false; 1847} 1848 1849TypeSourceInfo* 1850TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 1851 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 1852 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 1853 assert(OldTInfo && "substituting function without type source info"); 1854 assert(Params.empty() && "parameter vector is non-empty at start"); 1855 TypeSourceInfo *NewTInfo 1856 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 1857 D->getTypeSpecStartLoc(), 1858 D->getDeclName()); 1859 if (!NewTInfo) 1860 return 0; 1861 1862 if (NewTInfo != OldTInfo) { 1863 // Get parameters from the new type info. 1864 TypeLoc OldTL = OldTInfo->getTypeLoc(); 1865 if (FunctionProtoTypeLoc *OldProtoLoc 1866 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 1867 TypeLoc NewTL = NewTInfo->getTypeLoc(); 1868 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL); 1869 assert(NewProtoLoc && "Missing prototype?"); 1870 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i) { 1871 // FIXME: Variadic templates will break this. 1872 Params.push_back(NewProtoLoc->getArg(i)); 1873 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 1874 OldProtoLoc->getArg(i), 1875 NewProtoLoc->getArg(i)); 1876 } 1877 } 1878 } else { 1879 // The function type itself was not dependent and therefore no 1880 // substitution occurred. However, we still need to instantiate 1881 // the function parameters themselves. 1882 TypeLoc OldTL = OldTInfo->getTypeLoc(); 1883 if (FunctionProtoTypeLoc *OldProtoLoc 1884 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 1885 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) { 1886 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i)); 1887 if (!Parm) 1888 return 0; 1889 Params.push_back(Parm); 1890 } 1891 } 1892 } 1893 return NewTInfo; 1894} 1895 1896/// \brief Initializes the common fields of an instantiation function 1897/// declaration (New) from the corresponding fields of its template (Tmpl). 1898/// 1899/// \returns true if there was an error 1900bool 1901TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 1902 FunctionDecl *Tmpl) { 1903 if (Tmpl->isDeleted()) 1904 New->setDeleted(); 1905 1906 // If we are performing substituting explicitly-specified template arguments 1907 // or deduced template arguments into a function template and we reach this 1908 // point, we are now past the point where SFINAE applies and have committed 1909 // to keeping the new function template specialization. We therefore 1910 // convert the active template instantiation for the function template 1911 // into a template instantiation for this specific function template 1912 // specialization, which is not a SFINAE context, so that we diagnose any 1913 // further errors in the declaration itself. 1914 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 1915 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 1916 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 1917 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 1918 if (FunctionTemplateDecl *FunTmpl 1919 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 1920 assert(FunTmpl->getTemplatedDecl() == Tmpl && 1921 "Deduction from the wrong function template?"); 1922 (void) FunTmpl; 1923 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 1924 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 1925 --SemaRef.NonInstantiationEntries; 1926 } 1927 } 1928 1929 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 1930 assert(Proto && "Function template without prototype?"); 1931 1932 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() || 1933 Proto->getNoReturnAttr()) { 1934 // The function has an exception specification or a "noreturn" 1935 // attribute. Substitute into each of the exception types. 1936 llvm::SmallVector<QualType, 4> Exceptions; 1937 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 1938 // FIXME: Poor location information! 1939 QualType T 1940 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 1941 New->getLocation(), New->getDeclName()); 1942 if (T.isNull() || 1943 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 1944 continue; 1945 1946 Exceptions.push_back(T); 1947 } 1948 1949 // Rebuild the function type 1950 1951 const FunctionProtoType *NewProto 1952 = New->getType()->getAs<FunctionProtoType>(); 1953 assert(NewProto && "Template instantiation without function prototype?"); 1954 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 1955 NewProto->arg_type_begin(), 1956 NewProto->getNumArgs(), 1957 NewProto->isVariadic(), 1958 NewProto->getTypeQuals(), 1959 Proto->hasExceptionSpec(), 1960 Proto->hasAnyExceptionSpec(), 1961 Exceptions.size(), 1962 Exceptions.data(), 1963 Proto->getExtInfo())); 1964 } 1965 1966 return false; 1967} 1968 1969/// \brief Initializes common fields of an instantiated method 1970/// declaration (New) from the corresponding fields of its template 1971/// (Tmpl). 1972/// 1973/// \returns true if there was an error 1974bool 1975TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 1976 CXXMethodDecl *Tmpl) { 1977 if (InitFunctionInstantiation(New, Tmpl)) 1978 return true; 1979 1980 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 1981 New->setAccess(Tmpl->getAccess()); 1982 if (Tmpl->isVirtualAsWritten()) 1983 Record->setMethodAsVirtual(New); 1984 1985 // FIXME: attributes 1986 // FIXME: New needs a pointer to Tmpl 1987 return false; 1988} 1989 1990/// \brief Instantiate the definition of the given function from its 1991/// template. 1992/// 1993/// \param PointOfInstantiation the point at which the instantiation was 1994/// required. Note that this is not precisely a "point of instantiation" 1995/// for the function, but it's close. 1996/// 1997/// \param Function the already-instantiated declaration of a 1998/// function template specialization or member function of a class template 1999/// specialization. 2000/// 2001/// \param Recursive if true, recursively instantiates any functions that 2002/// are required by this instantiation. 2003/// 2004/// \param DefinitionRequired if true, then we are performing an explicit 2005/// instantiation where the body of the function is required. Complain if 2006/// there is no such body. 2007void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 2008 FunctionDecl *Function, 2009 bool Recursive, 2010 bool DefinitionRequired) { 2011 if (Function->isInvalidDecl() || Function->getBody()) 2012 return; 2013 2014 // Never instantiate an explicit specialization. 2015 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 2016 return; 2017 2018 // Find the function body that we'll be substituting. 2019 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 2020 Stmt *Pattern = 0; 2021 if (PatternDecl) 2022 Pattern = PatternDecl->getBody(PatternDecl); 2023 2024 if (!Pattern) { 2025 if (DefinitionRequired) { 2026 if (Function->getPrimaryTemplate()) 2027 Diag(PointOfInstantiation, 2028 diag::err_explicit_instantiation_undefined_func_template) 2029 << Function->getPrimaryTemplate(); 2030 else 2031 Diag(PointOfInstantiation, 2032 diag::err_explicit_instantiation_undefined_member) 2033 << 1 << Function->getDeclName() << Function->getDeclContext(); 2034 2035 if (PatternDecl) 2036 Diag(PatternDecl->getLocation(), 2037 diag::note_explicit_instantiation_here); 2038 Function->setInvalidDecl(); 2039 } 2040 2041 return; 2042 } 2043 2044 // C++0x [temp.explicit]p9: 2045 // Except for inline functions, other explicit instantiation declarations 2046 // have the effect of suppressing the implicit instantiation of the entity 2047 // to which they refer. 2048 if (Function->getTemplateSpecializationKind() 2049 == TSK_ExplicitInstantiationDeclaration && 2050 !PatternDecl->isInlined()) 2051 return; 2052 2053 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 2054 if (Inst) 2055 return; 2056 2057 // If we're performing recursive template instantiation, create our own 2058 // queue of pending implicit instantiations that we will instantiate later, 2059 // while we're still within our own instantiation context. 2060 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 2061 if (Recursive) 2062 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2063 2064 EnterExpressionEvaluationContext EvalContext(*this, 2065 Action::PotentiallyEvaluated); 2066 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 2067 2068 // Introduce a new scope where local variable instantiations will be 2069 // recorded, unless we're actually a member function within a local 2070 // class, in which case we need to merge our results with the parent 2071 // scope (of the enclosing function). 2072 bool MergeWithParentScope = false; 2073 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 2074 MergeWithParentScope = Rec->isLocalClass(); 2075 2076 LocalInstantiationScope Scope(*this, MergeWithParentScope); 2077 2078 // Introduce the instantiated function parameters into the local 2079 // instantiation scope. 2080 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 2081 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 2082 Function->getParamDecl(I)); 2083 2084 // Enter the scope of this instantiation. We don't use 2085 // PushDeclContext because we don't have a scope. 2086 DeclContext *PreviousContext = CurContext; 2087 CurContext = Function; 2088 2089 MultiLevelTemplateArgumentList TemplateArgs = 2090 getTemplateInstantiationArgs(Function, 0, false, PatternDecl); 2091 2092 // If this is a constructor, instantiate the member initializers. 2093 if (const CXXConstructorDecl *Ctor = 2094 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 2095 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 2096 TemplateArgs); 2097 } 2098 2099 // Instantiate the function body. 2100 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs); 2101 2102 if (Body.isInvalid()) 2103 Function->setInvalidDecl(); 2104 2105 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 2106 /*IsInstantiation=*/true); 2107 2108 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 2109 2110 CurContext = PreviousContext; 2111 2112 DeclGroupRef DG(Function); 2113 Consumer.HandleTopLevelDecl(DG); 2114 2115 // This class may have local implicit instantiations that need to be 2116 // instantiation within this scope. 2117 PerformPendingImplicitInstantiations(/*LocalOnly=*/true); 2118 Scope.Exit(); 2119 2120 if (Recursive) { 2121 // Instantiate any pending implicit instantiations found during the 2122 // instantiation of this template. 2123 PerformPendingImplicitInstantiations(); 2124 2125 // Restore the set of pending implicit instantiations. 2126 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2127 } 2128} 2129 2130/// \brief Instantiate the definition of the given variable from its 2131/// template. 2132/// 2133/// \param PointOfInstantiation the point at which the instantiation was 2134/// required. Note that this is not precisely a "point of instantiation" 2135/// for the function, but it's close. 2136/// 2137/// \param Var the already-instantiated declaration of a static member 2138/// variable of a class template specialization. 2139/// 2140/// \param Recursive if true, recursively instantiates any functions that 2141/// are required by this instantiation. 2142/// 2143/// \param DefinitionRequired if true, then we are performing an explicit 2144/// instantiation where an out-of-line definition of the member variable 2145/// is required. Complain if there is no such definition. 2146void Sema::InstantiateStaticDataMemberDefinition( 2147 SourceLocation PointOfInstantiation, 2148 VarDecl *Var, 2149 bool Recursive, 2150 bool DefinitionRequired) { 2151 if (Var->isInvalidDecl()) 2152 return; 2153 2154 // Find the out-of-line definition of this static data member. 2155 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 2156 assert(Def && "This data member was not instantiated from a template?"); 2157 assert(Def->isStaticDataMember() && "Not a static data member?"); 2158 Def = Def->getOutOfLineDefinition(); 2159 2160 if (!Def) { 2161 // We did not find an out-of-line definition of this static data member, 2162 // so we won't perform any instantiation. Rather, we rely on the user to 2163 // instantiate this definition (or provide a specialization for it) in 2164 // another translation unit. 2165 if (DefinitionRequired) { 2166 Def = Var->getInstantiatedFromStaticDataMember(); 2167 Diag(PointOfInstantiation, 2168 diag::err_explicit_instantiation_undefined_member) 2169 << 2 << Var->getDeclName() << Var->getDeclContext(); 2170 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 2171 } 2172 2173 return; 2174 } 2175 2176 // Never instantiate an explicit specialization. 2177 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 2178 return; 2179 2180 // C++0x [temp.explicit]p9: 2181 // Except for inline functions, other explicit instantiation declarations 2182 // have the effect of suppressing the implicit instantiation of the entity 2183 // to which they refer. 2184 if (Var->getTemplateSpecializationKind() 2185 == TSK_ExplicitInstantiationDeclaration) 2186 return; 2187 2188 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 2189 if (Inst) 2190 return; 2191 2192 // If we're performing recursive template instantiation, create our own 2193 // queue of pending implicit instantiations that we will instantiate later, 2194 // while we're still within our own instantiation context. 2195 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 2196 if (Recursive) 2197 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2198 2199 // Enter the scope of this instantiation. We don't use 2200 // PushDeclContext because we don't have a scope. 2201 DeclContext *PreviousContext = CurContext; 2202 CurContext = Var->getDeclContext(); 2203 2204 VarDecl *OldVar = Var; 2205 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 2206 getTemplateInstantiationArgs(Var))); 2207 CurContext = PreviousContext; 2208 2209 if (Var) { 2210 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 2211 assert(MSInfo && "Missing member specialization information?"); 2212 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 2213 MSInfo->getPointOfInstantiation()); 2214 DeclGroupRef DG(Var); 2215 Consumer.HandleTopLevelDecl(DG); 2216 } 2217 2218 if (Recursive) { 2219 // Instantiate any pending implicit instantiations found during the 2220 // instantiation of this template. 2221 PerformPendingImplicitInstantiations(); 2222 2223 // Restore the set of pending implicit instantiations. 2224 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 2225 } 2226} 2227 2228void 2229Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 2230 const CXXConstructorDecl *Tmpl, 2231 const MultiLevelTemplateArgumentList &TemplateArgs) { 2232 2233 llvm::SmallVector<MemInitTy*, 4> NewInits; 2234 bool AnyErrors = false; 2235 2236 // Instantiate all the initializers. 2237 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 2238 InitsEnd = Tmpl->init_end(); 2239 Inits != InitsEnd; ++Inits) { 2240 CXXBaseOrMemberInitializer *Init = *Inits; 2241 2242 SourceLocation LParenLoc, RParenLoc; 2243 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this); 2244 llvm::SmallVector<SourceLocation, 4> CommaLocs; 2245 2246 // Instantiate the initializer. 2247 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs, 2248 LParenLoc, CommaLocs, NewArgs, RParenLoc)) { 2249 AnyErrors = true; 2250 continue; 2251 } 2252 2253 MemInitResult NewInit; 2254 if (Init->isBaseInitializer()) { 2255 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(), 2256 TemplateArgs, 2257 Init->getSourceLocation(), 2258 New->getDeclName()); 2259 if (!BaseTInfo) { 2260 AnyErrors = true; 2261 New->setInvalidDecl(); 2262 continue; 2263 } 2264 2265 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo, 2266 (Expr **)NewArgs.data(), 2267 NewArgs.size(), 2268 Init->getLParenLoc(), 2269 Init->getRParenLoc(), 2270 New->getParent()); 2271 } else if (Init->isMemberInitializer()) { 2272 FieldDecl *Member; 2273 2274 // Is this an anonymous union? 2275 if (FieldDecl *UnionInit = Init->getAnonUnionMember()) 2276 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(), 2277 UnionInit, TemplateArgs)); 2278 else 2279 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(), 2280 Init->getMember(), 2281 TemplateArgs)); 2282 2283 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 2284 NewArgs.size(), 2285 Init->getSourceLocation(), 2286 Init->getLParenLoc(), 2287 Init->getRParenLoc()); 2288 } 2289 2290 if (NewInit.isInvalid()) { 2291 AnyErrors = true; 2292 New->setInvalidDecl(); 2293 } else { 2294 // FIXME: It would be nice if ASTOwningVector had a release function. 2295 NewArgs.take(); 2296 2297 NewInits.push_back((MemInitTy *)NewInit.get()); 2298 } 2299 } 2300 2301 // Assign all the initializers to the new constructor. 2302 ActOnMemInitializers(DeclPtrTy::make(New), 2303 /*FIXME: ColonLoc */ 2304 SourceLocation(), 2305 NewInits.data(), NewInits.size(), 2306 AnyErrors); 2307} 2308 2309// TODO: this could be templated if the various decl types used the 2310// same method name. 2311static bool isInstantiationOf(ClassTemplateDecl *Pattern, 2312 ClassTemplateDecl *Instance) { 2313 Pattern = Pattern->getCanonicalDecl(); 2314 2315 do { 2316 Instance = Instance->getCanonicalDecl(); 2317 if (Pattern == Instance) return true; 2318 Instance = Instance->getInstantiatedFromMemberTemplate(); 2319 } while (Instance); 2320 2321 return false; 2322} 2323 2324static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 2325 FunctionTemplateDecl *Instance) { 2326 Pattern = Pattern->getCanonicalDecl(); 2327 2328 do { 2329 Instance = Instance->getCanonicalDecl(); 2330 if (Pattern == Instance) return true; 2331 Instance = Instance->getInstantiatedFromMemberTemplate(); 2332 } while (Instance); 2333 2334 return false; 2335} 2336 2337static bool 2338isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 2339 ClassTemplatePartialSpecializationDecl *Instance) { 2340 Pattern 2341 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 2342 do { 2343 Instance = cast<ClassTemplatePartialSpecializationDecl>( 2344 Instance->getCanonicalDecl()); 2345 if (Pattern == Instance) 2346 return true; 2347 Instance = Instance->getInstantiatedFromMember(); 2348 } while (Instance); 2349 2350 return false; 2351} 2352 2353static bool isInstantiationOf(CXXRecordDecl *Pattern, 2354 CXXRecordDecl *Instance) { 2355 Pattern = Pattern->getCanonicalDecl(); 2356 2357 do { 2358 Instance = Instance->getCanonicalDecl(); 2359 if (Pattern == Instance) return true; 2360 Instance = Instance->getInstantiatedFromMemberClass(); 2361 } while (Instance); 2362 2363 return false; 2364} 2365 2366static bool isInstantiationOf(FunctionDecl *Pattern, 2367 FunctionDecl *Instance) { 2368 Pattern = Pattern->getCanonicalDecl(); 2369 2370 do { 2371 Instance = Instance->getCanonicalDecl(); 2372 if (Pattern == Instance) return true; 2373 Instance = Instance->getInstantiatedFromMemberFunction(); 2374 } while (Instance); 2375 2376 return false; 2377} 2378 2379static bool isInstantiationOf(EnumDecl *Pattern, 2380 EnumDecl *Instance) { 2381 Pattern = Pattern->getCanonicalDecl(); 2382 2383 do { 2384 Instance = Instance->getCanonicalDecl(); 2385 if (Pattern == Instance) return true; 2386 Instance = Instance->getInstantiatedFromMemberEnum(); 2387 } while (Instance); 2388 2389 return false; 2390} 2391 2392static bool isInstantiationOf(UsingShadowDecl *Pattern, 2393 UsingShadowDecl *Instance, 2394 ASTContext &C) { 2395 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 2396} 2397 2398static bool isInstantiationOf(UsingDecl *Pattern, 2399 UsingDecl *Instance, 2400 ASTContext &C) { 2401 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2402} 2403 2404static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 2405 UsingDecl *Instance, 2406 ASTContext &C) { 2407 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2408} 2409 2410static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 2411 UsingDecl *Instance, 2412 ASTContext &C) { 2413 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2414} 2415 2416static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 2417 VarDecl *Instance) { 2418 assert(Instance->isStaticDataMember()); 2419 2420 Pattern = Pattern->getCanonicalDecl(); 2421 2422 do { 2423 Instance = Instance->getCanonicalDecl(); 2424 if (Pattern == Instance) return true; 2425 Instance = Instance->getInstantiatedFromStaticDataMember(); 2426 } while (Instance); 2427 2428 return false; 2429} 2430 2431// Other is the prospective instantiation 2432// D is the prospective pattern 2433static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 2434 if (D->getKind() != Other->getKind()) { 2435 if (UnresolvedUsingTypenameDecl *UUD 2436 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 2437 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2438 return isInstantiationOf(UUD, UD, Ctx); 2439 } 2440 } 2441 2442 if (UnresolvedUsingValueDecl *UUD 2443 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 2444 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2445 return isInstantiationOf(UUD, UD, Ctx); 2446 } 2447 } 2448 2449 return false; 2450 } 2451 2452 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 2453 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 2454 2455 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 2456 return isInstantiationOf(cast<FunctionDecl>(D), Function); 2457 2458 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 2459 return isInstantiationOf(cast<EnumDecl>(D), Enum); 2460 2461 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 2462 if (Var->isStaticDataMember()) 2463 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 2464 2465 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 2466 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 2467 2468 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 2469 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 2470 2471 if (ClassTemplatePartialSpecializationDecl *PartialSpec 2472 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 2473 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 2474 PartialSpec); 2475 2476 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 2477 if (!Field->getDeclName()) { 2478 // This is an unnamed field. 2479 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 2480 cast<FieldDecl>(D); 2481 } 2482 } 2483 2484 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 2485 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 2486 2487 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 2488 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 2489 2490 return D->getDeclName() && isa<NamedDecl>(Other) && 2491 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 2492} 2493 2494template<typename ForwardIterator> 2495static NamedDecl *findInstantiationOf(ASTContext &Ctx, 2496 NamedDecl *D, 2497 ForwardIterator first, 2498 ForwardIterator last) { 2499 for (; first != last; ++first) 2500 if (isInstantiationOf(Ctx, D, *first)) 2501 return cast<NamedDecl>(*first); 2502 2503 return 0; 2504} 2505 2506/// \brief Finds the instantiation of the given declaration context 2507/// within the current instantiation. 2508/// 2509/// \returns NULL if there was an error 2510DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 2511 const MultiLevelTemplateArgumentList &TemplateArgs) { 2512 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 2513 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 2514 return cast_or_null<DeclContext>(ID); 2515 } else return DC; 2516} 2517 2518/// \brief Find the instantiation of the given declaration within the 2519/// current instantiation. 2520/// 2521/// This routine is intended to be used when \p D is a declaration 2522/// referenced from within a template, that needs to mapped into the 2523/// corresponding declaration within an instantiation. For example, 2524/// given: 2525/// 2526/// \code 2527/// template<typename T> 2528/// struct X { 2529/// enum Kind { 2530/// KnownValue = sizeof(T) 2531/// }; 2532/// 2533/// bool getKind() const { return KnownValue; } 2534/// }; 2535/// 2536/// template struct X<int>; 2537/// \endcode 2538/// 2539/// In the instantiation of X<int>::getKind(), we need to map the 2540/// EnumConstantDecl for KnownValue (which refers to 2541/// X<T>::<Kind>::KnownValue) to its instantiation 2542/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 2543/// this mapping from within the instantiation of X<int>. 2544NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 2545 const MultiLevelTemplateArgumentList &TemplateArgs) { 2546 DeclContext *ParentDC = D->getDeclContext(); 2547 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 2548 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 2549 ParentDC->isFunctionOrMethod()) { 2550 // D is a local of some kind. Look into the map of local 2551 // declarations to their instantiations. 2552 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 2553 } 2554 2555 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 2556 if (!Record->isDependentContext()) 2557 return D; 2558 2559 // If the RecordDecl is actually the injected-class-name or a 2560 // "templated" declaration for a class template, class template 2561 // partial specialization, or a member class of a class template, 2562 // substitute into the injected-class-name of the class template 2563 // or partial specialization to find the new DeclContext. 2564 QualType T; 2565 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 2566 2567 if (ClassTemplate) { 2568 T = ClassTemplate->getInjectedClassNameSpecialization(Context); 2569 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 2570 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 2571 ClassTemplate = PartialSpec->getSpecializedTemplate(); 2572 2573 // If we call SubstType with an InjectedClassNameType here we 2574 // can end up in an infinite loop. 2575 T = Context.getTypeDeclType(Record); 2576 assert(isa<InjectedClassNameType>(T) && 2577 "type of partial specialization is not an InjectedClassNameType"); 2578 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 2579 } 2580 2581 if (!T.isNull()) { 2582 // Substitute into the injected-class-name to get the type 2583 // corresponding to the instantiation we want, which may also be 2584 // the current instantiation (if we're in a template 2585 // definition). This substitution should never fail, since we 2586 // know we can instantiate the injected-class-name or we 2587 // wouldn't have gotten to the injected-class-name! 2588 2589 // FIXME: Can we use the CurrentInstantiationScope to avoid this 2590 // extra instantiation in the common case? 2591 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName()); 2592 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail."); 2593 2594 if (!T->isDependentType()) { 2595 assert(T->isRecordType() && "Instantiation must produce a record type"); 2596 return T->getAs<RecordType>()->getDecl(); 2597 } 2598 2599 // We are performing "partial" template instantiation to create 2600 // the member declarations for the members of a class template 2601 // specialization. Therefore, D is actually referring to something 2602 // in the current instantiation. Look through the current 2603 // context, which contains actual instantiations, to find the 2604 // instantiation of the "current instantiation" that D refers 2605 // to. 2606 bool SawNonDependentContext = false; 2607 for (DeclContext *DC = CurContext; !DC->isFileContext(); 2608 DC = DC->getParent()) { 2609 if (ClassTemplateSpecializationDecl *Spec 2610 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 2611 if (isInstantiationOf(ClassTemplate, 2612 Spec->getSpecializedTemplate())) 2613 return Spec; 2614 2615 if (!DC->isDependentContext()) 2616 SawNonDependentContext = true; 2617 } 2618 2619 // We're performing "instantiation" of a member of the current 2620 // instantiation while we are type-checking the 2621 // definition. Compute the declaration context and return that. 2622 assert(!SawNonDependentContext && 2623 "No dependent context while instantiating record"); 2624 DeclContext *DC = computeDeclContext(T); 2625 assert(DC && 2626 "Unable to find declaration for the current instantiation"); 2627 return cast<CXXRecordDecl>(DC); 2628 } 2629 2630 // Fall through to deal with other dependent record types (e.g., 2631 // anonymous unions in class templates). 2632 } 2633 2634 if (!ParentDC->isDependentContext()) 2635 return D; 2636 2637 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 2638 if (!ParentDC) 2639 return 0; 2640 2641 if (ParentDC != D->getDeclContext()) { 2642 // We performed some kind of instantiation in the parent context, 2643 // so now we need to look into the instantiated parent context to 2644 // find the instantiation of the declaration D. 2645 2646 // If our context used to be dependent, we may need to instantiate 2647 // it before performing lookup into that context. 2648 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 2649 if (!Spec->isDependentContext()) { 2650 QualType T = Context.getTypeDeclType(Spec); 2651 const RecordType *Tag = T->getAs<RecordType>(); 2652 assert(Tag && "type of non-dependent record is not a RecordType"); 2653 if (!Tag->isBeingDefined() && 2654 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 2655 return 0; 2656 } 2657 } 2658 2659 NamedDecl *Result = 0; 2660 if (D->getDeclName()) { 2661 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 2662 Result = findInstantiationOf(Context, D, Found.first, Found.second); 2663 } else { 2664 // Since we don't have a name for the entity we're looking for, 2665 // our only option is to walk through all of the declarations to 2666 // find that name. This will occur in a few cases: 2667 // 2668 // - anonymous struct/union within a template 2669 // - unnamed class/struct/union/enum within a template 2670 // 2671 // FIXME: Find a better way to find these instantiations! 2672 Result = findInstantiationOf(Context, D, 2673 ParentDC->decls_begin(), 2674 ParentDC->decls_end()); 2675 } 2676 2677 // UsingShadowDecls can instantiate to nothing because of using hiding. 2678 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() || 2679 cast<Decl>(ParentDC)->isInvalidDecl()) 2680 && "Unable to find instantiation of declaration!"); 2681 2682 D = Result; 2683 } 2684 2685 return D; 2686} 2687 2688/// \brief Performs template instantiation for all implicit template 2689/// instantiations we have seen until this point. 2690void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) { 2691 while (!PendingLocalImplicitInstantiations.empty() || 2692 (!LocalOnly && !PendingImplicitInstantiations.empty())) { 2693 PendingImplicitInstantiation Inst; 2694 2695 if (PendingLocalImplicitInstantiations.empty()) { 2696 Inst = PendingImplicitInstantiations.front(); 2697 PendingImplicitInstantiations.pop_front(); 2698 } else { 2699 Inst = PendingLocalImplicitInstantiations.front(); 2700 PendingLocalImplicitInstantiations.pop_front(); 2701 } 2702 2703 // Instantiate function definitions 2704 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 2705 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function), 2706 Function->getLocation(), *this, 2707 Context.getSourceManager(), 2708 "instantiating function definition"); 2709 2710 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 2711 continue; 2712 } 2713 2714 // Instantiate static data member definitions. 2715 VarDecl *Var = cast<VarDecl>(Inst.first); 2716 assert(Var->isStaticDataMember() && "Not a static data member?"); 2717 2718 // Don't try to instantiate declarations if the most recent redeclaration 2719 // is invalid. 2720 if (Var->getMostRecentDeclaration()->isInvalidDecl()) 2721 continue; 2722 2723 // Check if the most recent declaration has changed the specialization kind 2724 // and removed the need for implicit instantiation. 2725 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) { 2726 case TSK_Undeclared: 2727 assert(false && "Cannot instantitiate an undeclared specialization."); 2728 case TSK_ExplicitInstantiationDeclaration: 2729 case TSK_ExplicitInstantiationDefinition: 2730 case TSK_ExplicitSpecialization: 2731 continue; // No longer need implicit instantiation. 2732 case TSK_ImplicitInstantiation: 2733 break; 2734 } 2735 2736 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var), 2737 Var->getLocation(), *this, 2738 Context.getSourceManager(), 2739 "instantiating static data member " 2740 "definition"); 2741 2742 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 2743 } 2744} 2745 2746void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 2747 const MultiLevelTemplateArgumentList &TemplateArgs) { 2748 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(), 2749 E = Pattern->ddiag_end(); I != E; ++I) { 2750 DependentDiagnostic *DD = *I; 2751 2752 switch (DD->getKind()) { 2753 case DependentDiagnostic::Access: 2754 HandleDependentAccessCheck(*DD, TemplateArgs); 2755 break; 2756 } 2757 } 2758} 2759