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