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