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