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