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