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