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