SemaTemplateInstantiateDecl.cpp revision a24dc2e38c7fb0f7f138b3d14b5f0f241fd0eccf
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 "Sema.h" 13#include "clang/AST/ASTConsumer.h" 14#include "clang/AST/ASTContext.h" 15#include "clang/AST/DeclTemplate.h" 16#include "clang/AST/DeclVisitor.h" 17#include "clang/AST/Expr.h" 18#include "clang/Basic/PrettyStackTrace.h" 19#include "clang/Lex/Preprocessor.h" 20#include "llvm/Support/Compiler.h" 21 22using namespace clang; 23 24namespace { 25 class VISIBILITY_HIDDEN TemplateDeclInstantiator 26 : public DeclVisitor<TemplateDeclInstantiator, Decl *> { 27 Sema &SemaRef; 28 DeclContext *Owner; 29 const MultiLevelTemplateArgumentList &TemplateArgs; 30 31 void InstantiateAttrs(Decl *Tmpl, Decl *New); 32 33 public: 34 typedef Sema::OwningExprResult OwningExprResult; 35 36 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner, 37 const MultiLevelTemplateArgumentList &TemplateArgs) 38 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { } 39 40 // FIXME: Once we get closer to completion, replace these manually-written 41 // declarations with automatically-generated ones from 42 // clang/AST/DeclNodes.def. 43 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D); 44 Decl *VisitNamespaceDecl(NamespaceDecl *D); 45 Decl *VisitTypedefDecl(TypedefDecl *D); 46 Decl *VisitVarDecl(VarDecl *D); 47 Decl *VisitFieldDecl(FieldDecl *D); 48 Decl *VisitStaticAssertDecl(StaticAssertDecl *D); 49 Decl *VisitEnumDecl(EnumDecl *D); 50 Decl *VisitEnumConstantDecl(EnumConstantDecl *D); 51 Decl *VisitFriendDecl(FriendDecl *D); 52 Decl *VisitFunctionDecl(FunctionDecl *D, 53 TemplateParameterList *TemplateParams = 0); 54 Decl *VisitCXXRecordDecl(CXXRecordDecl *D); 55 Decl *VisitCXXMethodDecl(CXXMethodDecl *D, 56 TemplateParameterList *TemplateParams = 0); 57 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D); 58 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D); 59 Decl *VisitCXXConversionDecl(CXXConversionDecl *D); 60 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D); 61 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D); 62 Decl *VisitClassTemplatePartialSpecializationDecl( 63 ClassTemplatePartialSpecializationDecl *D); 64 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 65 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 66 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 67 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 68 Decl *VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D); 69 70 // Base case. FIXME: Remove once we can instantiate everything. 71 Decl *VisitDecl(Decl *) { 72 assert(false && "Template instantiation of unknown declaration kind!"); 73 return 0; 74 } 75 76 const LangOptions &getLangOptions() { 77 return SemaRef.getLangOptions(); 78 } 79 80 // Helper functions for instantiating methods. 81 QualType SubstFunctionType(FunctionDecl *D, 82 llvm::SmallVectorImpl<ParmVarDecl *> &Params); 83 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl); 84 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl); 85 86 TemplateParameterList * 87 SubstTemplateParams(TemplateParameterList *List); 88 89 bool InstantiateClassTemplatePartialSpecialization( 90 ClassTemplateDecl *ClassTemplate, 91 ClassTemplatePartialSpecializationDecl *PartialSpec); 92 }; 93} 94 95// FIXME: Is this too simple? 96void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) { 97 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr; 98 TmplAttr = TmplAttr->getNext()) { 99 100 // FIXME: Is cloning correct for all attributes? 101 Attr *NewAttr = TmplAttr->clone(SemaRef.Context); 102 103 New->addAttr(NewAttr); 104 } 105} 106 107Decl * 108TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 109 assert(false && "Translation units cannot be instantiated"); 110 return D; 111} 112 113Decl * 114TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 115 assert(false && "Namespaces cannot be instantiated"); 116 return D; 117} 118 119Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 120 bool Invalid = false; 121 DeclaratorInfo *DI = D->getTypeDeclaratorInfo(); 122 if (DI->getType()->isDependentType()) { 123 DI = SemaRef.SubstType(DI, TemplateArgs, 124 D->getLocation(), D->getDeclName()); 125 if (!DI) { 126 Invalid = true; 127 DI = SemaRef.Context.getTrivialDeclaratorInfo(SemaRef.Context.IntTy); 128 } 129 } 130 131 // Create the new typedef 132 TypedefDecl *Typedef 133 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(), 134 D->getIdentifier(), DI); 135 if (Invalid) 136 Typedef->setInvalidDecl(); 137 138 Owner->addDecl(Typedef); 139 140 return Typedef; 141} 142 143Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 144 // Do substitution on the type of the declaration 145 DeclaratorInfo *DI = SemaRef.SubstType(D->getDeclaratorInfo(), 146 TemplateArgs, 147 D->getTypeSpecStartLoc(), 148 D->getDeclName()); 149 if (!DI) 150 return 0; 151 152 // Build the instantiated declaration 153 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 154 D->getLocation(), D->getIdentifier(), 155 DI->getType(), DI, 156 D->getStorageClass()); 157 Var->setThreadSpecified(D->isThreadSpecified()); 158 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 159 Var->setDeclaredInCondition(D->isDeclaredInCondition()); 160 161 // If we are instantiating a static data member defined 162 // out-of-line, the instantiation will have the same lexical 163 // context (which will be a namespace scope) as the template. 164 if (D->isOutOfLine()) 165 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 166 167 // FIXME: In theory, we could have a previous declaration for variables that 168 // are not static data members. 169 bool Redeclaration = false; 170 SemaRef.CheckVariableDeclaration(Var, 0, Redeclaration); 171 172 if (D->isOutOfLine()) { 173 D->getLexicalDeclContext()->addDecl(Var); 174 Owner->makeDeclVisibleInContext(Var); 175 } else { 176 Owner->addDecl(Var); 177 } 178 179 // Link instantiations of static data members back to the template from 180 // which they were instantiated. 181 if (Var->isStaticDataMember()) 182 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 183 TSK_ImplicitInstantiation); 184 185 if (D->getInit()) { 186 OwningExprResult Init 187 = SemaRef.SubstExpr(D->getInit(), TemplateArgs); 188 if (Init.isInvalid()) 189 Var->setInvalidDecl(); 190 else if (!D->getType()->isDependentType() && 191 !D->getInit()->isTypeDependent() && 192 !D->getInit()->isValueDependent()) { 193 // If neither the declaration's type nor its initializer are dependent, 194 // we don't want to redo all the checking, especially since the 195 // initializer might have been wrapped by a CXXConstructExpr since we did 196 // it the first time. 197 Var->setInit(SemaRef.Context, Init.takeAs<Expr>()); 198 } 199 else if (ParenListExpr *PLE = dyn_cast<ParenListExpr>((Expr *)Init.get())) { 200 // FIXME: We're faking all of the comma locations, which is suboptimal. 201 // Do we even need these comma locations? 202 llvm::SmallVector<SourceLocation, 4> FakeCommaLocs; 203 if (PLE->getNumExprs() > 0) { 204 FakeCommaLocs.reserve(PLE->getNumExprs() - 1); 205 for (unsigned I = 0, N = PLE->getNumExprs() - 1; I != N; ++I) { 206 Expr *E = PLE->getExpr(I)->Retain(); 207 FakeCommaLocs.push_back( 208 SemaRef.PP.getLocForEndOfToken(E->getLocEnd())); 209 } 210 PLE->getExpr(PLE->getNumExprs() - 1)->Retain(); 211 } 212 213 // Add the direct initializer to the declaration. 214 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var), 215 PLE->getLParenLoc(), 216 Sema::MultiExprArg(SemaRef, 217 (void**)PLE->getExprs(), 218 PLE->getNumExprs()), 219 FakeCommaLocs.data(), 220 PLE->getRParenLoc()); 221 222 // When Init is destroyed, it will destroy the instantiated ParenListExpr; 223 // we've explicitly retained all of its subexpressions already. 224 } else 225 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var), move(Init), 226 D->hasCXXDirectInitializer()); 227 } else if (!Var->isStaticDataMember() || Var->isOutOfLine()) 228 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false); 229 230 return Var; 231} 232 233Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 234 bool Invalid = false; 235 DeclaratorInfo *DI = D->getDeclaratorInfo(); 236 if (DI->getType()->isDependentType()) { 237 DI = SemaRef.SubstType(DI, TemplateArgs, 238 D->getLocation(), D->getDeclName()); 239 if (!DI) { 240 DI = D->getDeclaratorInfo(); 241 Invalid = true; 242 } else if (DI->getType()->isFunctionType()) { 243 // C++ [temp.arg.type]p3: 244 // If a declaration acquires a function type through a type 245 // dependent on a template-parameter and this causes a 246 // declaration that does not use the syntactic form of a 247 // function declarator to have function type, the program is 248 // ill-formed. 249 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 250 << DI->getType(); 251 Invalid = true; 252 } 253 } 254 255 Expr *BitWidth = D->getBitWidth(); 256 if (Invalid) 257 BitWidth = 0; 258 else if (BitWidth) { 259 // The bit-width expression is not potentially evaluated. 260 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 261 262 OwningExprResult InstantiatedBitWidth 263 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 264 if (InstantiatedBitWidth.isInvalid()) { 265 Invalid = true; 266 BitWidth = 0; 267 } else 268 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 269 } 270 271 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 272 DI->getType(), DI, 273 cast<RecordDecl>(Owner), 274 D->getLocation(), 275 D->isMutable(), 276 BitWidth, 277 D->getTypeSpecStartLoc(), 278 D->getAccess(), 279 0); 280 if (!Field) { 281 cast<Decl>(Owner)->setInvalidDecl(); 282 return 0; 283 } 284 285 InstantiateAttrs(D, Field); 286 287 if (Invalid) 288 Field->setInvalidDecl(); 289 290 if (!Field->getDeclName()) { 291 // Keep track of where this decl came from. 292 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 293 } 294 295 Field->setImplicit(D->isImplicit()); 296 Owner->addDecl(Field); 297 298 return Field; 299} 300 301Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 302 FriendDecl::FriendUnion FU; 303 304 // Handle friend type expressions by simply substituting template 305 // parameters into the pattern type. 306 if (Type *Ty = D->getFriendType()) { 307 QualType T = SemaRef.SubstType(QualType(Ty,0), TemplateArgs, 308 D->getLocation(), DeclarationName()); 309 if (T.isNull()) return 0; 310 311 assert(getLangOptions().CPlusPlus0x || T->isRecordType()); 312 FU = T.getTypePtr(); 313 314 // Handle everything else by appropriate substitution. 315 } else { 316 NamedDecl *ND = D->getFriendDecl(); 317 assert(ND && "friend decl must be a decl or a type!"); 318 319 // FIXME: We have a problem here, because the nested call to Visit(ND) 320 // will inject the thing that the friend references into the current 321 // owner, which is wrong. 322 Decl *NewND = Visit(ND); 323 if (!NewND) return 0; 324 325 FU = cast<NamedDecl>(NewND); 326 } 327 328 FriendDecl *FD = 329 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU, 330 D->getFriendLoc()); 331 FD->setAccess(AS_public); 332 Owner->addDecl(FD); 333 return FD; 334} 335 336Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 337 Expr *AssertExpr = D->getAssertExpr(); 338 339 // The expression in a static assertion is not potentially evaluated. 340 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated); 341 342 OwningExprResult InstantiatedAssertExpr 343 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 344 if (InstantiatedAssertExpr.isInvalid()) 345 return 0; 346 347 OwningExprResult Message(SemaRef, D->getMessage()); 348 D->getMessage()->Retain(); 349 Decl *StaticAssert 350 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 351 move(InstantiatedAssertExpr), 352 move(Message)).getAs<Decl>(); 353 return StaticAssert; 354} 355 356Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 357 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, 358 D->getLocation(), D->getIdentifier(), 359 D->getTagKeywordLoc(), 360 /*PrevDecl=*/0); 361 Enum->setInstantiationOfMemberEnum(D); 362 Enum->setAccess(D->getAccess()); 363 Owner->addDecl(Enum); 364 Enum->startDefinition(); 365 366 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators; 367 368 EnumConstantDecl *LastEnumConst = 0; 369 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 370 ECEnd = D->enumerator_end(); 371 EC != ECEnd; ++EC) { 372 // The specified value for the enumerator. 373 OwningExprResult Value = SemaRef.Owned((Expr *)0); 374 if (Expr *UninstValue = EC->getInitExpr()) { 375 // The enumerator's value expression is not potentially evaluated. 376 EnterExpressionEvaluationContext Unevaluated(SemaRef, 377 Action::Unevaluated); 378 379 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 380 } 381 382 // Drop the initial value and continue. 383 bool isInvalid = false; 384 if (Value.isInvalid()) { 385 Value = SemaRef.Owned((Expr *)0); 386 isInvalid = true; 387 } 388 389 EnumConstantDecl *EnumConst 390 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 391 EC->getLocation(), EC->getIdentifier(), 392 move(Value)); 393 394 if (isInvalid) { 395 if (EnumConst) 396 EnumConst->setInvalidDecl(); 397 Enum->setInvalidDecl(); 398 } 399 400 if (EnumConst) { 401 Enum->addDecl(EnumConst); 402 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst)); 403 LastEnumConst = EnumConst; 404 } 405 } 406 407 // FIXME: Fixup LBraceLoc and RBraceLoc 408 // FIXME: Empty Scope and AttributeList (required to handle attribute packed). 409 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 410 Sema::DeclPtrTy::make(Enum), 411 &Enumerators[0], Enumerators.size(), 412 0, 0); 413 414 return Enum; 415} 416 417Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 418 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 419 return 0; 420} 421 422namespace { 423 class SortDeclByLocation { 424 SourceManager &SourceMgr; 425 426 public: 427 explicit SortDeclByLocation(SourceManager &SourceMgr) 428 : SourceMgr(SourceMgr) { } 429 430 bool operator()(const Decl *X, const Decl *Y) const { 431 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(), 432 Y->getLocation()); 433 } 434 }; 435} 436 437Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 438 // Create a local instantiation scope for this class template, which 439 // will contain the instantiations of the template parameters. 440 Sema::LocalInstantiationScope Scope(SemaRef); 441 TemplateParameterList *TempParams = D->getTemplateParameters(); 442 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 443 if (!InstParams) 444 return NULL; 445 446 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 447 CXXRecordDecl *RecordInst 448 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), Owner, 449 Pattern->getLocation(), Pattern->getIdentifier(), 450 Pattern->getTagKeywordLoc(), /*PrevDecl=*/ NULL, 451 /*DelayTypeCreation=*/true); 452 453 ClassTemplateDecl *Inst 454 = ClassTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 455 D->getIdentifier(), InstParams, RecordInst, 0); 456 RecordInst->setDescribedClassTemplate(Inst); 457 if (D->getFriendObjectKind()) 458 Inst->setObjectOfFriendDecl(true); 459 else 460 Inst->setAccess(D->getAccess()); 461 Inst->setInstantiatedFromMemberTemplate(D); 462 463 // Trigger creation of the type for the instantiation. 464 SemaRef.Context.getTypeDeclType(RecordInst); 465 466 // Finish handling of friends. 467 if (Inst->getFriendObjectKind()) { 468 return Inst; 469 } 470 471 Owner->addDecl(Inst); 472 473 // First, we sort the partial specializations by location, so 474 // that we instantiate them in the order they were declared. 475 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 476 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 477 P = D->getPartialSpecializations().begin(), 478 PEnd = D->getPartialSpecializations().end(); 479 P != PEnd; ++P) 480 PartialSpecs.push_back(&*P); 481 std::sort(PartialSpecs.begin(), PartialSpecs.end(), 482 SortDeclByLocation(SemaRef.SourceMgr)); 483 484 // Instantiate all of the partial specializations of this member class 485 // template. 486 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 487 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]); 488 489 return Inst; 490} 491 492Decl * 493TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 494 ClassTemplatePartialSpecializationDecl *D) { 495 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 496 497 // Lookup the already-instantiated declaration in the instantiation 498 // of the class template and return that. 499 DeclContext::lookup_result Found 500 = Owner->lookup(ClassTemplate->getDeclName()); 501 if (Found.first == Found.second) 502 return 0; 503 504 ClassTemplateDecl *InstClassTemplate 505 = dyn_cast<ClassTemplateDecl>(*Found.first); 506 if (!InstClassTemplate) 507 return 0; 508 509 Decl *DCanon = D->getCanonicalDecl(); 510 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator 511 P = InstClassTemplate->getPartialSpecializations().begin(), 512 PEnd = InstClassTemplate->getPartialSpecializations().end(); 513 P != PEnd; ++P) { 514 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon) 515 return &*P; 516 } 517 518 return 0; 519} 520 521Decl * 522TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 523 // Create a local instantiation scope for this function template, which 524 // will contain the instantiations of the template parameters and then get 525 // merged with the local instantiation scope for the function template 526 // itself. 527 Sema::LocalInstantiationScope Scope(SemaRef); 528 529 TemplateParameterList *TempParams = D->getTemplateParameters(); 530 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 531 if (!InstParams) 532 return NULL; 533 534 FunctionDecl *Instantiated = 0; 535 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 536 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 537 InstParams)); 538 else 539 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 540 D->getTemplatedDecl(), 541 InstParams)); 542 543 if (!Instantiated) 544 return 0; 545 546 // Link the instantiated function template declaration to the function 547 // template from which it was instantiated. 548 FunctionTemplateDecl *InstTemplate 549 = Instantiated->getDescribedFunctionTemplate(); 550 InstTemplate->setAccess(D->getAccess()); 551 assert(InstTemplate && 552 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 553 if (!InstTemplate->getInstantiatedFromMemberTemplate()) 554 InstTemplate->setInstantiatedFromMemberTemplate(D); 555 556 // Add non-friends into the owner. 557 if (!InstTemplate->getFriendObjectKind()) 558 Owner->addDecl(InstTemplate); 559 return InstTemplate; 560} 561 562Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 563 CXXRecordDecl *PrevDecl = 0; 564 if (D->isInjectedClassName()) 565 PrevDecl = cast<CXXRecordDecl>(Owner); 566 567 CXXRecordDecl *Record 568 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 569 D->getLocation(), D->getIdentifier(), 570 D->getTagKeywordLoc(), PrevDecl); 571 Record->setImplicit(D->isImplicit()); 572 // FIXME: Check against AS_none is an ugly hack to work around the issue that 573 // the tag decls introduced by friend class declarations don't have an access 574 // specifier. Remove once this area of the code gets sorted out. 575 if (D->getAccess() != AS_none) 576 Record->setAccess(D->getAccess()); 577 if (!D->isInjectedClassName()) 578 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 579 580 // If the original function was part of a friend declaration, 581 // inherit its namespace state. 582 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 583 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 584 585 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion()); 586 587 Owner->addDecl(Record); 588 return Record; 589} 590 591/// Normal class members are of more specific types and therefore 592/// don't make it here. This function serves two purposes: 593/// 1) instantiating function templates 594/// 2) substituting friend declarations 595/// FIXME: preserve function definitions in case #2 596 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 597 TemplateParameterList *TemplateParams) { 598 // Check whether there is already a function template specialization for 599 // this declaration. 600 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 601 void *InsertPos = 0; 602 if (FunctionTemplate && !TemplateParams) { 603 llvm::FoldingSetNodeID ID; 604 FunctionTemplateSpecializationInfo::Profile(ID, 605 TemplateArgs.getInnermost().getFlatArgumentList(), 606 TemplateArgs.getInnermost().flat_size(), 607 SemaRef.Context); 608 609 FunctionTemplateSpecializationInfo *Info 610 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 611 InsertPos); 612 613 // If we already have a function template specialization, return it. 614 if (Info) 615 return Info->Function; 616 } 617 618 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0); 619 620 llvm::SmallVector<ParmVarDecl *, 4> Params; 621 QualType T = SubstFunctionType(D, Params); 622 if (T.isNull()) 623 return 0; 624 625 // Build the instantiated method declaration. 626 DeclContext *DC = SemaRef.FindInstantiatedContext(D->getDeclContext(), 627 TemplateArgs); 628 FunctionDecl *Function = 629 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(), 630 D->getDeclName(), T, D->getDeclaratorInfo(), 631 D->getStorageClass(), 632 D->isInlineSpecified(), D->hasWrittenPrototype()); 633 Function->setLexicalDeclContext(Owner); 634 635 // Attach the parameters 636 for (unsigned P = 0; P < Params.size(); ++P) 637 Params[P]->setOwningFunction(Function); 638 Function->setParams(SemaRef.Context, Params.data(), Params.size()); 639 640 if (TemplateParams) { 641 // Our resulting instantiation is actually a function template, since we 642 // are substituting only the outer template parameters. For example, given 643 // 644 // template<typename T> 645 // struct X { 646 // template<typename U> friend void f(T, U); 647 // }; 648 // 649 // X<int> x; 650 // 651 // We are instantiating the friend function template "f" within X<int>, 652 // which means substituting int for T, but leaving "f" as a friend function 653 // template. 654 // Build the function template itself. 655 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Owner, 656 Function->getLocation(), 657 Function->getDeclName(), 658 TemplateParams, Function); 659 Function->setDescribedFunctionTemplate(FunctionTemplate); 660 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 661 } else if (FunctionTemplate) { 662 // Record this function template specialization. 663 Function->setFunctionTemplateSpecialization(SemaRef.Context, 664 FunctionTemplate, 665 &TemplateArgs.getInnermost(), 666 InsertPos); 667 } 668 669 if (InitFunctionInstantiation(Function, D)) 670 Function->setInvalidDecl(); 671 672 bool Redeclaration = false; 673 bool OverloadableAttrRequired = false; 674 675 NamedDecl *PrevDecl = 0; 676 if (TemplateParams || !FunctionTemplate) { 677 // Look only into the namespace where the friend would be declared to 678 // find a previous declaration. This is the innermost enclosing namespace, 679 // as described in ActOnFriendFunctionDecl. 680 Sema::LookupResult R(SemaRef, Function->getDeclName(), SourceLocation(), 681 Sema::LookupOrdinaryName, 682 Sema::LookupResult::ForRedeclaration); 683 SemaRef.LookupQualifiedName(R, DC); 684 685 PrevDecl = R.getAsSingleDecl(SemaRef.Context); 686 687 // In C++, the previous declaration we find might be a tag type 688 // (class or enum). In this case, the new declaration will hide the 689 // tag type. Note that this does does not apply if we're declaring a 690 // typedef (C++ [dcl.typedef]p4). 691 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 692 PrevDecl = 0; 693 } 694 695 SemaRef.CheckFunctionDeclaration(Function, PrevDecl, false, Redeclaration, 696 /*FIXME:*/OverloadableAttrRequired); 697 698 // If the original function was part of a friend declaration, 699 // inherit its namespace state and add it to the owner. 700 NamedDecl *FromFriendD 701 = TemplateParams? cast<NamedDecl>(D->getDescribedFunctionTemplate()) : D; 702 if (FromFriendD->getFriendObjectKind()) { 703 NamedDecl *ToFriendD = 0; 704 if (TemplateParams) { 705 ToFriendD = cast<NamedDecl>(FunctionTemplate); 706 PrevDecl = FunctionTemplate->getPreviousDeclaration(); 707 } else { 708 ToFriendD = Function; 709 PrevDecl = Function->getPreviousDeclaration(); 710 } 711 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL); 712 if (!Owner->isDependentContext() && !PrevDecl) 713 DC->makeDeclVisibleInContext(ToFriendD, /* Recoverable = */ false); 714 715 if (!TemplateParams) 716 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 717 } 718 719 return Function; 720} 721 722Decl * 723TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 724 TemplateParameterList *TemplateParams) { 725 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 726 void *InsertPos = 0; 727 if (FunctionTemplate && !TemplateParams) { 728 // We are creating a function template specialization from a function 729 // template. Check whether there is already a function template 730 // specialization for this particular set of template arguments. 731 llvm::FoldingSetNodeID ID; 732 FunctionTemplateSpecializationInfo::Profile(ID, 733 TemplateArgs.getInnermost().getFlatArgumentList(), 734 TemplateArgs.getInnermost().flat_size(), 735 SemaRef.Context); 736 737 FunctionTemplateSpecializationInfo *Info 738 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID, 739 InsertPos); 740 741 // If we already have a function template specialization, return it. 742 if (Info) 743 return Info->Function; 744 } 745 746 Sema::LocalInstantiationScope Scope(SemaRef, TemplateParams != 0); 747 748 llvm::SmallVector<ParmVarDecl *, 4> Params; 749 QualType T = SubstFunctionType(D, Params); 750 if (T.isNull()) 751 return 0; 752 753 // Build the instantiated method declaration. 754 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 755 CXXMethodDecl *Method = 0; 756 757 DeclarationName Name = D->getDeclName(); 758 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 759 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 760 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName( 761 SemaRef.Context.getCanonicalType(ClassTy)); 762 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 763 Constructor->getLocation(), 764 Name, T, 765 Constructor->getDeclaratorInfo(), 766 Constructor->isExplicit(), 767 Constructor->isInlineSpecified(), false); 768 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 769 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record); 770 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName( 771 SemaRef.Context.getCanonicalType(ClassTy)); 772 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 773 Destructor->getLocation(), Name, 774 T, Destructor->isInlineSpecified(), false); 775 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 776 CanQualType ConvTy 777 = SemaRef.Context.getCanonicalType( 778 T->getAs<FunctionType>()->getResultType()); 779 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName( 780 ConvTy); 781 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 782 Conversion->getLocation(), Name, 783 T, Conversion->getDeclaratorInfo(), 784 Conversion->isInlineSpecified(), 785 Conversion->isExplicit()); 786 } else { 787 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(), 788 D->getDeclName(), T, D->getDeclaratorInfo(), 789 D->isStatic(), D->isInlineSpecified()); 790 } 791 792 if (TemplateParams) { 793 // Our resulting instantiation is actually a function template, since we 794 // are substituting only the outer template parameters. For example, given 795 // 796 // template<typename T> 797 // struct X { 798 // template<typename U> void f(T, U); 799 // }; 800 // 801 // X<int> x; 802 // 803 // We are instantiating the member template "f" within X<int>, which means 804 // substituting int for T, but leaving "f" as a member function template. 805 // Build the function template itself. 806 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 807 Method->getLocation(), 808 Method->getDeclName(), 809 TemplateParams, Method); 810 if (D->isOutOfLine()) 811 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 812 Method->setDescribedFunctionTemplate(FunctionTemplate); 813 } else if (FunctionTemplate) { 814 // Record this function template specialization. 815 Method->setFunctionTemplateSpecialization(SemaRef.Context, 816 FunctionTemplate, 817 &TemplateArgs.getInnermost(), 818 InsertPos); 819 } else { 820 // Record that this is an instantiation of a member function. 821 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 822 } 823 824 // If we are instantiating a member function defined 825 // out-of-line, the instantiation will have the same lexical 826 // context (which will be a namespace scope) as the template. 827 if (D->isOutOfLine()) 828 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 829 830 // Attach the parameters 831 for (unsigned P = 0; P < Params.size(); ++P) 832 Params[P]->setOwningFunction(Method); 833 Method->setParams(SemaRef.Context, Params.data(), Params.size()); 834 835 if (InitMethodInstantiation(Method, D)) 836 Method->setInvalidDecl(); 837 838 NamedDecl *PrevDecl = 0; 839 840 if (!FunctionTemplate || TemplateParams) { 841 Sema::LookupResult R(SemaRef, Name, SourceLocation(), 842 Sema::LookupOrdinaryName, 843 Sema::LookupResult::ForRedeclaration); 844 SemaRef.LookupQualifiedName(R, Owner); 845 PrevDecl = R.getAsSingleDecl(SemaRef.Context); 846 847 // In C++, the previous declaration we find might be a tag type 848 // (class or enum). In this case, the new declaration will hide the 849 // tag type. Note that this does does not apply if we're declaring a 850 // typedef (C++ [dcl.typedef]p4). 851 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 852 PrevDecl = 0; 853 } 854 855 bool Redeclaration = false; 856 bool OverloadableAttrRequired = false; 857 SemaRef.CheckFunctionDeclaration(Method, PrevDecl, false, Redeclaration, 858 /*FIXME:*/OverloadableAttrRequired); 859 860 if (!FunctionTemplate && (!Method->isInvalidDecl() || !PrevDecl) && 861 !Method->getFriendObjectKind()) 862 Owner->addDecl(Method); 863 864 return Method; 865} 866 867Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 868 return VisitCXXMethodDecl(D); 869} 870 871Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 872 return VisitCXXMethodDecl(D); 873} 874 875Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 876 return VisitCXXMethodDecl(D); 877} 878 879ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 880 QualType T; 881 DeclaratorInfo *DI = D->getDeclaratorInfo(); 882 if (DI) { 883 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 884 D->getDeclName()); 885 if (DI) T = DI->getType(); 886 } else { 887 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 888 D->getDeclName()); 889 DI = 0; 890 } 891 892 if (T.isNull()) 893 return 0; 894 895 T = SemaRef.adjustParameterType(T); 896 897 // Allocate the parameter 898 ParmVarDecl *Param 899 = ParmVarDecl::Create(SemaRef.Context, Owner, D->getLocation(), 900 D->getIdentifier(), T, DI, D->getStorageClass(), 0); 901 902 // Mark the default argument as being uninstantiated. 903 if (D->hasUninstantiatedDefaultArg()) 904 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg()); 905 else if (Expr *Arg = D->getDefaultArg()) 906 Param->setUninstantiatedDefaultArg(Arg); 907 908 // Note: we don't try to instantiate function parameters until after 909 // we've instantiated the function's type. Therefore, we don't have 910 // to check for 'void' parameter types here. 911 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 912 return Param; 913} 914 915Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 916 TemplateTypeParmDecl *D) { 917 // TODO: don't always clone when decls are refcounted. 918 const Type* T = D->getTypeForDecl(); 919 assert(T->isTemplateTypeParmType()); 920 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>(); 921 922 TemplateTypeParmDecl *Inst = 923 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 924 TTPT->getDepth() - 1, TTPT->getIndex(), 925 TTPT->getName(), 926 D->wasDeclaredWithTypename(), 927 D->isParameterPack()); 928 929 if (D->hasDefaultArgument()) 930 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 931 932 // Introduce this template parameter's instantiation into the instantiation 933 // scope. 934 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 935 936 return Inst; 937} 938 939Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 940 NonTypeTemplateParmDecl *D) { 941 // Substitute into the type of the non-type template parameter. 942 QualType T; 943 DeclaratorInfo *DI = D->getDeclaratorInfo(); 944 if (DI) { 945 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(), 946 D->getDeclName()); 947 if (DI) T = DI->getType(); 948 } else { 949 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(), 950 D->getDeclName()); 951 DI = 0; 952 } 953 if (T.isNull()) 954 return 0; 955 956 // Check that this type is acceptable for a non-type template parameter. 957 bool Invalid = false; 958 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation()); 959 if (T.isNull()) { 960 T = SemaRef.Context.IntTy; 961 Invalid = true; 962 } 963 964 NonTypeTemplateParmDecl *Param 965 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 966 D->getDepth() - 1, D->getPosition(), 967 D->getIdentifier(), T, DI); 968 if (Invalid) 969 Param->setInvalidDecl(); 970 971 Param->setDefaultArgument(D->getDefaultArgument()); 972 973 // Introduce this template parameter's instantiation into the instantiation 974 // scope. 975 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 976 return Param; 977} 978 979Decl * 980TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 981 TemplateTemplateParmDecl *D) { 982 // Instantiate the template parameter list of the template template parameter. 983 TemplateParameterList *TempParams = D->getTemplateParameters(); 984 TemplateParameterList *InstParams; 985 { 986 // Perform the actual substitution of template parameters within a new, 987 // local instantiation scope. 988 Sema::LocalInstantiationScope Scope(SemaRef); 989 InstParams = SubstTemplateParams(TempParams); 990 if (!InstParams) 991 return NULL; 992 } 993 994 // Build the template template parameter. 995 TemplateTemplateParmDecl *Param 996 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 997 D->getDepth() - 1, D->getPosition(), 998 D->getIdentifier(), InstParams); 999 Param->setDefaultArgument(D->getDefaultArgument()); 1000 1001 // Introduce this template parameter's instantiation into the instantiation 1002 // scope. 1003 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1004 1005 return Param; 1006} 1007 1008Decl * 1009TemplateDeclInstantiator::VisitUnresolvedUsingDecl(UnresolvedUsingDecl *D) { 1010 NestedNameSpecifier *NNS = 1011 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(), 1012 D->getTargetNestedNameRange(), 1013 TemplateArgs); 1014 if (!NNS) 1015 return 0; 1016 1017 CXXScopeSpec SS; 1018 SS.setRange(D->getTargetNestedNameRange()); 1019 SS.setScopeRep(NNS); 1020 1021 NamedDecl *UD = 1022 SemaRef.BuildUsingDeclaration(D->getLocation(), SS, 1023 D->getTargetNameLocation(), 1024 D->getTargetName(), 0, D->isTypeName()); 1025 if (UD) 1026 SemaRef.Context.setInstantiatedFromUnresolvedUsingDecl(cast<UsingDecl>(UD), 1027 D); 1028 return UD; 1029} 1030 1031Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 1032 const MultiLevelTemplateArgumentList &TemplateArgs) { 1033 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 1034 return Instantiator.Visit(D); 1035} 1036 1037/// \brief Instantiates a nested template parameter list in the current 1038/// instantiation context. 1039/// 1040/// \param L The parameter list to instantiate 1041/// 1042/// \returns NULL if there was an error 1043TemplateParameterList * 1044TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 1045 // Get errors for all the parameters before bailing out. 1046 bool Invalid = false; 1047 1048 unsigned N = L->size(); 1049 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector; 1050 ParamVector Params; 1051 Params.reserve(N); 1052 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 1053 PI != PE; ++PI) { 1054 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 1055 Params.push_back(D); 1056 Invalid = Invalid || !D || D->isInvalidDecl(); 1057 } 1058 1059 // Clean up if we had an error. 1060 if (Invalid) { 1061 for (ParamVector::iterator PI = Params.begin(), PE = Params.end(); 1062 PI != PE; ++PI) 1063 if (*PI) 1064 (*PI)->Destroy(SemaRef.Context); 1065 return NULL; 1066 } 1067 1068 TemplateParameterList *InstL 1069 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 1070 L->getLAngleLoc(), &Params.front(), N, 1071 L->getRAngleLoc()); 1072 return InstL; 1073} 1074 1075/// \brief Instantiate the declaration of a class template partial 1076/// specialization. 1077/// 1078/// \param ClassTemplate the (instantiated) class template that is partially 1079// specialized by the instantiation of \p PartialSpec. 1080/// 1081/// \param PartialSpec the (uninstantiated) class template partial 1082/// specialization that we are instantiating. 1083/// 1084/// \returns true if there was an error, false otherwise. 1085bool 1086TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 1087 ClassTemplateDecl *ClassTemplate, 1088 ClassTemplatePartialSpecializationDecl *PartialSpec) { 1089 // Create a local instantiation scope for this class template partial 1090 // specialization, which will contain the instantiations of the template 1091 // parameters. 1092 Sema::LocalInstantiationScope Scope(SemaRef); 1093 1094 // Substitute into the template parameters of the class template partial 1095 // specialization. 1096 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 1097 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1098 if (!InstParams) 1099 return true; 1100 1101 // Substitute into the template arguments of the class template partial 1102 // specialization. 1103 const TemplateArgumentLoc *PartialSpecTemplateArgs 1104 = PartialSpec->getTemplateArgsAsWritten(); 1105 unsigned N = PartialSpec->getNumTemplateArgsAsWritten(); 1106 1107 llvm::SmallVector<TemplateArgumentLoc, 4> InstTemplateArgs(N); 1108 for (unsigned I = 0; I != N; ++I) { 1109 if (SemaRef.Subst(PartialSpecTemplateArgs[I], InstTemplateArgs[I], 1110 TemplateArgs)) 1111 return true; 1112 } 1113 1114 1115 // Check that the template argument list is well-formed for this 1116 // class template. 1117 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 1118 InstTemplateArgs.size()); 1119 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 1120 PartialSpec->getLocation(), 1121 /*FIXME:*/PartialSpec->getLocation(), 1122 InstTemplateArgs.data(), 1123 InstTemplateArgs.size(), 1124 /*FIXME:*/PartialSpec->getLocation(), 1125 false, 1126 Converted)) 1127 return true; 1128 1129 // Figure out where to insert this class template partial specialization 1130 // in the member template's set of class template partial specializations. 1131 llvm::FoldingSetNodeID ID; 1132 ClassTemplatePartialSpecializationDecl::Profile(ID, 1133 Converted.getFlatArguments(), 1134 Converted.flatSize(), 1135 SemaRef.Context); 1136 void *InsertPos = 0; 1137 ClassTemplateSpecializationDecl *PrevDecl 1138 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 1139 InsertPos); 1140 1141 // Build the canonical type that describes the converted template 1142 // arguments of the class template partial specialization. 1143 QualType CanonType 1144 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1145 Converted.getFlatArguments(), 1146 Converted.flatSize()); 1147 1148 // Build the fully-sugared type for this class template 1149 // specialization as the user wrote in the specialization 1150 // itself. This means that we'll pretty-print the type retrieved 1151 // from the specialization's declaration the way that the user 1152 // actually wrote the specialization, rather than formatting the 1153 // name based on the "canonical" representation used to store the 1154 // template arguments in the specialization. 1155 QualType WrittenTy 1156 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 1157 InstTemplateArgs.data(), 1158 InstTemplateArgs.size(), 1159 CanonType); 1160 1161 if (PrevDecl) { 1162 // We've already seen a partial specialization with the same template 1163 // parameters and template arguments. This can happen, for example, when 1164 // substituting the outer template arguments ends up causing two 1165 // class template partial specializations of a member class template 1166 // to have identical forms, e.g., 1167 // 1168 // template<typename T, typename U> 1169 // struct Outer { 1170 // template<typename X, typename Y> struct Inner; 1171 // template<typename Y> struct Inner<T, Y>; 1172 // template<typename Y> struct Inner<U, Y>; 1173 // }; 1174 // 1175 // Outer<int, int> outer; // error: the partial specializations of Inner 1176 // // have the same signature. 1177 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 1178 << WrittenTy; 1179 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 1180 << SemaRef.Context.getTypeDeclType(PrevDecl); 1181 return true; 1182 } 1183 1184 1185 // Create the class template partial specialization declaration. 1186 ClassTemplatePartialSpecializationDecl *InstPartialSpec 1187 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner, 1188 PartialSpec->getLocation(), 1189 InstParams, 1190 ClassTemplate, 1191 Converted, 1192 InstTemplateArgs.data(), 1193 InstTemplateArgs.size(), 1194 0); 1195 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 1196 InstPartialSpec->setTypeAsWritten(WrittenTy); 1197 1198 // Add this partial specialization to the set of class template partial 1199 // specializations. 1200 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec, 1201 InsertPos); 1202 return false; 1203} 1204 1205/// \brief Does substitution on the type of the given function, including 1206/// all of the function parameters. 1207/// 1208/// \param D The function whose type will be the basis of the substitution 1209/// 1210/// \param Params the instantiated parameter declarations 1211 1212/// \returns the instantiated function's type if successful, a NULL 1213/// type if there was an error. 1214QualType 1215TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 1216 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 1217 bool InvalidDecl = false; 1218 1219 // Substitute all of the function's formal parameter types. 1220 TemplateDeclInstantiator ParamInstantiator(SemaRef, 0, TemplateArgs); 1221 llvm::SmallVector<QualType, 4> ParamTys; 1222 for (FunctionDecl::param_iterator P = D->param_begin(), 1223 PEnd = D->param_end(); 1224 P != PEnd; ++P) { 1225 if (ParmVarDecl *PInst = ParamInstantiator.VisitParmVarDecl(*P)) { 1226 if (PInst->getType()->isVoidType()) { 1227 SemaRef.Diag(PInst->getLocation(), diag::err_param_with_void_type); 1228 PInst->setInvalidDecl(); 1229 } else if (SemaRef.RequireNonAbstractType(PInst->getLocation(), 1230 PInst->getType(), 1231 diag::err_abstract_type_in_decl, 1232 Sema::AbstractParamType)) 1233 PInst->setInvalidDecl(); 1234 1235 Params.push_back(PInst); 1236 ParamTys.push_back(PInst->getType()); 1237 1238 if (PInst->isInvalidDecl()) 1239 InvalidDecl = true; 1240 } else 1241 InvalidDecl = true; 1242 } 1243 1244 // FIXME: Deallocate dead declarations. 1245 if (InvalidDecl) 1246 return QualType(); 1247 1248 const FunctionProtoType *Proto = D->getType()->getAs<FunctionProtoType>(); 1249 assert(Proto && "Missing prototype?"); 1250 QualType ResultType 1251 = SemaRef.SubstType(Proto->getResultType(), TemplateArgs, 1252 D->getLocation(), D->getDeclName()); 1253 if (ResultType.isNull()) 1254 return QualType(); 1255 1256 return SemaRef.BuildFunctionType(ResultType, ParamTys.data(), ParamTys.size(), 1257 Proto->isVariadic(), Proto->getTypeQuals(), 1258 D->getLocation(), D->getDeclName()); 1259} 1260 1261/// \brief Initializes the common fields of an instantiation function 1262/// declaration (New) from the corresponding fields of its template (Tmpl). 1263/// 1264/// \returns true if there was an error 1265bool 1266TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 1267 FunctionDecl *Tmpl) { 1268 if (Tmpl->isDeleted()) 1269 New->setDeleted(); 1270 1271 // If we are performing substituting explicitly-specified template arguments 1272 // or deduced template arguments into a function template and we reach this 1273 // point, we are now past the point where SFINAE applies and have committed 1274 // to keeping the new function template specialization. We therefore 1275 // convert the active template instantiation for the function template 1276 // into a template instantiation for this specific function template 1277 // specialization, which is not a SFINAE context, so that we diagnose any 1278 // further errors in the declaration itself. 1279 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 1280 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 1281 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 1282 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 1283 if (FunctionTemplateDecl *FunTmpl 1284 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 1285 assert(FunTmpl->getTemplatedDecl() == Tmpl && 1286 "Deduction from the wrong function template?"); 1287 (void) FunTmpl; 1288 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 1289 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 1290 --SemaRef.NonInstantiationEntries; 1291 } 1292 } 1293 1294 return false; 1295} 1296 1297/// \brief Initializes common fields of an instantiated method 1298/// declaration (New) from the corresponding fields of its template 1299/// (Tmpl). 1300/// 1301/// \returns true if there was an error 1302bool 1303TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 1304 CXXMethodDecl *Tmpl) { 1305 if (InitFunctionInstantiation(New, Tmpl)) 1306 return true; 1307 1308 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner); 1309 New->setAccess(Tmpl->getAccess()); 1310 if (Tmpl->isVirtualAsWritten()) { 1311 New->setVirtualAsWritten(true); 1312 Record->setAggregate(false); 1313 Record->setPOD(false); 1314 Record->setEmpty(false); 1315 Record->setPolymorphic(true); 1316 } 1317 if (Tmpl->isPure()) { 1318 New->setPure(); 1319 Record->setAbstract(true); 1320 } 1321 1322 // FIXME: attributes 1323 // FIXME: New needs a pointer to Tmpl 1324 return false; 1325} 1326 1327/// \brief Instantiate the definition of the given function from its 1328/// template. 1329/// 1330/// \param PointOfInstantiation the point at which the instantiation was 1331/// required. Note that this is not precisely a "point of instantiation" 1332/// for the function, but it's close. 1333/// 1334/// \param Function the already-instantiated declaration of a 1335/// function template specialization or member function of a class template 1336/// specialization. 1337/// 1338/// \param Recursive if true, recursively instantiates any functions that 1339/// are required by this instantiation. 1340/// 1341/// \param DefinitionRequired if true, then we are performing an explicit 1342/// instantiation where the body of the function is required. Complain if 1343/// there is no such body. 1344void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 1345 FunctionDecl *Function, 1346 bool Recursive, 1347 bool DefinitionRequired) { 1348 if (Function->isInvalidDecl()) 1349 return; 1350 1351 assert(!Function->getBody() && "Already instantiated!"); 1352 1353 // Never instantiate an explicit specialization. 1354 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1355 return; 1356 1357 // Find the function body that we'll be substituting. 1358 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 1359 Stmt *Pattern = 0; 1360 if (PatternDecl) 1361 Pattern = PatternDecl->getBody(PatternDecl); 1362 1363 if (!Pattern) { 1364 if (DefinitionRequired) { 1365 if (Function->getPrimaryTemplate()) 1366 Diag(PointOfInstantiation, 1367 diag::err_explicit_instantiation_undefined_func_template) 1368 << Function->getPrimaryTemplate(); 1369 else 1370 Diag(PointOfInstantiation, 1371 diag::err_explicit_instantiation_undefined_member) 1372 << 1 << Function->getDeclName() << Function->getDeclContext(); 1373 1374 if (PatternDecl) 1375 Diag(PatternDecl->getLocation(), 1376 diag::note_explicit_instantiation_here); 1377 } 1378 1379 return; 1380 } 1381 1382 // C++0x [temp.explicit]p9: 1383 // Except for inline functions, other explicit instantiation declarations 1384 // have the effect of suppressing the implicit instantiation of the entity 1385 // to which they refer. 1386 if (Function->getTemplateSpecializationKind() 1387 == TSK_ExplicitInstantiationDeclaration && 1388 !PatternDecl->isInlined()) 1389 return; 1390 1391 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 1392 if (Inst) 1393 return; 1394 1395 // If we're performing recursive template instantiation, create our own 1396 // queue of pending implicit instantiations that we will instantiate later, 1397 // while we're still within our own instantiation context. 1398 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1399 if (Recursive) 1400 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1401 1402 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function)); 1403 1404 // Introduce a new scope where local variable instantiations will be 1405 // recorded. 1406 LocalInstantiationScope Scope(*this); 1407 1408 // Introduce the instantiated function parameters into the local 1409 // instantiation scope. 1410 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) 1411 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I), 1412 Function->getParamDecl(I)); 1413 1414 // Enter the scope of this instantiation. We don't use 1415 // PushDeclContext because we don't have a scope. 1416 DeclContext *PreviousContext = CurContext; 1417 CurContext = Function; 1418 1419 MultiLevelTemplateArgumentList TemplateArgs = 1420 getTemplateInstantiationArgs(Function); 1421 1422 // If this is a constructor, instantiate the member initializers. 1423 if (const CXXConstructorDecl *Ctor = 1424 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 1425 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 1426 TemplateArgs); 1427 } 1428 1429 // Instantiate the function body. 1430 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs); 1431 1432 if (Body.isInvalid()) 1433 Function->setInvalidDecl(); 1434 1435 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body), 1436 /*IsInstantiation=*/true); 1437 1438 CurContext = PreviousContext; 1439 1440 DeclGroupRef DG(Function); 1441 Consumer.HandleTopLevelDecl(DG); 1442 1443 if (Recursive) { 1444 // Instantiate any pending implicit instantiations found during the 1445 // instantiation of this template. 1446 PerformPendingImplicitInstantiations(); 1447 1448 // Restore the set of pending implicit instantiations. 1449 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1450 } 1451} 1452 1453/// \brief Instantiate the definition of the given variable from its 1454/// template. 1455/// 1456/// \param PointOfInstantiation the point at which the instantiation was 1457/// required. Note that this is not precisely a "point of instantiation" 1458/// for the function, but it's close. 1459/// 1460/// \param Var the already-instantiated declaration of a static member 1461/// variable of a class template specialization. 1462/// 1463/// \param Recursive if true, recursively instantiates any functions that 1464/// are required by this instantiation. 1465/// 1466/// \param DefinitionRequired if true, then we are performing an explicit 1467/// instantiation where an out-of-line definition of the member variable 1468/// is required. Complain if there is no such definition. 1469void Sema::InstantiateStaticDataMemberDefinition( 1470 SourceLocation PointOfInstantiation, 1471 VarDecl *Var, 1472 bool Recursive, 1473 bool DefinitionRequired) { 1474 if (Var->isInvalidDecl()) 1475 return; 1476 1477 // Find the out-of-line definition of this static data member. 1478 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 1479 assert(Def && "This data member was not instantiated from a template?"); 1480 assert(Def->isStaticDataMember() && "Not a static data member?"); 1481 Def = Def->getOutOfLineDefinition(); 1482 1483 if (!Def) { 1484 // We did not find an out-of-line definition of this static data member, 1485 // so we won't perform any instantiation. Rather, we rely on the user to 1486 // instantiate this definition (or provide a specialization for it) in 1487 // another translation unit. 1488 if (DefinitionRequired) { 1489 Def = Var->getInstantiatedFromStaticDataMember(); 1490 Diag(PointOfInstantiation, 1491 diag::err_explicit_instantiation_undefined_member) 1492 << 2 << Var->getDeclName() << Var->getDeclContext(); 1493 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 1494 } 1495 1496 return; 1497 } 1498 1499 // Never instantiate an explicit specialization. 1500 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1501 return; 1502 1503 // C++0x [temp.explicit]p9: 1504 // Except for inline functions, other explicit instantiation declarations 1505 // have the effect of suppressing the implicit instantiation of the entity 1506 // to which they refer. 1507 if (Var->getTemplateSpecializationKind() 1508 == TSK_ExplicitInstantiationDeclaration) 1509 return; 1510 1511 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 1512 if (Inst) 1513 return; 1514 1515 // If we're performing recursive template instantiation, create our own 1516 // queue of pending implicit instantiations that we will instantiate later, 1517 // while we're still within our own instantiation context. 1518 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations; 1519 if (Recursive) 1520 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1521 1522 // Enter the scope of this instantiation. We don't use 1523 // PushDeclContext because we don't have a scope. 1524 DeclContext *PreviousContext = CurContext; 1525 CurContext = Var->getDeclContext(); 1526 1527 VarDecl *OldVar = Var; 1528 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 1529 getTemplateInstantiationArgs(Var))); 1530 CurContext = PreviousContext; 1531 1532 if (Var) { 1533 Var->setPreviousDeclaration(OldVar); 1534 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 1535 assert(MSInfo && "Missing member specialization information?"); 1536 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 1537 MSInfo->getPointOfInstantiation()); 1538 DeclGroupRef DG(Var); 1539 Consumer.HandleTopLevelDecl(DG); 1540 } 1541 1542 if (Recursive) { 1543 // Instantiate any pending implicit instantiations found during the 1544 // instantiation of this template. 1545 PerformPendingImplicitInstantiations(); 1546 1547 // Restore the set of pending implicit instantiations. 1548 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations); 1549 } 1550} 1551 1552void 1553Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 1554 const CXXConstructorDecl *Tmpl, 1555 const MultiLevelTemplateArgumentList &TemplateArgs) { 1556 1557 llvm::SmallVector<MemInitTy*, 4> NewInits; 1558 1559 // Instantiate all the initializers. 1560 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 1561 InitsEnd = Tmpl->init_end(); 1562 Inits != InitsEnd; ++Inits) { 1563 CXXBaseOrMemberInitializer *Init = *Inits; 1564 1565 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this); 1566 1567 // Instantiate all the arguments. 1568 for (ExprIterator Args = Init->arg_begin(), ArgsEnd = Init->arg_end(); 1569 Args != ArgsEnd; ++Args) { 1570 OwningExprResult NewArg = SubstExpr(*Args, TemplateArgs); 1571 1572 if (NewArg.isInvalid()) 1573 New->setInvalidDecl(); 1574 else 1575 NewArgs.push_back(NewArg.takeAs<Expr>()); 1576 } 1577 1578 MemInitResult NewInit; 1579 1580 if (Init->isBaseInitializer()) { 1581 QualType BaseType(Init->getBaseClass(), 0); 1582 BaseType = SubstType(BaseType, TemplateArgs, Init->getSourceLocation(), 1583 New->getDeclName()); 1584 1585 NewInit = BuildBaseInitializer(BaseType, 1586 (Expr **)NewArgs.data(), 1587 NewArgs.size(), 1588 Init->getSourceLocation(), 1589 Init->getRParenLoc(), 1590 New->getParent()); 1591 } else if (Init->isMemberInitializer()) { 1592 FieldDecl *Member; 1593 1594 // Is this an anonymous union? 1595 if (FieldDecl *UnionInit = Init->getAnonUnionMember()) 1596 Member = cast<FieldDecl>(FindInstantiatedDecl(UnionInit, TemplateArgs)); 1597 else 1598 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMember(), 1599 TemplateArgs)); 1600 1601 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 1602 NewArgs.size(), 1603 Init->getSourceLocation(), 1604 Init->getRParenLoc()); 1605 } 1606 1607 if (NewInit.isInvalid()) 1608 New->setInvalidDecl(); 1609 else { 1610 // FIXME: It would be nice if ASTOwningVector had a release function. 1611 NewArgs.take(); 1612 1613 NewInits.push_back((MemInitTy *)NewInit.get()); 1614 } 1615 } 1616 1617 // Assign all the initializers to the new constructor. 1618 ActOnMemInitializers(DeclPtrTy::make(New), 1619 /*FIXME: ColonLoc */ 1620 SourceLocation(), 1621 NewInits.data(), NewInits.size()); 1622} 1623 1624// TODO: this could be templated if the various decl types used the 1625// same method name. 1626static bool isInstantiationOf(ClassTemplateDecl *Pattern, 1627 ClassTemplateDecl *Instance) { 1628 Pattern = Pattern->getCanonicalDecl(); 1629 1630 do { 1631 Instance = Instance->getCanonicalDecl(); 1632 if (Pattern == Instance) return true; 1633 Instance = Instance->getInstantiatedFromMemberTemplate(); 1634 } while (Instance); 1635 1636 return false; 1637} 1638 1639static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 1640 FunctionTemplateDecl *Instance) { 1641 Pattern = Pattern->getCanonicalDecl(); 1642 1643 do { 1644 Instance = Instance->getCanonicalDecl(); 1645 if (Pattern == Instance) return true; 1646 Instance = Instance->getInstantiatedFromMemberTemplate(); 1647 } while (Instance); 1648 1649 return false; 1650} 1651 1652static bool 1653isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 1654 ClassTemplatePartialSpecializationDecl *Instance) { 1655 Pattern 1656 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 1657 do { 1658 Instance = cast<ClassTemplatePartialSpecializationDecl>( 1659 Instance->getCanonicalDecl()); 1660 if (Pattern == Instance) 1661 return true; 1662 Instance = Instance->getInstantiatedFromMember(); 1663 } while (Instance); 1664 1665 return false; 1666} 1667 1668static bool isInstantiationOf(CXXRecordDecl *Pattern, 1669 CXXRecordDecl *Instance) { 1670 Pattern = Pattern->getCanonicalDecl(); 1671 1672 do { 1673 Instance = Instance->getCanonicalDecl(); 1674 if (Pattern == Instance) return true; 1675 Instance = Instance->getInstantiatedFromMemberClass(); 1676 } while (Instance); 1677 1678 return false; 1679} 1680 1681static bool isInstantiationOf(FunctionDecl *Pattern, 1682 FunctionDecl *Instance) { 1683 Pattern = Pattern->getCanonicalDecl(); 1684 1685 do { 1686 Instance = Instance->getCanonicalDecl(); 1687 if (Pattern == Instance) return true; 1688 Instance = Instance->getInstantiatedFromMemberFunction(); 1689 } while (Instance); 1690 1691 return false; 1692} 1693 1694static bool isInstantiationOf(EnumDecl *Pattern, 1695 EnumDecl *Instance) { 1696 Pattern = Pattern->getCanonicalDecl(); 1697 1698 do { 1699 Instance = Instance->getCanonicalDecl(); 1700 if (Pattern == Instance) return true; 1701 Instance = Instance->getInstantiatedFromMemberEnum(); 1702 } while (Instance); 1703 1704 return false; 1705} 1706 1707static bool isInstantiationOf(UnresolvedUsingDecl *Pattern, 1708 UsingDecl *Instance, 1709 ASTContext &C) { 1710 return C.getInstantiatedFromUnresolvedUsingDecl(Instance) == Pattern; 1711} 1712 1713static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 1714 VarDecl *Instance) { 1715 assert(Instance->isStaticDataMember()); 1716 1717 Pattern = Pattern->getCanonicalDecl(); 1718 1719 do { 1720 Instance = Instance->getCanonicalDecl(); 1721 if (Pattern == Instance) return true; 1722 Instance = Instance->getInstantiatedFromStaticDataMember(); 1723 } while (Instance); 1724 1725 return false; 1726} 1727 1728static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 1729 if (D->getKind() != Other->getKind()) { 1730 if (UnresolvedUsingDecl *UUD = dyn_cast<UnresolvedUsingDecl>(D)) { 1731 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 1732 return isInstantiationOf(UUD, UD, Ctx); 1733 } 1734 } 1735 1736 return false; 1737 } 1738 1739 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 1740 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 1741 1742 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 1743 return isInstantiationOf(cast<FunctionDecl>(D), Function); 1744 1745 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 1746 return isInstantiationOf(cast<EnumDecl>(D), Enum); 1747 1748 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 1749 if (Var->isStaticDataMember()) 1750 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 1751 1752 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 1753 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 1754 1755 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 1756 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 1757 1758 if (ClassTemplatePartialSpecializationDecl *PartialSpec 1759 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 1760 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 1761 PartialSpec); 1762 1763 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 1764 if (!Field->getDeclName()) { 1765 // This is an unnamed field. 1766 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 1767 cast<FieldDecl>(D); 1768 } 1769 } 1770 1771 return D->getDeclName() && isa<NamedDecl>(Other) && 1772 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 1773} 1774 1775template<typename ForwardIterator> 1776static NamedDecl *findInstantiationOf(ASTContext &Ctx, 1777 NamedDecl *D, 1778 ForwardIterator first, 1779 ForwardIterator last) { 1780 for (; first != last; ++first) 1781 if (isInstantiationOf(Ctx, D, *first)) 1782 return cast<NamedDecl>(*first); 1783 1784 return 0; 1785} 1786 1787/// \brief Finds the instantiation of the given declaration context 1788/// within the current instantiation. 1789/// 1790/// \returns NULL if there was an error 1791DeclContext *Sema::FindInstantiatedContext(DeclContext* DC, 1792 const MultiLevelTemplateArgumentList &TemplateArgs) { 1793 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 1794 Decl* ID = FindInstantiatedDecl(D, TemplateArgs); 1795 return cast_or_null<DeclContext>(ID); 1796 } else return DC; 1797} 1798 1799/// \brief Find the instantiation of the given declaration within the 1800/// current instantiation. 1801/// 1802/// This routine is intended to be used when \p D is a declaration 1803/// referenced from within a template, that needs to mapped into the 1804/// corresponding declaration within an instantiation. For example, 1805/// given: 1806/// 1807/// \code 1808/// template<typename T> 1809/// struct X { 1810/// enum Kind { 1811/// KnownValue = sizeof(T) 1812/// }; 1813/// 1814/// bool getKind() const { return KnownValue; } 1815/// }; 1816/// 1817/// template struct X<int>; 1818/// \endcode 1819/// 1820/// In the instantiation of X<int>::getKind(), we need to map the 1821/// EnumConstantDecl for KnownValue (which refers to 1822/// X<T>::<Kind>::KnownValue) to its instantiation 1823/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 1824/// this mapping from within the instantiation of X<int>. 1825NamedDecl *Sema::FindInstantiatedDecl(NamedDecl *D, 1826 const MultiLevelTemplateArgumentList &TemplateArgs) { 1827 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D)) { 1828 // Transform all of the elements of the overloaded function set. 1829 OverloadedFunctionDecl *Result 1830 = OverloadedFunctionDecl::Create(Context, CurContext, Ovl->getDeclName()); 1831 1832 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 1833 FEnd = Ovl->function_end(); 1834 F != FEnd; ++F) { 1835 Result->addOverload( 1836 AnyFunctionDecl::getFromNamedDecl(FindInstantiatedDecl(*F, 1837 TemplateArgs))); 1838 } 1839 1840 return Result; 1841 } 1842 1843 DeclContext *ParentDC = D->getDeclContext(); 1844 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 1845 isa<TemplateTypeParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 1846 ParentDC->isFunctionOrMethod()) { 1847 // D is a local of some kind. Look into the map of local 1848 // declarations to their instantiations. 1849 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D)); 1850 } 1851 1852 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 1853 if (!Record->isDependentContext()) 1854 return D; 1855 1856 // If the RecordDecl is actually the injected-class-name or a "templated" 1857 // declaration for a class template or class template partial 1858 // specialization, substitute into the injected-class-name of the 1859 // class template or partial specialization to find the new DeclContext. 1860 QualType T; 1861 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 1862 1863 if (ClassTemplate) { 1864 T = ClassTemplate->getInjectedClassNameType(Context); 1865 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 1866 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 1867 T = Context.getTypeDeclType(Record); 1868 ClassTemplate = PartialSpec->getSpecializedTemplate(); 1869 } 1870 1871 if (!T.isNull()) { 1872 // Substitute into the injected-class-name to get the type corresponding 1873 // to the instantiation we want. This substitution should never fail, 1874 // since we know we can instantiate the injected-class-name or we wouldn't 1875 // have gotten to the injected-class-name! 1876 // FIXME: Can we use the CurrentInstantiationScope to avoid this extra 1877 // instantiation in the common case? 1878 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName()); 1879 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail."); 1880 1881 if (!T->isDependentType()) { 1882 assert(T->isRecordType() && "Instantiation must produce a record type"); 1883 return T->getAs<RecordType>()->getDecl(); 1884 } 1885 1886 // We are performing "partial" template instantiation to create the 1887 // member declarations for the members of a class template 1888 // specialization. Therefore, D is actually referring to something in 1889 // the current instantiation. Look through the current context, 1890 // which contains actual instantiations, to find the instantiation of 1891 // the "current instantiation" that D refers to. 1892 for (DeclContext *DC = CurContext; !DC->isFileContext(); 1893 DC = DC->getParent()) { 1894 if (ClassTemplateSpecializationDecl *Spec 1895 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 1896 if (isInstantiationOf(ClassTemplate, 1897 Spec->getSpecializedTemplate())) 1898 return Spec; 1899 } 1900 1901 assert(false && 1902 "Unable to find declaration for the current instantiation"); 1903 return Record; 1904 } 1905 1906 // Fall through to deal with other dependent record types (e.g., 1907 // anonymous unions in class templates). 1908 } 1909 1910 if (!ParentDC->isDependentContext()) 1911 return D; 1912 1913 ParentDC = FindInstantiatedContext(ParentDC, TemplateArgs); 1914 if (!ParentDC) 1915 return 0; 1916 1917 if (ParentDC != D->getDeclContext()) { 1918 // We performed some kind of instantiation in the parent context, 1919 // so now we need to look into the instantiated parent context to 1920 // find the instantiation of the declaration D. 1921 NamedDecl *Result = 0; 1922 if (D->getDeclName()) { 1923 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 1924 Result = findInstantiationOf(Context, D, Found.first, Found.second); 1925 } else { 1926 // Since we don't have a name for the entity we're looking for, 1927 // our only option is to walk through all of the declarations to 1928 // find that name. This will occur in a few cases: 1929 // 1930 // - anonymous struct/union within a template 1931 // - unnamed class/struct/union/enum within a template 1932 // 1933 // FIXME: Find a better way to find these instantiations! 1934 Result = findInstantiationOf(Context, D, 1935 ParentDC->decls_begin(), 1936 ParentDC->decls_end()); 1937 } 1938 1939 assert(Result && "Unable to find instantiation of declaration!"); 1940 D = Result; 1941 } 1942 1943 return D; 1944} 1945 1946/// \brief Performs template instantiation for all implicit template 1947/// instantiations we have seen until this point. 1948void Sema::PerformPendingImplicitInstantiations() { 1949 while (!PendingImplicitInstantiations.empty()) { 1950 PendingImplicitInstantiation Inst = PendingImplicitInstantiations.front(); 1951 PendingImplicitInstantiations.pop_front(); 1952 1953 // Instantiate function definitions 1954 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 1955 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function), 1956 Function->getLocation(), *this, 1957 Context.getSourceManager(), 1958 "instantiating function definition"); 1959 1960 if (!Function->getBody()) 1961 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true); 1962 continue; 1963 } 1964 1965 // Instantiate static data member definitions. 1966 VarDecl *Var = cast<VarDecl>(Inst.first); 1967 assert(Var->isStaticDataMember() && "Not a static data member?"); 1968 1969 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var), 1970 Var->getLocation(), *this, 1971 Context.getSourceManager(), 1972 "instantiating static data member " 1973 "definition"); 1974 1975 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true); 1976 } 1977} 1978