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