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 "clang/Sema/SemaInternal.h" 13 #include "clang/Sema/Lookup.h" 14 #include "clang/Sema/PrettyDeclStackTrace.h" 15 #include "clang/Sema/Template.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/DeclTemplate.h" 19 #include "clang/AST/DeclVisitor.h" 20 #include "clang/AST/DependentDiagnostic.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/TypeLoc.h" 24 #include "clang/Lex/Preprocessor.h" 25 26 using namespace clang; 27 28 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 29 DeclaratorDecl *NewDecl) { 30 if (!OldDecl->getQualifierLoc()) 31 return false; 32 33 NestedNameSpecifierLoc NewQualifierLoc 34 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 35 TemplateArgs); 36 37 if (!NewQualifierLoc) 38 return true; 39 40 NewDecl->setQualifierInfo(NewQualifierLoc); 41 return false; 42 } 43 44 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 45 TagDecl *NewDecl) { 46 if (!OldDecl->getQualifierLoc()) 47 return false; 48 49 NestedNameSpecifierLoc NewQualifierLoc 50 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 51 TemplateArgs); 52 53 if (!NewQualifierLoc) 54 return true; 55 56 NewDecl->setQualifierInfo(NewQualifierLoc); 57 return false; 58 } 59 60 // FIXME: Is this still too simple? 61 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 62 const Decl *Tmpl, Decl *New) { 63 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end(); 64 i != e; ++i) { 65 const Attr *TmplAttr = *i; 66 // FIXME: This should be generalized to more than just the AlignedAttr. 67 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) { 68 if (Aligned->isAlignmentDependent()) { 69 // The alignment expression is not potentially evaluated. 70 EnterExpressionEvaluationContext Unevaluated(*this, 71 Sema::Unevaluated); 72 73 if (Aligned->isAlignmentExpr()) { 74 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(), 75 TemplateArgs); 76 if (!Result.isInvalid()) 77 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>()); 78 } 79 else { 80 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(), 81 TemplateArgs, 82 Aligned->getLocation(), 83 DeclarationName()); 84 if (Result) 85 AddAlignedAttr(Aligned->getLocation(), New, Result); 86 } 87 continue; 88 } 89 } 90 91 // FIXME: Is cloning correct for all attributes? 92 Attr *NewAttr = TmplAttr->clone(Context); 93 New->addAttr(NewAttr); 94 } 95 } 96 97 Decl * 98 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 99 assert(false && "Translation units cannot be instantiated"); 100 return D; 101 } 102 103 Decl * 104 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 105 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 106 D->getIdentifier()); 107 Owner->addDecl(Inst); 108 return Inst; 109 } 110 111 Decl * 112 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 113 assert(false && "Namespaces cannot be instantiated"); 114 return D; 115 } 116 117 Decl * 118 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 119 NamespaceAliasDecl *Inst 120 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 121 D->getNamespaceLoc(), 122 D->getAliasLoc(), 123 D->getIdentifier(), 124 D->getQualifierLoc(), 125 D->getTargetNameLoc(), 126 D->getNamespace()); 127 Owner->addDecl(Inst); 128 return Inst; 129 } 130 131 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 132 bool IsTypeAlias) { 133 bool Invalid = false; 134 TypeSourceInfo *DI = D->getTypeSourceInfo(); 135 if (DI->getType()->isInstantiationDependentType() || 136 DI->getType()->isVariablyModifiedType()) { 137 DI = SemaRef.SubstType(DI, TemplateArgs, 138 D->getLocation(), D->getDeclName()); 139 if (!DI) { 140 Invalid = true; 141 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 142 } 143 } else { 144 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 145 } 146 147 // Create the new typedef 148 TypedefNameDecl *Typedef; 149 if (IsTypeAlias) 150 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 151 D->getLocation(), D->getIdentifier(), DI); 152 else 153 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 154 D->getLocation(), D->getIdentifier(), DI); 155 if (Invalid) 156 Typedef->setInvalidDecl(); 157 158 // If the old typedef was the name for linkage purposes of an anonymous 159 // tag decl, re-establish that relationship for the new typedef. 160 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 161 TagDecl *oldTag = oldTagType->getDecl(); 162 if (oldTag->getTypedefNameForAnonDecl() == D) { 163 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 164 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl()); 165 newTag->setTypedefNameForAnonDecl(Typedef); 166 } 167 } 168 169 if (TypedefNameDecl *Prev = D->getPreviousDeclaration()) { 170 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 171 TemplateArgs); 172 if (!InstPrev) 173 return 0; 174 175 Typedef->setPreviousDeclaration(cast<TypedefNameDecl>(InstPrev)); 176 } 177 178 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); 179 180 Typedef->setAccess(D->getAccess()); 181 182 return Typedef; 183 } 184 185 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 186 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); 187 Owner->addDecl(Typedef); 188 return Typedef; 189 } 190 191 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { 192 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); 193 Owner->addDecl(Typedef); 194 return Typedef; 195 } 196 197 Decl * 198 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 199 // Create a local instantiation scope for this type alias template, which 200 // will contain the instantiations of the template parameters. 201 LocalInstantiationScope Scope(SemaRef); 202 203 TemplateParameterList *TempParams = D->getTemplateParameters(); 204 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 205 if (!InstParams) 206 return 0; 207 208 TypeAliasDecl *Pattern = D->getTemplatedDecl(); 209 210 TypeAliasTemplateDecl *PrevAliasTemplate = 0; 211 if (Pattern->getPreviousDeclaration()) { 212 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 213 if (Found.first != Found.second) { 214 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first); 215 } 216 } 217 218 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( 219 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); 220 if (!AliasInst) 221 return 0; 222 223 TypeAliasTemplateDecl *Inst 224 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 225 D->getDeclName(), InstParams, AliasInst); 226 if (PrevAliasTemplate) 227 Inst->setPreviousDeclaration(PrevAliasTemplate); 228 229 Inst->setAccess(D->getAccess()); 230 231 if (!PrevAliasTemplate) 232 Inst->setInstantiatedFromMemberTemplate(D); 233 234 Owner->addDecl(Inst); 235 236 return Inst; 237 } 238 239 /// \brief Instantiate an initializer, breaking it into separate 240 /// initialization arguments. 241 /// 242 /// \param Init The initializer to instantiate. 243 /// 244 /// \param TemplateArgs Template arguments to be substituted into the 245 /// initializer. 246 /// 247 /// \param NewArgs Will be filled in with the instantiation arguments. 248 /// 249 /// \returns true if an error occurred, false otherwise 250 bool Sema::InstantiateInitializer(Expr *Init, 251 const MultiLevelTemplateArgumentList &TemplateArgs, 252 SourceLocation &LParenLoc, 253 ASTOwningVector<Expr*> &NewArgs, 254 SourceLocation &RParenLoc) { 255 NewArgs.clear(); 256 LParenLoc = SourceLocation(); 257 RParenLoc = SourceLocation(); 258 259 if (!Init) 260 return false; 261 262 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init)) 263 Init = ExprTemp->getSubExpr(); 264 265 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init)) 266 Init = Binder->getSubExpr(); 267 268 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init)) 269 Init = ICE->getSubExprAsWritten(); 270 271 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 272 LParenLoc = ParenList->getLParenLoc(); 273 RParenLoc = ParenList->getRParenLoc(); 274 return SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(), 275 true, TemplateArgs, NewArgs); 276 } 277 278 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) { 279 if (!isa<CXXTemporaryObjectExpr>(Construct)) { 280 if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true, 281 TemplateArgs, NewArgs)) 282 return true; 283 284 // FIXME: Fake locations! 285 LParenLoc = PP.getLocForEndOfToken(Init->getLocStart()); 286 RParenLoc = LParenLoc; 287 return false; 288 } 289 } 290 291 ExprResult Result = SubstExpr(Init, TemplateArgs); 292 if (Result.isInvalid()) 293 return true; 294 295 NewArgs.push_back(Result.takeAs<Expr>()); 296 return false; 297 } 298 299 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 300 // If this is the variable for an anonymous struct or union, 301 // instantiate the anonymous struct/union type first. 302 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 303 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 304 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 305 return 0; 306 307 // Do substitution on the type of the declaration 308 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 309 TemplateArgs, 310 D->getTypeSpecStartLoc(), 311 D->getDeclName()); 312 if (!DI) 313 return 0; 314 315 if (DI->getType()->isFunctionType()) { 316 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 317 << D->isStaticDataMember() << DI->getType(); 318 return 0; 319 } 320 321 // Build the instantiated declaration 322 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner, 323 D->getInnerLocStart(), 324 D->getLocation(), D->getIdentifier(), 325 DI->getType(), DI, 326 D->getStorageClass(), 327 D->getStorageClassAsWritten()); 328 Var->setThreadSpecified(D->isThreadSpecified()); 329 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer()); 330 Var->setCXXForRangeDecl(D->isCXXForRangeDecl()); 331 332 // Substitute the nested name specifier, if any. 333 if (SubstQualifier(D, Var)) 334 return 0; 335 336 // If we are instantiating a static data member defined 337 // out-of-line, the instantiation will have the same lexical 338 // context (which will be a namespace scope) as the template. 339 if (D->isOutOfLine()) 340 Var->setLexicalDeclContext(D->getLexicalDeclContext()); 341 342 Var->setAccess(D->getAccess()); 343 344 if (!D->isStaticDataMember()) { 345 Var->setUsed(D->isUsed(false)); 346 Var->setReferenced(D->isReferenced()); 347 } 348 349 // FIXME: In theory, we could have a previous declaration for variables that 350 // are not static data members. 351 bool Redeclaration = false; 352 // FIXME: having to fake up a LookupResult is dumb. 353 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(), 354 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 355 if (D->isStaticDataMember()) 356 SemaRef.LookupQualifiedName(Previous, Owner, false); 357 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration); 358 359 if (D->isOutOfLine()) { 360 if (!D->isStaticDataMember()) 361 D->getLexicalDeclContext()->addDecl(Var); 362 Owner->makeDeclVisibleInContext(Var); 363 } else { 364 Owner->addDecl(Var); 365 if (Owner->isFunctionOrMethod()) 366 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var); 367 } 368 SemaRef.InstantiateAttrs(TemplateArgs, D, Var); 369 370 // Link instantiations of static data members back to the template from 371 // which they were instantiated. 372 if (Var->isStaticDataMember()) 373 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D, 374 TSK_ImplicitInstantiation); 375 376 if (Var->getAnyInitializer()) { 377 // We already have an initializer in the class. 378 } else if (D->getInit()) { 379 if (Var->isStaticDataMember() && !D->isOutOfLine()) 380 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated); 381 else 382 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated); 383 384 // Instantiate the initializer. 385 SourceLocation LParenLoc, RParenLoc; 386 ASTOwningVector<Expr*> InitArgs(SemaRef); 387 if (!SemaRef.InstantiateInitializer(D->getInit(), TemplateArgs, LParenLoc, 388 InitArgs, RParenLoc)) { 389 bool TypeMayContainAuto = true; 390 // Attach the initializer to the declaration, if we have one. 391 if (InitArgs.size() == 0) 392 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto); 393 else if (D->hasCXXDirectInitializer()) { 394 // Add the direct initializer to the declaration. 395 SemaRef.AddCXXDirectInitializerToDecl(Var, 396 LParenLoc, 397 move_arg(InitArgs), 398 RParenLoc, 399 TypeMayContainAuto); 400 } else { 401 assert(InitArgs.size() == 1); 402 Expr *Init = InitArgs.take()[0]; 403 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto); 404 } 405 } else { 406 // FIXME: Not too happy about invalidating the declaration 407 // because of a bogus initializer. 408 Var->setInvalidDecl(); 409 } 410 411 SemaRef.PopExpressionEvaluationContext(); 412 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) && 413 !Var->isCXXForRangeDecl()) 414 SemaRef.ActOnUninitializedDecl(Var, false); 415 416 // Diagnose unused local variables with dependent types, where the diagnostic 417 // will have been deferred. 418 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() && 419 D->getType()->isDependentType()) 420 SemaRef.DiagnoseUnusedDecl(Var); 421 422 return Var; 423 } 424 425 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { 426 AccessSpecDecl* AD 427 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner, 428 D->getAccessSpecifierLoc(), D->getColonLoc()); 429 Owner->addHiddenDecl(AD); 430 return AD; 431 } 432 433 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 434 bool Invalid = false; 435 TypeSourceInfo *DI = D->getTypeSourceInfo(); 436 if (DI->getType()->isInstantiationDependentType() || 437 DI->getType()->isVariablyModifiedType()) { 438 DI = SemaRef.SubstType(DI, TemplateArgs, 439 D->getLocation(), D->getDeclName()); 440 if (!DI) { 441 DI = D->getTypeSourceInfo(); 442 Invalid = true; 443 } else if (DI->getType()->isFunctionType()) { 444 // C++ [temp.arg.type]p3: 445 // If a declaration acquires a function type through a type 446 // dependent on a template-parameter and this causes a 447 // declaration that does not use the syntactic form of a 448 // function declarator to have function type, the program is 449 // ill-formed. 450 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 451 << DI->getType(); 452 Invalid = true; 453 } 454 } else { 455 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 456 } 457 458 Expr *BitWidth = D->getBitWidth(); 459 if (Invalid) 460 BitWidth = 0; 461 else if (BitWidth) { 462 // The bit-width expression is not potentially evaluated. 463 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated); 464 465 ExprResult InstantiatedBitWidth 466 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 467 if (InstantiatedBitWidth.isInvalid()) { 468 Invalid = true; 469 BitWidth = 0; 470 } else 471 BitWidth = InstantiatedBitWidth.takeAs<Expr>(); 472 } 473 474 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 475 DI->getType(), DI, 476 cast<RecordDecl>(Owner), 477 D->getLocation(), 478 D->isMutable(), 479 BitWidth, 480 D->hasInClassInitializer(), 481 D->getTypeSpecStartLoc(), 482 D->getAccess(), 483 0); 484 if (!Field) { 485 cast<Decl>(Owner)->setInvalidDecl(); 486 return 0; 487 } 488 489 SemaRef.InstantiateAttrs(TemplateArgs, D, Field); 490 491 if (Invalid) 492 Field->setInvalidDecl(); 493 494 if (!Field->getDeclName()) { 495 // Keep track of where this decl came from. 496 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 497 } 498 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 499 if (Parent->isAnonymousStructOrUnion() && 500 Parent->getRedeclContext()->isFunctionOrMethod()) 501 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 502 } 503 504 Field->setImplicit(D->isImplicit()); 505 Field->setAccess(D->getAccess()); 506 Owner->addDecl(Field); 507 508 return Field; 509 } 510 511 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 512 NamedDecl **NamedChain = 513 new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; 514 515 int i = 0; 516 for (IndirectFieldDecl::chain_iterator PI = 517 D->chain_begin(), PE = D->chain_end(); 518 PI != PE; ++PI) { 519 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI, 520 TemplateArgs); 521 if (!Next) 522 return 0; 523 524 NamedChain[i++] = Next; 525 } 526 527 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType(); 528 IndirectFieldDecl* IndirectField 529 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(), 530 D->getIdentifier(), T, 531 NamedChain, D->getChainingSize()); 532 533 534 IndirectField->setImplicit(D->isImplicit()); 535 IndirectField->setAccess(D->getAccess()); 536 Owner->addDecl(IndirectField); 537 return IndirectField; 538 } 539 540 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 541 // Handle friend type expressions by simply substituting template 542 // parameters into the pattern type and checking the result. 543 if (TypeSourceInfo *Ty = D->getFriendType()) { 544 TypeSourceInfo *InstTy; 545 // If this is an unsupported friend, don't bother substituting template 546 // arguments into it. The actual type referred to won't be used by any 547 // parts of Clang, and may not be valid for instantiating. Just use the 548 // same info for the instantiated friend. 549 if (D->isUnsupportedFriend()) { 550 InstTy = Ty; 551 } else { 552 InstTy = SemaRef.SubstType(Ty, TemplateArgs, 553 D->getLocation(), DeclarationName()); 554 } 555 if (!InstTy) 556 return 0; 557 558 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy); 559 if (!FD) 560 return 0; 561 562 FD->setAccess(AS_public); 563 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 564 Owner->addDecl(FD); 565 return FD; 566 } 567 568 NamedDecl *ND = D->getFriendDecl(); 569 assert(ND && "friend decl must be a decl or a type!"); 570 571 // All of the Visit implementations for the various potential friend 572 // declarations have to be carefully written to work for friend 573 // objects, with the most important detail being that the target 574 // decl should almost certainly not be placed in Owner. 575 Decl *NewND = Visit(ND); 576 if (!NewND) return 0; 577 578 FriendDecl *FD = 579 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 580 cast<NamedDecl>(NewND), D->getFriendLoc()); 581 FD->setAccess(AS_public); 582 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 583 Owner->addDecl(FD); 584 return FD; 585 } 586 587 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 588 Expr *AssertExpr = D->getAssertExpr(); 589 590 // The expression in a static assertion is not potentially evaluated. 591 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated); 592 593 ExprResult InstantiatedAssertExpr 594 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 595 if (InstantiatedAssertExpr.isInvalid()) 596 return 0; 597 598 ExprResult Message(D->getMessage()); 599 D->getMessage(); 600 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(), 601 InstantiatedAssertExpr.get(), 602 Message.get(), 603 D->getRParenLoc()); 604 } 605 606 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 607 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 608 D->getLocation(), D->getIdentifier(), 609 /*PrevDecl=*/0, D->isScoped(), 610 D->isScopedUsingClassTag(), D->isFixed()); 611 if (D->isFixed()) { 612 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) { 613 // If we have type source information for the underlying type, it means it 614 // has been explicitly set by the user. Perform substitution on it before 615 // moving on. 616 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 617 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI, 618 TemplateArgs, 619 UnderlyingLoc, 620 DeclarationName())); 621 622 if (!Enum->getIntegerTypeSourceInfo()) 623 Enum->setIntegerType(SemaRef.Context.IntTy); 624 } 625 else { 626 assert(!D->getIntegerType()->isDependentType() 627 && "Dependent type without type source info"); 628 Enum->setIntegerType(D->getIntegerType()); 629 } 630 } 631 632 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); 633 634 Enum->setInstantiationOfMemberEnum(D); 635 Enum->setAccess(D->getAccess()); 636 if (SubstQualifier(D, Enum)) return 0; 637 Owner->addDecl(Enum); 638 Enum->startDefinition(); 639 640 if (D->getDeclContext()->isFunctionOrMethod()) 641 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 642 643 llvm::SmallVector<Decl*, 4> Enumerators; 644 645 EnumConstantDecl *LastEnumConst = 0; 646 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(), 647 ECEnd = D->enumerator_end(); 648 EC != ECEnd; ++EC) { 649 // The specified value for the enumerator. 650 ExprResult Value = SemaRef.Owned((Expr *)0); 651 if (Expr *UninstValue = EC->getInitExpr()) { 652 // The enumerator's value expression is not potentially evaluated. 653 EnterExpressionEvaluationContext Unevaluated(SemaRef, 654 Sema::Unevaluated); 655 656 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 657 } 658 659 // Drop the initial value and continue. 660 bool isInvalid = false; 661 if (Value.isInvalid()) { 662 Value = SemaRef.Owned((Expr *)0); 663 isInvalid = true; 664 } 665 666 EnumConstantDecl *EnumConst 667 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 668 EC->getLocation(), EC->getIdentifier(), 669 Value.get()); 670 671 if (isInvalid) { 672 if (EnumConst) 673 EnumConst->setInvalidDecl(); 674 Enum->setInvalidDecl(); 675 } 676 677 if (EnumConst) { 678 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst); 679 680 EnumConst->setAccess(Enum->getAccess()); 681 Enum->addDecl(EnumConst); 682 Enumerators.push_back(EnumConst); 683 LastEnumConst = EnumConst; 684 685 if (D->getDeclContext()->isFunctionOrMethod()) { 686 // If the enumeration is within a function or method, record the enum 687 // constant as a local. 688 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst); 689 } 690 } 691 } 692 693 // FIXME: Fixup LBraceLoc and RBraceLoc 694 // FIXME: Empty Scope and AttributeList (required to handle attribute packed). 695 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(), 696 Enum, 697 Enumerators.data(), Enumerators.size(), 698 0, 0); 699 700 return Enum; 701 } 702 703 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 704 assert(false && "EnumConstantDecls can only occur within EnumDecls."); 705 return 0; 706 } 707 708 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 709 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 710 711 // Create a local instantiation scope for this class template, which 712 // will contain the instantiations of the template parameters. 713 LocalInstantiationScope Scope(SemaRef); 714 TemplateParameterList *TempParams = D->getTemplateParameters(); 715 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 716 if (!InstParams) 717 return NULL; 718 719 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 720 721 // Instantiate the qualifier. We have to do this first in case 722 // we're a friend declaration, because if we are then we need to put 723 // the new declaration in the appropriate context. 724 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); 725 if (QualifierLoc) { 726 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 727 TemplateArgs); 728 if (!QualifierLoc) 729 return 0; 730 } 731 732 CXXRecordDecl *PrevDecl = 0; 733 ClassTemplateDecl *PrevClassTemplate = 0; 734 735 if (!isFriend && Pattern->getPreviousDeclaration()) { 736 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 737 if (Found.first != Found.second) { 738 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first); 739 if (PrevClassTemplate) 740 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 741 } 742 } 743 744 // If this isn't a friend, then it's a member template, in which 745 // case we just want to build the instantiation in the 746 // specialization. If it is a friend, we want to build it in 747 // the appropriate context. 748 DeclContext *DC = Owner; 749 if (isFriend) { 750 if (QualifierLoc) { 751 CXXScopeSpec SS; 752 SS.Adopt(QualifierLoc); 753 DC = SemaRef.computeDeclContext(SS); 754 if (!DC) return 0; 755 } else { 756 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 757 Pattern->getDeclContext(), 758 TemplateArgs); 759 } 760 761 // Look for a previous declaration of the template in the owning 762 // context. 763 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 764 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 765 SemaRef.LookupQualifiedName(R, DC); 766 767 if (R.isSingleResult()) { 768 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 769 if (PrevClassTemplate) 770 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 771 } 772 773 if (!PrevClassTemplate && QualifierLoc) { 774 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 775 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 776 << QualifierLoc.getSourceRange(); 777 return 0; 778 } 779 780 bool AdoptedPreviousTemplateParams = false; 781 if (PrevClassTemplate) { 782 bool Complain = true; 783 784 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 785 // template for struct std::tr1::__detail::_Map_base, where the 786 // template parameters of the friend declaration don't match the 787 // template parameters of the original declaration. In this one 788 // case, we don't complain about the ill-formed friend 789 // declaration. 790 if (isFriend && Pattern->getIdentifier() && 791 Pattern->getIdentifier()->isStr("_Map_base") && 792 DC->isNamespace() && 793 cast<NamespaceDecl>(DC)->getIdentifier() && 794 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 795 DeclContext *DCParent = DC->getParent(); 796 if (DCParent->isNamespace() && 797 cast<NamespaceDecl>(DCParent)->getIdentifier() && 798 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 799 DeclContext *DCParent2 = DCParent->getParent(); 800 if (DCParent2->isNamespace() && 801 cast<NamespaceDecl>(DCParent2)->getIdentifier() && 802 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") && 803 DCParent2->getParent()->isTranslationUnit()) 804 Complain = false; 805 } 806 } 807 808 TemplateParameterList *PrevParams 809 = PrevClassTemplate->getTemplateParameters(); 810 811 // Make sure the parameter lists match. 812 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 813 Complain, 814 Sema::TPL_TemplateMatch)) { 815 if (Complain) 816 return 0; 817 818 AdoptedPreviousTemplateParams = true; 819 InstParams = PrevParams; 820 } 821 822 // Do some additional validation, then merge default arguments 823 // from the existing declarations. 824 if (!AdoptedPreviousTemplateParams && 825 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 826 Sema::TPC_ClassTemplate)) 827 return 0; 828 } 829 } 830 831 CXXRecordDecl *RecordInst 832 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 833 Pattern->getLocStart(), Pattern->getLocation(), 834 Pattern->getIdentifier(), PrevDecl, 835 /*DelayTypeCreation=*/true); 836 837 if (QualifierLoc) 838 RecordInst->setQualifierInfo(QualifierLoc); 839 840 ClassTemplateDecl *Inst 841 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 842 D->getIdentifier(), InstParams, RecordInst, 843 PrevClassTemplate); 844 RecordInst->setDescribedClassTemplate(Inst); 845 846 if (isFriend) { 847 if (PrevClassTemplate) 848 Inst->setAccess(PrevClassTemplate->getAccess()); 849 else 850 Inst->setAccess(D->getAccess()); 851 852 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0); 853 // TODO: do we want to track the instantiation progeny of this 854 // friend target decl? 855 } else { 856 Inst->setAccess(D->getAccess()); 857 if (!PrevClassTemplate) 858 Inst->setInstantiatedFromMemberTemplate(D); 859 } 860 861 // Trigger creation of the type for the instantiation. 862 SemaRef.Context.getInjectedClassNameType(RecordInst, 863 Inst->getInjectedClassNameSpecialization()); 864 865 // Finish handling of friends. 866 if (isFriend) { 867 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false); 868 return Inst; 869 } 870 871 Owner->addDecl(Inst); 872 873 if (!PrevClassTemplate) { 874 // Queue up any out-of-line partial specializations of this member 875 // class template; the client will force their instantiation once 876 // the enclosing class has been instantiated. 877 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 878 D->getPartialSpecializations(PartialSpecs); 879 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 880 if (PartialSpecs[I]->isOutOfLine()) 881 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I])); 882 } 883 884 return Inst; 885 } 886 887 Decl * 888 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 889 ClassTemplatePartialSpecializationDecl *D) { 890 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 891 892 // Lookup the already-instantiated declaration in the instantiation 893 // of the class template and return that. 894 DeclContext::lookup_result Found 895 = Owner->lookup(ClassTemplate->getDeclName()); 896 if (Found.first == Found.second) 897 return 0; 898 899 ClassTemplateDecl *InstClassTemplate 900 = dyn_cast<ClassTemplateDecl>(*Found.first); 901 if (!InstClassTemplate) 902 return 0; 903 904 if (ClassTemplatePartialSpecializationDecl *Result 905 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) 906 return Result; 907 908 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D); 909 } 910 911 Decl * 912 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 913 // Create a local instantiation scope for this function template, which 914 // will contain the instantiations of the template parameters and then get 915 // merged with the local instantiation scope for the function template 916 // itself. 917 LocalInstantiationScope Scope(SemaRef); 918 919 TemplateParameterList *TempParams = D->getTemplateParameters(); 920 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 921 if (!InstParams) 922 return NULL; 923 924 FunctionDecl *Instantiated = 0; 925 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 926 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 927 InstParams)); 928 else 929 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 930 D->getTemplatedDecl(), 931 InstParams)); 932 933 if (!Instantiated) 934 return 0; 935 936 Instantiated->setAccess(D->getAccess()); 937 938 // Link the instantiated function template declaration to the function 939 // template from which it was instantiated. 940 FunctionTemplateDecl *InstTemplate 941 = Instantiated->getDescribedFunctionTemplate(); 942 InstTemplate->setAccess(D->getAccess()); 943 assert(InstTemplate && 944 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 945 946 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 947 948 // Link the instantiation back to the pattern *unless* this is a 949 // non-definition friend declaration. 950 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 951 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 952 InstTemplate->setInstantiatedFromMemberTemplate(D); 953 954 // Make declarations visible in the appropriate context. 955 if (!isFriend) 956 Owner->addDecl(InstTemplate); 957 958 return InstTemplate; 959 } 960 961 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 962 CXXRecordDecl *PrevDecl = 0; 963 if (D->isInjectedClassName()) 964 PrevDecl = cast<CXXRecordDecl>(Owner); 965 else if (D->getPreviousDeclaration()) { 966 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 967 D->getPreviousDeclaration(), 968 TemplateArgs); 969 if (!Prev) return 0; 970 PrevDecl = cast<CXXRecordDecl>(Prev); 971 } 972 973 CXXRecordDecl *Record 974 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 975 D->getLocStart(), D->getLocation(), 976 D->getIdentifier(), PrevDecl); 977 978 // Substitute the nested name specifier, if any. 979 if (SubstQualifier(D, Record)) 980 return 0; 981 982 Record->setImplicit(D->isImplicit()); 983 // FIXME: Check against AS_none is an ugly hack to work around the issue that 984 // the tag decls introduced by friend class declarations don't have an access 985 // specifier. Remove once this area of the code gets sorted out. 986 if (D->getAccess() != AS_none) 987 Record->setAccess(D->getAccess()); 988 if (!D->isInjectedClassName()) 989 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 990 991 // If the original function was part of a friend declaration, 992 // inherit its namespace state. 993 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind()) 994 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared); 995 996 // Make sure that anonymous structs and unions are recorded. 997 if (D->isAnonymousStructOrUnion()) { 998 Record->setAnonymousStructOrUnion(true); 999 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod()) 1000 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 1001 } 1002 1003 Owner->addDecl(Record); 1004 return Record; 1005 } 1006 1007 /// Normal class members are of more specific types and therefore 1008 /// don't make it here. This function serves two purposes: 1009 /// 1) instantiating function templates 1010 /// 2) substituting friend declarations 1011 /// FIXME: preserve function definitions in case #2 1012 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 1013 TemplateParameterList *TemplateParams) { 1014 // Check whether there is already a function template specialization for 1015 // this declaration. 1016 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1017 void *InsertPos = 0; 1018 if (FunctionTemplate && !TemplateParams) { 1019 std::pair<const TemplateArgument *, unsigned> Innermost 1020 = TemplateArgs.getInnermost(); 1021 1022 FunctionDecl *SpecFunc 1023 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second, 1024 InsertPos); 1025 1026 // If we already have a function template specialization, return it. 1027 if (SpecFunc) 1028 return SpecFunc; 1029 } 1030 1031 bool isFriend; 1032 if (FunctionTemplate) 1033 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1034 else 1035 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1036 1037 bool MergeWithParentScope = (TemplateParams != 0) || 1038 Owner->isFunctionOrMethod() || 1039 !(isa<Decl>(Owner) && 1040 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1041 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1042 1043 llvm::SmallVector<ParmVarDecl *, 4> Params; 1044 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 1045 TInfo = SubstFunctionType(D, Params); 1046 if (!TInfo) 1047 return 0; 1048 QualType T = TInfo->getType(); 1049 1050 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1051 if (QualifierLoc) { 1052 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1053 TemplateArgs); 1054 if (!QualifierLoc) 1055 return 0; 1056 } 1057 1058 // If we're instantiating a local function declaration, put the result 1059 // in the owner; otherwise we need to find the instantiated context. 1060 DeclContext *DC; 1061 if (D->getDeclContext()->isFunctionOrMethod()) 1062 DC = Owner; 1063 else if (isFriend && QualifierLoc) { 1064 CXXScopeSpec SS; 1065 SS.Adopt(QualifierLoc); 1066 DC = SemaRef.computeDeclContext(SS); 1067 if (!DC) return 0; 1068 } else { 1069 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 1070 TemplateArgs); 1071 } 1072 1073 FunctionDecl *Function = 1074 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 1075 D->getLocation(), D->getDeclName(), T, TInfo, 1076 D->getStorageClass(), D->getStorageClassAsWritten(), 1077 D->isInlineSpecified(), D->hasWrittenPrototype()); 1078 1079 if (QualifierLoc) 1080 Function->setQualifierInfo(QualifierLoc); 1081 1082 DeclContext *LexicalDC = Owner; 1083 if (!isFriend && D->isOutOfLine()) { 1084 assert(D->getDeclContext()->isFileContext()); 1085 LexicalDC = D->getDeclContext(); 1086 } 1087 1088 Function->setLexicalDeclContext(LexicalDC); 1089 1090 // Attach the parameters 1091 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) { 1092 // Adopt the already-instantiated parameters into our own context. 1093 for (unsigned P = 0; P < Params.size(); ++P) 1094 if (Params[P]) 1095 Params[P]->setOwningFunction(Function); 1096 } else { 1097 // Since we were instantiated via a typedef of a function type, create 1098 // new parameters. 1099 const FunctionProtoType *Proto 1100 = Function->getType()->getAs<FunctionProtoType>(); 1101 assert(Proto && "No function prototype in template instantiation?"); 1102 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(), 1103 AE = Proto->arg_type_end(); AI != AE; ++AI) { 1104 ParmVarDecl *Param 1105 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(), 1106 *AI); 1107 Param->setScopeInfo(0, Params.size()); 1108 Params.push_back(Param); 1109 } 1110 } 1111 Function->setParams(Params.data(), Params.size()); 1112 1113 SourceLocation InstantiateAtPOI; 1114 if (TemplateParams) { 1115 // Our resulting instantiation is actually a function template, since we 1116 // are substituting only the outer template parameters. For example, given 1117 // 1118 // template<typename T> 1119 // struct X { 1120 // template<typename U> friend void f(T, U); 1121 // }; 1122 // 1123 // X<int> x; 1124 // 1125 // We are instantiating the friend function template "f" within X<int>, 1126 // which means substituting int for T, but leaving "f" as a friend function 1127 // template. 1128 // Build the function template itself. 1129 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1130 Function->getLocation(), 1131 Function->getDeclName(), 1132 TemplateParams, Function); 1133 Function->setDescribedFunctionTemplate(FunctionTemplate); 1134 1135 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1136 1137 if (isFriend && D->isThisDeclarationADefinition()) { 1138 // TODO: should we remember this connection regardless of whether 1139 // the friend declaration provided a body? 1140 FunctionTemplate->setInstantiatedFromMemberTemplate( 1141 D->getDescribedFunctionTemplate()); 1142 } 1143 } else if (FunctionTemplate) { 1144 // Record this function template specialization. 1145 std::pair<const TemplateArgument *, unsigned> Innermost 1146 = TemplateArgs.getInnermost(); 1147 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1148 TemplateArgumentList::CreateCopy(SemaRef.Context, 1149 Innermost.first, 1150 Innermost.second), 1151 InsertPos); 1152 } else if (isFriend && D->isThisDeclarationADefinition()) { 1153 // TODO: should we remember this connection regardless of whether 1154 // the friend declaration provided a body? 1155 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1156 } 1157 1158 if (InitFunctionInstantiation(Function, D)) 1159 Function->setInvalidDecl(); 1160 1161 bool Redeclaration = false; 1162 bool isExplicitSpecialization = false; 1163 1164 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(), 1165 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 1166 1167 if (DependentFunctionTemplateSpecializationInfo *Info 1168 = D->getDependentSpecializationInfo()) { 1169 assert(isFriend && "non-friend has dependent specialization info?"); 1170 1171 // This needs to be set now for future sanity. 1172 Function->setObjectOfFriendDecl(/*HasPrevious*/ true); 1173 1174 // Instantiate the explicit template arguments. 1175 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1176 Info->getRAngleLoc()); 1177 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1178 ExplicitArgs, TemplateArgs)) 1179 return 0; 1180 1181 // Map the candidate templates to their instantiations. 1182 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1183 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1184 Info->getTemplate(I), 1185 TemplateArgs); 1186 if (!Temp) return 0; 1187 1188 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1189 } 1190 1191 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1192 &ExplicitArgs, 1193 Previous)) 1194 Function->setInvalidDecl(); 1195 1196 isExplicitSpecialization = true; 1197 1198 } else if (TemplateParams || !FunctionTemplate) { 1199 // Look only into the namespace where the friend would be declared to 1200 // find a previous declaration. This is the innermost enclosing namespace, 1201 // as described in ActOnFriendFunctionDecl. 1202 SemaRef.LookupQualifiedName(Previous, DC); 1203 1204 // In C++, the previous declaration we find might be a tag type 1205 // (class or enum). In this case, the new declaration will hide the 1206 // tag type. Note that this does does not apply if we're declaring a 1207 // typedef (C++ [dcl.typedef]p4). 1208 if (Previous.isSingleTagDecl()) 1209 Previous.clear(); 1210 } 1211 1212 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous, 1213 isExplicitSpecialization, Redeclaration); 1214 1215 NamedDecl *PrincipalDecl = (TemplateParams 1216 ? cast<NamedDecl>(FunctionTemplate) 1217 : Function); 1218 1219 // If the original function was part of a friend declaration, 1220 // inherit its namespace state and add it to the owner. 1221 if (isFriend) { 1222 NamedDecl *PrevDecl; 1223 if (TemplateParams) 1224 PrevDecl = FunctionTemplate->getPreviousDeclaration(); 1225 else 1226 PrevDecl = Function->getPreviousDeclaration(); 1227 1228 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0); 1229 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false); 1230 1231 bool queuedInstantiation = false; 1232 1233 if (!SemaRef.getLangOptions().CPlusPlus0x && 1234 D->isThisDeclarationADefinition()) { 1235 // Check for a function body. 1236 const FunctionDecl *Definition = 0; 1237 if (Function->isDefined(Definition) && 1238 Definition->getTemplateSpecializationKind() == TSK_Undeclared) { 1239 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 1240 << Function->getDeclName(); 1241 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition); 1242 Function->setInvalidDecl(); 1243 } 1244 // Check for redefinitions due to other instantiations of this or 1245 // a similar friend function. 1246 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(), 1247 REnd = Function->redecls_end(); 1248 R != REnd; ++R) { 1249 if (*R == Function) 1250 continue; 1251 switch (R->getFriendObjectKind()) { 1252 case Decl::FOK_None: 1253 if (!queuedInstantiation && R->isUsed(false)) { 1254 if (MemberSpecializationInfo *MSInfo 1255 = Function->getMemberSpecializationInfo()) { 1256 if (MSInfo->getPointOfInstantiation().isInvalid()) { 1257 SourceLocation Loc = R->getLocation(); // FIXME 1258 MSInfo->setPointOfInstantiation(Loc); 1259 SemaRef.PendingLocalImplicitInstantiations.push_back( 1260 std::make_pair(Function, Loc)); 1261 queuedInstantiation = true; 1262 } 1263 } 1264 } 1265 break; 1266 default: 1267 if (const FunctionDecl *RPattern 1268 = R->getTemplateInstantiationPattern()) 1269 if (RPattern->isDefined(RPattern)) { 1270 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 1271 << Function->getDeclName(); 1272 SemaRef.Diag(R->getLocation(), diag::note_previous_definition); 1273 Function->setInvalidDecl(); 1274 break; 1275 } 1276 } 1277 } 1278 } 1279 } 1280 1281 if (Function->isOverloadedOperator() && !DC->isRecord() && 1282 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1283 PrincipalDecl->setNonMemberOperator(); 1284 1285 assert(!D->isDefaulted() && "only methods should be defaulted"); 1286 return Function; 1287 } 1288 1289 Decl * 1290 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 1291 TemplateParameterList *TemplateParams) { 1292 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1293 void *InsertPos = 0; 1294 if (FunctionTemplate && !TemplateParams) { 1295 // We are creating a function template specialization from a function 1296 // template. Check whether there is already a function template 1297 // specialization for this particular set of template arguments. 1298 std::pair<const TemplateArgument *, unsigned> Innermost 1299 = TemplateArgs.getInnermost(); 1300 1301 FunctionDecl *SpecFunc 1302 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second, 1303 InsertPos); 1304 1305 // If we already have a function template specialization, return it. 1306 if (SpecFunc) 1307 return SpecFunc; 1308 } 1309 1310 bool isFriend; 1311 if (FunctionTemplate) 1312 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1313 else 1314 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1315 1316 bool MergeWithParentScope = (TemplateParams != 0) || 1317 !(isa<Decl>(Owner) && 1318 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1319 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1320 1321 // Instantiate enclosing template arguments for friends. 1322 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists; 1323 unsigned NumTempParamLists = 0; 1324 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 1325 TempParamLists.set_size(NumTempParamLists); 1326 for (unsigned I = 0; I != NumTempParamLists; ++I) { 1327 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 1328 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1329 if (!InstParams) 1330 return NULL; 1331 TempParamLists[I] = InstParams; 1332 } 1333 } 1334 1335 llvm::SmallVector<ParmVarDecl *, 4> Params; 1336 TypeSourceInfo *TInfo = D->getTypeSourceInfo(); 1337 TInfo = SubstFunctionType(D, Params); 1338 if (!TInfo) 1339 return 0; 1340 QualType T = TInfo->getType(); 1341 1342 // \brief If the type of this function, after ignoring parentheses, 1343 // is not *directly* a function type, then we're instantiating a function 1344 // that was declared via a typedef, e.g., 1345 // 1346 // typedef int functype(int, int); 1347 // functype func; 1348 // 1349 // In this case, we'll just go instantiate the ParmVarDecls that we 1350 // synthesized in the method declaration. 1351 if (!isa<FunctionProtoType>(T.IgnoreParens())) { 1352 assert(!Params.size() && "Instantiating type could not yield parameters"); 1353 llvm::SmallVector<QualType, 4> ParamTypes; 1354 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(), 1355 D->getNumParams(), TemplateArgs, ParamTypes, 1356 &Params)) 1357 return 0; 1358 } 1359 1360 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1361 if (QualifierLoc) { 1362 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1363 TemplateArgs); 1364 if (!QualifierLoc) 1365 return 0; 1366 } 1367 1368 DeclContext *DC = Owner; 1369 if (isFriend) { 1370 if (QualifierLoc) { 1371 CXXScopeSpec SS; 1372 SS.Adopt(QualifierLoc); 1373 DC = SemaRef.computeDeclContext(SS); 1374 1375 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 1376 return 0; 1377 } else { 1378 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 1379 D->getDeclContext(), 1380 TemplateArgs); 1381 } 1382 if (!DC) return 0; 1383 } 1384 1385 // Build the instantiated method declaration. 1386 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1387 CXXMethodDecl *Method = 0; 1388 1389 SourceLocation StartLoc = D->getInnerLocStart(); 1390 DeclarationNameInfo NameInfo 1391 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1392 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1393 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 1394 StartLoc, NameInfo, T, TInfo, 1395 Constructor->isExplicit(), 1396 Constructor->isInlineSpecified(), 1397 false); 1398 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 1399 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 1400 StartLoc, NameInfo, T, TInfo, 1401 Destructor->isInlineSpecified(), 1402 false); 1403 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 1404 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 1405 StartLoc, NameInfo, T, TInfo, 1406 Conversion->isInlineSpecified(), 1407 Conversion->isExplicit(), 1408 Conversion->getLocEnd()); 1409 } else { 1410 Method = CXXMethodDecl::Create(SemaRef.Context, Record, 1411 StartLoc, NameInfo, T, TInfo, 1412 D->isStatic(), 1413 D->getStorageClassAsWritten(), 1414 D->isInlineSpecified(), 1415 D->getLocEnd()); 1416 } 1417 1418 if (QualifierLoc) 1419 Method->setQualifierInfo(QualifierLoc); 1420 1421 if (TemplateParams) { 1422 // Our resulting instantiation is actually a function template, since we 1423 // are substituting only the outer template parameters. For example, given 1424 // 1425 // template<typename T> 1426 // struct X { 1427 // template<typename U> void f(T, U); 1428 // }; 1429 // 1430 // X<int> x; 1431 // 1432 // We are instantiating the member template "f" within X<int>, which means 1433 // substituting int for T, but leaving "f" as a member function template. 1434 // Build the function template itself. 1435 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 1436 Method->getLocation(), 1437 Method->getDeclName(), 1438 TemplateParams, Method); 1439 if (isFriend) { 1440 FunctionTemplate->setLexicalDeclContext(Owner); 1441 FunctionTemplate->setObjectOfFriendDecl(true); 1442 } else if (D->isOutOfLine()) 1443 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 1444 Method->setDescribedFunctionTemplate(FunctionTemplate); 1445 } else if (FunctionTemplate) { 1446 // Record this function template specialization. 1447 std::pair<const TemplateArgument *, unsigned> Innermost 1448 = TemplateArgs.getInnermost(); 1449 Method->setFunctionTemplateSpecialization(FunctionTemplate, 1450 TemplateArgumentList::CreateCopy(SemaRef.Context, 1451 Innermost.first, 1452 Innermost.second), 1453 InsertPos); 1454 } else if (!isFriend) { 1455 // Record that this is an instantiation of a member function. 1456 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1457 } 1458 1459 // If we are instantiating a member function defined 1460 // out-of-line, the instantiation will have the same lexical 1461 // context (which will be a namespace scope) as the template. 1462 if (isFriend) { 1463 if (NumTempParamLists) 1464 Method->setTemplateParameterListsInfo(SemaRef.Context, 1465 NumTempParamLists, 1466 TempParamLists.data()); 1467 1468 Method->setLexicalDeclContext(Owner); 1469 Method->setObjectOfFriendDecl(true); 1470 } else if (D->isOutOfLine()) 1471 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 1472 1473 // Attach the parameters 1474 for (unsigned P = 0; P < Params.size(); ++P) 1475 Params[P]->setOwningFunction(Method); 1476 Method->setParams(Params.data(), Params.size()); 1477 1478 if (InitMethodInstantiation(Method, D)) 1479 Method->setInvalidDecl(); 1480 1481 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 1482 Sema::ForRedeclaration); 1483 1484 if (!FunctionTemplate || TemplateParams || isFriend) { 1485 SemaRef.LookupQualifiedName(Previous, Record); 1486 1487 // In C++, the previous declaration we find might be a tag type 1488 // (class or enum). In this case, the new declaration will hide the 1489 // tag type. Note that this does does not apply if we're declaring a 1490 // typedef (C++ [dcl.typedef]p4). 1491 if (Previous.isSingleTagDecl()) 1492 Previous.clear(); 1493 } 1494 1495 bool Redeclaration = false; 1496 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration); 1497 1498 if (D->isPure()) 1499 SemaRef.CheckPureMethod(Method, SourceRange()); 1500 1501 Method->setAccess(D->getAccess()); 1502 1503 SemaRef.CheckOverrideControl(Method); 1504 1505 if (FunctionTemplate) { 1506 // If there's a function template, let our caller handle it. 1507 } else if (Method->isInvalidDecl() && !Previous.empty()) { 1508 // Don't hide a (potentially) valid declaration with an invalid one. 1509 } else { 1510 NamedDecl *DeclToAdd = (TemplateParams 1511 ? cast<NamedDecl>(FunctionTemplate) 1512 : Method); 1513 if (isFriend) 1514 Record->makeDeclVisibleInContext(DeclToAdd); 1515 else 1516 Owner->addDecl(DeclToAdd); 1517 } 1518 1519 if (D->isExplicitlyDefaulted()) { 1520 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 1521 } else { 1522 assert(!D->isDefaulted() && 1523 "should not implicitly default uninstantiated function"); 1524 } 1525 1526 return Method; 1527 } 1528 1529 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1530 return VisitCXXMethodDecl(D); 1531 } 1532 1533 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1534 return VisitCXXMethodDecl(D); 1535 } 1536 1537 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 1538 return VisitCXXMethodDecl(D); 1539 } 1540 1541 ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 1542 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, 1543 llvm::Optional<unsigned>()); 1544 } 1545 1546 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1547 TemplateTypeParmDecl *D) { 1548 // TODO: don't always clone when decls are refcounted. 1549 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 1550 1551 TemplateTypeParmDecl *Inst = 1552 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, 1553 D->getLocStart(), D->getLocation(), 1554 D->getDepth() - TemplateArgs.getNumLevels(), 1555 D->getIndex(), D->getIdentifier(), 1556 D->wasDeclaredWithTypename(), 1557 D->isParameterPack()); 1558 Inst->setAccess(AS_public); 1559 1560 if (D->hasDefaultArgument()) 1561 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false); 1562 1563 // Introduce this template parameter's instantiation into the instantiation 1564 // scope. 1565 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1566 1567 return Inst; 1568 } 1569 1570 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1571 NonTypeTemplateParmDecl *D) { 1572 // Substitute into the type of the non-type template parameter. 1573 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 1574 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 1575 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes; 1576 bool IsExpandedParameterPack = false; 1577 TypeSourceInfo *DI; 1578 QualType T; 1579 bool Invalid = false; 1580 1581 if (D->isExpandedParameterPack()) { 1582 // The non-type template parameter pack is an already-expanded pack 1583 // expansion of types. Substitute into each of the expanded types. 1584 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 1585 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 1586 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 1587 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), 1588 TemplateArgs, 1589 D->getLocation(), 1590 D->getDeclName()); 1591 if (!NewDI) 1592 return 0; 1593 1594 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1595 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(), 1596 D->getLocation()); 1597 if (NewT.isNull()) 1598 return 0; 1599 ExpandedParameterPackTypes.push_back(NewT); 1600 } 1601 1602 IsExpandedParameterPack = true; 1603 DI = D->getTypeSourceInfo(); 1604 T = DI->getType(); 1605 } else if (isa<PackExpansionTypeLoc>(TL)) { 1606 // The non-type template parameter pack's type is a pack expansion of types. 1607 // Determine whether we need to expand this parameter pack into separate 1608 // types. 1609 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL); 1610 TypeLoc Pattern = Expansion.getPatternLoc(); 1611 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1612 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 1613 1614 // Determine whether the set of unexpanded parameter packs can and should 1615 // be expanded. 1616 bool Expand = true; 1617 bool RetainExpansion = false; 1618 llvm::Optional<unsigned> OrigNumExpansions 1619 = Expansion.getTypePtr()->getNumExpansions(); 1620 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions; 1621 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 1622 Pattern.getSourceRange(), 1623 Unexpanded.data(), 1624 Unexpanded.size(), 1625 TemplateArgs, 1626 Expand, RetainExpansion, 1627 NumExpansions)) 1628 return 0; 1629 1630 if (Expand) { 1631 for (unsigned I = 0; I != *NumExpansions; ++I) { 1632 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 1633 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 1634 D->getLocation(), 1635 D->getDeclName()); 1636 if (!NewDI) 1637 return 0; 1638 1639 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1640 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType( 1641 NewDI->getType(), 1642 D->getLocation()); 1643 if (NewT.isNull()) 1644 return 0; 1645 ExpandedParameterPackTypes.push_back(NewT); 1646 } 1647 1648 // Note that we have an expanded parameter pack. The "type" of this 1649 // expanded parameter pack is the original expansion type, but callers 1650 // will end up using the expanded parameter pack types for type-checking. 1651 IsExpandedParameterPack = true; 1652 DI = D->getTypeSourceInfo(); 1653 T = DI->getType(); 1654 } else { 1655 // We cannot fully expand the pack expansion now, so substitute into the 1656 // pattern and create a new pack expansion type. 1657 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 1658 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 1659 D->getLocation(), 1660 D->getDeclName()); 1661 if (!NewPattern) 1662 return 0; 1663 1664 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 1665 NumExpansions); 1666 if (!DI) 1667 return 0; 1668 1669 T = DI->getType(); 1670 } 1671 } else { 1672 // Simple case: substitution into a parameter that is not a parameter pack. 1673 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 1674 D->getLocation(), D->getDeclName()); 1675 if (!DI) 1676 return 0; 1677 1678 // Check that this type is acceptable for a non-type template parameter. 1679 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(), 1680 D->getLocation()); 1681 if (T.isNull()) { 1682 T = SemaRef.Context.IntTy; 1683 Invalid = true; 1684 } 1685 } 1686 1687 NonTypeTemplateParmDecl *Param; 1688 if (IsExpandedParameterPack) 1689 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1690 D->getInnerLocStart(), 1691 D->getLocation(), 1692 D->getDepth() - TemplateArgs.getNumLevels(), 1693 D->getPosition(), 1694 D->getIdentifier(), T, 1695 DI, 1696 ExpandedParameterPackTypes.data(), 1697 ExpandedParameterPackTypes.size(), 1698 ExpandedParameterPackTypesAsWritten.data()); 1699 else 1700 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1701 D->getInnerLocStart(), 1702 D->getLocation(), 1703 D->getDepth() - TemplateArgs.getNumLevels(), 1704 D->getPosition(), 1705 D->getIdentifier(), T, 1706 D->isParameterPack(), DI); 1707 1708 Param->setAccess(AS_public); 1709 if (Invalid) 1710 Param->setInvalidDecl(); 1711 1712 Param->setDefaultArgument(D->getDefaultArgument(), false); 1713 1714 // Introduce this template parameter's instantiation into the instantiation 1715 // scope. 1716 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1717 return Param; 1718 } 1719 1720 Decl * 1721 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1722 TemplateTemplateParmDecl *D) { 1723 // Instantiate the template parameter list of the template template parameter. 1724 TemplateParameterList *TempParams = D->getTemplateParameters(); 1725 TemplateParameterList *InstParams; 1726 { 1727 // Perform the actual substitution of template parameters within a new, 1728 // local instantiation scope. 1729 LocalInstantiationScope Scope(SemaRef); 1730 InstParams = SubstTemplateParams(TempParams); 1731 if (!InstParams) 1732 return NULL; 1733 } 1734 1735 // Build the template template parameter. 1736 TemplateTemplateParmDecl *Param 1737 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1738 D->getDepth() - TemplateArgs.getNumLevels(), 1739 D->getPosition(), D->isParameterPack(), 1740 D->getIdentifier(), InstParams); 1741 Param->setDefaultArgument(D->getDefaultArgument(), false); 1742 Param->setAccess(AS_public); 1743 1744 // Introduce this template parameter's instantiation into the instantiation 1745 // scope. 1746 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1747 1748 return Param; 1749 } 1750 1751 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 1752 // Using directives are never dependent (and never contain any types or 1753 // expressions), so they require no explicit instantiation work. 1754 1755 UsingDirectiveDecl *Inst 1756 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1757 D->getNamespaceKeyLocation(), 1758 D->getQualifierLoc(), 1759 D->getIdentLocation(), 1760 D->getNominatedNamespace(), 1761 D->getCommonAncestor()); 1762 Owner->addDecl(Inst); 1763 return Inst; 1764 } 1765 1766 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 1767 1768 // The nested name specifier may be dependent, for example 1769 // template <typename T> struct t { 1770 // struct s1 { T f1(); }; 1771 // struct s2 : s1 { using s1::f1; }; 1772 // }; 1773 // template struct t<int>; 1774 // Here, in using s1::f1, s1 refers to t<T>::s1; 1775 // we need to substitute for t<int>::s1. 1776 NestedNameSpecifierLoc QualifierLoc 1777 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 1778 TemplateArgs); 1779 if (!QualifierLoc) 1780 return 0; 1781 1782 // The name info is non-dependent, so no transformation 1783 // is required. 1784 DeclarationNameInfo NameInfo = D->getNameInfo(); 1785 1786 // We only need to do redeclaration lookups if we're in a class 1787 // scope (in fact, it's not really even possible in non-class 1788 // scopes). 1789 bool CheckRedeclaration = Owner->isRecord(); 1790 1791 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 1792 Sema::ForRedeclaration); 1793 1794 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 1795 D->getUsingLocation(), 1796 QualifierLoc, 1797 NameInfo, 1798 D->isTypeName()); 1799 1800 CXXScopeSpec SS; 1801 SS.Adopt(QualifierLoc); 1802 if (CheckRedeclaration) { 1803 Prev.setHideTags(false); 1804 SemaRef.LookupQualifiedName(Prev, Owner); 1805 1806 // Check for invalid redeclarations. 1807 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(), 1808 D->isTypeName(), SS, 1809 D->getLocation(), Prev)) 1810 NewUD->setInvalidDecl(); 1811 1812 } 1813 1814 if (!NewUD->isInvalidDecl() && 1815 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS, 1816 D->getLocation())) 1817 NewUD->setInvalidDecl(); 1818 1819 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 1820 NewUD->setAccess(D->getAccess()); 1821 Owner->addDecl(NewUD); 1822 1823 // Don't process the shadow decls for an invalid decl. 1824 if (NewUD->isInvalidDecl()) 1825 return NewUD; 1826 1827 bool isFunctionScope = Owner->isFunctionOrMethod(); 1828 1829 // Process the shadow decls. 1830 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end(); 1831 I != E; ++I) { 1832 UsingShadowDecl *Shadow = *I; 1833 NamedDecl *InstTarget = 1834 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 1835 Shadow->getLocation(), 1836 Shadow->getTargetDecl(), 1837 TemplateArgs)); 1838 if (!InstTarget) 1839 return 0; 1840 1841 if (CheckRedeclaration && 1842 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev)) 1843 continue; 1844 1845 UsingShadowDecl *InstShadow 1846 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget); 1847 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 1848 1849 if (isFunctionScope) 1850 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 1851 } 1852 1853 return NewUD; 1854 } 1855 1856 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 1857 // Ignore these; we handle them in bulk when processing the UsingDecl. 1858 return 0; 1859 } 1860 1861 Decl * TemplateDeclInstantiator 1862 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 1863 NestedNameSpecifierLoc QualifierLoc 1864 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 1865 TemplateArgs); 1866 if (!QualifierLoc) 1867 return 0; 1868 1869 CXXScopeSpec SS; 1870 SS.Adopt(QualifierLoc); 1871 1872 // Since NameInfo refers to a typename, it cannot be a C++ special name. 1873 // Hence, no tranformation is required for it. 1874 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation()); 1875 NamedDecl *UD = 1876 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1877 D->getUsingLoc(), SS, NameInfo, 0, 1878 /*instantiation*/ true, 1879 /*typename*/ true, D->getTypenameLoc()); 1880 if (UD) 1881 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1882 1883 return UD; 1884 } 1885 1886 Decl * TemplateDeclInstantiator 1887 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 1888 NestedNameSpecifierLoc QualifierLoc 1889 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs); 1890 if (!QualifierLoc) 1891 return 0; 1892 1893 CXXScopeSpec SS; 1894 SS.Adopt(QualifierLoc); 1895 1896 DeclarationNameInfo NameInfo 1897 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1898 1899 NamedDecl *UD = 1900 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(), 1901 D->getUsingLoc(), SS, NameInfo, 0, 1902 /*instantiation*/ true, 1903 /*typename*/ false, SourceLocation()); 1904 if (UD) 1905 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 1906 1907 return UD; 1908 } 1909 1910 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 1911 const MultiLevelTemplateArgumentList &TemplateArgs) { 1912 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 1913 if (D->isInvalidDecl()) 1914 return 0; 1915 1916 return Instantiator.Visit(D); 1917 } 1918 1919 /// \brief Instantiates a nested template parameter list in the current 1920 /// instantiation context. 1921 /// 1922 /// \param L The parameter list to instantiate 1923 /// 1924 /// \returns NULL if there was an error 1925 TemplateParameterList * 1926 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 1927 // Get errors for all the parameters before bailing out. 1928 bool Invalid = false; 1929 1930 unsigned N = L->size(); 1931 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector; 1932 ParamVector Params; 1933 Params.reserve(N); 1934 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 1935 PI != PE; ++PI) { 1936 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 1937 Params.push_back(D); 1938 Invalid = Invalid || !D || D->isInvalidDecl(); 1939 } 1940 1941 // Clean up if we had an error. 1942 if (Invalid) 1943 return NULL; 1944 1945 TemplateParameterList *InstL 1946 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 1947 L->getLAngleLoc(), &Params.front(), N, 1948 L->getRAngleLoc()); 1949 return InstL; 1950 } 1951 1952 /// \brief Instantiate the declaration of a class template partial 1953 /// specialization. 1954 /// 1955 /// \param ClassTemplate the (instantiated) class template that is partially 1956 // specialized by the instantiation of \p PartialSpec. 1957 /// 1958 /// \param PartialSpec the (uninstantiated) class template partial 1959 /// specialization that we are instantiating. 1960 /// 1961 /// \returns The instantiated partial specialization, if successful; otherwise, 1962 /// NULL to indicate an error. 1963 ClassTemplatePartialSpecializationDecl * 1964 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 1965 ClassTemplateDecl *ClassTemplate, 1966 ClassTemplatePartialSpecializationDecl *PartialSpec) { 1967 // Create a local instantiation scope for this class template partial 1968 // specialization, which will contain the instantiations of the template 1969 // parameters. 1970 LocalInstantiationScope Scope(SemaRef); 1971 1972 // Substitute into the template parameters of the class template partial 1973 // specialization. 1974 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 1975 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1976 if (!InstParams) 1977 return 0; 1978 1979 // Substitute into the template arguments of the class template partial 1980 // specialization. 1981 TemplateArgumentListInfo InstTemplateArgs; // no angle locations 1982 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(), 1983 PartialSpec->getNumTemplateArgsAsWritten(), 1984 InstTemplateArgs, TemplateArgs)) 1985 return 0; 1986 1987 // Check that the template argument list is well-formed for this 1988 // class template. 1989 llvm::SmallVector<TemplateArgument, 4> Converted; 1990 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 1991 PartialSpec->getLocation(), 1992 InstTemplateArgs, 1993 false, 1994 Converted)) 1995 return 0; 1996 1997 // Figure out where to insert this class template partial specialization 1998 // in the member template's set of class template partial specializations. 1999 void *InsertPos = 0; 2000 ClassTemplateSpecializationDecl *PrevDecl 2001 = ClassTemplate->findPartialSpecialization(Converted.data(), 2002 Converted.size(), InsertPos); 2003 2004 // Build the canonical type that describes the converted template 2005 // arguments of the class template partial specialization. 2006 QualType CanonType 2007 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 2008 Converted.data(), 2009 Converted.size()); 2010 2011 // Build the fully-sugared type for this class template 2012 // specialization as the user wrote in the specialization 2013 // itself. This means that we'll pretty-print the type retrieved 2014 // from the specialization's declaration the way that the user 2015 // actually wrote the specialization, rather than formatting the 2016 // name based on the "canonical" representation used to store the 2017 // template arguments in the specialization. 2018 TypeSourceInfo *WrittenTy 2019 = SemaRef.Context.getTemplateSpecializationTypeInfo( 2020 TemplateName(ClassTemplate), 2021 PartialSpec->getLocation(), 2022 InstTemplateArgs, 2023 CanonType); 2024 2025 if (PrevDecl) { 2026 // We've already seen a partial specialization with the same template 2027 // parameters and template arguments. This can happen, for example, when 2028 // substituting the outer template arguments ends up causing two 2029 // class template partial specializations of a member class template 2030 // to have identical forms, e.g., 2031 // 2032 // template<typename T, typename U> 2033 // struct Outer { 2034 // template<typename X, typename Y> struct Inner; 2035 // template<typename Y> struct Inner<T, Y>; 2036 // template<typename Y> struct Inner<U, Y>; 2037 // }; 2038 // 2039 // Outer<int, int> outer; // error: the partial specializations of Inner 2040 // // have the same signature. 2041 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 2042 << WrittenTy->getType(); 2043 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 2044 << SemaRef.Context.getTypeDeclType(PrevDecl); 2045 return 0; 2046 } 2047 2048 2049 // Create the class template partial specialization declaration. 2050 ClassTemplatePartialSpecializationDecl *InstPartialSpec 2051 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, 2052 PartialSpec->getTagKind(), 2053 Owner, 2054 PartialSpec->getLocStart(), 2055 PartialSpec->getLocation(), 2056 InstParams, 2057 ClassTemplate, 2058 Converted.data(), 2059 Converted.size(), 2060 InstTemplateArgs, 2061 CanonType, 2062 0, 2063 ClassTemplate->getNextPartialSpecSequenceNumber()); 2064 // Substitute the nested name specifier, if any. 2065 if (SubstQualifier(PartialSpec, InstPartialSpec)) 2066 return 0; 2067 2068 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 2069 InstPartialSpec->setTypeAsWritten(WrittenTy); 2070 2071 // Add this partial specialization to the set of class template partial 2072 // specializations. 2073 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos); 2074 return InstPartialSpec; 2075 } 2076 2077 TypeSourceInfo* 2078 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 2079 llvm::SmallVectorImpl<ParmVarDecl *> &Params) { 2080 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 2081 assert(OldTInfo && "substituting function without type source info"); 2082 assert(Params.empty() && "parameter vector is non-empty at start"); 2083 TypeSourceInfo *NewTInfo 2084 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 2085 D->getTypeSpecStartLoc(), 2086 D->getDeclName()); 2087 if (!NewTInfo) 2088 return 0; 2089 2090 if (NewTInfo != OldTInfo) { 2091 // Get parameters from the new type info. 2092 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 2093 if (FunctionProtoTypeLoc *OldProtoLoc 2094 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 2095 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 2096 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL); 2097 assert(NewProtoLoc && "Missing prototype?"); 2098 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs(); 2099 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs(); 2100 OldIdx != NumOldParams; ++OldIdx) { 2101 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx); 2102 if (!OldParam->isParameterPack() || 2103 (NewIdx < NumNewParams && 2104 NewProtoLoc->getArg(NewIdx)->isParameterPack())) { 2105 // Simple case: normal parameter, or a parameter pack that's 2106 // instantiated to a (still-dependent) parameter pack. 2107 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++); 2108 Params.push_back(NewParam); 2109 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, 2110 NewParam); 2111 continue; 2112 } 2113 2114 // Parameter pack: make the instantiation an argument pack. 2115 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack( 2116 OldParam); 2117 unsigned NumArgumentsInExpansion 2118 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 2119 TemplateArgs); 2120 while (NumArgumentsInExpansion--) { 2121 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++); 2122 Params.push_back(NewParam); 2123 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam, 2124 NewParam); 2125 } 2126 } 2127 } 2128 } else { 2129 // The function type itself was not dependent and therefore no 2130 // substitution occurred. However, we still need to instantiate 2131 // the function parameters themselves. 2132 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 2133 if (FunctionProtoTypeLoc *OldProtoLoc 2134 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) { 2135 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) { 2136 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i)); 2137 if (!Parm) 2138 return 0; 2139 Params.push_back(Parm); 2140 } 2141 } 2142 } 2143 return NewTInfo; 2144 } 2145 2146 /// \brief Initializes the common fields of an instantiation function 2147 /// declaration (New) from the corresponding fields of its template (Tmpl). 2148 /// 2149 /// \returns true if there was an error 2150 bool 2151 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 2152 FunctionDecl *Tmpl) { 2153 if (Tmpl->isDeletedAsWritten()) 2154 New->setDeletedAsWritten(); 2155 2156 // If we are performing substituting explicitly-specified template arguments 2157 // or deduced template arguments into a function template and we reach this 2158 // point, we are now past the point where SFINAE applies and have committed 2159 // to keeping the new function template specialization. We therefore 2160 // convert the active template instantiation for the function template 2161 // into a template instantiation for this specific function template 2162 // specialization, which is not a SFINAE context, so that we diagnose any 2163 // further errors in the declaration itself. 2164 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 2165 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 2166 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 2167 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 2168 if (FunctionTemplateDecl *FunTmpl 2169 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) { 2170 assert(FunTmpl->getTemplatedDecl() == Tmpl && 2171 "Deduction from the wrong function template?"); 2172 (void) FunTmpl; 2173 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 2174 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New); 2175 --SemaRef.NonInstantiationEntries; 2176 } 2177 } 2178 2179 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 2180 assert(Proto && "Function template without prototype?"); 2181 2182 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 2183 // The function has an exception specification or a "noreturn" 2184 // attribute. Substitute into each of the exception types. 2185 llvm::SmallVector<QualType, 4> Exceptions; 2186 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 2187 // FIXME: Poor location information! 2188 if (const PackExpansionType *PackExpansion 2189 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) { 2190 // We have a pack expansion. Instantiate it. 2191 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2192 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(), 2193 Unexpanded); 2194 assert(!Unexpanded.empty() && 2195 "Pack expansion without parameter packs?"); 2196 2197 bool Expand = false; 2198 bool RetainExpansion = false; 2199 llvm::Optional<unsigned> NumExpansions 2200 = PackExpansion->getNumExpansions(); 2201 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(), 2202 SourceRange(), 2203 Unexpanded.data(), 2204 Unexpanded.size(), 2205 TemplateArgs, 2206 Expand, 2207 RetainExpansion, 2208 NumExpansions)) 2209 break; 2210 2211 if (!Expand) { 2212 // We can't expand this pack expansion into separate arguments yet; 2213 // just substitute into the pattern and create a new pack expansion 2214 // type. 2215 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2216 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 2217 TemplateArgs, 2218 New->getLocation(), New->getDeclName()); 2219 if (T.isNull()) 2220 break; 2221 2222 T = SemaRef.Context.getPackExpansionType(T, NumExpansions); 2223 Exceptions.push_back(T); 2224 continue; 2225 } 2226 2227 // Substitute into the pack expansion pattern for each template 2228 bool Invalid = false; 2229 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) { 2230 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx); 2231 2232 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 2233 TemplateArgs, 2234 New->getLocation(), New->getDeclName()); 2235 if (T.isNull()) { 2236 Invalid = true; 2237 break; 2238 } 2239 2240 Exceptions.push_back(T); 2241 } 2242 2243 if (Invalid) 2244 break; 2245 2246 continue; 2247 } 2248 2249 QualType T 2250 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 2251 New->getLocation(), New->getDeclName()); 2252 if (T.isNull() || 2253 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 2254 continue; 2255 2256 Exceptions.push_back(T); 2257 } 2258 Expr *NoexceptExpr = 0; 2259 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) { 2260 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated); 2261 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs); 2262 if (E.isUsable()) 2263 NoexceptExpr = E.take(); 2264 } 2265 2266 // Rebuild the function type 2267 2268 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 2269 EPI.ExceptionSpecType = Proto->getExceptionSpecType(); 2270 EPI.NumExceptions = Exceptions.size(); 2271 EPI.Exceptions = Exceptions.data(); 2272 EPI.NoexceptExpr = NoexceptExpr; 2273 EPI.ExtInfo = Proto->getExtInfo(); 2274 2275 const FunctionProtoType *NewProto 2276 = New->getType()->getAs<FunctionProtoType>(); 2277 assert(NewProto && "Template instantiation without function prototype?"); 2278 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(), 2279 NewProto->arg_type_begin(), 2280 NewProto->getNumArgs(), 2281 EPI)); 2282 } 2283 2284 const FunctionDecl* Definition = Tmpl; 2285 2286 // Get the definition. Leaves the variable unchanged if undefined. 2287 Tmpl->isDefined(Definition); 2288 2289 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New); 2290 2291 return false; 2292 } 2293 2294 /// \brief Initializes common fields of an instantiated method 2295 /// declaration (New) from the corresponding fields of its template 2296 /// (Tmpl). 2297 /// 2298 /// \returns true if there was an error 2299 bool 2300 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 2301 CXXMethodDecl *Tmpl) { 2302 if (InitFunctionInstantiation(New, Tmpl)) 2303 return true; 2304 2305 New->setAccess(Tmpl->getAccess()); 2306 if (Tmpl->isVirtualAsWritten()) 2307 New->setVirtualAsWritten(true); 2308 2309 // FIXME: attributes 2310 // FIXME: New needs a pointer to Tmpl 2311 return false; 2312 } 2313 2314 /// \brief Instantiate the definition of the given function from its 2315 /// template. 2316 /// 2317 /// \param PointOfInstantiation the point at which the instantiation was 2318 /// required. Note that this is not precisely a "point of instantiation" 2319 /// for the function, but it's close. 2320 /// 2321 /// \param Function the already-instantiated declaration of a 2322 /// function template specialization or member function of a class template 2323 /// specialization. 2324 /// 2325 /// \param Recursive if true, recursively instantiates any functions that 2326 /// are required by this instantiation. 2327 /// 2328 /// \param DefinitionRequired if true, then we are performing an explicit 2329 /// instantiation where the body of the function is required. Complain if 2330 /// there is no such body. 2331 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 2332 FunctionDecl *Function, 2333 bool Recursive, 2334 bool DefinitionRequired) { 2335 if (Function->isInvalidDecl() || Function->isDefined()) 2336 return; 2337 2338 // Never instantiate an explicit specialization. 2339 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 2340 return; 2341 2342 // Find the function body that we'll be substituting. 2343 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 2344 assert(PatternDecl && "instantiating a non-template"); 2345 2346 Stmt *Pattern = PatternDecl->getBody(PatternDecl); 2347 assert(PatternDecl && "template definition is not a template"); 2348 if (!Pattern) { 2349 // Try to find a defaulted definition 2350 PatternDecl->isDefined(PatternDecl); 2351 } 2352 assert(PatternDecl && "template definition is not a template"); 2353 2354 // Postpone late parsed template instantiations. 2355 if (PatternDecl->isLateTemplateParsed() && 2356 !LateTemplateParser) { 2357 PendingInstantiations.push_back( 2358 std::make_pair(Function, PointOfInstantiation)); 2359 return; 2360 } 2361 2362 // Call the LateTemplateParser callback if there a need to late parse 2363 // a templated function definition. 2364 if (!Pattern && PatternDecl->isLateTemplateParsed() && 2365 LateTemplateParser) { 2366 LateTemplateParser(OpaqueParser, PatternDecl); 2367 Pattern = PatternDecl->getBody(PatternDecl); 2368 } 2369 2370 if (!Pattern && !PatternDecl->isDefaulted()) { 2371 if (DefinitionRequired) { 2372 if (Function->getPrimaryTemplate()) 2373 Diag(PointOfInstantiation, 2374 diag::err_explicit_instantiation_undefined_func_template) 2375 << Function->getPrimaryTemplate(); 2376 else 2377 Diag(PointOfInstantiation, 2378 diag::err_explicit_instantiation_undefined_member) 2379 << 1 << Function->getDeclName() << Function->getDeclContext(); 2380 2381 if (PatternDecl) 2382 Diag(PatternDecl->getLocation(), 2383 diag::note_explicit_instantiation_here); 2384 Function->setInvalidDecl(); 2385 } else if (Function->getTemplateSpecializationKind() 2386 == TSK_ExplicitInstantiationDefinition) { 2387 PendingInstantiations.push_back( 2388 std::make_pair(Function, PointOfInstantiation)); 2389 } 2390 2391 return; 2392 } 2393 2394 // C++0x [temp.explicit]p9: 2395 // Except for inline functions, other explicit instantiation declarations 2396 // have the effect of suppressing the implicit instantiation of the entity 2397 // to which they refer. 2398 if (Function->getTemplateSpecializationKind() 2399 == TSK_ExplicitInstantiationDeclaration && 2400 !PatternDecl->isInlined()) 2401 return; 2402 2403 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 2404 if (Inst) 2405 return; 2406 2407 // If we're performing recursive template instantiation, create our own 2408 // queue of pending implicit instantiations that we will instantiate later, 2409 // while we're still within our own instantiation context. 2410 llvm::SmallVector<VTableUse, 16> SavedVTableUses; 2411 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 2412 if (Recursive) { 2413 VTableUses.swap(SavedVTableUses); 2414 PendingInstantiations.swap(SavedPendingInstantiations); 2415 } 2416 2417 EnterExpressionEvaluationContext EvalContext(*this, 2418 Sema::PotentiallyEvaluated); 2419 ActOnStartOfFunctionDef(0, Function); 2420 2421 // Introduce a new scope where local variable instantiations will be 2422 // recorded, unless we're actually a member function within a local 2423 // class, in which case we need to merge our results with the parent 2424 // scope (of the enclosing function). 2425 bool MergeWithParentScope = false; 2426 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 2427 MergeWithParentScope = Rec->isLocalClass(); 2428 2429 LocalInstantiationScope Scope(*this, MergeWithParentScope); 2430 2431 // Introduce the instantiated function parameters into the local 2432 // instantiation scope, and set the parameter names to those used 2433 // in the template. 2434 unsigned FParamIdx = 0; 2435 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 2436 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 2437 if (!PatternParam->isParameterPack()) { 2438 // Simple case: not a parameter pack. 2439 assert(FParamIdx < Function->getNumParams()); 2440 ParmVarDecl *FunctionParam = Function->getParamDecl(I); 2441 FunctionParam->setDeclName(PatternParam->getDeclName()); 2442 Scope.InstantiatedLocal(PatternParam, FunctionParam); 2443 ++FParamIdx; 2444 continue; 2445 } 2446 2447 // Expand the parameter pack. 2448 Scope.MakeInstantiatedLocalArgPack(PatternParam); 2449 for (unsigned NumFParams = Function->getNumParams(); 2450 FParamIdx < NumFParams; 2451 ++FParamIdx) { 2452 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 2453 FunctionParam->setDeclName(PatternParam->getDeclName()); 2454 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 2455 } 2456 } 2457 2458 // Enter the scope of this instantiation. We don't use 2459 // PushDeclContext because we don't have a scope. 2460 Sema::ContextRAII savedContext(*this, Function); 2461 2462 MultiLevelTemplateArgumentList TemplateArgs = 2463 getTemplateInstantiationArgs(Function, 0, false, PatternDecl); 2464 2465 if (PatternDecl->isDefaulted()) { 2466 ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true); 2467 2468 SetDeclDefaulted(Function, PatternDecl->getLocation()); 2469 } else { 2470 // If this is a constructor, instantiate the member initializers. 2471 if (const CXXConstructorDecl *Ctor = 2472 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 2473 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 2474 TemplateArgs); 2475 } 2476 2477 // Instantiate the function body. 2478 StmtResult Body = SubstStmt(Pattern, TemplateArgs); 2479 2480 if (Body.isInvalid()) 2481 Function->setInvalidDecl(); 2482 2483 ActOnFinishFunctionBody(Function, Body.get(), 2484 /*IsInstantiation=*/true); 2485 } 2486 2487 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 2488 2489 savedContext.pop(); 2490 2491 DeclGroupRef DG(Function); 2492 Consumer.HandleTopLevelDecl(DG); 2493 2494 // This class may have local implicit instantiations that need to be 2495 // instantiation within this scope. 2496 PerformPendingInstantiations(/*LocalOnly=*/true); 2497 Scope.Exit(); 2498 2499 if (Recursive) { 2500 // Define any pending vtables. 2501 DefineUsedVTables(); 2502 2503 // Instantiate any pending implicit instantiations found during the 2504 // instantiation of this template. 2505 PerformPendingInstantiations(); 2506 2507 // Restore the set of pending vtables. 2508 assert(VTableUses.empty() && 2509 "VTableUses should be empty before it is discarded."); 2510 VTableUses.swap(SavedVTableUses); 2511 2512 // Restore the set of pending implicit instantiations. 2513 assert(PendingInstantiations.empty() && 2514 "PendingInstantiations should be empty before it is discarded."); 2515 PendingInstantiations.swap(SavedPendingInstantiations); 2516 } 2517 } 2518 2519 /// \brief Instantiate the definition of the given variable from its 2520 /// template. 2521 /// 2522 /// \param PointOfInstantiation the point at which the instantiation was 2523 /// required. Note that this is not precisely a "point of instantiation" 2524 /// for the function, but it's close. 2525 /// 2526 /// \param Var the already-instantiated declaration of a static member 2527 /// variable of a class template specialization. 2528 /// 2529 /// \param Recursive if true, recursively instantiates any functions that 2530 /// are required by this instantiation. 2531 /// 2532 /// \param DefinitionRequired if true, then we are performing an explicit 2533 /// instantiation where an out-of-line definition of the member variable 2534 /// is required. Complain if there is no such definition. 2535 void Sema::InstantiateStaticDataMemberDefinition( 2536 SourceLocation PointOfInstantiation, 2537 VarDecl *Var, 2538 bool Recursive, 2539 bool DefinitionRequired) { 2540 if (Var->isInvalidDecl()) 2541 return; 2542 2543 // Find the out-of-line definition of this static data member. 2544 VarDecl *Def = Var->getInstantiatedFromStaticDataMember(); 2545 assert(Def && "This data member was not instantiated from a template?"); 2546 assert(Def->isStaticDataMember() && "Not a static data member?"); 2547 Def = Def->getOutOfLineDefinition(); 2548 2549 if (!Def) { 2550 // We did not find an out-of-line definition of this static data member, 2551 // so we won't perform any instantiation. Rather, we rely on the user to 2552 // instantiate this definition (or provide a specialization for it) in 2553 // another translation unit. 2554 if (DefinitionRequired) { 2555 Def = Var->getInstantiatedFromStaticDataMember(); 2556 Diag(PointOfInstantiation, 2557 diag::err_explicit_instantiation_undefined_member) 2558 << 2 << Var->getDeclName() << Var->getDeclContext(); 2559 Diag(Def->getLocation(), diag::note_explicit_instantiation_here); 2560 } else if (Var->getTemplateSpecializationKind() 2561 == TSK_ExplicitInstantiationDefinition) { 2562 PendingInstantiations.push_back( 2563 std::make_pair(Var, PointOfInstantiation)); 2564 } 2565 2566 return; 2567 } 2568 2569 // Never instantiate an explicit specialization. 2570 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 2571 return; 2572 2573 // C++0x [temp.explicit]p9: 2574 // Except for inline functions, other explicit instantiation declarations 2575 // have the effect of suppressing the implicit instantiation of the entity 2576 // to which they refer. 2577 if (Var->getTemplateSpecializationKind() 2578 == TSK_ExplicitInstantiationDeclaration) 2579 return; 2580 2581 // If we already have a definition, we're done. 2582 if (Var->getDefinition()) 2583 return; 2584 2585 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 2586 if (Inst) 2587 return; 2588 2589 // If we're performing recursive template instantiation, create our own 2590 // queue of pending implicit instantiations that we will instantiate later, 2591 // while we're still within our own instantiation context. 2592 llvm::SmallVector<VTableUse, 16> SavedVTableUses; 2593 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 2594 if (Recursive) { 2595 VTableUses.swap(SavedVTableUses); 2596 PendingInstantiations.swap(SavedPendingInstantiations); 2597 } 2598 2599 // Enter the scope of this instantiation. We don't use 2600 // PushDeclContext because we don't have a scope. 2601 ContextRAII previousContext(*this, Var->getDeclContext()); 2602 2603 VarDecl *OldVar = Var; 2604 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 2605 getTemplateInstantiationArgs(Var))); 2606 2607 previousContext.pop(); 2608 2609 if (Var) { 2610 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo(); 2611 assert(MSInfo && "Missing member specialization information?"); 2612 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(), 2613 MSInfo->getPointOfInstantiation()); 2614 DeclGroupRef DG(Var); 2615 Consumer.HandleTopLevelDecl(DG); 2616 } 2617 2618 if (Recursive) { 2619 // Define any newly required vtables. 2620 DefineUsedVTables(); 2621 2622 // Instantiate any pending implicit instantiations found during the 2623 // instantiation of this template. 2624 PerformPendingInstantiations(); 2625 2626 // Restore the set of pending vtables. 2627 assert(VTableUses.empty() && 2628 "VTableUses should be empty before it is discarded, " 2629 "while instantiating static data member."); 2630 VTableUses.swap(SavedVTableUses); 2631 2632 // Restore the set of pending implicit instantiations. 2633 assert(PendingInstantiations.empty() && 2634 "PendingInstantiations should be empty before it is discarded, " 2635 "while instantiating static data member."); 2636 PendingInstantiations.swap(SavedPendingInstantiations); 2637 } 2638 } 2639 2640 void 2641 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 2642 const CXXConstructorDecl *Tmpl, 2643 const MultiLevelTemplateArgumentList &TemplateArgs) { 2644 2645 llvm::SmallVector<MemInitTy*, 4> NewInits; 2646 bool AnyErrors = false; 2647 2648 // Instantiate all the initializers. 2649 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(), 2650 InitsEnd = Tmpl->init_end(); 2651 Inits != InitsEnd; ++Inits) { 2652 CXXCtorInitializer *Init = *Inits; 2653 2654 // Only instantiate written initializers, let Sema re-construct implicit 2655 // ones. 2656 if (!Init->isWritten()) 2657 continue; 2658 2659 SourceLocation LParenLoc, RParenLoc; 2660 ASTOwningVector<Expr*> NewArgs(*this); 2661 2662 SourceLocation EllipsisLoc; 2663 2664 if (Init->isPackExpansion()) { 2665 // This is a pack expansion. We should expand it now. 2666 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc(); 2667 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2668 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 2669 bool ShouldExpand = false; 2670 bool RetainExpansion = false; 2671 llvm::Optional<unsigned> NumExpansions; 2672 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 2673 BaseTL.getSourceRange(), 2674 Unexpanded.data(), 2675 Unexpanded.size(), 2676 TemplateArgs, ShouldExpand, 2677 RetainExpansion, 2678 NumExpansions)) { 2679 AnyErrors = true; 2680 New->setInvalidDecl(); 2681 continue; 2682 } 2683 assert(ShouldExpand && "Partial instantiation of base initializer?"); 2684 2685 // Loop over all of the arguments in the argument pack(s), 2686 for (unsigned I = 0; I != *NumExpansions; ++I) { 2687 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 2688 2689 // Instantiate the initializer. 2690 if (InstantiateInitializer(Init->getInit(), TemplateArgs, 2691 LParenLoc, NewArgs, RParenLoc)) { 2692 AnyErrors = true; 2693 break; 2694 } 2695 2696 // Instantiate the base type. 2697 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(), 2698 TemplateArgs, 2699 Init->getSourceLocation(), 2700 New->getDeclName()); 2701 if (!BaseTInfo) { 2702 AnyErrors = true; 2703 break; 2704 } 2705 2706 // Build the initializer. 2707 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 2708 BaseTInfo, 2709 (Expr **)NewArgs.data(), 2710 NewArgs.size(), 2711 Init->getLParenLoc(), 2712 Init->getRParenLoc(), 2713 New->getParent(), 2714 SourceLocation()); 2715 if (NewInit.isInvalid()) { 2716 AnyErrors = true; 2717 break; 2718 } 2719 2720 NewInits.push_back(NewInit.get()); 2721 NewArgs.clear(); 2722 } 2723 2724 continue; 2725 } 2726 2727 // Instantiate the initializer. 2728 if (InstantiateInitializer(Init->getInit(), TemplateArgs, 2729 LParenLoc, NewArgs, RParenLoc)) { 2730 AnyErrors = true; 2731 continue; 2732 } 2733 2734 MemInitResult NewInit; 2735 if (Init->isBaseInitializer()) { 2736 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(), 2737 TemplateArgs, 2738 Init->getSourceLocation(), 2739 New->getDeclName()); 2740 if (!BaseTInfo) { 2741 AnyErrors = true; 2742 New->setInvalidDecl(); 2743 continue; 2744 } 2745 2746 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo, 2747 (Expr **)NewArgs.data(), 2748 NewArgs.size(), 2749 Init->getLParenLoc(), 2750 Init->getRParenLoc(), 2751 New->getParent(), 2752 EllipsisLoc); 2753 } else if (Init->isMemberInitializer()) { 2754 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 2755 Init->getMemberLocation(), 2756 Init->getMember(), 2757 TemplateArgs)); 2758 if (!Member) { 2759 AnyErrors = true; 2760 New->setInvalidDecl(); 2761 continue; 2762 } 2763 2764 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(), 2765 NewArgs.size(), 2766 Init->getSourceLocation(), 2767 Init->getLParenLoc(), 2768 Init->getRParenLoc()); 2769 } else if (Init->isIndirectMemberInitializer()) { 2770 IndirectFieldDecl *IndirectMember = 2771 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 2772 Init->getMemberLocation(), 2773 Init->getIndirectMember(), TemplateArgs)); 2774 2775 if (!IndirectMember) { 2776 AnyErrors = true; 2777 New->setInvalidDecl(); 2778 continue; 2779 } 2780 2781 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(), 2782 NewArgs.size(), 2783 Init->getSourceLocation(), 2784 Init->getLParenLoc(), 2785 Init->getRParenLoc()); 2786 } 2787 2788 if (NewInit.isInvalid()) { 2789 AnyErrors = true; 2790 New->setInvalidDecl(); 2791 } else { 2792 // FIXME: It would be nice if ASTOwningVector had a release function. 2793 NewArgs.take(); 2794 2795 NewInits.push_back((MemInitTy *)NewInit.get()); 2796 } 2797 } 2798 2799 // Assign all the initializers to the new constructor. 2800 ActOnMemInitializers(New, 2801 /*FIXME: ColonLoc */ 2802 SourceLocation(), 2803 NewInits.data(), NewInits.size(), 2804 AnyErrors); 2805 } 2806 2807 // TODO: this could be templated if the various decl types used the 2808 // same method name. 2809 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 2810 ClassTemplateDecl *Instance) { 2811 Pattern = Pattern->getCanonicalDecl(); 2812 2813 do { 2814 Instance = Instance->getCanonicalDecl(); 2815 if (Pattern == Instance) return true; 2816 Instance = Instance->getInstantiatedFromMemberTemplate(); 2817 } while (Instance); 2818 2819 return false; 2820 } 2821 2822 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 2823 FunctionTemplateDecl *Instance) { 2824 Pattern = Pattern->getCanonicalDecl(); 2825 2826 do { 2827 Instance = Instance->getCanonicalDecl(); 2828 if (Pattern == Instance) return true; 2829 Instance = Instance->getInstantiatedFromMemberTemplate(); 2830 } while (Instance); 2831 2832 return false; 2833 } 2834 2835 static bool 2836 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 2837 ClassTemplatePartialSpecializationDecl *Instance) { 2838 Pattern 2839 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 2840 do { 2841 Instance = cast<ClassTemplatePartialSpecializationDecl>( 2842 Instance->getCanonicalDecl()); 2843 if (Pattern == Instance) 2844 return true; 2845 Instance = Instance->getInstantiatedFromMember(); 2846 } while (Instance); 2847 2848 return false; 2849 } 2850 2851 static bool isInstantiationOf(CXXRecordDecl *Pattern, 2852 CXXRecordDecl *Instance) { 2853 Pattern = Pattern->getCanonicalDecl(); 2854 2855 do { 2856 Instance = Instance->getCanonicalDecl(); 2857 if (Pattern == Instance) return true; 2858 Instance = Instance->getInstantiatedFromMemberClass(); 2859 } while (Instance); 2860 2861 return false; 2862 } 2863 2864 static bool isInstantiationOf(FunctionDecl *Pattern, 2865 FunctionDecl *Instance) { 2866 Pattern = Pattern->getCanonicalDecl(); 2867 2868 do { 2869 Instance = Instance->getCanonicalDecl(); 2870 if (Pattern == Instance) return true; 2871 Instance = Instance->getInstantiatedFromMemberFunction(); 2872 } while (Instance); 2873 2874 return false; 2875 } 2876 2877 static bool isInstantiationOf(EnumDecl *Pattern, 2878 EnumDecl *Instance) { 2879 Pattern = Pattern->getCanonicalDecl(); 2880 2881 do { 2882 Instance = Instance->getCanonicalDecl(); 2883 if (Pattern == Instance) return true; 2884 Instance = Instance->getInstantiatedFromMemberEnum(); 2885 } while (Instance); 2886 2887 return false; 2888 } 2889 2890 static bool isInstantiationOf(UsingShadowDecl *Pattern, 2891 UsingShadowDecl *Instance, 2892 ASTContext &C) { 2893 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 2894 } 2895 2896 static bool isInstantiationOf(UsingDecl *Pattern, 2897 UsingDecl *Instance, 2898 ASTContext &C) { 2899 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2900 } 2901 2902 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 2903 UsingDecl *Instance, 2904 ASTContext &C) { 2905 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2906 } 2907 2908 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 2909 UsingDecl *Instance, 2910 ASTContext &C) { 2911 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 2912 } 2913 2914 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 2915 VarDecl *Instance) { 2916 assert(Instance->isStaticDataMember()); 2917 2918 Pattern = Pattern->getCanonicalDecl(); 2919 2920 do { 2921 Instance = Instance->getCanonicalDecl(); 2922 if (Pattern == Instance) return true; 2923 Instance = Instance->getInstantiatedFromStaticDataMember(); 2924 } while (Instance); 2925 2926 return false; 2927 } 2928 2929 // Other is the prospective instantiation 2930 // D is the prospective pattern 2931 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 2932 if (D->getKind() != Other->getKind()) { 2933 if (UnresolvedUsingTypenameDecl *UUD 2934 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 2935 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2936 return isInstantiationOf(UUD, UD, Ctx); 2937 } 2938 } 2939 2940 if (UnresolvedUsingValueDecl *UUD 2941 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 2942 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 2943 return isInstantiationOf(UUD, UD, Ctx); 2944 } 2945 } 2946 2947 return false; 2948 } 2949 2950 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 2951 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 2952 2953 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 2954 return isInstantiationOf(cast<FunctionDecl>(D), Function); 2955 2956 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 2957 return isInstantiationOf(cast<EnumDecl>(D), Enum); 2958 2959 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 2960 if (Var->isStaticDataMember()) 2961 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 2962 2963 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 2964 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 2965 2966 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 2967 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 2968 2969 if (ClassTemplatePartialSpecializationDecl *PartialSpec 2970 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 2971 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 2972 PartialSpec); 2973 2974 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 2975 if (!Field->getDeclName()) { 2976 // This is an unnamed field. 2977 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 2978 cast<FieldDecl>(D); 2979 } 2980 } 2981 2982 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 2983 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 2984 2985 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 2986 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 2987 2988 return D->getDeclName() && isa<NamedDecl>(Other) && 2989 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 2990 } 2991 2992 template<typename ForwardIterator> 2993 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 2994 NamedDecl *D, 2995 ForwardIterator first, 2996 ForwardIterator last) { 2997 for (; first != last; ++first) 2998 if (isInstantiationOf(Ctx, D, *first)) 2999 return cast<NamedDecl>(*first); 3000 3001 return 0; 3002 } 3003 3004 /// \brief Finds the instantiation of the given declaration context 3005 /// within the current instantiation. 3006 /// 3007 /// \returns NULL if there was an error 3008 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 3009 const MultiLevelTemplateArgumentList &TemplateArgs) { 3010 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 3011 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 3012 return cast_or_null<DeclContext>(ID); 3013 } else return DC; 3014 } 3015 3016 /// \brief Find the instantiation of the given declaration within the 3017 /// current instantiation. 3018 /// 3019 /// This routine is intended to be used when \p D is a declaration 3020 /// referenced from within a template, that needs to mapped into the 3021 /// corresponding declaration within an instantiation. For example, 3022 /// given: 3023 /// 3024 /// \code 3025 /// template<typename T> 3026 /// struct X { 3027 /// enum Kind { 3028 /// KnownValue = sizeof(T) 3029 /// }; 3030 /// 3031 /// bool getKind() const { return KnownValue; } 3032 /// }; 3033 /// 3034 /// template struct X<int>; 3035 /// \endcode 3036 /// 3037 /// In the instantiation of X<int>::getKind(), we need to map the 3038 /// EnumConstantDecl for KnownValue (which refers to 3039 /// X<T>::<Kind>::KnownValue) to its instantiation 3040 /// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs 3041 /// this mapping from within the instantiation of X<int>. 3042 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 3043 const MultiLevelTemplateArgumentList &TemplateArgs) { 3044 DeclContext *ParentDC = D->getDeclContext(); 3045 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 3046 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 3047 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) { 3048 // D is a local of some kind. Look into the map of local 3049 // declarations to their instantiations. 3050 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 3051 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found 3052 = CurrentInstantiationScope->findInstantiationOf(D); 3053 3054 if (Found) { 3055 if (Decl *FD = Found->dyn_cast<Decl *>()) 3056 return cast<NamedDecl>(FD); 3057 3058 unsigned PackIdx = ArgumentPackSubstitutionIndex; 3059 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 3060 } 3061 3062 // If we didn't find the decl, then we must have a label decl that hasn't 3063 // been found yet. Lazily instantiate it and return it now. 3064 assert(isa<LabelDecl>(D)); 3065 3066 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 3067 assert(Inst && "Failed to instantiate label??"); 3068 3069 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 3070 return cast<LabelDecl>(Inst); 3071 } 3072 3073 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 3074 if (!Record->isDependentContext()) 3075 return D; 3076 3077 // If the RecordDecl is actually the injected-class-name or a 3078 // "templated" declaration for a class template, class template 3079 // partial specialization, or a member class of a class template, 3080 // substitute into the injected-class-name of the class template 3081 // or partial specialization to find the new DeclContext. 3082 QualType T; 3083 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 3084 3085 if (ClassTemplate) { 3086 T = ClassTemplate->getInjectedClassNameSpecialization(); 3087 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec 3088 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 3089 ClassTemplate = PartialSpec->getSpecializedTemplate(); 3090 3091 // If we call SubstType with an InjectedClassNameType here we 3092 // can end up in an infinite loop. 3093 T = Context.getTypeDeclType(Record); 3094 assert(isa<InjectedClassNameType>(T) && 3095 "type of partial specialization is not an InjectedClassNameType"); 3096 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType(); 3097 } 3098 3099 if (!T.isNull()) { 3100 // Substitute into the injected-class-name to get the type 3101 // corresponding to the instantiation we want, which may also be 3102 // the current instantiation (if we're in a template 3103 // definition). This substitution should never fail, since we 3104 // know we can instantiate the injected-class-name or we 3105 // wouldn't have gotten to the injected-class-name! 3106 3107 // FIXME: Can we use the CurrentInstantiationScope to avoid this 3108 // extra instantiation in the common case? 3109 T = SubstType(T, TemplateArgs, Loc, DeclarationName()); 3110 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail."); 3111 3112 if (!T->isDependentType()) { 3113 assert(T->isRecordType() && "Instantiation must produce a record type"); 3114 return T->getAs<RecordType>()->getDecl(); 3115 } 3116 3117 // We are performing "partial" template instantiation to create 3118 // the member declarations for the members of a class template 3119 // specialization. Therefore, D is actually referring to something 3120 // in the current instantiation. Look through the current 3121 // context, which contains actual instantiations, to find the 3122 // instantiation of the "current instantiation" that D refers 3123 // to. 3124 bool SawNonDependentContext = false; 3125 for (DeclContext *DC = CurContext; !DC->isFileContext(); 3126 DC = DC->getParent()) { 3127 if (ClassTemplateSpecializationDecl *Spec 3128 = dyn_cast<ClassTemplateSpecializationDecl>(DC)) 3129 if (isInstantiationOf(ClassTemplate, 3130 Spec->getSpecializedTemplate())) 3131 return Spec; 3132 3133 if (!DC->isDependentContext()) 3134 SawNonDependentContext = true; 3135 } 3136 3137 // We're performing "instantiation" of a member of the current 3138 // instantiation while we are type-checking the 3139 // definition. Compute the declaration context and return that. 3140 assert(!SawNonDependentContext && 3141 "No dependent context while instantiating record"); 3142 DeclContext *DC = computeDeclContext(T); 3143 assert(DC && 3144 "Unable to find declaration for the current instantiation"); 3145 return cast<CXXRecordDecl>(DC); 3146 } 3147 3148 // Fall through to deal with other dependent record types (e.g., 3149 // anonymous unions in class templates). 3150 } 3151 3152 if (!ParentDC->isDependentContext()) 3153 return D; 3154 3155 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 3156 if (!ParentDC) 3157 return 0; 3158 3159 if (ParentDC != D->getDeclContext()) { 3160 // We performed some kind of instantiation in the parent context, 3161 // so now we need to look into the instantiated parent context to 3162 // find the instantiation of the declaration D. 3163 3164 // If our context used to be dependent, we may need to instantiate 3165 // it before performing lookup into that context. 3166 bool IsBeingInstantiated = false; 3167 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 3168 if (!Spec->isDependentContext()) { 3169 QualType T = Context.getTypeDeclType(Spec); 3170 const RecordType *Tag = T->getAs<RecordType>(); 3171 assert(Tag && "type of non-dependent record is not a RecordType"); 3172 if (Tag->isBeingDefined()) 3173 IsBeingInstantiated = true; 3174 if (!Tag->isBeingDefined() && 3175 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 3176 return 0; 3177 3178 ParentDC = Tag->getDecl(); 3179 } 3180 } 3181 3182 NamedDecl *Result = 0; 3183 if (D->getDeclName()) { 3184 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 3185 Result = findInstantiationOf(Context, D, Found.first, Found.second); 3186 } else { 3187 // Since we don't have a name for the entity we're looking for, 3188 // our only option is to walk through all of the declarations to 3189 // find that name. This will occur in a few cases: 3190 // 3191 // - anonymous struct/union within a template 3192 // - unnamed class/struct/union/enum within a template 3193 // 3194 // FIXME: Find a better way to find these instantiations! 3195 Result = findInstantiationOf(Context, D, 3196 ParentDC->decls_begin(), 3197 ParentDC->decls_end()); 3198 } 3199 3200 if (!Result) { 3201 if (isa<UsingShadowDecl>(D)) { 3202 // UsingShadowDecls can instantiate to nothing because of using hiding. 3203 } else if (Diags.hasErrorOccurred()) { 3204 // We've already complained about something, so most likely this 3205 // declaration failed to instantiate. There's no point in complaining 3206 // further, since this is normal in invalid code. 3207 } else if (IsBeingInstantiated) { 3208 // The class in which this member exists is currently being 3209 // instantiated, and we haven't gotten around to instantiating this 3210 // member yet. This can happen when the code uses forward declarations 3211 // of member classes, and introduces ordering dependencies via 3212 // template instantiation. 3213 Diag(Loc, diag::err_member_not_yet_instantiated) 3214 << D->getDeclName() 3215 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 3216 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 3217 } else { 3218 // We should have found something, but didn't. 3219 llvm_unreachable("Unable to find instantiation of declaration!"); 3220 } 3221 } 3222 3223 D = Result; 3224 } 3225 3226 return D; 3227 } 3228 3229 /// \brief Performs template instantiation for all implicit template 3230 /// instantiations we have seen until this point. 3231 void Sema::PerformPendingInstantiations(bool LocalOnly) { 3232 while (!PendingLocalImplicitInstantiations.empty() || 3233 (!LocalOnly && !PendingInstantiations.empty())) { 3234 PendingImplicitInstantiation Inst; 3235 3236 if (PendingLocalImplicitInstantiations.empty()) { 3237 Inst = PendingInstantiations.front(); 3238 PendingInstantiations.pop_front(); 3239 } else { 3240 Inst = PendingLocalImplicitInstantiations.front(); 3241 PendingLocalImplicitInstantiations.pop_front(); 3242 } 3243 3244 // Instantiate function definitions 3245 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 3246 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(), 3247 "instantiating function definition"); 3248 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 3249 TSK_ExplicitInstantiationDefinition; 3250 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true, 3251 DefinitionRequired); 3252 continue; 3253 } 3254 3255 // Instantiate static data member definitions. 3256 VarDecl *Var = cast<VarDecl>(Inst.first); 3257 assert(Var->isStaticDataMember() && "Not a static data member?"); 3258 3259 // Don't try to instantiate declarations if the most recent redeclaration 3260 // is invalid. 3261 if (Var->getMostRecentDeclaration()->isInvalidDecl()) 3262 continue; 3263 3264 // Check if the most recent declaration has changed the specialization kind 3265 // and removed the need for implicit instantiation. 3266 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) { 3267 case TSK_Undeclared: 3268 assert(false && "Cannot instantitiate an undeclared specialization."); 3269 case TSK_ExplicitInstantiationDeclaration: 3270 case TSK_ExplicitSpecialization: 3271 continue; // No longer need to instantiate this type. 3272 case TSK_ExplicitInstantiationDefinition: 3273 // We only need an instantiation if the pending instantiation *is* the 3274 // explicit instantiation. 3275 if (Var != Var->getMostRecentDeclaration()) continue; 3276 case TSK_ImplicitInstantiation: 3277 break; 3278 } 3279 3280 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(), 3281 "instantiating static data member " 3282 "definition"); 3283 3284 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 3285 TSK_ExplicitInstantiationDefinition; 3286 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true, 3287 DefinitionRequired); 3288 } 3289 } 3290 3291 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 3292 const MultiLevelTemplateArgumentList &TemplateArgs) { 3293 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(), 3294 E = Pattern->ddiag_end(); I != E; ++I) { 3295 DependentDiagnostic *DD = *I; 3296 3297 switch (DD->getKind()) { 3298 case DependentDiagnostic::Access: 3299 HandleDependentAccessCheck(*DD, TemplateArgs); 3300 break; 3301 } 3302 } 3303 } 3304