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