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