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