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