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/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTMutationListener.h" 16 #include "clang/AST/DeclTemplate.h" 17 #include "clang/AST/DeclVisitor.h" 18 #include "clang/AST/DependentDiagnostic.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/ExprCXX.h" 21 #include "clang/AST/TypeLoc.h" 22 #include "clang/Sema/Lookup.h" 23 #include "clang/Sema/PrettyDeclStackTrace.h" 24 #include "clang/Sema/Template.h" 25 26 using namespace clang; 27 28 static bool isDeclWithinFunction(const Decl *D) { 29 const DeclContext *DC = D->getDeclContext(); 30 if (DC->isFunctionOrMethod()) 31 return true; 32 33 if (DC->isRecord()) 34 return cast<CXXRecordDecl>(DC)->isLocalClass(); 35 36 return false; 37 } 38 39 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 40 DeclaratorDecl *NewDecl) { 41 if (!OldDecl->getQualifierLoc()) 42 return false; 43 44 NestedNameSpecifierLoc NewQualifierLoc 45 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 46 TemplateArgs); 47 48 if (!NewQualifierLoc) 49 return true; 50 51 NewDecl->setQualifierInfo(NewQualifierLoc); 52 return false; 53 } 54 55 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 56 TagDecl *NewDecl) { 57 if (!OldDecl->getQualifierLoc()) 58 return false; 59 60 NestedNameSpecifierLoc NewQualifierLoc 61 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 62 TemplateArgs); 63 64 if (!NewQualifierLoc) 65 return true; 66 67 NewDecl->setQualifierInfo(NewQualifierLoc); 68 return false; 69 } 70 71 // Include attribute instantiation code. 72 #include "clang/Sema/AttrTemplateInstantiate.inc" 73 74 static void instantiateDependentAlignedAttr( 75 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 76 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) { 77 if (Aligned->isAlignmentExpr()) { 78 // The alignment expression is a constant expression. 79 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated); 80 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs); 81 if (!Result.isInvalid()) 82 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(), 83 Aligned->getSpellingListIndex(), IsPackExpansion); 84 } else { 85 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(), 86 TemplateArgs, Aligned->getLocation(), 87 DeclarationName()); 88 if (Result) 89 S.AddAlignedAttr(Aligned->getLocation(), New, Result, 90 Aligned->getSpellingListIndex(), IsPackExpansion); 91 } 92 } 93 94 static void instantiateDependentAlignedAttr( 95 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 96 const AlignedAttr *Aligned, Decl *New) { 97 if (!Aligned->isPackExpansion()) { 98 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 99 return; 100 } 101 102 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 103 if (Aligned->isAlignmentExpr()) 104 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(), 105 Unexpanded); 106 else 107 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(), 108 Unexpanded); 109 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); 110 111 // Determine whether we can expand this attribute pack yet. 112 bool Expand = true, RetainExpansion = false; 113 Optional<unsigned> NumExpansions; 114 // FIXME: Use the actual location of the ellipsis. 115 SourceLocation EllipsisLoc = Aligned->getLocation(); 116 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(), 117 Unexpanded, TemplateArgs, Expand, 118 RetainExpansion, NumExpansions)) 119 return; 120 121 if (!Expand) { 122 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1); 123 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true); 124 } else { 125 for (unsigned I = 0; I != *NumExpansions; ++I) { 126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I); 127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 128 } 129 } 130 } 131 132 static void instantiateDependentEnableIfAttr( 133 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 134 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) { 135 Expr *Cond = nullptr; 136 { 137 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated); 138 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs); 139 if (Result.isInvalid()) 140 return; 141 Cond = Result.getAs<Expr>(); 142 } 143 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) { 144 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 145 if (Converted.isInvalid()) 146 return; 147 Cond = Converted.get(); 148 } 149 150 SmallVector<PartialDiagnosticAt, 8> Diags; 151 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() && 152 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl), 153 Diags)) { 154 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr); 155 for (int I = 0, N = Diags.size(); I != N; ++I) 156 S.Diag(Diags[I].first, Diags[I].second); 157 return; 158 } 159 160 EnableIfAttr *EIA = new (S.getASTContext()) 161 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond, 162 A->getMessage(), 163 A->getSpellingListIndex()); 164 New->addAttr(EIA); 165 } 166 167 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 168 const Decl *Tmpl, Decl *New, 169 LateInstantiatedAttrVec *LateAttrs, 170 LocalInstantiationScope *OuterMostScope) { 171 for (const auto *TmplAttr : Tmpl->attrs()) { 172 // FIXME: This should be generalized to more than just the AlignedAttr. 173 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr); 174 if (Aligned && Aligned->isAlignmentDependent()) { 175 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New); 176 continue; 177 } 178 179 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr); 180 if (EnableIf && EnableIf->getCond()->isValueDependent()) { 181 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl, 182 New); 183 continue; 184 } 185 186 assert(!TmplAttr->isPackExpansion()); 187 if (TmplAttr->isLateParsed() && LateAttrs) { 188 // Late parsed attributes must be instantiated and attached after the 189 // enclosing class has been instantiated. See Sema::InstantiateClass. 190 LocalInstantiationScope *Saved = nullptr; 191 if (CurrentInstantiationScope) 192 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); 193 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); 194 } else { 195 // Allow 'this' within late-parsed attributes. 196 NamedDecl *ND = dyn_cast<NamedDecl>(New); 197 CXXRecordDecl *ThisContext = 198 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); 199 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0, 200 ND && ND->isCXXInstanceMember()); 201 202 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, 203 *this, TemplateArgs); 204 if (NewAttr) 205 New->addAttr(NewAttr); 206 } 207 } 208 } 209 210 Decl * 211 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 212 llvm_unreachable("Translation units cannot be instantiated"); 213 } 214 215 Decl * 216 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 217 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 218 D->getIdentifier()); 219 Owner->addDecl(Inst); 220 return Inst; 221 } 222 223 Decl * 224 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 225 llvm_unreachable("Namespaces cannot be instantiated"); 226 } 227 228 Decl * 229 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 230 NamespaceAliasDecl *Inst 231 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 232 D->getNamespaceLoc(), 233 D->getAliasLoc(), 234 D->getIdentifier(), 235 D->getQualifierLoc(), 236 D->getTargetNameLoc(), 237 D->getNamespace()); 238 Owner->addDecl(Inst); 239 return Inst; 240 } 241 242 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 243 bool IsTypeAlias) { 244 bool Invalid = false; 245 TypeSourceInfo *DI = D->getTypeSourceInfo(); 246 if (DI->getType()->isInstantiationDependentType() || 247 DI->getType()->isVariablyModifiedType()) { 248 DI = SemaRef.SubstType(DI, TemplateArgs, 249 D->getLocation(), D->getDeclName()); 250 if (!DI) { 251 Invalid = true; 252 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 253 } 254 } else { 255 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 256 } 257 258 // HACK: g++ has a bug where it gets the value kind of ?: wrong. 259 // libstdc++ relies upon this bug in its implementation of common_type. 260 // If we happen to be processing that implementation, fake up the g++ ?: 261 // semantics. See LWG issue 2141 for more information on the bug. 262 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>(); 263 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 264 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) && 265 DT->isReferenceType() && 266 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() && 267 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") && 268 D->getIdentifier() && D->getIdentifier()->isStr("type") && 269 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart())) 270 // Fold it to the (non-reference) type which g++ would have produced. 271 DI = SemaRef.Context.getTrivialTypeSourceInfo( 272 DI->getType().getNonReferenceType()); 273 274 // Create the new typedef 275 TypedefNameDecl *Typedef; 276 if (IsTypeAlias) 277 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 278 D->getLocation(), D->getIdentifier(), DI); 279 else 280 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 281 D->getLocation(), D->getIdentifier(), DI); 282 if (Invalid) 283 Typedef->setInvalidDecl(); 284 285 // If the old typedef was the name for linkage purposes of an anonymous 286 // tag decl, re-establish that relationship for the new typedef. 287 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 288 TagDecl *oldTag = oldTagType->getDecl(); 289 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) { 290 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 291 assert(!newTag->hasNameForLinkage()); 292 newTag->setTypedefNameForAnonDecl(Typedef); 293 } 294 } 295 296 if (TypedefNameDecl *Prev = D->getPreviousDecl()) { 297 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 298 TemplateArgs); 299 if (!InstPrev) 300 return nullptr; 301 302 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev); 303 304 // If the typedef types are not identical, reject them. 305 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); 306 307 Typedef->setPreviousDecl(InstPrevTypedef); 308 } 309 310 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); 311 312 Typedef->setAccess(D->getAccess()); 313 314 return Typedef; 315 } 316 317 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 318 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); 319 Owner->addDecl(Typedef); 320 return Typedef; 321 } 322 323 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { 324 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); 325 Owner->addDecl(Typedef); 326 return Typedef; 327 } 328 329 Decl * 330 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 331 // Create a local instantiation scope for this type alias template, which 332 // will contain the instantiations of the template parameters. 333 LocalInstantiationScope Scope(SemaRef); 334 335 TemplateParameterList *TempParams = D->getTemplateParameters(); 336 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 337 if (!InstParams) 338 return nullptr; 339 340 TypeAliasDecl *Pattern = D->getTemplatedDecl(); 341 342 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr; 343 if (Pattern->getPreviousDecl()) { 344 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 345 if (!Found.empty()) { 346 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front()); 347 } 348 } 349 350 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( 351 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); 352 if (!AliasInst) 353 return nullptr; 354 355 TypeAliasTemplateDecl *Inst 356 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 357 D->getDeclName(), InstParams, AliasInst); 358 if (PrevAliasTemplate) 359 Inst->setPreviousDecl(PrevAliasTemplate); 360 361 Inst->setAccess(D->getAccess()); 362 363 if (!PrevAliasTemplate) 364 Inst->setInstantiatedFromMemberTemplate(D); 365 366 Owner->addDecl(Inst); 367 368 return Inst; 369 } 370 371 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 372 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false); 373 } 374 375 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, 376 bool InstantiatingVarTemplate) { 377 378 // If this is the variable for an anonymous struct or union, 379 // instantiate the anonymous struct/union type first. 380 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 381 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 382 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 383 return nullptr; 384 385 // Do substitution on the type of the declaration 386 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(), 387 TemplateArgs, 388 D->getTypeSpecStartLoc(), 389 D->getDeclName()); 390 if (!DI) 391 return nullptr; 392 393 if (DI->getType()->isFunctionType()) { 394 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 395 << D->isStaticDataMember() << DI->getType(); 396 return nullptr; 397 } 398 399 DeclContext *DC = Owner; 400 if (D->isLocalExternDecl()) 401 SemaRef.adjustContextForLocalExternDecl(DC); 402 403 // Build the instantiated declaration. 404 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 405 D->getLocation(), D->getIdentifier(), 406 DI->getType(), DI, D->getStorageClass()); 407 408 // In ARC, infer 'retaining' for variables of retainable type. 409 if (SemaRef.getLangOpts().ObjCAutoRefCount && 410 SemaRef.inferObjCARCLifetime(Var)) 411 Var->setInvalidDecl(); 412 413 // Substitute the nested name specifier, if any. 414 if (SubstQualifier(D, Var)) 415 return nullptr; 416 417 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 418 StartingScope, InstantiatingVarTemplate); 419 420 if (D->isNRVOVariable()) { 421 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType(); 422 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false)) 423 Var->setNRVOVariable(true); 424 } 425 426 Var->setImplicit(D->isImplicit()); 427 428 return Var; 429 } 430 431 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { 432 AccessSpecDecl* AD 433 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner, 434 D->getAccessSpecifierLoc(), D->getColonLoc()); 435 Owner->addHiddenDecl(AD); 436 return AD; 437 } 438 439 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 440 bool Invalid = false; 441 TypeSourceInfo *DI = D->getTypeSourceInfo(); 442 if (DI->getType()->isInstantiationDependentType() || 443 DI->getType()->isVariablyModifiedType()) { 444 DI = SemaRef.SubstType(DI, TemplateArgs, 445 D->getLocation(), D->getDeclName()); 446 if (!DI) { 447 DI = D->getTypeSourceInfo(); 448 Invalid = true; 449 } else if (DI->getType()->isFunctionType()) { 450 // C++ [temp.arg.type]p3: 451 // If a declaration acquires a function type through a type 452 // dependent on a template-parameter and this causes a 453 // declaration that does not use the syntactic form of a 454 // function declarator to have function type, the program is 455 // ill-formed. 456 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 457 << DI->getType(); 458 Invalid = true; 459 } 460 } else { 461 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 462 } 463 464 Expr *BitWidth = D->getBitWidth(); 465 if (Invalid) 466 BitWidth = nullptr; 467 else if (BitWidth) { 468 // The bit-width expression is a constant expression. 469 EnterExpressionEvaluationContext Unevaluated(SemaRef, 470 Sema::ConstantEvaluated); 471 472 ExprResult InstantiatedBitWidth 473 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 474 if (InstantiatedBitWidth.isInvalid()) { 475 Invalid = true; 476 BitWidth = nullptr; 477 } else 478 BitWidth = InstantiatedBitWidth.getAs<Expr>(); 479 } 480 481 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 482 DI->getType(), DI, 483 cast<RecordDecl>(Owner), 484 D->getLocation(), 485 D->isMutable(), 486 BitWidth, 487 D->getInClassInitStyle(), 488 D->getInnerLocStart(), 489 D->getAccess(), 490 nullptr); 491 if (!Field) { 492 cast<Decl>(Owner)->setInvalidDecl(); 493 return nullptr; 494 } 495 496 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope); 497 498 if (Field->hasAttrs()) 499 SemaRef.CheckAlignasUnderalignment(Field); 500 501 if (Invalid) 502 Field->setInvalidDecl(); 503 504 if (!Field->getDeclName()) { 505 // Keep track of where this decl came from. 506 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 507 } 508 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 509 if (Parent->isAnonymousStructOrUnion() && 510 Parent->getRedeclContext()->isFunctionOrMethod()) 511 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 512 } 513 514 Field->setImplicit(D->isImplicit()); 515 Field->setAccess(D->getAccess()); 516 Owner->addDecl(Field); 517 518 return Field; 519 } 520 521 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) { 522 bool Invalid = false; 523 TypeSourceInfo *DI = D->getTypeSourceInfo(); 524 525 if (DI->getType()->isVariablyModifiedType()) { 526 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified) 527 << D; 528 Invalid = true; 529 } else if (DI->getType()->isInstantiationDependentType()) { 530 DI = SemaRef.SubstType(DI, TemplateArgs, 531 D->getLocation(), D->getDeclName()); 532 if (!DI) { 533 DI = D->getTypeSourceInfo(); 534 Invalid = true; 535 } else if (DI->getType()->isFunctionType()) { 536 // C++ [temp.arg.type]p3: 537 // If a declaration acquires a function type through a type 538 // dependent on a template-parameter and this causes a 539 // declaration that does not use the syntactic form of a 540 // function declarator to have function type, the program is 541 // ill-formed. 542 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 543 << DI->getType(); 544 Invalid = true; 545 } 546 } else { 547 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 548 } 549 550 MSPropertyDecl *Property = MSPropertyDecl::Create( 551 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(), 552 DI, D->getLocStart(), D->getGetterId(), D->getSetterId()); 553 554 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs, 555 StartingScope); 556 557 if (Invalid) 558 Property->setInvalidDecl(); 559 560 Property->setAccess(D->getAccess()); 561 Owner->addDecl(Property); 562 563 return Property; 564 } 565 566 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 567 NamedDecl **NamedChain = 568 new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; 569 570 int i = 0; 571 for (auto *PI : D->chain()) { 572 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI, 573 TemplateArgs); 574 if (!Next) 575 return nullptr; 576 577 NamedChain[i++] = Next; 578 } 579 580 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType(); 581 IndirectFieldDecl* IndirectField 582 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(), 583 D->getIdentifier(), T, 584 NamedChain, D->getChainingSize()); 585 586 587 IndirectField->setImplicit(D->isImplicit()); 588 IndirectField->setAccess(D->getAccess()); 589 Owner->addDecl(IndirectField); 590 return IndirectField; 591 } 592 593 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 594 // Handle friend type expressions by simply substituting template 595 // parameters into the pattern type and checking the result. 596 if (TypeSourceInfo *Ty = D->getFriendType()) { 597 TypeSourceInfo *InstTy; 598 // If this is an unsupported friend, don't bother substituting template 599 // arguments into it. The actual type referred to won't be used by any 600 // parts of Clang, and may not be valid for instantiating. Just use the 601 // same info for the instantiated friend. 602 if (D->isUnsupportedFriend()) { 603 InstTy = Ty; 604 } else { 605 InstTy = SemaRef.SubstType(Ty, TemplateArgs, 606 D->getLocation(), DeclarationName()); 607 } 608 if (!InstTy) 609 return nullptr; 610 611 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(), 612 D->getFriendLoc(), InstTy); 613 if (!FD) 614 return nullptr; 615 616 FD->setAccess(AS_public); 617 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 618 Owner->addDecl(FD); 619 return FD; 620 } 621 622 NamedDecl *ND = D->getFriendDecl(); 623 assert(ND && "friend decl must be a decl or a type!"); 624 625 // All of the Visit implementations for the various potential friend 626 // declarations have to be carefully written to work for friend 627 // objects, with the most important detail being that the target 628 // decl should almost certainly not be placed in Owner. 629 Decl *NewND = Visit(ND); 630 if (!NewND) return nullptr; 631 632 FriendDecl *FD = 633 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 634 cast<NamedDecl>(NewND), D->getFriendLoc()); 635 FD->setAccess(AS_public); 636 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 637 Owner->addDecl(FD); 638 return FD; 639 } 640 641 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 642 Expr *AssertExpr = D->getAssertExpr(); 643 644 // The expression in a static assertion is a constant expression. 645 EnterExpressionEvaluationContext Unevaluated(SemaRef, 646 Sema::ConstantEvaluated); 647 648 ExprResult InstantiatedAssertExpr 649 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 650 if (InstantiatedAssertExpr.isInvalid()) 651 return nullptr; 652 653 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(), 654 InstantiatedAssertExpr.get(), 655 D->getMessage(), 656 D->getRParenLoc(), 657 D->isFailed()); 658 } 659 660 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 661 EnumDecl *PrevDecl = nullptr; 662 if (D->getPreviousDecl()) { 663 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 664 D->getPreviousDecl(), 665 TemplateArgs); 666 if (!Prev) return nullptr; 667 PrevDecl = cast<EnumDecl>(Prev); 668 } 669 670 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(), 671 D->getLocation(), D->getIdentifier(), 672 PrevDecl, D->isScoped(), 673 D->isScopedUsingClassTag(), D->isFixed()); 674 if (D->isFixed()) { 675 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { 676 // If we have type source information for the underlying type, it means it 677 // has been explicitly set by the user. Perform substitution on it before 678 // moving on. 679 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 680 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc, 681 DeclarationName()); 682 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI)) 683 Enum->setIntegerType(SemaRef.Context.IntTy); 684 else 685 Enum->setIntegerTypeSourceInfo(NewTI); 686 } else { 687 assert(!D->getIntegerType()->isDependentType() 688 && "Dependent type without type source info"); 689 Enum->setIntegerType(D->getIntegerType()); 690 } 691 } 692 693 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); 694 695 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation); 696 Enum->setAccess(D->getAccess()); 697 // Forward the mangling number from the template to the instantiated decl. 698 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D)); 699 if (SubstQualifier(D, Enum)) return nullptr; 700 Owner->addDecl(Enum); 701 702 EnumDecl *Def = D->getDefinition(); 703 if (Def && Def != D) { 704 // If this is an out-of-line definition of an enum member template, check 705 // that the underlying types match in the instantiation of both 706 // declarations. 707 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { 708 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 709 QualType DefnUnderlying = 710 SemaRef.SubstType(TI->getType(), TemplateArgs, 711 UnderlyingLoc, DeclarationName()); 712 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(), 713 DefnUnderlying, Enum); 714 } 715 } 716 717 // C++11 [temp.inst]p1: The implicit instantiation of a class template 718 // specialization causes the implicit instantiation of the declarations, but 719 // not the definitions of scoped member enumerations. 720 // 721 // DR1484 clarifies that enumeration definitions inside of a template 722 // declaration aren't considered entities that can be separately instantiated 723 // from the rest of the entity they are declared inside of. 724 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) { 725 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 726 InstantiateEnumDefinition(Enum, Def); 727 } 728 729 return Enum; 730 } 731 732 void TemplateDeclInstantiator::InstantiateEnumDefinition( 733 EnumDecl *Enum, EnumDecl *Pattern) { 734 Enum->startDefinition(); 735 736 // Update the location to refer to the definition. 737 Enum->setLocation(Pattern->getLocation()); 738 739 SmallVector<Decl*, 4> Enumerators; 740 741 EnumConstantDecl *LastEnumConst = nullptr; 742 for (auto *EC : Pattern->enumerators()) { 743 // The specified value for the enumerator. 744 ExprResult Value((Expr *)nullptr); 745 if (Expr *UninstValue = EC->getInitExpr()) { 746 // The enumerator's value expression is a constant expression. 747 EnterExpressionEvaluationContext Unevaluated(SemaRef, 748 Sema::ConstantEvaluated); 749 750 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 751 } 752 753 // Drop the initial value and continue. 754 bool isInvalid = false; 755 if (Value.isInvalid()) { 756 Value = nullptr; 757 isInvalid = true; 758 } 759 760 EnumConstantDecl *EnumConst 761 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 762 EC->getLocation(), EC->getIdentifier(), 763 Value.get()); 764 765 if (isInvalid) { 766 if (EnumConst) 767 EnumConst->setInvalidDecl(); 768 Enum->setInvalidDecl(); 769 } 770 771 if (EnumConst) { 772 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst); 773 774 EnumConst->setAccess(Enum->getAccess()); 775 Enum->addDecl(EnumConst); 776 Enumerators.push_back(EnumConst); 777 LastEnumConst = EnumConst; 778 779 if (Pattern->getDeclContext()->isFunctionOrMethod() && 780 !Enum->isScoped()) { 781 // If the enumeration is within a function or method, record the enum 782 // constant as a local. 783 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst); 784 } 785 } 786 } 787 788 // FIXME: Fixup LBraceLoc 789 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), 790 Enum->getRBraceLoc(), Enum, 791 Enumerators, 792 nullptr, nullptr); 793 } 794 795 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 796 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls."); 797 } 798 799 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 800 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 801 802 // Create a local instantiation scope for this class template, which 803 // will contain the instantiations of the template parameters. 804 LocalInstantiationScope Scope(SemaRef); 805 TemplateParameterList *TempParams = D->getTemplateParameters(); 806 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 807 if (!InstParams) 808 return nullptr; 809 810 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 811 812 // Instantiate the qualifier. We have to do this first in case 813 // we're a friend declaration, because if we are then we need to put 814 // the new declaration in the appropriate context. 815 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); 816 if (QualifierLoc) { 817 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 818 TemplateArgs); 819 if (!QualifierLoc) 820 return nullptr; 821 } 822 823 CXXRecordDecl *PrevDecl = nullptr; 824 ClassTemplateDecl *PrevClassTemplate = nullptr; 825 826 if (!isFriend && Pattern->getPreviousDecl()) { 827 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 828 if (!Found.empty()) { 829 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front()); 830 if (PrevClassTemplate) 831 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 832 } 833 } 834 835 // If this isn't a friend, then it's a member template, in which 836 // case we just want to build the instantiation in the 837 // specialization. If it is a friend, we want to build it in 838 // the appropriate context. 839 DeclContext *DC = Owner; 840 if (isFriend) { 841 if (QualifierLoc) { 842 CXXScopeSpec SS; 843 SS.Adopt(QualifierLoc); 844 DC = SemaRef.computeDeclContext(SS); 845 if (!DC) return nullptr; 846 } else { 847 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 848 Pattern->getDeclContext(), 849 TemplateArgs); 850 } 851 852 // Look for a previous declaration of the template in the owning 853 // context. 854 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 855 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 856 SemaRef.LookupQualifiedName(R, DC); 857 858 if (R.isSingleResult()) { 859 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 860 if (PrevClassTemplate) 861 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 862 } 863 864 if (!PrevClassTemplate && QualifierLoc) { 865 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 866 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 867 << QualifierLoc.getSourceRange(); 868 return nullptr; 869 } 870 871 bool AdoptedPreviousTemplateParams = false; 872 if (PrevClassTemplate) { 873 bool Complain = true; 874 875 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 876 // template for struct std::tr1::__detail::_Map_base, where the 877 // template parameters of the friend declaration don't match the 878 // template parameters of the original declaration. In this one 879 // case, we don't complain about the ill-formed friend 880 // declaration. 881 if (isFriend && Pattern->getIdentifier() && 882 Pattern->getIdentifier()->isStr("_Map_base") && 883 DC->isNamespace() && 884 cast<NamespaceDecl>(DC)->getIdentifier() && 885 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 886 DeclContext *DCParent = DC->getParent(); 887 if (DCParent->isNamespace() && 888 cast<NamespaceDecl>(DCParent)->getIdentifier() && 889 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 890 if (cast<Decl>(DCParent)->isInStdNamespace()) 891 Complain = false; 892 } 893 } 894 895 TemplateParameterList *PrevParams 896 = PrevClassTemplate->getTemplateParameters(); 897 898 // Make sure the parameter lists match. 899 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 900 Complain, 901 Sema::TPL_TemplateMatch)) { 902 if (Complain) 903 return nullptr; 904 905 AdoptedPreviousTemplateParams = true; 906 InstParams = PrevParams; 907 } 908 909 // Do some additional validation, then merge default arguments 910 // from the existing declarations. 911 if (!AdoptedPreviousTemplateParams && 912 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 913 Sema::TPC_ClassTemplate)) 914 return nullptr; 915 } 916 } 917 918 CXXRecordDecl *RecordInst 919 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC, 920 Pattern->getLocStart(), Pattern->getLocation(), 921 Pattern->getIdentifier(), PrevDecl, 922 /*DelayTypeCreation=*/true); 923 924 if (QualifierLoc) 925 RecordInst->setQualifierInfo(QualifierLoc); 926 927 ClassTemplateDecl *Inst 928 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 929 D->getIdentifier(), InstParams, RecordInst, 930 PrevClassTemplate); 931 RecordInst->setDescribedClassTemplate(Inst); 932 933 if (isFriend) { 934 if (PrevClassTemplate) 935 Inst->setAccess(PrevClassTemplate->getAccess()); 936 else 937 Inst->setAccess(D->getAccess()); 938 939 Inst->setObjectOfFriendDecl(); 940 // TODO: do we want to track the instantiation progeny of this 941 // friend target decl? 942 } else { 943 Inst->setAccess(D->getAccess()); 944 if (!PrevClassTemplate) 945 Inst->setInstantiatedFromMemberTemplate(D); 946 } 947 948 // Trigger creation of the type for the instantiation. 949 SemaRef.Context.getInjectedClassNameType(RecordInst, 950 Inst->getInjectedClassNameSpecialization()); 951 952 // Finish handling of friends. 953 if (isFriend) { 954 DC->makeDeclVisibleInContext(Inst); 955 Inst->setLexicalDeclContext(Owner); 956 RecordInst->setLexicalDeclContext(Owner); 957 return Inst; 958 } 959 960 if (D->isOutOfLine()) { 961 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 962 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); 963 } 964 965 Owner->addDecl(Inst); 966 967 if (!PrevClassTemplate) { 968 // Queue up any out-of-line partial specializations of this member 969 // class template; the client will force their instantiation once 970 // the enclosing class has been instantiated. 971 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 972 D->getPartialSpecializations(PartialSpecs); 973 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 974 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 975 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I])); 976 } 977 978 return Inst; 979 } 980 981 Decl * 982 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 983 ClassTemplatePartialSpecializationDecl *D) { 984 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 985 986 // Lookup the already-instantiated declaration in the instantiation 987 // of the class template and return that. 988 DeclContext::lookup_result Found 989 = Owner->lookup(ClassTemplate->getDeclName()); 990 if (Found.empty()) 991 return nullptr; 992 993 ClassTemplateDecl *InstClassTemplate 994 = dyn_cast<ClassTemplateDecl>(Found.front()); 995 if (!InstClassTemplate) 996 return nullptr; 997 998 if (ClassTemplatePartialSpecializationDecl *Result 999 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) 1000 return Result; 1001 1002 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D); 1003 } 1004 1005 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) { 1006 assert(D->getTemplatedDecl()->isStaticDataMember() && 1007 "Only static data member templates are allowed."); 1008 1009 // Create a local instantiation scope for this variable template, which 1010 // will contain the instantiations of the template parameters. 1011 LocalInstantiationScope Scope(SemaRef); 1012 TemplateParameterList *TempParams = D->getTemplateParameters(); 1013 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1014 if (!InstParams) 1015 return nullptr; 1016 1017 VarDecl *Pattern = D->getTemplatedDecl(); 1018 VarTemplateDecl *PrevVarTemplate = nullptr; 1019 1020 if (Pattern->getPreviousDecl()) { 1021 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 1022 if (!Found.empty()) 1023 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 1024 } 1025 1026 VarDecl *VarInst = 1027 cast_or_null<VarDecl>(VisitVarDecl(Pattern, 1028 /*InstantiatingVarTemplate=*/true)); 1029 1030 DeclContext *DC = Owner; 1031 1032 VarTemplateDecl *Inst = VarTemplateDecl::Create( 1033 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams, 1034 VarInst); 1035 VarInst->setDescribedVarTemplate(Inst); 1036 Inst->setPreviousDecl(PrevVarTemplate); 1037 1038 Inst->setAccess(D->getAccess()); 1039 if (!PrevVarTemplate) 1040 Inst->setInstantiatedFromMemberTemplate(D); 1041 1042 if (D->isOutOfLine()) { 1043 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 1044 VarInst->setLexicalDeclContext(D->getLexicalDeclContext()); 1045 } 1046 1047 Owner->addDecl(Inst); 1048 1049 if (!PrevVarTemplate) { 1050 // Queue up any out-of-line partial specializations of this member 1051 // variable template; the client will force their instantiation once 1052 // the enclosing class has been instantiated. 1053 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 1054 D->getPartialSpecializations(PartialSpecs); 1055 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 1056 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 1057 OutOfLineVarPartialSpecs.push_back( 1058 std::make_pair(Inst, PartialSpecs[I])); 1059 } 1060 1061 return Inst; 1062 } 1063 1064 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl( 1065 VarTemplatePartialSpecializationDecl *D) { 1066 assert(D->isStaticDataMember() && 1067 "Only static data member templates are allowed."); 1068 1069 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 1070 1071 // Lookup the already-instantiated declaration and return that. 1072 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName()); 1073 assert(!Found.empty() && "Instantiation found nothing?"); 1074 1075 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 1076 assert(InstVarTemplate && "Instantiation did not find a variable template?"); 1077 1078 if (VarTemplatePartialSpecializationDecl *Result = 1079 InstVarTemplate->findPartialSpecInstantiatedFromMember(D)) 1080 return Result; 1081 1082 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D); 1083 } 1084 1085 Decl * 1086 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 1087 // Create a local instantiation scope for this function template, which 1088 // will contain the instantiations of the template parameters and then get 1089 // merged with the local instantiation scope for the function template 1090 // itself. 1091 LocalInstantiationScope Scope(SemaRef); 1092 1093 TemplateParameterList *TempParams = D->getTemplateParameters(); 1094 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1095 if (!InstParams) 1096 return nullptr; 1097 1098 FunctionDecl *Instantiated = nullptr; 1099 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 1100 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 1101 InstParams)); 1102 else 1103 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 1104 D->getTemplatedDecl(), 1105 InstParams)); 1106 1107 if (!Instantiated) 1108 return nullptr; 1109 1110 // Link the instantiated function template declaration to the function 1111 // template from which it was instantiated. 1112 FunctionTemplateDecl *InstTemplate 1113 = Instantiated->getDescribedFunctionTemplate(); 1114 InstTemplate->setAccess(D->getAccess()); 1115 assert(InstTemplate && 1116 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 1117 1118 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 1119 1120 // Link the instantiation back to the pattern *unless* this is a 1121 // non-definition friend declaration. 1122 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 1123 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 1124 InstTemplate->setInstantiatedFromMemberTemplate(D); 1125 1126 // Make declarations visible in the appropriate context. 1127 if (!isFriend) { 1128 Owner->addDecl(InstTemplate); 1129 } else if (InstTemplate->getDeclContext()->isRecord() && 1130 !D->getPreviousDecl()) { 1131 SemaRef.CheckFriendAccess(InstTemplate); 1132 } 1133 1134 return InstTemplate; 1135 } 1136 1137 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 1138 CXXRecordDecl *PrevDecl = nullptr; 1139 if (D->isInjectedClassName()) 1140 PrevDecl = cast<CXXRecordDecl>(Owner); 1141 else if (D->getPreviousDecl()) { 1142 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 1143 D->getPreviousDecl(), 1144 TemplateArgs); 1145 if (!Prev) return nullptr; 1146 PrevDecl = cast<CXXRecordDecl>(Prev); 1147 } 1148 1149 CXXRecordDecl *Record 1150 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner, 1151 D->getLocStart(), D->getLocation(), 1152 D->getIdentifier(), PrevDecl); 1153 1154 // Substitute the nested name specifier, if any. 1155 if (SubstQualifier(D, Record)) 1156 return nullptr; 1157 1158 Record->setImplicit(D->isImplicit()); 1159 // FIXME: Check against AS_none is an ugly hack to work around the issue that 1160 // the tag decls introduced by friend class declarations don't have an access 1161 // specifier. Remove once this area of the code gets sorted out. 1162 if (D->getAccess() != AS_none) 1163 Record->setAccess(D->getAccess()); 1164 if (!D->isInjectedClassName()) 1165 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 1166 1167 // If the original function was part of a friend declaration, 1168 // inherit its namespace state. 1169 if (D->getFriendObjectKind()) 1170 Record->setObjectOfFriendDecl(); 1171 1172 // Make sure that anonymous structs and unions are recorded. 1173 if (D->isAnonymousStructOrUnion()) 1174 Record->setAnonymousStructOrUnion(true); 1175 1176 if (D->isLocalClass()) 1177 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 1178 1179 // Forward the mangling number from the template to the instantiated decl. 1180 SemaRef.Context.setManglingNumber(Record, 1181 SemaRef.Context.getManglingNumber(D)); 1182 1183 Owner->addDecl(Record); 1184 1185 // DR1484 clarifies that the members of a local class are instantiated as part 1186 // of the instantiation of their enclosing entity. 1187 if (D->isCompleteDefinition() && D->isLocalClass()) { 1188 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs, 1189 TSK_ImplicitInstantiation, 1190 /*Complain=*/true); 1191 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs, 1192 TSK_ImplicitInstantiation); 1193 } 1194 return Record; 1195 } 1196 1197 /// \brief Adjust the given function type for an instantiation of the 1198 /// given declaration, to cope with modifications to the function's type that 1199 /// aren't reflected in the type-source information. 1200 /// 1201 /// \param D The declaration we're instantiating. 1202 /// \param TInfo The already-instantiated type. 1203 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, 1204 FunctionDecl *D, 1205 TypeSourceInfo *TInfo) { 1206 const FunctionProtoType *OrigFunc 1207 = D->getType()->castAs<FunctionProtoType>(); 1208 const FunctionProtoType *NewFunc 1209 = TInfo->getType()->castAs<FunctionProtoType>(); 1210 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo()) 1211 return TInfo->getType(); 1212 1213 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo(); 1214 NewEPI.ExtInfo = OrigFunc->getExtInfo(); 1215 return Context.getFunctionType(NewFunc->getReturnType(), 1216 NewFunc->getParamTypes(), NewEPI); 1217 } 1218 1219 /// Normal class members are of more specific types and therefore 1220 /// don't make it here. This function serves two purposes: 1221 /// 1) instantiating function templates 1222 /// 2) substituting friend declarations 1223 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 1224 TemplateParameterList *TemplateParams) { 1225 // Check whether there is already a function template specialization for 1226 // this declaration. 1227 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1228 if (FunctionTemplate && !TemplateParams) { 1229 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1230 1231 void *InsertPos = nullptr; 1232 FunctionDecl *SpecFunc 1233 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(), 1234 InsertPos); 1235 1236 // If we already have a function template specialization, return it. 1237 if (SpecFunc) 1238 return SpecFunc; 1239 } 1240 1241 bool isFriend; 1242 if (FunctionTemplate) 1243 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1244 else 1245 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1246 1247 bool MergeWithParentScope = (TemplateParams != nullptr) || 1248 Owner->isFunctionOrMethod() || 1249 !(isa<Decl>(Owner) && 1250 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1251 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1252 1253 SmallVector<ParmVarDecl *, 4> Params; 1254 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1255 if (!TInfo) 1256 return nullptr; 1257 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 1258 1259 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1260 if (QualifierLoc) { 1261 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1262 TemplateArgs); 1263 if (!QualifierLoc) 1264 return nullptr; 1265 } 1266 1267 // If we're instantiating a local function declaration, put the result 1268 // in the enclosing namespace; otherwise we need to find the instantiated 1269 // context. 1270 DeclContext *DC; 1271 if (D->isLocalExternDecl()) { 1272 DC = Owner; 1273 SemaRef.adjustContextForLocalExternDecl(DC); 1274 } else if (isFriend && QualifierLoc) { 1275 CXXScopeSpec SS; 1276 SS.Adopt(QualifierLoc); 1277 DC = SemaRef.computeDeclContext(SS); 1278 if (!DC) return nullptr; 1279 } else { 1280 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 1281 TemplateArgs); 1282 } 1283 1284 FunctionDecl *Function = 1285 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 1286 D->getNameInfo(), T, TInfo, 1287 D->getCanonicalDecl()->getStorageClass(), 1288 D->isInlineSpecified(), D->hasWrittenPrototype(), 1289 D->isConstexpr()); 1290 Function->setRangeEnd(D->getSourceRange().getEnd()); 1291 1292 if (D->isInlined()) 1293 Function->setImplicitlyInline(); 1294 1295 if (QualifierLoc) 1296 Function->setQualifierInfo(QualifierLoc); 1297 1298 if (D->isLocalExternDecl()) 1299 Function->setLocalExternDecl(); 1300 1301 DeclContext *LexicalDC = Owner; 1302 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) { 1303 assert(D->getDeclContext()->isFileContext()); 1304 LexicalDC = D->getDeclContext(); 1305 } 1306 1307 Function->setLexicalDeclContext(LexicalDC); 1308 1309 // Attach the parameters 1310 for (unsigned P = 0; P < Params.size(); ++P) 1311 if (Params[P]) 1312 Params[P]->setOwningFunction(Function); 1313 Function->setParams(Params); 1314 1315 SourceLocation InstantiateAtPOI; 1316 if (TemplateParams) { 1317 // Our resulting instantiation is actually a function template, since we 1318 // are substituting only the outer template parameters. For example, given 1319 // 1320 // template<typename T> 1321 // struct X { 1322 // template<typename U> friend void f(T, U); 1323 // }; 1324 // 1325 // X<int> x; 1326 // 1327 // We are instantiating the friend function template "f" within X<int>, 1328 // which means substituting int for T, but leaving "f" as a friend function 1329 // template. 1330 // Build the function template itself. 1331 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1332 Function->getLocation(), 1333 Function->getDeclName(), 1334 TemplateParams, Function); 1335 Function->setDescribedFunctionTemplate(FunctionTemplate); 1336 1337 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1338 1339 if (isFriend && D->isThisDeclarationADefinition()) { 1340 // TODO: should we remember this connection regardless of whether 1341 // the friend declaration provided a body? 1342 FunctionTemplate->setInstantiatedFromMemberTemplate( 1343 D->getDescribedFunctionTemplate()); 1344 } 1345 } else if (FunctionTemplate) { 1346 // Record this function template specialization. 1347 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1348 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1349 TemplateArgumentList::CreateCopy(SemaRef.Context, 1350 Innermost.begin(), 1351 Innermost.size()), 1352 /*InsertPos=*/nullptr); 1353 } else if (isFriend) { 1354 // Note, we need this connection even if the friend doesn't have a body. 1355 // Its body may exist but not have been attached yet due to deferred 1356 // parsing. 1357 // FIXME: It might be cleaner to set this when attaching the body to the 1358 // friend function declaration, however that would require finding all the 1359 // instantiations and modifying them. 1360 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1361 } 1362 1363 if (InitFunctionInstantiation(Function, D)) 1364 Function->setInvalidDecl(); 1365 1366 bool isExplicitSpecialization = false; 1367 1368 LookupResult Previous( 1369 SemaRef, Function->getDeclName(), SourceLocation(), 1370 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 1371 : Sema::LookupOrdinaryName, 1372 Sema::ForRedeclaration); 1373 1374 if (DependentFunctionTemplateSpecializationInfo *Info 1375 = D->getDependentSpecializationInfo()) { 1376 assert(isFriend && "non-friend has dependent specialization info?"); 1377 1378 // This needs to be set now for future sanity. 1379 Function->setObjectOfFriendDecl(); 1380 1381 // Instantiate the explicit template arguments. 1382 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1383 Info->getRAngleLoc()); 1384 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1385 ExplicitArgs, TemplateArgs)) 1386 return nullptr; 1387 1388 // Map the candidate templates to their instantiations. 1389 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1390 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1391 Info->getTemplate(I), 1392 TemplateArgs); 1393 if (!Temp) return nullptr; 1394 1395 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1396 } 1397 1398 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1399 &ExplicitArgs, 1400 Previous)) 1401 Function->setInvalidDecl(); 1402 1403 isExplicitSpecialization = true; 1404 1405 } else if (TemplateParams || !FunctionTemplate) { 1406 // Look only into the namespace where the friend would be declared to 1407 // find a previous declaration. This is the innermost enclosing namespace, 1408 // as described in ActOnFriendFunctionDecl. 1409 SemaRef.LookupQualifiedName(Previous, DC); 1410 1411 // In C++, the previous declaration we find might be a tag type 1412 // (class or enum). In this case, the new declaration will hide the 1413 // tag type. Note that this does does not apply if we're declaring a 1414 // typedef (C++ [dcl.typedef]p4). 1415 if (Previous.isSingleTagDecl()) 1416 Previous.clear(); 1417 } 1418 1419 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous, 1420 isExplicitSpecialization); 1421 1422 NamedDecl *PrincipalDecl = (TemplateParams 1423 ? cast<NamedDecl>(FunctionTemplate) 1424 : Function); 1425 1426 // If the original function was part of a friend declaration, 1427 // inherit its namespace state and add it to the owner. 1428 if (isFriend) { 1429 PrincipalDecl->setObjectOfFriendDecl(); 1430 DC->makeDeclVisibleInContext(PrincipalDecl); 1431 1432 bool QueuedInstantiation = false; 1433 1434 // C++11 [temp.friend]p4 (DR329): 1435 // When a function is defined in a friend function declaration in a class 1436 // template, the function is instantiated when the function is odr-used. 1437 // The same restrictions on multiple declarations and definitions that 1438 // apply to non-template function declarations and definitions also apply 1439 // to these implicit definitions. 1440 if (D->isThisDeclarationADefinition()) { 1441 // Check for a function body. 1442 const FunctionDecl *Definition = nullptr; 1443 if (Function->isDefined(Definition) && 1444 Definition->getTemplateSpecializationKind() == TSK_Undeclared) { 1445 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 1446 << Function->getDeclName(); 1447 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition); 1448 } 1449 // Check for redefinitions due to other instantiations of this or 1450 // a similar friend function. 1451 else for (auto R : Function->redecls()) { 1452 if (R == Function) 1453 continue; 1454 1455 // If some prior declaration of this function has been used, we need 1456 // to instantiate its definition. 1457 if (!QueuedInstantiation && R->isUsed(false)) { 1458 if (MemberSpecializationInfo *MSInfo = 1459 Function->getMemberSpecializationInfo()) { 1460 if (MSInfo->getPointOfInstantiation().isInvalid()) { 1461 SourceLocation Loc = R->getLocation(); // FIXME 1462 MSInfo->setPointOfInstantiation(Loc); 1463 SemaRef.PendingLocalImplicitInstantiations.push_back( 1464 std::make_pair(Function, Loc)); 1465 QueuedInstantiation = true; 1466 } 1467 } 1468 } 1469 1470 // If some prior declaration of this function was a friend with an 1471 // uninstantiated definition, reject it. 1472 if (R->getFriendObjectKind()) { 1473 if (const FunctionDecl *RPattern = 1474 R->getTemplateInstantiationPattern()) { 1475 if (RPattern->isDefined(RPattern)) { 1476 SemaRef.Diag(Function->getLocation(), diag::err_redefinition) 1477 << Function->getDeclName(); 1478 SemaRef.Diag(R->getLocation(), diag::note_previous_definition); 1479 break; 1480 } 1481 } 1482 } 1483 } 1484 } 1485 } 1486 1487 if (Function->isLocalExternDecl() && !Function->getPreviousDecl()) 1488 DC->makeDeclVisibleInContext(PrincipalDecl); 1489 1490 if (Function->isOverloadedOperator() && !DC->isRecord() && 1491 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1492 PrincipalDecl->setNonMemberOperator(); 1493 1494 assert(!D->isDefaulted() && "only methods should be defaulted"); 1495 return Function; 1496 } 1497 1498 Decl * 1499 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D, 1500 TemplateParameterList *TemplateParams, 1501 bool IsClassScopeSpecialization) { 1502 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1503 if (FunctionTemplate && !TemplateParams) { 1504 // We are creating a function template specialization from a function 1505 // template. Check whether there is already a function template 1506 // specialization for this particular set of template arguments. 1507 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1508 1509 void *InsertPos = nullptr; 1510 FunctionDecl *SpecFunc 1511 = FunctionTemplate->findSpecialization(Innermost.begin(), 1512 Innermost.size(), 1513 InsertPos); 1514 1515 // If we already have a function template specialization, return it. 1516 if (SpecFunc) 1517 return SpecFunc; 1518 } 1519 1520 bool isFriend; 1521 if (FunctionTemplate) 1522 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1523 else 1524 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1525 1526 bool MergeWithParentScope = (TemplateParams != nullptr) || 1527 !(isa<Decl>(Owner) && 1528 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1529 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1530 1531 // Instantiate enclosing template arguments for friends. 1532 SmallVector<TemplateParameterList *, 4> TempParamLists; 1533 unsigned NumTempParamLists = 0; 1534 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 1535 TempParamLists.set_size(NumTempParamLists); 1536 for (unsigned I = 0; I != NumTempParamLists; ++I) { 1537 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 1538 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1539 if (!InstParams) 1540 return nullptr; 1541 TempParamLists[I] = InstParams; 1542 } 1543 } 1544 1545 SmallVector<ParmVarDecl *, 4> Params; 1546 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1547 if (!TInfo) 1548 return nullptr; 1549 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 1550 1551 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1552 if (QualifierLoc) { 1553 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1554 TemplateArgs); 1555 if (!QualifierLoc) 1556 return nullptr; 1557 } 1558 1559 DeclContext *DC = Owner; 1560 if (isFriend) { 1561 if (QualifierLoc) { 1562 CXXScopeSpec SS; 1563 SS.Adopt(QualifierLoc); 1564 DC = SemaRef.computeDeclContext(SS); 1565 1566 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 1567 return nullptr; 1568 } else { 1569 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 1570 D->getDeclContext(), 1571 TemplateArgs); 1572 } 1573 if (!DC) return nullptr; 1574 } 1575 1576 // Build the instantiated method declaration. 1577 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 1578 CXXMethodDecl *Method = nullptr; 1579 1580 SourceLocation StartLoc = D->getInnerLocStart(); 1581 DeclarationNameInfo NameInfo 1582 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1583 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1584 Method = CXXConstructorDecl::Create(SemaRef.Context, Record, 1585 StartLoc, NameInfo, T, TInfo, 1586 Constructor->isExplicit(), 1587 Constructor->isInlineSpecified(), 1588 false, Constructor->isConstexpr()); 1589 1590 // Claim that the instantiation of a constructor or constructor template 1591 // inherits the same constructor that the template does. 1592 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>( 1593 Constructor->getInheritedConstructor())) { 1594 // If we're instantiating a specialization of a function template, our 1595 // "inherited constructor" will actually itself be a function template. 1596 // Instantiate a declaration of it, too. 1597 if (FunctionTemplate) { 1598 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() && 1599 !Inh->getParent()->isDependentContext() && 1600 "inheriting constructor template in dependent context?"); 1601 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(), 1602 Inh); 1603 if (Inst.isInvalid()) 1604 return nullptr; 1605 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext()); 1606 LocalInstantiationScope LocalScope(SemaRef); 1607 1608 // Use the same template arguments that we deduced for the inheriting 1609 // constructor. There's no way they could be deduced differently. 1610 MultiLevelTemplateArgumentList InheritedArgs; 1611 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost()); 1612 Inh = cast_or_null<CXXConstructorDecl>( 1613 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs)); 1614 if (!Inh) 1615 return nullptr; 1616 } 1617 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh); 1618 } 1619 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 1620 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 1621 StartLoc, NameInfo, T, TInfo, 1622 Destructor->isInlineSpecified(), 1623 false); 1624 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 1625 Method = CXXConversionDecl::Create(SemaRef.Context, Record, 1626 StartLoc, NameInfo, T, TInfo, 1627 Conversion->isInlineSpecified(), 1628 Conversion->isExplicit(), 1629 Conversion->isConstexpr(), 1630 Conversion->getLocEnd()); 1631 } else { 1632 StorageClass SC = D->isStatic() ? SC_Static : SC_None; 1633 Method = CXXMethodDecl::Create(SemaRef.Context, Record, 1634 StartLoc, NameInfo, T, TInfo, 1635 SC, D->isInlineSpecified(), 1636 D->isConstexpr(), D->getLocEnd()); 1637 } 1638 1639 if (D->isInlined()) 1640 Method->setImplicitlyInline(); 1641 1642 if (QualifierLoc) 1643 Method->setQualifierInfo(QualifierLoc); 1644 1645 if (TemplateParams) { 1646 // Our resulting instantiation is actually a function template, since we 1647 // are substituting only the outer template parameters. For example, given 1648 // 1649 // template<typename T> 1650 // struct X { 1651 // template<typename U> void f(T, U); 1652 // }; 1653 // 1654 // X<int> x; 1655 // 1656 // We are instantiating the member template "f" within X<int>, which means 1657 // substituting int for T, but leaving "f" as a member function template. 1658 // Build the function template itself. 1659 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 1660 Method->getLocation(), 1661 Method->getDeclName(), 1662 TemplateParams, Method); 1663 if (isFriend) { 1664 FunctionTemplate->setLexicalDeclContext(Owner); 1665 FunctionTemplate->setObjectOfFriendDecl(); 1666 } else if (D->isOutOfLine()) 1667 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 1668 Method->setDescribedFunctionTemplate(FunctionTemplate); 1669 } else if (FunctionTemplate) { 1670 // Record this function template specialization. 1671 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1672 Method->setFunctionTemplateSpecialization(FunctionTemplate, 1673 TemplateArgumentList::CreateCopy(SemaRef.Context, 1674 Innermost.begin(), 1675 Innermost.size()), 1676 /*InsertPos=*/nullptr); 1677 } else if (!isFriend) { 1678 // Record that this is an instantiation of a member function. 1679 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1680 } 1681 1682 // If we are instantiating a member function defined 1683 // out-of-line, the instantiation will have the same lexical 1684 // context (which will be a namespace scope) as the template. 1685 if (isFriend) { 1686 if (NumTempParamLists) 1687 Method->setTemplateParameterListsInfo(SemaRef.Context, 1688 NumTempParamLists, 1689 TempParamLists.data()); 1690 1691 Method->setLexicalDeclContext(Owner); 1692 Method->setObjectOfFriendDecl(); 1693 } else if (D->isOutOfLine()) 1694 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 1695 1696 // Attach the parameters 1697 for (unsigned P = 0; P < Params.size(); ++P) 1698 Params[P]->setOwningFunction(Method); 1699 Method->setParams(Params); 1700 1701 if (InitMethodInstantiation(Method, D)) 1702 Method->setInvalidDecl(); 1703 1704 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 1705 Sema::ForRedeclaration); 1706 1707 if (!FunctionTemplate || TemplateParams || isFriend) { 1708 SemaRef.LookupQualifiedName(Previous, Record); 1709 1710 // In C++, the previous declaration we find might be a tag type 1711 // (class or enum). In this case, the new declaration will hide the 1712 // tag type. Note that this does does not apply if we're declaring a 1713 // typedef (C++ [dcl.typedef]p4). 1714 if (Previous.isSingleTagDecl()) 1715 Previous.clear(); 1716 } 1717 1718 if (!IsClassScopeSpecialization) 1719 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false); 1720 1721 if (D->isPure()) 1722 SemaRef.CheckPureMethod(Method, SourceRange()); 1723 1724 // Propagate access. For a non-friend declaration, the access is 1725 // whatever we're propagating from. For a friend, it should be the 1726 // previous declaration we just found. 1727 if (isFriend && Method->getPreviousDecl()) 1728 Method->setAccess(Method->getPreviousDecl()->getAccess()); 1729 else 1730 Method->setAccess(D->getAccess()); 1731 if (FunctionTemplate) 1732 FunctionTemplate->setAccess(Method->getAccess()); 1733 1734 SemaRef.CheckOverrideControl(Method); 1735 1736 // If a function is defined as defaulted or deleted, mark it as such now. 1737 if (D->isExplicitlyDefaulted()) 1738 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 1739 if (D->isDeletedAsWritten()) 1740 SemaRef.SetDeclDeleted(Method, Method->getLocation()); 1741 1742 // If there's a function template, let our caller handle it. 1743 if (FunctionTemplate) { 1744 // do nothing 1745 1746 // Don't hide a (potentially) valid declaration with an invalid one. 1747 } else if (Method->isInvalidDecl() && !Previous.empty()) { 1748 // do nothing 1749 1750 // Otherwise, check access to friends and make them visible. 1751 } else if (isFriend) { 1752 // We only need to re-check access for methods which we didn't 1753 // manage to match during parsing. 1754 if (!D->getPreviousDecl()) 1755 SemaRef.CheckFriendAccess(Method); 1756 1757 Record->makeDeclVisibleInContext(Method); 1758 1759 // Otherwise, add the declaration. We don't need to do this for 1760 // class-scope specializations because we'll have matched them with 1761 // the appropriate template. 1762 } else if (!IsClassScopeSpecialization) { 1763 Owner->addDecl(Method); 1764 } 1765 1766 return Method; 1767 } 1768 1769 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 1770 return VisitCXXMethodDecl(D); 1771 } 1772 1773 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 1774 return VisitCXXMethodDecl(D); 1775 } 1776 1777 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 1778 return VisitCXXMethodDecl(D); 1779 } 1780 1781 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 1782 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None, 1783 /*ExpectParameterPack=*/ false); 1784 } 1785 1786 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 1787 TemplateTypeParmDecl *D) { 1788 // TODO: don't always clone when decls are refcounted. 1789 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 1790 1791 TemplateTypeParmDecl *Inst = 1792 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, 1793 D->getLocStart(), D->getLocation(), 1794 D->getDepth() - TemplateArgs.getNumLevels(), 1795 D->getIndex(), D->getIdentifier(), 1796 D->wasDeclaredWithTypename(), 1797 D->isParameterPack()); 1798 Inst->setAccess(AS_public); 1799 1800 if (D->hasDefaultArgument()) { 1801 TypeSourceInfo *InstantiatedDefaultArg = 1802 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, 1803 D->getDefaultArgumentLoc(), D->getDeclName()); 1804 if (InstantiatedDefaultArg) 1805 Inst->setDefaultArgument(InstantiatedDefaultArg, false); 1806 } 1807 1808 // Introduce this template parameter's instantiation into the instantiation 1809 // scope. 1810 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 1811 1812 return Inst; 1813 } 1814 1815 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 1816 NonTypeTemplateParmDecl *D) { 1817 // Substitute into the type of the non-type template parameter. 1818 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 1819 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 1820 SmallVector<QualType, 4> ExpandedParameterPackTypes; 1821 bool IsExpandedParameterPack = false; 1822 TypeSourceInfo *DI; 1823 QualType T; 1824 bool Invalid = false; 1825 1826 if (D->isExpandedParameterPack()) { 1827 // The non-type template parameter pack is an already-expanded pack 1828 // expansion of types. Substitute into each of the expanded types. 1829 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 1830 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 1831 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 1832 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), 1833 TemplateArgs, 1834 D->getLocation(), 1835 D->getDeclName()); 1836 if (!NewDI) 1837 return nullptr; 1838 1839 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1840 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(), 1841 D->getLocation()); 1842 if (NewT.isNull()) 1843 return nullptr; 1844 ExpandedParameterPackTypes.push_back(NewT); 1845 } 1846 1847 IsExpandedParameterPack = true; 1848 DI = D->getTypeSourceInfo(); 1849 T = DI->getType(); 1850 } else if (D->isPackExpansion()) { 1851 // The non-type template parameter pack's type is a pack expansion of types. 1852 // Determine whether we need to expand this parameter pack into separate 1853 // types. 1854 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); 1855 TypeLoc Pattern = Expansion.getPatternLoc(); 1856 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 1857 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 1858 1859 // Determine whether the set of unexpanded parameter packs can and should 1860 // be expanded. 1861 bool Expand = true; 1862 bool RetainExpansion = false; 1863 Optional<unsigned> OrigNumExpansions 1864 = Expansion.getTypePtr()->getNumExpansions(); 1865 Optional<unsigned> NumExpansions = OrigNumExpansions; 1866 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 1867 Pattern.getSourceRange(), 1868 Unexpanded, 1869 TemplateArgs, 1870 Expand, RetainExpansion, 1871 NumExpansions)) 1872 return nullptr; 1873 1874 if (Expand) { 1875 for (unsigned I = 0; I != *NumExpansions; ++I) { 1876 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 1877 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 1878 D->getLocation(), 1879 D->getDeclName()); 1880 if (!NewDI) 1881 return nullptr; 1882 1883 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 1884 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType( 1885 NewDI->getType(), 1886 D->getLocation()); 1887 if (NewT.isNull()) 1888 return nullptr; 1889 ExpandedParameterPackTypes.push_back(NewT); 1890 } 1891 1892 // Note that we have an expanded parameter pack. The "type" of this 1893 // expanded parameter pack is the original expansion type, but callers 1894 // will end up using the expanded parameter pack types for type-checking. 1895 IsExpandedParameterPack = true; 1896 DI = D->getTypeSourceInfo(); 1897 T = DI->getType(); 1898 } else { 1899 // We cannot fully expand the pack expansion now, so substitute into the 1900 // pattern and create a new pack expansion type. 1901 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 1902 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 1903 D->getLocation(), 1904 D->getDeclName()); 1905 if (!NewPattern) 1906 return nullptr; 1907 1908 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 1909 NumExpansions); 1910 if (!DI) 1911 return nullptr; 1912 1913 T = DI->getType(); 1914 } 1915 } else { 1916 // Simple case: substitution into a parameter that is not a parameter pack. 1917 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 1918 D->getLocation(), D->getDeclName()); 1919 if (!DI) 1920 return nullptr; 1921 1922 // Check that this type is acceptable for a non-type template parameter. 1923 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(), 1924 D->getLocation()); 1925 if (T.isNull()) { 1926 T = SemaRef.Context.IntTy; 1927 Invalid = true; 1928 } 1929 } 1930 1931 NonTypeTemplateParmDecl *Param; 1932 if (IsExpandedParameterPack) 1933 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1934 D->getInnerLocStart(), 1935 D->getLocation(), 1936 D->getDepth() - TemplateArgs.getNumLevels(), 1937 D->getPosition(), 1938 D->getIdentifier(), T, 1939 DI, 1940 ExpandedParameterPackTypes.data(), 1941 ExpandedParameterPackTypes.size(), 1942 ExpandedParameterPackTypesAsWritten.data()); 1943 else 1944 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, 1945 D->getInnerLocStart(), 1946 D->getLocation(), 1947 D->getDepth() - TemplateArgs.getNumLevels(), 1948 D->getPosition(), 1949 D->getIdentifier(), T, 1950 D->isParameterPack(), DI); 1951 1952 Param->setAccess(AS_public); 1953 if (Invalid) 1954 Param->setInvalidDecl(); 1955 1956 if (D->hasDefaultArgument()) { 1957 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs); 1958 if (!Value.isInvalid()) 1959 Param->setDefaultArgument(Value.get(), false); 1960 } 1961 1962 // Introduce this template parameter's instantiation into the instantiation 1963 // scope. 1964 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 1965 return Param; 1966 } 1967 1968 static void collectUnexpandedParameterPacks( 1969 Sema &S, 1970 TemplateParameterList *Params, 1971 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 1972 for (TemplateParameterList::const_iterator I = Params->begin(), 1973 E = Params->end(); I != E; ++I) { 1974 if ((*I)->isTemplateParameterPack()) 1975 continue; 1976 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I)) 1977 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), 1978 Unexpanded); 1979 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I)) 1980 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), 1981 Unexpanded); 1982 } 1983 } 1984 1985 Decl * 1986 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 1987 TemplateTemplateParmDecl *D) { 1988 // Instantiate the template parameter list of the template template parameter. 1989 TemplateParameterList *TempParams = D->getTemplateParameters(); 1990 TemplateParameterList *InstParams; 1991 SmallVector<TemplateParameterList*, 8> ExpandedParams; 1992 1993 bool IsExpandedParameterPack = false; 1994 1995 if (D->isExpandedParameterPack()) { 1996 // The template template parameter pack is an already-expanded pack 1997 // expansion of template parameters. Substitute into each of the expanded 1998 // parameters. 1999 ExpandedParams.reserve(D->getNumExpansionTemplateParameters()); 2000 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 2001 I != N; ++I) { 2002 LocalInstantiationScope Scope(SemaRef); 2003 TemplateParameterList *Expansion = 2004 SubstTemplateParams(D->getExpansionTemplateParameters(I)); 2005 if (!Expansion) 2006 return nullptr; 2007 ExpandedParams.push_back(Expansion); 2008 } 2009 2010 IsExpandedParameterPack = true; 2011 InstParams = TempParams; 2012 } else if (D->isPackExpansion()) { 2013 // The template template parameter pack expands to a pack of template 2014 // template parameters. Determine whether we need to expand this parameter 2015 // pack into separate parameters. 2016 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2017 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), 2018 Unexpanded); 2019 2020 // Determine whether the set of unexpanded parameter packs can and should 2021 // be expanded. 2022 bool Expand = true; 2023 bool RetainExpansion = false; 2024 Optional<unsigned> NumExpansions; 2025 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), 2026 TempParams->getSourceRange(), 2027 Unexpanded, 2028 TemplateArgs, 2029 Expand, RetainExpansion, 2030 NumExpansions)) 2031 return nullptr; 2032 2033 if (Expand) { 2034 for (unsigned I = 0; I != *NumExpansions; ++I) { 2035 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2036 LocalInstantiationScope Scope(SemaRef); 2037 TemplateParameterList *Expansion = SubstTemplateParams(TempParams); 2038 if (!Expansion) 2039 return nullptr; 2040 ExpandedParams.push_back(Expansion); 2041 } 2042 2043 // Note that we have an expanded parameter pack. The "type" of this 2044 // expanded parameter pack is the original expansion type, but callers 2045 // will end up using the expanded parameter pack types for type-checking. 2046 IsExpandedParameterPack = true; 2047 InstParams = TempParams; 2048 } else { 2049 // We cannot fully expand the pack expansion now, so just substitute 2050 // into the pattern. 2051 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2052 2053 LocalInstantiationScope Scope(SemaRef); 2054 InstParams = SubstTemplateParams(TempParams); 2055 if (!InstParams) 2056 return nullptr; 2057 } 2058 } else { 2059 // Perform the actual substitution of template parameters within a new, 2060 // local instantiation scope. 2061 LocalInstantiationScope Scope(SemaRef); 2062 InstParams = SubstTemplateParams(TempParams); 2063 if (!InstParams) 2064 return nullptr; 2065 } 2066 2067 // Build the template template parameter. 2068 TemplateTemplateParmDecl *Param; 2069 if (IsExpandedParameterPack) 2070 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, 2071 D->getLocation(), 2072 D->getDepth() - TemplateArgs.getNumLevels(), 2073 D->getPosition(), 2074 D->getIdentifier(), InstParams, 2075 ExpandedParams); 2076 else 2077 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, 2078 D->getLocation(), 2079 D->getDepth() - TemplateArgs.getNumLevels(), 2080 D->getPosition(), 2081 D->isParameterPack(), 2082 D->getIdentifier(), InstParams); 2083 if (D->hasDefaultArgument()) { 2084 NestedNameSpecifierLoc QualifierLoc = 2085 D->getDefaultArgument().getTemplateQualifierLoc(); 2086 QualifierLoc = 2087 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs); 2088 TemplateName TName = SemaRef.SubstTemplateName( 2089 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(), 2090 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); 2091 if (!TName.isNull()) 2092 Param->setDefaultArgument( 2093 TemplateArgumentLoc(TemplateArgument(TName), 2094 D->getDefaultArgument().getTemplateQualifierLoc(), 2095 D->getDefaultArgument().getTemplateNameLoc()), 2096 false); 2097 } 2098 Param->setAccess(AS_public); 2099 2100 // Introduce this template parameter's instantiation into the instantiation 2101 // scope. 2102 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2103 2104 return Param; 2105 } 2106 2107 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 2108 // Using directives are never dependent (and never contain any types or 2109 // expressions), so they require no explicit instantiation work. 2110 2111 UsingDirectiveDecl *Inst 2112 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 2113 D->getNamespaceKeyLocation(), 2114 D->getQualifierLoc(), 2115 D->getIdentLocation(), 2116 D->getNominatedNamespace(), 2117 D->getCommonAncestor()); 2118 2119 // Add the using directive to its declaration context 2120 // only if this is not a function or method. 2121 if (!Owner->isFunctionOrMethod()) 2122 Owner->addDecl(Inst); 2123 2124 return Inst; 2125 } 2126 2127 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 2128 2129 // The nested name specifier may be dependent, for example 2130 // template <typename T> struct t { 2131 // struct s1 { T f1(); }; 2132 // struct s2 : s1 { using s1::f1; }; 2133 // }; 2134 // template struct t<int>; 2135 // Here, in using s1::f1, s1 refers to t<T>::s1; 2136 // we need to substitute for t<int>::s1. 2137 NestedNameSpecifierLoc QualifierLoc 2138 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2139 TemplateArgs); 2140 if (!QualifierLoc) 2141 return nullptr; 2142 2143 // The name info is non-dependent, so no transformation 2144 // is required. 2145 DeclarationNameInfo NameInfo = D->getNameInfo(); 2146 2147 // We only need to do redeclaration lookups if we're in a class 2148 // scope (in fact, it's not really even possible in non-class 2149 // scopes). 2150 bool CheckRedeclaration = Owner->isRecord(); 2151 2152 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 2153 Sema::ForRedeclaration); 2154 2155 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 2156 D->getUsingLoc(), 2157 QualifierLoc, 2158 NameInfo, 2159 D->hasTypename()); 2160 2161 CXXScopeSpec SS; 2162 SS.Adopt(QualifierLoc); 2163 if (CheckRedeclaration) { 2164 Prev.setHideTags(false); 2165 SemaRef.LookupQualifiedName(Prev, Owner); 2166 2167 // Check for invalid redeclarations. 2168 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(), 2169 D->hasTypename(), SS, 2170 D->getLocation(), Prev)) 2171 NewUD->setInvalidDecl(); 2172 2173 } 2174 2175 if (!NewUD->isInvalidDecl() && 2176 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo, 2177 D->getLocation())) 2178 NewUD->setInvalidDecl(); 2179 2180 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 2181 NewUD->setAccess(D->getAccess()); 2182 Owner->addDecl(NewUD); 2183 2184 // Don't process the shadow decls for an invalid decl. 2185 if (NewUD->isInvalidDecl()) 2186 return NewUD; 2187 2188 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) { 2189 SemaRef.CheckInheritingConstructorUsingDecl(NewUD); 2190 return NewUD; 2191 } 2192 2193 bool isFunctionScope = Owner->isFunctionOrMethod(); 2194 2195 // Process the shadow decls. 2196 for (auto *Shadow : D->shadows()) { 2197 NamedDecl *InstTarget = 2198 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 2199 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs)); 2200 if (!InstTarget) 2201 return nullptr; 2202 2203 UsingShadowDecl *PrevDecl = nullptr; 2204 if (CheckRedeclaration) { 2205 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl)) 2206 continue; 2207 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) { 2208 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( 2209 Shadow->getLocation(), OldPrev, TemplateArgs)); 2210 } 2211 2212 UsingShadowDecl *InstShadow = 2213 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget, 2214 PrevDecl); 2215 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 2216 2217 if (isFunctionScope) 2218 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 2219 } 2220 2221 return NewUD; 2222 } 2223 2224 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 2225 // Ignore these; we handle them in bulk when processing the UsingDecl. 2226 return nullptr; 2227 } 2228 2229 Decl * TemplateDeclInstantiator 2230 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) { 2231 NestedNameSpecifierLoc QualifierLoc 2232 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2233 TemplateArgs); 2234 if (!QualifierLoc) 2235 return nullptr; 2236 2237 CXXScopeSpec SS; 2238 SS.Adopt(QualifierLoc); 2239 2240 // Since NameInfo refers to a typename, it cannot be a C++ special name. 2241 // Hence, no transformation is required for it. 2242 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation()); 2243 NamedDecl *UD = 2244 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(), 2245 D->getUsingLoc(), SS, NameInfo, nullptr, 2246 /*instantiation*/ true, 2247 /*typename*/ true, D->getTypenameLoc()); 2248 if (UD) 2249 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 2250 2251 return UD; 2252 } 2253 2254 Decl * TemplateDeclInstantiator 2255 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) { 2256 NestedNameSpecifierLoc QualifierLoc 2257 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs); 2258 if (!QualifierLoc) 2259 return nullptr; 2260 2261 CXXScopeSpec SS; 2262 SS.Adopt(QualifierLoc); 2263 2264 DeclarationNameInfo NameInfo 2265 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2266 2267 NamedDecl *UD = 2268 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(), 2269 D->getUsingLoc(), SS, NameInfo, nullptr, 2270 /*instantiation*/ true, 2271 /*typename*/ false, SourceLocation()); 2272 if (UD) 2273 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D); 2274 2275 return UD; 2276 } 2277 2278 2279 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 2280 ClassScopeFunctionSpecializationDecl *Decl) { 2281 CXXMethodDecl *OldFD = Decl->getSpecialization(); 2282 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 2283 nullptr, true)); 2284 2285 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName, 2286 Sema::ForRedeclaration); 2287 2288 TemplateArgumentListInfo TemplateArgs; 2289 TemplateArgumentListInfo *TemplateArgsPtr = nullptr; 2290 if (Decl->hasExplicitTemplateArgs()) { 2291 TemplateArgs = Decl->templateArgs(); 2292 TemplateArgsPtr = &TemplateArgs; 2293 } 2294 2295 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext); 2296 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr, 2297 Previous)) { 2298 NewFD->setInvalidDecl(); 2299 return NewFD; 2300 } 2301 2302 // Associate the specialization with the pattern. 2303 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl()); 2304 assert(Specialization && "Class scope Specialization is null"); 2305 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD); 2306 2307 return NewFD; 2308 } 2309 2310 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( 2311 OMPThreadPrivateDecl *D) { 2312 SmallVector<Expr *, 5> Vars; 2313 for (auto *I : D->varlists()) { 2314 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 2315 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"); 2316 Vars.push_back(Var); 2317 } 2318 2319 OMPThreadPrivateDecl *TD = 2320 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars); 2321 2322 TD->setAccess(AS_public); 2323 Owner->addDecl(TD); 2324 2325 return TD; 2326 } 2327 2328 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 2329 return VisitFunctionDecl(D, nullptr); 2330 } 2331 2332 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 2333 return VisitCXXMethodDecl(D, nullptr); 2334 } 2335 2336 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 2337 llvm_unreachable("There are only CXXRecordDecls in C++"); 2338 } 2339 2340 Decl * 2341 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 2342 ClassTemplateSpecializationDecl *D) { 2343 // As a MS extension, we permit class-scope explicit specialization 2344 // of member class templates. 2345 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 2346 assert(ClassTemplate->getDeclContext()->isRecord() && 2347 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 2348 "can only instantiate an explicit specialization " 2349 "for a member class template"); 2350 2351 // Lookup the already-instantiated declaration in the instantiation 2352 // of the class template. FIXME: Diagnose or assert if this fails? 2353 DeclContext::lookup_result Found 2354 = Owner->lookup(ClassTemplate->getDeclName()); 2355 if (Found.empty()) 2356 return nullptr; 2357 ClassTemplateDecl *InstClassTemplate 2358 = dyn_cast<ClassTemplateDecl>(Found.front()); 2359 if (!InstClassTemplate) 2360 return nullptr; 2361 2362 // Substitute into the template arguments of the class template explicit 2363 // specialization. 2364 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). 2365 castAs<TemplateSpecializationTypeLoc>(); 2366 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), 2367 Loc.getRAngleLoc()); 2368 SmallVector<TemplateArgumentLoc, 4> ArgLocs; 2369 for (unsigned I = 0; I != Loc.getNumArgs(); ++I) 2370 ArgLocs.push_back(Loc.getArgLoc(I)); 2371 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(), 2372 InstTemplateArgs, TemplateArgs)) 2373 return nullptr; 2374 2375 // Check that the template argument list is well-formed for this 2376 // class template. 2377 SmallVector<TemplateArgument, 4> Converted; 2378 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, 2379 D->getLocation(), 2380 InstTemplateArgs, 2381 false, 2382 Converted)) 2383 return nullptr; 2384 2385 // Figure out where to insert this class template explicit specialization 2386 // in the member template's set of class template explicit specializations. 2387 void *InsertPos = nullptr; 2388 ClassTemplateSpecializationDecl *PrevDecl = 2389 InstClassTemplate->findSpecialization(Converted.data(), Converted.size(), 2390 InsertPos); 2391 2392 // Check whether we've already seen a conflicting instantiation of this 2393 // declaration (for instance, if there was a prior implicit instantiation). 2394 bool Ignored; 2395 if (PrevDecl && 2396 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(), 2397 D->getSpecializationKind(), 2398 PrevDecl, 2399 PrevDecl->getSpecializationKind(), 2400 PrevDecl->getPointOfInstantiation(), 2401 Ignored)) 2402 return nullptr; 2403 2404 // If PrevDecl was a definition and D is also a definition, diagnose. 2405 // This happens in cases like: 2406 // 2407 // template<typename T, typename U> 2408 // struct Outer { 2409 // template<typename X> struct Inner; 2410 // template<> struct Inner<T> {}; 2411 // template<> struct Inner<U> {}; 2412 // }; 2413 // 2414 // Outer<int, int> outer; // error: the explicit specializations of Inner 2415 // // have the same signature. 2416 if (PrevDecl && PrevDecl->getDefinition() && 2417 D->isThisDeclarationADefinition()) { 2418 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; 2419 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), 2420 diag::note_previous_definition); 2421 return nullptr; 2422 } 2423 2424 // Create the class template partial specialization declaration. 2425 ClassTemplateSpecializationDecl *InstD 2426 = ClassTemplateSpecializationDecl::Create(SemaRef.Context, 2427 D->getTagKind(), 2428 Owner, 2429 D->getLocStart(), 2430 D->getLocation(), 2431 InstClassTemplate, 2432 Converted.data(), 2433 Converted.size(), 2434 PrevDecl); 2435 2436 // Add this partial specialization to the set of class template partial 2437 // specializations. 2438 if (!PrevDecl) 2439 InstClassTemplate->AddSpecialization(InstD, InsertPos); 2440 2441 // Substitute the nested name specifier, if any. 2442 if (SubstQualifier(D, InstD)) 2443 return nullptr; 2444 2445 // Build the canonical type that describes the converted template 2446 // arguments of the class template explicit specialization. 2447 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 2448 TemplateName(InstClassTemplate), Converted.data(), Converted.size(), 2449 SemaRef.Context.getRecordType(InstD)); 2450 2451 // Build the fully-sugared type for this class template 2452 // specialization as the user wrote in the specialization 2453 // itself. This means that we'll pretty-print the type retrieved 2454 // from the specialization's declaration the way that the user 2455 // actually wrote the specialization, rather than formatting the 2456 // name based on the "canonical" representation used to store the 2457 // template arguments in the specialization. 2458 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 2459 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs, 2460 CanonType); 2461 2462 InstD->setAccess(D->getAccess()); 2463 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 2464 InstD->setSpecializationKind(D->getSpecializationKind()); 2465 InstD->setTypeAsWritten(WrittenTy); 2466 InstD->setExternLoc(D->getExternLoc()); 2467 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); 2468 2469 Owner->addDecl(InstD); 2470 2471 // Instantiate the members of the class-scope explicit specialization eagerly. 2472 // We don't have support for lazy instantiation of an explicit specialization 2473 // yet, and MSVC eagerly instantiates in this case. 2474 if (D->isThisDeclarationADefinition() && 2475 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs, 2476 TSK_ImplicitInstantiation, 2477 /*Complain=*/true)) 2478 return nullptr; 2479 2480 return InstD; 2481 } 2482 2483 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 2484 VarTemplateSpecializationDecl *D) { 2485 2486 TemplateArgumentListInfo VarTemplateArgsInfo; 2487 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 2488 assert(VarTemplate && 2489 "A template specialization without specialized template?"); 2490 2491 // Substitute the current template arguments. 2492 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 2493 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 2494 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 2495 2496 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(), 2497 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs)) 2498 return nullptr; 2499 2500 // Check that the template argument list is well-formed for this template. 2501 SmallVector<TemplateArgument, 4> Converted; 2502 if (SemaRef.CheckTemplateArgumentList( 2503 VarTemplate, VarTemplate->getLocStart(), 2504 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false, 2505 Converted)) 2506 return nullptr; 2507 2508 // Find the variable template specialization declaration that 2509 // corresponds to these arguments. 2510 void *InsertPos = nullptr; 2511 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization( 2512 Converted.data(), Converted.size(), InsertPos)) 2513 // If we already have a variable template specialization, return it. 2514 return VarSpec; 2515 2516 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos, 2517 VarTemplateArgsInfo, Converted); 2518 } 2519 2520 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 2521 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos, 2522 const TemplateArgumentListInfo &TemplateArgsInfo, 2523 llvm::ArrayRef<TemplateArgument> Converted) { 2524 2525 // If this is the variable for an anonymous struct or union, 2526 // instantiate the anonymous struct/union type first. 2527 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>()) 2528 if (RecordTy->getDecl()->isAnonymousStructOrUnion()) 2529 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl()))) 2530 return nullptr; 2531 2532 // Do substitution on the type of the declaration 2533 TypeSourceInfo *DI = 2534 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 2535 D->getTypeSpecStartLoc(), D->getDeclName()); 2536 if (!DI) 2537 return nullptr; 2538 2539 if (DI->getType()->isFunctionType()) { 2540 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 2541 << D->isStaticDataMember() << DI->getType(); 2542 return nullptr; 2543 } 2544 2545 // Build the instantiated declaration 2546 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 2547 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2548 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(), 2549 Converted.size()); 2550 Var->setTemplateArgsInfo(TemplateArgsInfo); 2551 if (InsertPos) 2552 VarTemplate->AddSpecialization(Var, InsertPos); 2553 2554 // Substitute the nested name specifier, if any. 2555 if (SubstQualifier(D, Var)) 2556 return nullptr; 2557 2558 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, 2559 Owner, StartingScope); 2560 2561 return Var; 2562 } 2563 2564 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 2565 llvm_unreachable("@defs is not supported in Objective-C++"); 2566 } 2567 2568 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 2569 // FIXME: We need to be able to instantiate FriendTemplateDecls. 2570 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 2571 DiagnosticsEngine::Error, 2572 "cannot instantiate %0 yet"); 2573 SemaRef.Diag(D->getLocation(), DiagID) 2574 << D->getDeclKindName(); 2575 2576 return nullptr; 2577 } 2578 2579 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 2580 llvm_unreachable("Unexpected decl"); 2581 } 2582 2583 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 2584 const MultiLevelTemplateArgumentList &TemplateArgs) { 2585 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 2586 if (D->isInvalidDecl()) 2587 return nullptr; 2588 2589 return Instantiator.Visit(D); 2590 } 2591 2592 /// \brief Instantiates a nested template parameter list in the current 2593 /// instantiation context. 2594 /// 2595 /// \param L The parameter list to instantiate 2596 /// 2597 /// \returns NULL if there was an error 2598 TemplateParameterList * 2599 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 2600 // Get errors for all the parameters before bailing out. 2601 bool Invalid = false; 2602 2603 unsigned N = L->size(); 2604 typedef SmallVector<NamedDecl *, 8> ParamVector; 2605 ParamVector Params; 2606 Params.reserve(N); 2607 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end(); 2608 PI != PE; ++PI) { 2609 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI)); 2610 Params.push_back(D); 2611 Invalid = Invalid || !D || D->isInvalidDecl(); 2612 } 2613 2614 // Clean up if we had an error. 2615 if (Invalid) 2616 return nullptr; 2617 2618 TemplateParameterList *InstL 2619 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 2620 L->getLAngleLoc(), &Params.front(), N, 2621 L->getRAngleLoc()); 2622 return InstL; 2623 } 2624 2625 /// \brief Instantiate the declaration of a class template partial 2626 /// specialization. 2627 /// 2628 /// \param ClassTemplate the (instantiated) class template that is partially 2629 // specialized by the instantiation of \p PartialSpec. 2630 /// 2631 /// \param PartialSpec the (uninstantiated) class template partial 2632 /// specialization that we are instantiating. 2633 /// 2634 /// \returns The instantiated partial specialization, if successful; otherwise, 2635 /// NULL to indicate an error. 2636 ClassTemplatePartialSpecializationDecl * 2637 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 2638 ClassTemplateDecl *ClassTemplate, 2639 ClassTemplatePartialSpecializationDecl *PartialSpec) { 2640 // Create a local instantiation scope for this class template partial 2641 // specialization, which will contain the instantiations of the template 2642 // parameters. 2643 LocalInstantiationScope Scope(SemaRef); 2644 2645 // Substitute into the template parameters of the class template partial 2646 // specialization. 2647 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 2648 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2649 if (!InstParams) 2650 return nullptr; 2651 2652 // Substitute into the template arguments of the class template partial 2653 // specialization. 2654 const ASTTemplateArgumentListInfo *TemplArgInfo 2655 = PartialSpec->getTemplateArgsAsWritten(); 2656 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 2657 TemplArgInfo->RAngleLoc); 2658 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 2659 TemplArgInfo->NumTemplateArgs, 2660 InstTemplateArgs, TemplateArgs)) 2661 return nullptr; 2662 2663 // Check that the template argument list is well-formed for this 2664 // class template. 2665 SmallVector<TemplateArgument, 4> Converted; 2666 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 2667 PartialSpec->getLocation(), 2668 InstTemplateArgs, 2669 false, 2670 Converted)) 2671 return nullptr; 2672 2673 // Figure out where to insert this class template partial specialization 2674 // in the member template's set of class template partial specializations. 2675 void *InsertPos = nullptr; 2676 ClassTemplateSpecializationDecl *PrevDecl 2677 = ClassTemplate->findPartialSpecialization(Converted.data(), 2678 Converted.size(), InsertPos); 2679 2680 // Build the canonical type that describes the converted template 2681 // arguments of the class template partial specialization. 2682 QualType CanonType 2683 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 2684 Converted.data(), 2685 Converted.size()); 2686 2687 // Build the fully-sugared type for this class template 2688 // specialization as the user wrote in the specialization 2689 // itself. This means that we'll pretty-print the type retrieved 2690 // from the specialization's declaration the way that the user 2691 // actually wrote the specialization, rather than formatting the 2692 // name based on the "canonical" representation used to store the 2693 // template arguments in the specialization. 2694 TypeSourceInfo *WrittenTy 2695 = SemaRef.Context.getTemplateSpecializationTypeInfo( 2696 TemplateName(ClassTemplate), 2697 PartialSpec->getLocation(), 2698 InstTemplateArgs, 2699 CanonType); 2700 2701 if (PrevDecl) { 2702 // We've already seen a partial specialization with the same template 2703 // parameters and template arguments. This can happen, for example, when 2704 // substituting the outer template arguments ends up causing two 2705 // class template partial specializations of a member class template 2706 // to have identical forms, e.g., 2707 // 2708 // template<typename T, typename U> 2709 // struct Outer { 2710 // template<typename X, typename Y> struct Inner; 2711 // template<typename Y> struct Inner<T, Y>; 2712 // template<typename Y> struct Inner<U, Y>; 2713 // }; 2714 // 2715 // Outer<int, int> outer; // error: the partial specializations of Inner 2716 // // have the same signature. 2717 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 2718 << WrittenTy->getType(); 2719 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 2720 << SemaRef.Context.getTypeDeclType(PrevDecl); 2721 return nullptr; 2722 } 2723 2724 2725 // Create the class template partial specialization declaration. 2726 ClassTemplatePartialSpecializationDecl *InstPartialSpec 2727 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, 2728 PartialSpec->getTagKind(), 2729 Owner, 2730 PartialSpec->getLocStart(), 2731 PartialSpec->getLocation(), 2732 InstParams, 2733 ClassTemplate, 2734 Converted.data(), 2735 Converted.size(), 2736 InstTemplateArgs, 2737 CanonType, 2738 nullptr); 2739 // Substitute the nested name specifier, if any. 2740 if (SubstQualifier(PartialSpec, InstPartialSpec)) 2741 return nullptr; 2742 2743 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 2744 InstPartialSpec->setTypeAsWritten(WrittenTy); 2745 2746 // Add this partial specialization to the set of class template partial 2747 // specializations. 2748 ClassTemplate->AddPartialSpecialization(InstPartialSpec, 2749 /*InsertPos=*/nullptr); 2750 return InstPartialSpec; 2751 } 2752 2753 /// \brief Instantiate the declaration of a variable template partial 2754 /// specialization. 2755 /// 2756 /// \param VarTemplate the (instantiated) variable template that is partially 2757 /// specialized by the instantiation of \p PartialSpec. 2758 /// 2759 /// \param PartialSpec the (uninstantiated) variable template partial 2760 /// specialization that we are instantiating. 2761 /// 2762 /// \returns The instantiated partial specialization, if successful; otherwise, 2763 /// NULL to indicate an error. 2764 VarTemplatePartialSpecializationDecl * 2765 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 2766 VarTemplateDecl *VarTemplate, 2767 VarTemplatePartialSpecializationDecl *PartialSpec) { 2768 // Create a local instantiation scope for this variable template partial 2769 // specialization, which will contain the instantiations of the template 2770 // parameters. 2771 LocalInstantiationScope Scope(SemaRef); 2772 2773 // Substitute into the template parameters of the variable template partial 2774 // specialization. 2775 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 2776 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2777 if (!InstParams) 2778 return nullptr; 2779 2780 // Substitute into the template arguments of the variable template partial 2781 // specialization. 2782 const ASTTemplateArgumentListInfo *TemplArgInfo 2783 = PartialSpec->getTemplateArgsAsWritten(); 2784 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 2785 TemplArgInfo->RAngleLoc); 2786 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 2787 TemplArgInfo->NumTemplateArgs, 2788 InstTemplateArgs, TemplateArgs)) 2789 return nullptr; 2790 2791 // Check that the template argument list is well-formed for this 2792 // class template. 2793 SmallVector<TemplateArgument, 4> Converted; 2794 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 2795 InstTemplateArgs, false, Converted)) 2796 return nullptr; 2797 2798 // Figure out where to insert this variable template partial specialization 2799 // in the member template's set of variable template partial specializations. 2800 void *InsertPos = nullptr; 2801 VarTemplateSpecializationDecl *PrevDecl = 2802 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(), 2803 InsertPos); 2804 2805 // Build the canonical type that describes the converted template 2806 // arguments of the variable template partial specialization. 2807 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 2808 TemplateName(VarTemplate), Converted.data(), Converted.size()); 2809 2810 // Build the fully-sugared type for this variable template 2811 // specialization as the user wrote in the specialization 2812 // itself. This means that we'll pretty-print the type retrieved 2813 // from the specialization's declaration the way that the user 2814 // actually wrote the specialization, rather than formatting the 2815 // name based on the "canonical" representation used to store the 2816 // template arguments in the specialization. 2817 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 2818 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 2819 CanonType); 2820 2821 if (PrevDecl) { 2822 // We've already seen a partial specialization with the same template 2823 // parameters and template arguments. This can happen, for example, when 2824 // substituting the outer template arguments ends up causing two 2825 // variable template partial specializations of a member variable template 2826 // to have identical forms, e.g., 2827 // 2828 // template<typename T, typename U> 2829 // struct Outer { 2830 // template<typename X, typename Y> pair<X,Y> p; 2831 // template<typename Y> pair<T, Y> p; 2832 // template<typename Y> pair<U, Y> p; 2833 // }; 2834 // 2835 // Outer<int, int> outer; // error: the partial specializations of Inner 2836 // // have the same signature. 2837 SemaRef.Diag(PartialSpec->getLocation(), 2838 diag::err_var_partial_spec_redeclared) 2839 << WrittenTy->getType(); 2840 SemaRef.Diag(PrevDecl->getLocation(), 2841 diag::note_var_prev_partial_spec_here); 2842 return nullptr; 2843 } 2844 2845 // Do substitution on the type of the declaration 2846 TypeSourceInfo *DI = SemaRef.SubstType( 2847 PartialSpec->getTypeSourceInfo(), TemplateArgs, 2848 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 2849 if (!DI) 2850 return nullptr; 2851 2852 if (DI->getType()->isFunctionType()) { 2853 SemaRef.Diag(PartialSpec->getLocation(), 2854 diag::err_variable_instantiates_to_function) 2855 << PartialSpec->isStaticDataMember() << DI->getType(); 2856 return nullptr; 2857 } 2858 2859 // Create the variable template partial specialization declaration. 2860 VarTemplatePartialSpecializationDecl *InstPartialSpec = 2861 VarTemplatePartialSpecializationDecl::Create( 2862 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 2863 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 2864 DI, PartialSpec->getStorageClass(), Converted.data(), 2865 Converted.size(), InstTemplateArgs); 2866 2867 // Substitute the nested name specifier, if any. 2868 if (SubstQualifier(PartialSpec, InstPartialSpec)) 2869 return nullptr; 2870 2871 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 2872 InstPartialSpec->setTypeAsWritten(WrittenTy); 2873 2874 // Add this partial specialization to the set of variable template partial 2875 // specializations. The instantiation of the initializer is not necessary. 2876 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr); 2877 2878 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 2879 LateAttrs, Owner, StartingScope); 2880 2881 return InstPartialSpec; 2882 } 2883 2884 TypeSourceInfo* 2885 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 2886 SmallVectorImpl<ParmVarDecl *> &Params) { 2887 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 2888 assert(OldTInfo && "substituting function without type source info"); 2889 assert(Params.empty() && "parameter vector is non-empty at start"); 2890 2891 CXXRecordDecl *ThisContext = nullptr; 2892 unsigned ThisTypeQuals = 0; 2893 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 2894 ThisContext = cast<CXXRecordDecl>(Owner); 2895 ThisTypeQuals = Method->getTypeQualifiers(); 2896 } 2897 2898 TypeSourceInfo *NewTInfo 2899 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 2900 D->getTypeSpecStartLoc(), 2901 D->getDeclName(), 2902 ThisContext, ThisTypeQuals); 2903 if (!NewTInfo) 2904 return nullptr; 2905 2906 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 2907 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 2908 if (NewTInfo != OldTInfo) { 2909 // Get parameters from the new type info. 2910 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 2911 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 2912 unsigned NewIdx = 0; 2913 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); 2914 OldIdx != NumOldParams; ++OldIdx) { 2915 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); 2916 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 2917 2918 Optional<unsigned> NumArgumentsInExpansion; 2919 if (OldParam->isParameterPack()) 2920 NumArgumentsInExpansion = 2921 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 2922 TemplateArgs); 2923 if (!NumArgumentsInExpansion) { 2924 // Simple case: normal parameter, or a parameter pack that's 2925 // instantiated to a (still-dependent) parameter pack. 2926 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 2927 Params.push_back(NewParam); 2928 Scope->InstantiatedLocal(OldParam, NewParam); 2929 } else { 2930 // Parameter pack expansion: make the instantiation an argument pack. 2931 Scope->MakeInstantiatedLocalArgPack(OldParam); 2932 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 2933 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 2934 Params.push_back(NewParam); 2935 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 2936 } 2937 } 2938 } 2939 } else { 2940 // The function type itself was not dependent and therefore no 2941 // substitution occurred. However, we still need to instantiate 2942 // the function parameters themselves. 2943 const FunctionProtoType *OldProto = 2944 cast<FunctionProtoType>(OldProtoLoc.getType()); 2945 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; 2946 ++i) { 2947 ParmVarDecl *OldParam = OldProtoLoc.getParam(i); 2948 if (!OldParam) { 2949 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 2950 D, D->getLocation(), OldProto->getParamType(i))); 2951 continue; 2952 } 2953 2954 ParmVarDecl *Parm = 2955 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 2956 if (!Parm) 2957 return nullptr; 2958 Params.push_back(Parm); 2959 } 2960 } 2961 } else { 2962 // If the type of this function, after ignoring parentheses, is not 2963 // *directly* a function type, then we're instantiating a function that 2964 // was declared via a typedef or with attributes, e.g., 2965 // 2966 // typedef int functype(int, int); 2967 // functype func; 2968 // int __cdecl meth(int, int); 2969 // 2970 // In this case, we'll just go instantiate the ParmVarDecls that we 2971 // synthesized in the method declaration. 2972 SmallVector<QualType, 4> ParamTypes; 2973 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(), 2974 D->getNumParams(), TemplateArgs, ParamTypes, 2975 &Params)) 2976 return nullptr; 2977 } 2978 2979 return NewTInfo; 2980 } 2981 2982 /// Introduce the instantiated function parameters into the local 2983 /// instantiation scope, and set the parameter names to those used 2984 /// in the template. 2985 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 2986 const FunctionDecl *PatternDecl, 2987 LocalInstantiationScope &Scope, 2988 const MultiLevelTemplateArgumentList &TemplateArgs) { 2989 unsigned FParamIdx = 0; 2990 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 2991 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 2992 if (!PatternParam->isParameterPack()) { 2993 // Simple case: not a parameter pack. 2994 assert(FParamIdx < Function->getNumParams()); 2995 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 2996 // If the parameter's type is not dependent, update it to match the type 2997 // in the pattern. They can differ in top-level cv-qualifiers, and we want 2998 // the pattern's type here. If the type is dependent, they can't differ, 2999 // per core issue 1668. 3000 // FIXME: Updating the type to work around this is at best fragile. 3001 if (!PatternDecl->getType()->isDependentType()) 3002 FunctionParam->setType(PatternParam->getType()); 3003 3004 FunctionParam->setDeclName(PatternParam->getDeclName()); 3005 Scope.InstantiatedLocal(PatternParam, FunctionParam); 3006 ++FParamIdx; 3007 continue; 3008 } 3009 3010 // Expand the parameter pack. 3011 Scope.MakeInstantiatedLocalArgPack(PatternParam); 3012 Optional<unsigned> NumArgumentsInExpansion 3013 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 3014 assert(NumArgumentsInExpansion && 3015 "should only be called when all template arguments are known"); 3016 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 3017 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 3018 if (!PatternDecl->getType()->isDependentType()) 3019 FunctionParam->setType(PatternParam->getType()); 3020 3021 FunctionParam->setDeclName(PatternParam->getDeclName()); 3022 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 3023 ++FParamIdx; 3024 } 3025 } 3026 } 3027 3028 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New, 3029 const FunctionProtoType *Proto, 3030 const MultiLevelTemplateArgumentList &TemplateArgs) { 3031 assert(Proto->getExceptionSpecType() != EST_Uninstantiated); 3032 3033 // C++11 [expr.prim.general]p3: 3034 // If a declaration declares a member function or member function 3035 // template of a class X, the expression this is a prvalue of type 3036 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq 3037 // and the end of the function-definition, member-declarator, or 3038 // declarator. 3039 CXXRecordDecl *ThisContext = nullptr; 3040 unsigned ThisTypeQuals = 0; 3041 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) { 3042 ThisContext = Method->getParent(); 3043 ThisTypeQuals = Method->getTypeQualifiers(); 3044 } 3045 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals, 3046 SemaRef.getLangOpts().CPlusPlus11); 3047 3048 // The function has an exception specification or a "noreturn" 3049 // attribute. Substitute into each of the exception types. 3050 SmallVector<QualType, 4> Exceptions; 3051 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) { 3052 // FIXME: Poor location information! 3053 if (const PackExpansionType *PackExpansion 3054 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) { 3055 // We have a pack expansion. Instantiate it. 3056 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 3057 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(), 3058 Unexpanded); 3059 assert(!Unexpanded.empty() && 3060 "Pack expansion without parameter packs?"); 3061 3062 bool Expand = false; 3063 bool RetainExpansion = false; 3064 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions(); 3065 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(), 3066 SourceRange(), 3067 Unexpanded, 3068 TemplateArgs, 3069 Expand, 3070 RetainExpansion, 3071 NumExpansions)) 3072 break; 3073 3074 if (!Expand) { 3075 // We can't expand this pack expansion into separate arguments yet; 3076 // just substitute into the pattern and create a new pack expansion 3077 // type. 3078 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 3079 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 3080 TemplateArgs, 3081 New->getLocation(), New->getDeclName()); 3082 if (T.isNull()) 3083 break; 3084 3085 T = SemaRef.Context.getPackExpansionType(T, NumExpansions); 3086 Exceptions.push_back(T); 3087 continue; 3088 } 3089 3090 // Substitute into the pack expansion pattern for each template 3091 bool Invalid = false; 3092 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) { 3093 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx); 3094 3095 QualType T = SemaRef.SubstType(PackExpansion->getPattern(), 3096 TemplateArgs, 3097 New->getLocation(), New->getDeclName()); 3098 if (T.isNull()) { 3099 Invalid = true; 3100 break; 3101 } 3102 3103 Exceptions.push_back(T); 3104 } 3105 3106 if (Invalid) 3107 break; 3108 3109 continue; 3110 } 3111 3112 QualType T 3113 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs, 3114 New->getLocation(), New->getDeclName()); 3115 if (T.isNull() || 3116 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation())) 3117 continue; 3118 3119 Exceptions.push_back(T); 3120 } 3121 Expr *NoexceptExpr = nullptr; 3122 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) { 3123 EnterExpressionEvaluationContext Unevaluated(SemaRef, 3124 Sema::ConstantEvaluated); 3125 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs); 3126 if (E.isUsable()) 3127 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart()); 3128 3129 if (E.isUsable()) { 3130 NoexceptExpr = E.get(); 3131 if (!NoexceptExpr->isTypeDependent() && 3132 !NoexceptExpr->isValueDependent()) 3133 NoexceptExpr 3134 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr, 3135 nullptr, diag::err_noexcept_needs_constant_expression, 3136 /*AllowFold*/ false).get(); 3137 } 3138 } 3139 3140 FunctionProtoType::ExtProtoInfo EPI; 3141 EPI.ExceptionSpecType = Proto->getExceptionSpecType(); 3142 EPI.NumExceptions = Exceptions.size(); 3143 EPI.Exceptions = Exceptions.data(); 3144 EPI.NoexceptExpr = NoexceptExpr; 3145 3146 SemaRef.UpdateExceptionSpec(New, EPI); 3147 } 3148 3149 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 3150 FunctionDecl *Decl) { 3151 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 3152 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 3153 return; 3154 3155 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 3156 InstantiatingTemplate::ExceptionSpecification()); 3157 if (Inst.isInvalid()) { 3158 // We hit the instantiation depth limit. Clear the exception specification 3159 // so that our callers don't have to cope with EST_Uninstantiated. 3160 FunctionProtoType::ExtProtoInfo EPI; 3161 EPI.ExceptionSpecType = EST_None; 3162 UpdateExceptionSpec(Decl, EPI); 3163 return; 3164 } 3165 3166 // Enter the scope of this instantiation. We don't use 3167 // PushDeclContext because we don't have a scope. 3168 Sema::ContextRAII savedContext(*this, Decl); 3169 LocalInstantiationScope Scope(*this); 3170 3171 MultiLevelTemplateArgumentList TemplateArgs = 3172 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true); 3173 3174 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 3175 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs); 3176 3177 ::InstantiateExceptionSpec(*this, Decl, 3178 Template->getType()->castAs<FunctionProtoType>(), 3179 TemplateArgs); 3180 } 3181 3182 /// \brief Initializes the common fields of an instantiation function 3183 /// declaration (New) from the corresponding fields of its template (Tmpl). 3184 /// 3185 /// \returns true if there was an error 3186 bool 3187 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 3188 FunctionDecl *Tmpl) { 3189 if (Tmpl->isDeleted()) 3190 New->setDeletedAsWritten(); 3191 3192 // Forward the mangling number from the template to the instantiated decl. 3193 SemaRef.Context.setManglingNumber(New, 3194 SemaRef.Context.getManglingNumber(Tmpl)); 3195 3196 // If we are performing substituting explicitly-specified template arguments 3197 // or deduced template arguments into a function template and we reach this 3198 // point, we are now past the point where SFINAE applies and have committed 3199 // to keeping the new function template specialization. We therefore 3200 // convert the active template instantiation for the function template 3201 // into a template instantiation for this specific function template 3202 // specialization, which is not a SFINAE context, so that we diagnose any 3203 // further errors in the declaration itself. 3204 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 3205 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 3206 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 3207 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 3208 if (FunctionTemplateDecl *FunTmpl 3209 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 3210 assert(FunTmpl->getTemplatedDecl() == Tmpl && 3211 "Deduction from the wrong function template?"); 3212 (void) FunTmpl; 3213 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 3214 ActiveInst.Entity = New; 3215 } 3216 } 3217 3218 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 3219 assert(Proto && "Function template without prototype?"); 3220 3221 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 3222 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3223 3224 // DR1330: In C++11, defer instantiation of a non-trivial 3225 // exception specification. 3226 if (SemaRef.getLangOpts().CPlusPlus11 && 3227 EPI.ExceptionSpecType != EST_None && 3228 EPI.ExceptionSpecType != EST_DynamicNone && 3229 EPI.ExceptionSpecType != EST_BasicNoexcept) { 3230 FunctionDecl *ExceptionSpecTemplate = Tmpl; 3231 if (EPI.ExceptionSpecType == EST_Uninstantiated) 3232 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate; 3233 ExceptionSpecificationType NewEST = EST_Uninstantiated; 3234 if (EPI.ExceptionSpecType == EST_Unevaluated) 3235 NewEST = EST_Unevaluated; 3236 3237 // Mark the function has having an uninstantiated exception specification. 3238 const FunctionProtoType *NewProto 3239 = New->getType()->getAs<FunctionProtoType>(); 3240 assert(NewProto && "Template instantiation without function prototype?"); 3241 EPI = NewProto->getExtProtoInfo(); 3242 EPI.ExceptionSpecType = NewEST; 3243 EPI.ExceptionSpecDecl = New; 3244 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate; 3245 New->setType(SemaRef.Context.getFunctionType( 3246 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 3247 } else { 3248 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs); 3249 } 3250 } 3251 3252 // Get the definition. Leaves the variable unchanged if undefined. 3253 const FunctionDecl *Definition = Tmpl; 3254 Tmpl->isDefined(Definition); 3255 3256 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 3257 LateAttrs, StartingScope); 3258 3259 return false; 3260 } 3261 3262 /// \brief Initializes common fields of an instantiated method 3263 /// declaration (New) from the corresponding fields of its template 3264 /// (Tmpl). 3265 /// 3266 /// \returns true if there was an error 3267 bool 3268 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 3269 CXXMethodDecl *Tmpl) { 3270 if (InitFunctionInstantiation(New, Tmpl)) 3271 return true; 3272 3273 New->setAccess(Tmpl->getAccess()); 3274 if (Tmpl->isVirtualAsWritten()) 3275 New->setVirtualAsWritten(true); 3276 3277 // FIXME: New needs a pointer to Tmpl 3278 return false; 3279 } 3280 3281 /// \brief Instantiate the definition of the given function from its 3282 /// template. 3283 /// 3284 /// \param PointOfInstantiation the point at which the instantiation was 3285 /// required. Note that this is not precisely a "point of instantiation" 3286 /// for the function, but it's close. 3287 /// 3288 /// \param Function the already-instantiated declaration of a 3289 /// function template specialization or member function of a class template 3290 /// specialization. 3291 /// 3292 /// \param Recursive if true, recursively instantiates any functions that 3293 /// are required by this instantiation. 3294 /// 3295 /// \param DefinitionRequired if true, then we are performing an explicit 3296 /// instantiation where the body of the function is required. Complain if 3297 /// there is no such body. 3298 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 3299 FunctionDecl *Function, 3300 bool Recursive, 3301 bool DefinitionRequired) { 3302 if (Function->isInvalidDecl() || Function->isDefined()) 3303 return; 3304 3305 // Never instantiate an explicit specialization except if it is a class scope 3306 // explicit specialization. 3307 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 3308 !Function->getClassScopeSpecializationPattern()) 3309 return; 3310 3311 // Find the function body that we'll be substituting. 3312 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 3313 assert(PatternDecl && "instantiating a non-template"); 3314 3315 Stmt *Pattern = PatternDecl->getBody(PatternDecl); 3316 assert(PatternDecl && "template definition is not a template"); 3317 if (!Pattern) { 3318 // Try to find a defaulted definition 3319 PatternDecl->isDefined(PatternDecl); 3320 } 3321 assert(PatternDecl && "template definition is not a template"); 3322 3323 // Postpone late parsed template instantiations. 3324 if (PatternDecl->isLateTemplateParsed() && 3325 !LateTemplateParser) { 3326 PendingInstantiations.push_back( 3327 std::make_pair(Function, PointOfInstantiation)); 3328 return; 3329 } 3330 3331 // Call the LateTemplateParser callback if there is a need to late parse 3332 // a templated function definition. 3333 if (!Pattern && PatternDecl->isLateTemplateParsed() && 3334 LateTemplateParser) { 3335 // FIXME: Optimize to allow individual templates to be deserialized. 3336 if (PatternDecl->isFromASTFile()) 3337 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 3338 3339 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl); 3340 assert(LPT && "missing LateParsedTemplate"); 3341 LateTemplateParser(OpaqueParser, *LPT); 3342 Pattern = PatternDecl->getBody(PatternDecl); 3343 } 3344 3345 if (!Pattern && !PatternDecl->isDefaulted()) { 3346 if (DefinitionRequired) { 3347 if (Function->getPrimaryTemplate()) 3348 Diag(PointOfInstantiation, 3349 diag::err_explicit_instantiation_undefined_func_template) 3350 << Function->getPrimaryTemplate(); 3351 else 3352 Diag(PointOfInstantiation, 3353 diag::err_explicit_instantiation_undefined_member) 3354 << 1 << Function->getDeclName() << Function->getDeclContext(); 3355 3356 if (PatternDecl) 3357 Diag(PatternDecl->getLocation(), 3358 diag::note_explicit_instantiation_here); 3359 Function->setInvalidDecl(); 3360 } else if (Function->getTemplateSpecializationKind() 3361 == TSK_ExplicitInstantiationDefinition) { 3362 PendingInstantiations.push_back( 3363 std::make_pair(Function, PointOfInstantiation)); 3364 } 3365 3366 return; 3367 } 3368 3369 // C++1y [temp.explicit]p10: 3370 // Except for inline functions, declarations with types deduced from their 3371 // initializer or return value, and class template specializations, other 3372 // explicit instantiation declarations have the effect of suppressing the 3373 // implicit instantiation of the entity to which they refer. 3374 if (Function->getTemplateSpecializationKind() == 3375 TSK_ExplicitInstantiationDeclaration && 3376 !PatternDecl->isInlined() && 3377 !PatternDecl->getReturnType()->getContainedAutoType()) 3378 return; 3379 3380 if (PatternDecl->isInlined()) { 3381 // Function, and all later redeclarations of it (from imported modules, 3382 // for instance), are now implicitly inline. 3383 for (auto *D = Function->getMostRecentDecl(); /**/; 3384 D = D->getPreviousDecl()) { 3385 D->setImplicitlyInline(); 3386 if (D == Function) 3387 break; 3388 } 3389 } 3390 3391 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 3392 if (Inst.isInvalid()) 3393 return; 3394 3395 // Copy the inner loc start from the pattern. 3396 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 3397 3398 // If we're performing recursive template instantiation, create our own 3399 // queue of pending implicit instantiations that we will instantiate later, 3400 // while we're still within our own instantiation context. 3401 SmallVector<VTableUse, 16> SavedVTableUses; 3402 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 3403 SavePendingLocalImplicitInstantiationsRAII 3404 SavedPendingLocalImplicitInstantiations(*this); 3405 if (Recursive) { 3406 VTableUses.swap(SavedVTableUses); 3407 PendingInstantiations.swap(SavedPendingInstantiations); 3408 } 3409 3410 EnterExpressionEvaluationContext EvalContext(*this, 3411 Sema::PotentiallyEvaluated); 3412 3413 // Introduce a new scope where local variable instantiations will be 3414 // recorded, unless we're actually a member function within a local 3415 // class, in which case we need to merge our results with the parent 3416 // scope (of the enclosing function). 3417 bool MergeWithParentScope = false; 3418 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 3419 MergeWithParentScope = Rec->isLocalClass(); 3420 3421 LocalInstantiationScope Scope(*this, MergeWithParentScope); 3422 3423 if (PatternDecl->isDefaulted()) 3424 SetDeclDefaulted(Function, PatternDecl->getLocation()); 3425 else { 3426 ActOnStartOfFunctionDef(nullptr, Function); 3427 3428 // Enter the scope of this instantiation. We don't use 3429 // PushDeclContext because we don't have a scope. 3430 Sema::ContextRAII savedContext(*this, Function); 3431 3432 MultiLevelTemplateArgumentList TemplateArgs = 3433 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl); 3434 3435 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 3436 TemplateArgs); 3437 3438 // If this is a constructor, instantiate the member initializers. 3439 if (const CXXConstructorDecl *Ctor = 3440 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 3441 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 3442 TemplateArgs); 3443 } 3444 3445 // Instantiate the function body. 3446 StmtResult Body = SubstStmt(Pattern, TemplateArgs); 3447 3448 if (Body.isInvalid()) 3449 Function->setInvalidDecl(); 3450 3451 ActOnFinishFunctionBody(Function, Body.get(), 3452 /*IsInstantiation=*/true); 3453 3454 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 3455 3456 if (auto *Listener = getASTMutationListener()) 3457 Listener->FunctionDefinitionInstantiated(Function); 3458 3459 savedContext.pop(); 3460 } 3461 3462 DeclGroupRef DG(Function); 3463 Consumer.HandleTopLevelDecl(DG); 3464 3465 // This class may have local implicit instantiations that need to be 3466 // instantiation within this scope. 3467 PerformPendingInstantiations(/*LocalOnly=*/true); 3468 Scope.Exit(); 3469 3470 if (Recursive) { 3471 // Define any pending vtables. 3472 DefineUsedVTables(); 3473 3474 // Instantiate any pending implicit instantiations found during the 3475 // instantiation of this template. 3476 PerformPendingInstantiations(); 3477 3478 // Restore the set of pending vtables. 3479 assert(VTableUses.empty() && 3480 "VTableUses should be empty before it is discarded."); 3481 VTableUses.swap(SavedVTableUses); 3482 3483 // Restore the set of pending implicit instantiations. 3484 assert(PendingInstantiations.empty() && 3485 "PendingInstantiations should be empty before it is discarded."); 3486 PendingInstantiations.swap(SavedPendingInstantiations); 3487 } 3488 } 3489 3490 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 3491 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 3492 const TemplateArgumentList &TemplateArgList, 3493 const TemplateArgumentListInfo &TemplateArgsInfo, 3494 SmallVectorImpl<TemplateArgument> &Converted, 3495 SourceLocation PointOfInstantiation, void *InsertPos, 3496 LateInstantiatedAttrVec *LateAttrs, 3497 LocalInstantiationScope *StartingScope) { 3498 if (FromVar->isInvalidDecl()) 3499 return nullptr; 3500 3501 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 3502 if (Inst.isInvalid()) 3503 return nullptr; 3504 3505 MultiLevelTemplateArgumentList TemplateArgLists; 3506 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 3507 3508 // Instantiate the first declaration of the variable template: for a partial 3509 // specialization of a static data member template, the first declaration may 3510 // or may not be the declaration in the class; if it's in the class, we want 3511 // to instantiate a member in the class (a declaration), and if it's outside, 3512 // we want to instantiate a definition. 3513 // 3514 // If we're instantiating an explicitly-specialized member template or member 3515 // partial specialization, don't do this. The member specialization completely 3516 // replaces the original declaration in this case. 3517 bool IsMemberSpec = false; 3518 if (VarTemplatePartialSpecializationDecl *PartialSpec = 3519 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) 3520 IsMemberSpec = PartialSpec->isMemberSpecialization(); 3521 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate()) 3522 IsMemberSpec = FromTemplate->isMemberSpecialization(); 3523 if (!IsMemberSpec) 3524 FromVar = FromVar->getFirstDecl(); 3525 3526 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 3527 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 3528 MultiLevelList); 3529 3530 // TODO: Set LateAttrs and StartingScope ... 3531 3532 return cast_or_null<VarTemplateSpecializationDecl>( 3533 Instantiator.VisitVarTemplateSpecializationDecl( 3534 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted)); 3535 } 3536 3537 /// \brief Instantiates a variable template specialization by completing it 3538 /// with appropriate type information and initializer. 3539 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 3540 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 3541 const MultiLevelTemplateArgumentList &TemplateArgs) { 3542 3543 // Do substitution on the type of the declaration 3544 TypeSourceInfo *DI = 3545 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 3546 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 3547 if (!DI) 3548 return nullptr; 3549 3550 // Update the type of this variable template specialization. 3551 VarSpec->setType(DI->getType()); 3552 3553 // Instantiate the initializer. 3554 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 3555 3556 return VarSpec; 3557 } 3558 3559 /// BuildVariableInstantiation - Used after a new variable has been created. 3560 /// Sets basic variable data and decides whether to postpone the 3561 /// variable instantiation. 3562 void Sema::BuildVariableInstantiation( 3563 VarDecl *NewVar, VarDecl *OldVar, 3564 const MultiLevelTemplateArgumentList &TemplateArgs, 3565 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 3566 LocalInstantiationScope *StartingScope, 3567 bool InstantiatingVarTemplate) { 3568 3569 // If we are instantiating a local extern declaration, the 3570 // instantiation belongs lexically to the containing function. 3571 // If we are instantiating a static data member defined 3572 // out-of-line, the instantiation will have the same lexical 3573 // context (which will be a namespace scope) as the template. 3574 if (OldVar->isLocalExternDecl()) { 3575 NewVar->setLocalExternDecl(); 3576 NewVar->setLexicalDeclContext(Owner); 3577 } else if (OldVar->isOutOfLine()) 3578 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 3579 NewVar->setTSCSpec(OldVar->getTSCSpec()); 3580 NewVar->setInitStyle(OldVar->getInitStyle()); 3581 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 3582 NewVar->setConstexpr(OldVar->isConstexpr()); 3583 NewVar->setInitCapture(OldVar->isInitCapture()); 3584 NewVar->setPreviousDeclInSameBlockScope( 3585 OldVar->isPreviousDeclInSameBlockScope()); 3586 NewVar->setAccess(OldVar->getAccess()); 3587 3588 if (!OldVar->isStaticDataMember()) { 3589 if (OldVar->isUsed(false)) 3590 NewVar->setIsUsed(); 3591 NewVar->setReferenced(OldVar->isReferenced()); 3592 } 3593 3594 // See if the old variable had a type-specifier that defined an anonymous tag. 3595 // If it did, mark the new variable as being the declarator for the new 3596 // anonymous tag. 3597 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) { 3598 TagDecl *OldTag = OldTagType->getDecl(); 3599 if (OldTag->getDeclaratorForAnonDecl() == OldVar) { 3600 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl(); 3601 assert(!NewTag->hasNameForLinkage() && 3602 !NewTag->hasDeclaratorForAnonDecl()); 3603 NewTag->setDeclaratorForAnonDecl(NewVar); 3604 } 3605 } 3606 3607 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 3608 3609 LookupResult Previous( 3610 *this, NewVar->getDeclName(), NewVar->getLocation(), 3611 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 3612 : Sema::LookupOrdinaryName, 3613 Sema::ForRedeclaration); 3614 3615 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 3616 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 3617 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 3618 // We have a previous declaration. Use that one, so we merge with the 3619 // right type. 3620 if (NamedDecl *NewPrev = FindInstantiatedDecl( 3621 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 3622 Previous.addDecl(NewPrev); 3623 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 3624 OldVar->hasLinkage()) 3625 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 3626 CheckVariableDeclaration(NewVar, Previous); 3627 3628 if (!InstantiatingVarTemplate) { 3629 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 3630 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 3631 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 3632 } 3633 3634 if (!OldVar->isOutOfLine()) { 3635 if (NewVar->getDeclContext()->isFunctionOrMethod()) 3636 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 3637 } 3638 3639 // Link instantiations of static data members back to the template from 3640 // which they were instantiated. 3641 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate) 3642 NewVar->setInstantiationOfStaticDataMember(OldVar, 3643 TSK_ImplicitInstantiation); 3644 3645 // Forward the mangling number from the template to the instantiated decl. 3646 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 3647 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar)); 3648 3649 // Delay instantiation of the initializer for variable templates until a 3650 // definition of the variable is needed. We need it right away if the type 3651 // contains 'auto'. 3652 if ((!isa<VarTemplateSpecializationDecl>(NewVar) && 3653 !InstantiatingVarTemplate) || 3654 NewVar->getType()->isUndeducedType()) 3655 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 3656 3657 // Diagnose unused local variables with dependent types, where the diagnostic 3658 // will have been deferred. 3659 if (!NewVar->isInvalidDecl() && 3660 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() && 3661 OldVar->getType()->isDependentType()) 3662 DiagnoseUnusedDecl(NewVar); 3663 } 3664 3665 /// \brief Instantiate the initializer of a variable. 3666 void Sema::InstantiateVariableInitializer( 3667 VarDecl *Var, VarDecl *OldVar, 3668 const MultiLevelTemplateArgumentList &TemplateArgs) { 3669 3670 if (Var->getAnyInitializer()) 3671 // We already have an initializer in the class. 3672 return; 3673 3674 if (Var->hasAttr<DLLImportAttr>() && 3675 !(OldVar->getInit() && OldVar->checkInitIsICE())) { 3676 // Do not dynamically initialize dllimport variables. 3677 return; 3678 } 3679 3680 if (OldVar->getInit()) { 3681 if (Var->isStaticDataMember() && !OldVar->isOutOfLine()) 3682 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar); 3683 else 3684 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar); 3685 3686 // Instantiate the initializer. 3687 ExprResult Init = 3688 SubstInitializer(OldVar->getInit(), TemplateArgs, 3689 OldVar->getInitStyle() == VarDecl::CallInit); 3690 if (!Init.isInvalid()) { 3691 bool TypeMayContainAuto = true; 3692 if (Init.get()) { 3693 bool DirectInit = OldVar->isDirectInit(); 3694 AddInitializerToDecl(Var, Init.get(), DirectInit, TypeMayContainAuto); 3695 } else 3696 ActOnUninitializedDecl(Var, TypeMayContainAuto); 3697 } else { 3698 // FIXME: Not too happy about invalidating the declaration 3699 // because of a bogus initializer. 3700 Var->setInvalidDecl(); 3701 } 3702 3703 PopExpressionEvaluationContext(); 3704 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) && 3705 !Var->isCXXForRangeDecl()) 3706 ActOnUninitializedDecl(Var, false); 3707 } 3708 3709 /// \brief Instantiate the definition of the given variable from its 3710 /// template. 3711 /// 3712 /// \param PointOfInstantiation the point at which the instantiation was 3713 /// required. Note that this is not precisely a "point of instantiation" 3714 /// for the function, but it's close. 3715 /// 3716 /// \param Var the already-instantiated declaration of a static member 3717 /// variable of a class template specialization. 3718 /// 3719 /// \param Recursive if true, recursively instantiates any functions that 3720 /// are required by this instantiation. 3721 /// 3722 /// \param DefinitionRequired if true, then we are performing an explicit 3723 /// instantiation where an out-of-line definition of the member variable 3724 /// is required. Complain if there is no such definition. 3725 void Sema::InstantiateStaticDataMemberDefinition( 3726 SourceLocation PointOfInstantiation, 3727 VarDecl *Var, 3728 bool Recursive, 3729 bool DefinitionRequired) { 3730 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive, 3731 DefinitionRequired); 3732 } 3733 3734 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 3735 VarDecl *Var, bool Recursive, 3736 bool DefinitionRequired) { 3737 if (Var->isInvalidDecl()) 3738 return; 3739 3740 VarTemplateSpecializationDecl *VarSpec = 3741 dyn_cast<VarTemplateSpecializationDecl>(Var); 3742 VarDecl *PatternDecl = nullptr, *Def = nullptr; 3743 MultiLevelTemplateArgumentList TemplateArgs = 3744 getTemplateInstantiationArgs(Var); 3745 3746 if (VarSpec) { 3747 // If this is a variable template specialization, make sure that it is 3748 // non-dependent, then find its instantiation pattern. 3749 bool InstantiationDependent = false; 3750 assert(!TemplateSpecializationType::anyDependentTemplateArguments( 3751 VarSpec->getTemplateArgsInfo(), InstantiationDependent) && 3752 "Only instantiate variable template specializations that are " 3753 "not type-dependent"); 3754 (void)InstantiationDependent; 3755 3756 // Find the variable initialization that we'll be substituting. If the 3757 // pattern was instantiated from a member template, look back further to 3758 // find the real pattern. 3759 assert(VarSpec->getSpecializedTemplate() && 3760 "Specialization without specialized template?"); 3761 llvm::PointerUnion<VarTemplateDecl *, 3762 VarTemplatePartialSpecializationDecl *> PatternPtr = 3763 VarSpec->getSpecializedTemplateOrPartial(); 3764 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) { 3765 VarTemplatePartialSpecializationDecl *Tmpl = 3766 PatternPtr.get<VarTemplatePartialSpecializationDecl *>(); 3767 while (VarTemplatePartialSpecializationDecl *From = 3768 Tmpl->getInstantiatedFromMember()) { 3769 if (Tmpl->isMemberSpecialization()) 3770 break; 3771 3772 Tmpl = From; 3773 } 3774 PatternDecl = Tmpl; 3775 } else { 3776 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>(); 3777 while (VarTemplateDecl *From = 3778 Tmpl->getInstantiatedFromMemberTemplate()) { 3779 if (Tmpl->isMemberSpecialization()) 3780 break; 3781 3782 Tmpl = From; 3783 } 3784 PatternDecl = Tmpl->getTemplatedDecl(); 3785 } 3786 3787 // If this is a static data member template, there might be an 3788 // uninstantiated initializer on the declaration. If so, instantiate 3789 // it now. 3790 if (PatternDecl->isStaticDataMember() && 3791 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 3792 !Var->hasInit()) { 3793 // FIXME: Factor out the duplicated instantiation context setup/tear down 3794 // code here. 3795 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 3796 if (Inst.isInvalid()) 3797 return; 3798 3799 // If we're performing recursive template instantiation, create our own 3800 // queue of pending implicit instantiations that we will instantiate 3801 // later, while we're still within our own instantiation context. 3802 SmallVector<VTableUse, 16> SavedVTableUses; 3803 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 3804 if (Recursive) { 3805 VTableUses.swap(SavedVTableUses); 3806 PendingInstantiations.swap(SavedPendingInstantiations); 3807 } 3808 3809 LocalInstantiationScope Local(*this); 3810 3811 // Enter the scope of this instantiation. We don't use 3812 // PushDeclContext because we don't have a scope. 3813 ContextRAII PreviousContext(*this, Var->getDeclContext()); 3814 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 3815 PreviousContext.pop(); 3816 3817 // FIXME: Need to inform the ASTConsumer that we instantiated the 3818 // initializer? 3819 3820 // This variable may have local implicit instantiations that need to be 3821 // instantiated within this scope. 3822 PerformPendingInstantiations(/*LocalOnly=*/true); 3823 3824 Local.Exit(); 3825 3826 if (Recursive) { 3827 // Define any newly required vtables. 3828 DefineUsedVTables(); 3829 3830 // Instantiate any pending implicit instantiations found during the 3831 // instantiation of this template. 3832 PerformPendingInstantiations(); 3833 3834 // Restore the set of pending vtables. 3835 assert(VTableUses.empty() && 3836 "VTableUses should be empty before it is discarded."); 3837 VTableUses.swap(SavedVTableUses); 3838 3839 // Restore the set of pending implicit instantiations. 3840 assert(PendingInstantiations.empty() && 3841 "PendingInstantiations should be empty before it is discarded."); 3842 PendingInstantiations.swap(SavedPendingInstantiations); 3843 } 3844 } 3845 3846 // Find actual definition 3847 Def = PatternDecl->getDefinition(getASTContext()); 3848 } else { 3849 // If this is a static data member, find its out-of-line definition. 3850 assert(Var->isStaticDataMember() && "not a static data member?"); 3851 PatternDecl = Var->getInstantiatedFromStaticDataMember(); 3852 3853 assert(PatternDecl && "data member was not instantiated from a template?"); 3854 assert(PatternDecl->isStaticDataMember() && "not a static data member?"); 3855 Def = PatternDecl->getOutOfLineDefinition(); 3856 } 3857 3858 // If we don't have a definition of the variable template, we won't perform 3859 // any instantiation. Rather, we rely on the user to instantiate this 3860 // definition (or provide a specialization for it) in another translation 3861 // unit. 3862 if (!Def) { 3863 if (DefinitionRequired) { 3864 if (VarSpec) 3865 Diag(PointOfInstantiation, 3866 diag::err_explicit_instantiation_undefined_var_template) << Var; 3867 else 3868 Diag(PointOfInstantiation, 3869 diag::err_explicit_instantiation_undefined_member) 3870 << 2 << Var->getDeclName() << Var->getDeclContext(); 3871 Diag(PatternDecl->getLocation(), 3872 diag::note_explicit_instantiation_here); 3873 if (VarSpec) 3874 Var->setInvalidDecl(); 3875 } else if (Var->getTemplateSpecializationKind() 3876 == TSK_ExplicitInstantiationDefinition) { 3877 PendingInstantiations.push_back( 3878 std::make_pair(Var, PointOfInstantiation)); 3879 } 3880 3881 return; 3882 } 3883 3884 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 3885 3886 // Never instantiate an explicit specialization. 3887 if (TSK == TSK_ExplicitSpecialization) 3888 return; 3889 3890 // C++11 [temp.explicit]p10: 3891 // Except for inline functions, [...] explicit instantiation declarations 3892 // have the effect of suppressing the implicit instantiation of the entity 3893 // to which they refer. 3894 if (TSK == TSK_ExplicitInstantiationDeclaration) 3895 return; 3896 3897 // Make sure to pass the instantiated variable to the consumer at the end. 3898 struct PassToConsumerRAII { 3899 ASTConsumer &Consumer; 3900 VarDecl *Var; 3901 3902 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 3903 : Consumer(Consumer), Var(Var) { } 3904 3905 ~PassToConsumerRAII() { 3906 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 3907 } 3908 } PassToConsumerRAII(Consumer, Var); 3909 3910 // If we already have a definition, we're done. 3911 if (VarDecl *Def = Var->getDefinition()) { 3912 // We may be explicitly instantiating something we've already implicitly 3913 // instantiated. 3914 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 3915 PointOfInstantiation); 3916 return; 3917 } 3918 3919 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 3920 if (Inst.isInvalid()) 3921 return; 3922 3923 // If we're performing recursive template instantiation, create our own 3924 // queue of pending implicit instantiations that we will instantiate later, 3925 // while we're still within our own instantiation context. 3926 SmallVector<VTableUse, 16> SavedVTableUses; 3927 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; 3928 SavePendingLocalImplicitInstantiationsRAII 3929 SavedPendingLocalImplicitInstantiations(*this); 3930 if (Recursive) { 3931 VTableUses.swap(SavedVTableUses); 3932 PendingInstantiations.swap(SavedPendingInstantiations); 3933 } 3934 3935 // Enter the scope of this instantiation. We don't use 3936 // PushDeclContext because we don't have a scope. 3937 ContextRAII PreviousContext(*this, Var->getDeclContext()); 3938 LocalInstantiationScope Local(*this); 3939 3940 VarDecl *OldVar = Var; 3941 if (!VarSpec) 3942 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 3943 TemplateArgs)); 3944 else if (Var->isStaticDataMember() && 3945 Var->getLexicalDeclContext()->isRecord()) { 3946 // We need to instantiate the definition of a static data member template, 3947 // and all we have is the in-class declaration of it. Instantiate a separate 3948 // declaration of the definition. 3949 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 3950 TemplateArgs); 3951 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 3952 VarSpec->getSpecializedTemplate(), Def, nullptr, 3953 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray())); 3954 if (Var) { 3955 llvm::PointerUnion<VarTemplateDecl *, 3956 VarTemplatePartialSpecializationDecl *> PatternPtr = 3957 VarSpec->getSpecializedTemplateOrPartial(); 3958 if (VarTemplatePartialSpecializationDecl *Partial = 3959 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 3960 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 3961 Partial, &VarSpec->getTemplateInstantiationArgs()); 3962 3963 // Merge the definition with the declaration. 3964 LookupResult R(*this, Var->getDeclName(), Var->getLocation(), 3965 LookupOrdinaryName, ForRedeclaration); 3966 R.addDecl(OldVar); 3967 MergeVarDecl(Var, R); 3968 3969 // Attach the initializer. 3970 InstantiateVariableInitializer(Var, Def, TemplateArgs); 3971 } 3972 } else 3973 // Complete the existing variable's definition with an appropriately 3974 // substituted type and initializer. 3975 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 3976 3977 PreviousContext.pop(); 3978 3979 if (Var) { 3980 PassToConsumerRAII.Var = Var; 3981 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 3982 OldVar->getPointOfInstantiation()); 3983 } 3984 3985 // This variable may have local implicit instantiations that need to be 3986 // instantiated within this scope. 3987 PerformPendingInstantiations(/*LocalOnly=*/true); 3988 3989 Local.Exit(); 3990 3991 if (Recursive) { 3992 // Define any newly required vtables. 3993 DefineUsedVTables(); 3994 3995 // Instantiate any pending implicit instantiations found during the 3996 // instantiation of this template. 3997 PerformPendingInstantiations(); 3998 3999 // Restore the set of pending vtables. 4000 assert(VTableUses.empty() && 4001 "VTableUses should be empty before it is discarded."); 4002 VTableUses.swap(SavedVTableUses); 4003 4004 // Restore the set of pending implicit instantiations. 4005 assert(PendingInstantiations.empty() && 4006 "PendingInstantiations should be empty before it is discarded."); 4007 PendingInstantiations.swap(SavedPendingInstantiations); 4008 } 4009 } 4010 4011 void 4012 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 4013 const CXXConstructorDecl *Tmpl, 4014 const MultiLevelTemplateArgumentList &TemplateArgs) { 4015 4016 SmallVector<CXXCtorInitializer*, 4> NewInits; 4017 bool AnyErrors = Tmpl->isInvalidDecl(); 4018 4019 // Instantiate all the initializers. 4020 for (const auto *Init : Tmpl->inits()) { 4021 // Only instantiate written initializers, let Sema re-construct implicit 4022 // ones. 4023 if (!Init->isWritten()) 4024 continue; 4025 4026 SourceLocation EllipsisLoc; 4027 4028 if (Init->isPackExpansion()) { 4029 // This is a pack expansion. We should expand it now. 4030 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 4031 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 4032 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 4033 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 4034 bool ShouldExpand = false; 4035 bool RetainExpansion = false; 4036 Optional<unsigned> NumExpansions; 4037 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 4038 BaseTL.getSourceRange(), 4039 Unexpanded, 4040 TemplateArgs, ShouldExpand, 4041 RetainExpansion, 4042 NumExpansions)) { 4043 AnyErrors = true; 4044 New->setInvalidDecl(); 4045 continue; 4046 } 4047 assert(ShouldExpand && "Partial instantiation of base initializer?"); 4048 4049 // Loop over all of the arguments in the argument pack(s), 4050 for (unsigned I = 0; I != *NumExpansions; ++I) { 4051 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 4052 4053 // Instantiate the initializer. 4054 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4055 /*CXXDirectInit=*/true); 4056 if (TempInit.isInvalid()) { 4057 AnyErrors = true; 4058 break; 4059 } 4060 4061 // Instantiate the base type. 4062 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 4063 TemplateArgs, 4064 Init->getSourceLocation(), 4065 New->getDeclName()); 4066 if (!BaseTInfo) { 4067 AnyErrors = true; 4068 break; 4069 } 4070 4071 // Build the initializer. 4072 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 4073 BaseTInfo, TempInit.get(), 4074 New->getParent(), 4075 SourceLocation()); 4076 if (NewInit.isInvalid()) { 4077 AnyErrors = true; 4078 break; 4079 } 4080 4081 NewInits.push_back(NewInit.get()); 4082 } 4083 4084 continue; 4085 } 4086 4087 // Instantiate the initializer. 4088 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4089 /*CXXDirectInit=*/true); 4090 if (TempInit.isInvalid()) { 4091 AnyErrors = true; 4092 continue; 4093 } 4094 4095 MemInitResult NewInit; 4096 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 4097 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 4098 TemplateArgs, 4099 Init->getSourceLocation(), 4100 New->getDeclName()); 4101 if (!TInfo) { 4102 AnyErrors = true; 4103 New->setInvalidDecl(); 4104 continue; 4105 } 4106 4107 if (Init->isBaseInitializer()) 4108 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(), 4109 New->getParent(), EllipsisLoc); 4110 else 4111 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(), 4112 cast<CXXRecordDecl>(CurContext->getParent())); 4113 } else if (Init->isMemberInitializer()) { 4114 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 4115 Init->getMemberLocation(), 4116 Init->getMember(), 4117 TemplateArgs)); 4118 if (!Member) { 4119 AnyErrors = true; 4120 New->setInvalidDecl(); 4121 continue; 4122 } 4123 4124 NewInit = BuildMemberInitializer(Member, TempInit.get(), 4125 Init->getSourceLocation()); 4126 } else if (Init->isIndirectMemberInitializer()) { 4127 IndirectFieldDecl *IndirectMember = 4128 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 4129 Init->getMemberLocation(), 4130 Init->getIndirectMember(), TemplateArgs)); 4131 4132 if (!IndirectMember) { 4133 AnyErrors = true; 4134 New->setInvalidDecl(); 4135 continue; 4136 } 4137 4138 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(), 4139 Init->getSourceLocation()); 4140 } 4141 4142 if (NewInit.isInvalid()) { 4143 AnyErrors = true; 4144 New->setInvalidDecl(); 4145 } else { 4146 NewInits.push_back(NewInit.get()); 4147 } 4148 } 4149 4150 // Assign all the initializers to the new constructor. 4151 ActOnMemInitializers(New, 4152 /*FIXME: ColonLoc */ 4153 SourceLocation(), 4154 NewInits, 4155 AnyErrors); 4156 } 4157 4158 // TODO: this could be templated if the various decl types used the 4159 // same method name. 4160 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 4161 ClassTemplateDecl *Instance) { 4162 Pattern = Pattern->getCanonicalDecl(); 4163 4164 do { 4165 Instance = Instance->getCanonicalDecl(); 4166 if (Pattern == Instance) return true; 4167 Instance = Instance->getInstantiatedFromMemberTemplate(); 4168 } while (Instance); 4169 4170 return false; 4171 } 4172 4173 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 4174 FunctionTemplateDecl *Instance) { 4175 Pattern = Pattern->getCanonicalDecl(); 4176 4177 do { 4178 Instance = Instance->getCanonicalDecl(); 4179 if (Pattern == Instance) return true; 4180 Instance = Instance->getInstantiatedFromMemberTemplate(); 4181 } while (Instance); 4182 4183 return false; 4184 } 4185 4186 static bool 4187 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 4188 ClassTemplatePartialSpecializationDecl *Instance) { 4189 Pattern 4190 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 4191 do { 4192 Instance = cast<ClassTemplatePartialSpecializationDecl>( 4193 Instance->getCanonicalDecl()); 4194 if (Pattern == Instance) 4195 return true; 4196 Instance = Instance->getInstantiatedFromMember(); 4197 } while (Instance); 4198 4199 return false; 4200 } 4201 4202 static bool isInstantiationOf(CXXRecordDecl *Pattern, 4203 CXXRecordDecl *Instance) { 4204 Pattern = Pattern->getCanonicalDecl(); 4205 4206 do { 4207 Instance = Instance->getCanonicalDecl(); 4208 if (Pattern == Instance) return true; 4209 Instance = Instance->getInstantiatedFromMemberClass(); 4210 } while (Instance); 4211 4212 return false; 4213 } 4214 4215 static bool isInstantiationOf(FunctionDecl *Pattern, 4216 FunctionDecl *Instance) { 4217 Pattern = Pattern->getCanonicalDecl(); 4218 4219 do { 4220 Instance = Instance->getCanonicalDecl(); 4221 if (Pattern == Instance) return true; 4222 Instance = Instance->getInstantiatedFromMemberFunction(); 4223 } while (Instance); 4224 4225 return false; 4226 } 4227 4228 static bool isInstantiationOf(EnumDecl *Pattern, 4229 EnumDecl *Instance) { 4230 Pattern = Pattern->getCanonicalDecl(); 4231 4232 do { 4233 Instance = Instance->getCanonicalDecl(); 4234 if (Pattern == Instance) return true; 4235 Instance = Instance->getInstantiatedFromMemberEnum(); 4236 } while (Instance); 4237 4238 return false; 4239 } 4240 4241 static bool isInstantiationOf(UsingShadowDecl *Pattern, 4242 UsingShadowDecl *Instance, 4243 ASTContext &C) { 4244 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern; 4245 } 4246 4247 static bool isInstantiationOf(UsingDecl *Pattern, 4248 UsingDecl *Instance, 4249 ASTContext &C) { 4250 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 4251 } 4252 4253 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 4254 UsingDecl *Instance, 4255 ASTContext &C) { 4256 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 4257 } 4258 4259 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 4260 UsingDecl *Instance, 4261 ASTContext &C) { 4262 return C.getInstantiatedFromUsingDecl(Instance) == Pattern; 4263 } 4264 4265 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 4266 VarDecl *Instance) { 4267 assert(Instance->isStaticDataMember()); 4268 4269 Pattern = Pattern->getCanonicalDecl(); 4270 4271 do { 4272 Instance = Instance->getCanonicalDecl(); 4273 if (Pattern == Instance) return true; 4274 Instance = Instance->getInstantiatedFromStaticDataMember(); 4275 } while (Instance); 4276 4277 return false; 4278 } 4279 4280 // Other is the prospective instantiation 4281 // D is the prospective pattern 4282 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 4283 if (D->getKind() != Other->getKind()) { 4284 if (UnresolvedUsingTypenameDecl *UUD 4285 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 4286 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 4287 return isInstantiationOf(UUD, UD, Ctx); 4288 } 4289 } 4290 4291 if (UnresolvedUsingValueDecl *UUD 4292 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 4293 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 4294 return isInstantiationOf(UUD, UD, Ctx); 4295 } 4296 } 4297 4298 return false; 4299 } 4300 4301 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 4302 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 4303 4304 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 4305 return isInstantiationOf(cast<FunctionDecl>(D), Function); 4306 4307 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 4308 return isInstantiationOf(cast<EnumDecl>(D), Enum); 4309 4310 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 4311 if (Var->isStaticDataMember()) 4312 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 4313 4314 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 4315 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 4316 4317 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 4318 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 4319 4320 if (ClassTemplatePartialSpecializationDecl *PartialSpec 4321 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 4322 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 4323 PartialSpec); 4324 4325 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 4326 if (!Field->getDeclName()) { 4327 // This is an unnamed field. 4328 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) == 4329 cast<FieldDecl>(D); 4330 } 4331 } 4332 4333 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 4334 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 4335 4336 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 4337 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 4338 4339 return D->getDeclName() && isa<NamedDecl>(Other) && 4340 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 4341 } 4342 4343 template<typename ForwardIterator> 4344 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 4345 NamedDecl *D, 4346 ForwardIterator first, 4347 ForwardIterator last) { 4348 for (; first != last; ++first) 4349 if (isInstantiationOf(Ctx, D, *first)) 4350 return cast<NamedDecl>(*first); 4351 4352 return nullptr; 4353 } 4354 4355 /// \brief Finds the instantiation of the given declaration context 4356 /// within the current instantiation. 4357 /// 4358 /// \returns NULL if there was an error 4359 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 4360 const MultiLevelTemplateArgumentList &TemplateArgs) { 4361 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 4362 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 4363 return cast_or_null<DeclContext>(ID); 4364 } else return DC; 4365 } 4366 4367 /// \brief Find the instantiation of the given declaration within the 4368 /// current instantiation. 4369 /// 4370 /// This routine is intended to be used when \p D is a declaration 4371 /// referenced from within a template, that needs to mapped into the 4372 /// corresponding declaration within an instantiation. For example, 4373 /// given: 4374 /// 4375 /// \code 4376 /// template<typename T> 4377 /// struct X { 4378 /// enum Kind { 4379 /// KnownValue = sizeof(T) 4380 /// }; 4381 /// 4382 /// bool getKind() const { return KnownValue; } 4383 /// }; 4384 /// 4385 /// template struct X<int>; 4386 /// \endcode 4387 /// 4388 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the 4389 /// \p EnumConstantDecl for \p KnownValue (which refers to 4390 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation 4391 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs 4392 /// this mapping from within the instantiation of <tt>X<int></tt>. 4393 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 4394 const MultiLevelTemplateArgumentList &TemplateArgs) { 4395 DeclContext *ParentDC = D->getDeclContext(); 4396 // FIXME: Parmeters of pointer to functions (y below) that are themselves 4397 // parameters (p below) can have their ParentDC set to the translation-unit 4398 // - thus we can not consistently check if the ParentDC of such a parameter 4399 // is Dependent or/and a FunctionOrMethod. 4400 // For e.g. this code, during Template argument deduction tries to 4401 // find an instantiated decl for (T y) when the ParentDC for y is 4402 // the translation unit. 4403 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 4404 // float baz(float(*)()) { return 0.0; } 4405 // Foo(baz); 4406 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 4407 // it gets here, always has a FunctionOrMethod as its ParentDC?? 4408 // For now: 4409 // - as long as we have a ParmVarDecl whose parent is non-dependent and 4410 // whose type is not instantiation dependent, do nothing to the decl 4411 // - otherwise find its instantiated decl. 4412 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() && 4413 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 4414 return D; 4415 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 4416 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 4417 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) || 4418 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 4419 // D is a local of some kind. Look into the map of local 4420 // declarations to their instantiations. 4421 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 4422 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found 4423 = CurrentInstantiationScope->findInstantiationOf(D); 4424 4425 if (Found) { 4426 if (Decl *FD = Found->dyn_cast<Decl *>()) 4427 return cast<NamedDecl>(FD); 4428 4429 int PackIdx = ArgumentPackSubstitutionIndex; 4430 assert(PackIdx != -1 && "found declaration pack but not pack expanding"); 4431 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 4432 } 4433 4434 // If we're performing a partial substitution during template argument 4435 // deduction, we may not have values for template parameters yet. They 4436 // just map to themselves. 4437 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 4438 isa<TemplateTemplateParmDecl>(D)) 4439 return D; 4440 4441 if (D->isInvalidDecl()) 4442 return nullptr; 4443 4444 // If we didn't find the decl, then we must have a label decl that hasn't 4445 // been found yet. Lazily instantiate it and return it now. 4446 assert(isa<LabelDecl>(D)); 4447 4448 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 4449 assert(Inst && "Failed to instantiate label??"); 4450 4451 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 4452 return cast<LabelDecl>(Inst); 4453 } 4454 4455 // For variable template specializations, update those that are still 4456 // type-dependent. 4457 if (VarTemplateSpecializationDecl *VarSpec = 4458 dyn_cast<VarTemplateSpecializationDecl>(D)) { 4459 bool InstantiationDependent = false; 4460 const TemplateArgumentListInfo &VarTemplateArgs = 4461 VarSpec->getTemplateArgsInfo(); 4462 if (TemplateSpecializationType::anyDependentTemplateArguments( 4463 VarTemplateArgs, InstantiationDependent)) 4464 D = cast<NamedDecl>( 4465 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs)); 4466 return D; 4467 } 4468 4469 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 4470 if (!Record->isDependentContext()) 4471 return D; 4472 4473 // Determine whether this record is the "templated" declaration describing 4474 // a class template or class template partial specialization. 4475 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 4476 if (ClassTemplate) 4477 ClassTemplate = ClassTemplate->getCanonicalDecl(); 4478 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 4479 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 4480 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 4481 4482 // Walk the current context to find either the record or an instantiation of 4483 // it. 4484 DeclContext *DC = CurContext; 4485 while (!DC->isFileContext()) { 4486 // If we're performing substitution while we're inside the template 4487 // definition, we'll find our own context. We're done. 4488 if (DC->Equals(Record)) 4489 return Record; 4490 4491 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 4492 // Check whether we're in the process of instantiating a class template 4493 // specialization of the template we're mapping. 4494 if (ClassTemplateSpecializationDecl *InstSpec 4495 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 4496 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 4497 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 4498 return InstRecord; 4499 } 4500 4501 // Check whether we're in the process of instantiating a member class. 4502 if (isInstantiationOf(Record, InstRecord)) 4503 return InstRecord; 4504 } 4505 4506 // Move to the outer template scope. 4507 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 4508 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 4509 DC = FD->getLexicalDeclContext(); 4510 continue; 4511 } 4512 } 4513 4514 DC = DC->getParent(); 4515 } 4516 4517 // Fall through to deal with other dependent record types (e.g., 4518 // anonymous unions in class templates). 4519 } 4520 4521 if (!ParentDC->isDependentContext()) 4522 return D; 4523 4524 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 4525 if (!ParentDC) 4526 return nullptr; 4527 4528 if (ParentDC != D->getDeclContext()) { 4529 // We performed some kind of instantiation in the parent context, 4530 // so now we need to look into the instantiated parent context to 4531 // find the instantiation of the declaration D. 4532 4533 // If our context used to be dependent, we may need to instantiate 4534 // it before performing lookup into that context. 4535 bool IsBeingInstantiated = false; 4536 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 4537 if (!Spec->isDependentContext()) { 4538 QualType T = Context.getTypeDeclType(Spec); 4539 const RecordType *Tag = T->getAs<RecordType>(); 4540 assert(Tag && "type of non-dependent record is not a RecordType"); 4541 if (Tag->isBeingDefined()) 4542 IsBeingInstantiated = true; 4543 if (!Tag->isBeingDefined() && 4544 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 4545 return nullptr; 4546 4547 ParentDC = Tag->getDecl(); 4548 } 4549 } 4550 4551 NamedDecl *Result = nullptr; 4552 if (D->getDeclName()) { 4553 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 4554 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 4555 } else { 4556 // Since we don't have a name for the entity we're looking for, 4557 // our only option is to walk through all of the declarations to 4558 // find that name. This will occur in a few cases: 4559 // 4560 // - anonymous struct/union within a template 4561 // - unnamed class/struct/union/enum within a template 4562 // 4563 // FIXME: Find a better way to find these instantiations! 4564 Result = findInstantiationOf(Context, D, 4565 ParentDC->decls_begin(), 4566 ParentDC->decls_end()); 4567 } 4568 4569 if (!Result) { 4570 if (isa<UsingShadowDecl>(D)) { 4571 // UsingShadowDecls can instantiate to nothing because of using hiding. 4572 } else if (Diags.hasErrorOccurred()) { 4573 // We've already complained about something, so most likely this 4574 // declaration failed to instantiate. There's no point in complaining 4575 // further, since this is normal in invalid code. 4576 } else if (IsBeingInstantiated) { 4577 // The class in which this member exists is currently being 4578 // instantiated, and we haven't gotten around to instantiating this 4579 // member yet. This can happen when the code uses forward declarations 4580 // of member classes, and introduces ordering dependencies via 4581 // template instantiation. 4582 Diag(Loc, diag::err_member_not_yet_instantiated) 4583 << D->getDeclName() 4584 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 4585 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 4586 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 4587 // This enumeration constant was found when the template was defined, 4588 // but can't be found in the instantiation. This can happen if an 4589 // unscoped enumeration member is explicitly specialized. 4590 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 4591 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 4592 TemplateArgs)); 4593 assert(Spec->getTemplateSpecializationKind() == 4594 TSK_ExplicitSpecialization); 4595 Diag(Loc, diag::err_enumerator_does_not_exist) 4596 << D->getDeclName() 4597 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 4598 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 4599 << Context.getTypeDeclType(Spec); 4600 } else { 4601 // We should have found something, but didn't. 4602 llvm_unreachable("Unable to find instantiation of declaration!"); 4603 } 4604 } 4605 4606 D = Result; 4607 } 4608 4609 return D; 4610 } 4611 4612 /// \brief Performs template instantiation for all implicit template 4613 /// instantiations we have seen until this point. 4614 void Sema::PerformPendingInstantiations(bool LocalOnly) { 4615 while (!PendingLocalImplicitInstantiations.empty() || 4616 (!LocalOnly && !PendingInstantiations.empty())) { 4617 PendingImplicitInstantiation Inst; 4618 4619 if (PendingLocalImplicitInstantiations.empty()) { 4620 Inst = PendingInstantiations.front(); 4621 PendingInstantiations.pop_front(); 4622 } else { 4623 Inst = PendingLocalImplicitInstantiations.front(); 4624 PendingLocalImplicitInstantiations.pop_front(); 4625 } 4626 4627 // Instantiate function definitions 4628 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 4629 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(), 4630 "instantiating function definition"); 4631 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 4632 TSK_ExplicitInstantiationDefinition; 4633 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true, 4634 DefinitionRequired); 4635 continue; 4636 } 4637 4638 // Instantiate variable definitions 4639 VarDecl *Var = cast<VarDecl>(Inst.first); 4640 4641 assert((Var->isStaticDataMember() || 4642 isa<VarTemplateSpecializationDecl>(Var)) && 4643 "Not a static data member, nor a variable template" 4644 " specialization?"); 4645 4646 // Don't try to instantiate declarations if the most recent redeclaration 4647 // is invalid. 4648 if (Var->getMostRecentDecl()->isInvalidDecl()) 4649 continue; 4650 4651 // Check if the most recent declaration has changed the specialization kind 4652 // and removed the need for implicit instantiation. 4653 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) { 4654 case TSK_Undeclared: 4655 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 4656 case TSK_ExplicitInstantiationDeclaration: 4657 case TSK_ExplicitSpecialization: 4658 continue; // No longer need to instantiate this type. 4659 case TSK_ExplicitInstantiationDefinition: 4660 // We only need an instantiation if the pending instantiation *is* the 4661 // explicit instantiation. 4662 if (Var != Var->getMostRecentDecl()) continue; 4663 case TSK_ImplicitInstantiation: 4664 break; 4665 } 4666 4667 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(), 4668 "instantiating variable definition"); 4669 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 4670 TSK_ExplicitInstantiationDefinition; 4671 4672 // Instantiate static data member definitions or variable template 4673 // specializations. 4674 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 4675 DefinitionRequired); 4676 } 4677 } 4678 4679 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 4680 const MultiLevelTemplateArgumentList &TemplateArgs) { 4681 for (auto DD : Pattern->ddiags()) { 4682 switch (DD->getKind()) { 4683 case DependentDiagnostic::Access: 4684 HandleDependentAccessCheck(*DD, TemplateArgs); 4685 break; 4686 } 4687 } 4688 } 4689