1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/ 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 //===----------------------------------------------------------------------===/ 7 // 8 // This file implements C++ template instantiation for declarations. 9 // 10 //===----------------------------------------------------------------------===/ 11 #include "clang/Sema/SemaInternal.h" 12 #include "clang/AST/ASTConsumer.h" 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/ASTMutationListener.h" 15 #include "clang/AST/DeclTemplate.h" 16 #include "clang/AST/DeclVisitor.h" 17 #include "clang/AST/DependentDiagnostic.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/PrettyDeclStackTrace.h" 21 #include "clang/AST/TypeLoc.h" 22 #include "clang/Sema/Initialization.h" 23 #include "clang/Sema/Lookup.h" 24 #include "clang/Sema/Template.h" 25 #include "clang/Sema/TemplateInstCallback.h" 26 #include "llvm/Support/TimeProfiler.h" 27 28 using namespace clang; 29 30 static bool isDeclWithinFunction(const Decl *D) { 31 const DeclContext *DC = D->getDeclContext(); 32 if (DC->isFunctionOrMethod()) 33 return true; 34 35 if (DC->isRecord()) 36 return cast<CXXRecordDecl>(DC)->isLocalClass(); 37 38 return false; 39 } 40 41 template<typename DeclT> 42 static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl, 43 const MultiLevelTemplateArgumentList &TemplateArgs) { 44 if (!OldDecl->getQualifierLoc()) 45 return false; 46 47 assert((NewDecl->getFriendObjectKind() || 48 !OldDecl->getLexicalDeclContext()->isDependentContext()) && 49 "non-friend with qualified name defined in dependent context"); 50 Sema::ContextRAII SavedContext( 51 SemaRef, 52 const_cast<DeclContext *>(NewDecl->getFriendObjectKind() 53 ? NewDecl->getLexicalDeclContext() 54 : OldDecl->getLexicalDeclContext())); 55 56 NestedNameSpecifierLoc NewQualifierLoc 57 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(), 58 TemplateArgs); 59 60 if (!NewQualifierLoc) 61 return true; 62 63 NewDecl->setQualifierInfo(NewQualifierLoc); 64 return false; 65 } 66 67 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, 68 DeclaratorDecl *NewDecl) { 69 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); 70 } 71 72 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, 73 TagDecl *NewDecl) { 74 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); 75 } 76 77 // Include attribute instantiation code. 78 #include "clang/Sema/AttrTemplateInstantiate.inc" 79 80 static void instantiateDependentAlignedAttr( 81 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 82 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) { 83 if (Aligned->isAlignmentExpr()) { 84 // The alignment expression is a constant expression. 85 EnterExpressionEvaluationContext Unevaluated( 86 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 87 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs); 88 if (!Result.isInvalid()) 89 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion); 90 } else { 91 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(), 92 TemplateArgs, Aligned->getLocation(), 93 DeclarationName()); 94 if (Result) 95 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion); 96 } 97 } 98 99 static void instantiateDependentAlignedAttr( 100 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 101 const AlignedAttr *Aligned, Decl *New) { 102 if (!Aligned->isPackExpansion()) { 103 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 104 return; 105 } 106 107 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 108 if (Aligned->isAlignmentExpr()) 109 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(), 110 Unexpanded); 111 else 112 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(), 113 Unexpanded); 114 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); 115 116 // Determine whether we can expand this attribute pack yet. 117 bool Expand = true, RetainExpansion = false; 118 Optional<unsigned> NumExpansions; 119 // FIXME: Use the actual location of the ellipsis. 120 SourceLocation EllipsisLoc = Aligned->getLocation(); 121 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(), 122 Unexpanded, TemplateArgs, Expand, 123 RetainExpansion, NumExpansions)) 124 return; 125 126 if (!Expand) { 127 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1); 128 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true); 129 } else { 130 for (unsigned I = 0; I != *NumExpansions; ++I) { 131 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I); 132 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 133 } 134 } 135 } 136 137 static void instantiateDependentAssumeAlignedAttr( 138 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 139 const AssumeAlignedAttr *Aligned, Decl *New) { 140 // The alignment expression is a constant expression. 141 EnterExpressionEvaluationContext Unevaluated( 142 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 143 144 Expr *E, *OE = nullptr; 145 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs); 146 if (Result.isInvalid()) 147 return; 148 E = Result.getAs<Expr>(); 149 150 if (Aligned->getOffset()) { 151 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs); 152 if (Result.isInvalid()) 153 return; 154 OE = Result.getAs<Expr>(); 155 } 156 157 S.AddAssumeAlignedAttr(New, *Aligned, E, OE); 158 } 159 160 static void instantiateDependentAlignValueAttr( 161 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 162 const AlignValueAttr *Aligned, Decl *New) { 163 // The alignment expression is a constant expression. 164 EnterExpressionEvaluationContext Unevaluated( 165 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 166 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs); 167 if (!Result.isInvalid()) 168 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>()); 169 } 170 171 static void instantiateDependentAllocAlignAttr( 172 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 173 const AllocAlignAttr *Align, Decl *New) { 174 Expr *Param = IntegerLiteral::Create( 175 S.getASTContext(), 176 llvm::APInt(64, Align->getParamIndex().getSourceIndex()), 177 S.getASTContext().UnsignedLongLongTy, Align->getLocation()); 178 S.AddAllocAlignAttr(New, *Align, Param); 179 } 180 181 static Expr *instantiateDependentFunctionAttrCondition( 182 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 183 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) { 184 Expr *Cond = nullptr; 185 { 186 Sema::ContextRAII SwitchContext(S, New); 187 EnterExpressionEvaluationContext Unevaluated( 188 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 189 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs); 190 if (Result.isInvalid()) 191 return nullptr; 192 Cond = Result.getAs<Expr>(); 193 } 194 if (!Cond->isTypeDependent()) { 195 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 196 if (Converted.isInvalid()) 197 return nullptr; 198 Cond = Converted.get(); 199 } 200 201 SmallVector<PartialDiagnosticAt, 8> Diags; 202 if (OldCond->isValueDependent() && !Cond->isValueDependent() && 203 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) { 204 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A; 205 for (const auto &P : Diags) 206 S.Diag(P.first, P.second); 207 return nullptr; 208 } 209 return Cond; 210 } 211 212 static void instantiateDependentEnableIfAttr( 213 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 214 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) { 215 Expr *Cond = instantiateDependentFunctionAttrCondition( 216 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New); 217 218 if (Cond) 219 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA, 220 Cond, EIA->getMessage())); 221 } 222 223 static void instantiateDependentDiagnoseIfAttr( 224 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 225 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) { 226 Expr *Cond = instantiateDependentFunctionAttrCondition( 227 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New); 228 229 if (Cond) 230 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr( 231 S.getASTContext(), *DIA, Cond, DIA->getMessage(), 232 DIA->getDiagnosticType(), DIA->getArgDependent(), New)); 233 } 234 235 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using 236 // template A as the base and arguments from TemplateArgs. 237 static void instantiateDependentCUDALaunchBoundsAttr( 238 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 239 const CUDALaunchBoundsAttr &Attr, Decl *New) { 240 // The alignment expression is a constant expression. 241 EnterExpressionEvaluationContext Unevaluated( 242 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 243 244 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs); 245 if (Result.isInvalid()) 246 return; 247 Expr *MaxThreads = Result.getAs<Expr>(); 248 249 Expr *MinBlocks = nullptr; 250 if (Attr.getMinBlocks()) { 251 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs); 252 if (Result.isInvalid()) 253 return; 254 MinBlocks = Result.getAs<Expr>(); 255 } 256 257 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks); 258 } 259 260 static void 261 instantiateDependentModeAttr(Sema &S, 262 const MultiLevelTemplateArgumentList &TemplateArgs, 263 const ModeAttr &Attr, Decl *New) { 264 S.AddModeAttr(New, Attr, Attr.getMode(), 265 /*InInstantiation=*/true); 266 } 267 268 /// Instantiation of 'declare simd' attribute and its arguments. 269 static void instantiateOMPDeclareSimdDeclAttr( 270 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 271 const OMPDeclareSimdDeclAttr &Attr, Decl *New) { 272 // Allow 'this' in clauses with varlists. 273 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New)) 274 New = FTD->getTemplatedDecl(); 275 auto *FD = cast<FunctionDecl>(New); 276 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext()); 277 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps; 278 SmallVector<unsigned, 4> LinModifiers; 279 280 auto SubstExpr = [&](Expr *E) -> ExprResult { 281 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 282 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 283 Sema::ContextRAII SavedContext(S, FD); 284 LocalInstantiationScope Local(S); 285 if (FD->getNumParams() > PVD->getFunctionScopeIndex()) 286 Local.InstantiatedLocal( 287 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex())); 288 return S.SubstExpr(E, TemplateArgs); 289 } 290 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(), 291 FD->isCXXInstanceMember()); 292 return S.SubstExpr(E, TemplateArgs); 293 }; 294 295 // Substitute a single OpenMP clause, which is a potentially-evaluated 296 // full-expression. 297 auto Subst = [&](Expr *E) -> ExprResult { 298 EnterExpressionEvaluationContext Evaluated( 299 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 300 ExprResult Res = SubstExpr(E); 301 if (Res.isInvalid()) 302 return Res; 303 return S.ActOnFinishFullExpr(Res.get(), false); 304 }; 305 306 ExprResult Simdlen; 307 if (auto *E = Attr.getSimdlen()) 308 Simdlen = Subst(E); 309 310 if (Attr.uniforms_size() > 0) { 311 for(auto *E : Attr.uniforms()) { 312 ExprResult Inst = Subst(E); 313 if (Inst.isInvalid()) 314 continue; 315 Uniforms.push_back(Inst.get()); 316 } 317 } 318 319 auto AI = Attr.alignments_begin(); 320 for (auto *E : Attr.aligneds()) { 321 ExprResult Inst = Subst(E); 322 if (Inst.isInvalid()) 323 continue; 324 Aligneds.push_back(Inst.get()); 325 Inst = ExprEmpty(); 326 if (*AI) 327 Inst = S.SubstExpr(*AI, TemplateArgs); 328 Alignments.push_back(Inst.get()); 329 ++AI; 330 } 331 332 auto SI = Attr.steps_begin(); 333 for (auto *E : Attr.linears()) { 334 ExprResult Inst = Subst(E); 335 if (Inst.isInvalid()) 336 continue; 337 Linears.push_back(Inst.get()); 338 Inst = ExprEmpty(); 339 if (*SI) 340 Inst = S.SubstExpr(*SI, TemplateArgs); 341 Steps.push_back(Inst.get()); 342 ++SI; 343 } 344 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end()); 345 (void)S.ActOnOpenMPDeclareSimdDirective( 346 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(), 347 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps, 348 Attr.getRange()); 349 } 350 351 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr( 352 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 353 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) { 354 // Both min and max expression are constant expressions. 355 EnterExpressionEvaluationContext Unevaluated( 356 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 357 358 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs); 359 if (Result.isInvalid()) 360 return; 361 Expr *MinExpr = Result.getAs<Expr>(); 362 363 Result = S.SubstExpr(Attr.getMax(), TemplateArgs); 364 if (Result.isInvalid()) 365 return; 366 Expr *MaxExpr = Result.getAs<Expr>(); 367 368 S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr); 369 } 370 371 static ExplicitSpecifier 372 instantiateExplicitSpecifier(Sema &S, 373 const MultiLevelTemplateArgumentList &TemplateArgs, 374 ExplicitSpecifier ES, FunctionDecl *New) { 375 if (!ES.getExpr()) 376 return ES; 377 Expr *OldCond = ES.getExpr(); 378 Expr *Cond = nullptr; 379 { 380 EnterExpressionEvaluationContext Unevaluated( 381 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 382 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs); 383 if (SubstResult.isInvalid()) { 384 return ExplicitSpecifier::Invalid(); 385 } 386 Cond = SubstResult.get(); 387 } 388 ExplicitSpecifier Result(Cond, ES.getKind()); 389 if (!Cond->isTypeDependent()) 390 S.tryResolveExplicitSpecifier(Result); 391 return Result; 392 } 393 394 static void instantiateDependentAMDGPUWavesPerEUAttr( 395 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 396 const AMDGPUWavesPerEUAttr &Attr, Decl *New) { 397 // Both min and max expression are constant expressions. 398 EnterExpressionEvaluationContext Unevaluated( 399 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 400 401 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs); 402 if (Result.isInvalid()) 403 return; 404 Expr *MinExpr = Result.getAs<Expr>(); 405 406 Expr *MaxExpr = nullptr; 407 if (auto Max = Attr.getMax()) { 408 Result = S.SubstExpr(Max, TemplateArgs); 409 if (Result.isInvalid()) 410 return; 411 MaxExpr = Result.getAs<Expr>(); 412 } 413 414 S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr); 415 } 416 417 void Sema::InstantiateAttrsForDecl( 418 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl, 419 Decl *New, LateInstantiatedAttrVec *LateAttrs, 420 LocalInstantiationScope *OuterMostScope) { 421 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) { 422 for (const auto *TmplAttr : Tmpl->attrs()) { 423 // FIXME: If any of the special case versions from InstantiateAttrs become 424 // applicable to template declaration, we'll need to add them here. 425 CXXThisScopeRAII ThisScope( 426 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()), 427 Qualifiers(), ND->isCXXInstanceMember()); 428 429 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl( 430 TmplAttr, Context, *this, TemplateArgs); 431 if (NewAttr) 432 New->addAttr(NewAttr); 433 } 434 } 435 } 436 437 static Sema::RetainOwnershipKind 438 attrToRetainOwnershipKind(const Attr *A) { 439 switch (A->getKind()) { 440 case clang::attr::CFConsumed: 441 return Sema::RetainOwnershipKind::CF; 442 case clang::attr::OSConsumed: 443 return Sema::RetainOwnershipKind::OS; 444 case clang::attr::NSConsumed: 445 return Sema::RetainOwnershipKind::NS; 446 default: 447 llvm_unreachable("Wrong argument supplied"); 448 } 449 } 450 451 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 452 const Decl *Tmpl, Decl *New, 453 LateInstantiatedAttrVec *LateAttrs, 454 LocalInstantiationScope *OuterMostScope) { 455 for (const auto *TmplAttr : Tmpl->attrs()) { 456 // FIXME: This should be generalized to more than just the AlignedAttr. 457 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr); 458 if (Aligned && Aligned->isAlignmentDependent()) { 459 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New); 460 continue; 461 } 462 463 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) { 464 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New); 465 continue; 466 } 467 468 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) { 469 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New); 470 continue; 471 } 472 473 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) { 474 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New); 475 continue; 476 } 477 478 479 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) { 480 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl, 481 cast<FunctionDecl>(New)); 482 continue; 483 } 484 485 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) { 486 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl, 487 cast<FunctionDecl>(New)); 488 continue; 489 } 490 491 if (const auto *CUDALaunchBounds = 492 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) { 493 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs, 494 *CUDALaunchBounds, New); 495 continue; 496 } 497 498 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) { 499 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New); 500 continue; 501 } 502 503 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) { 504 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New); 505 continue; 506 } 507 508 if (const auto *AMDGPUFlatWorkGroupSize = 509 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) { 510 instantiateDependentAMDGPUFlatWorkGroupSizeAttr( 511 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New); 512 } 513 514 if (const auto *AMDGPUFlatWorkGroupSize = 515 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) { 516 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs, 517 *AMDGPUFlatWorkGroupSize, New); 518 } 519 520 // Existing DLL attribute on the instantiation takes precedence. 521 if (TmplAttr->getKind() == attr::DLLExport || 522 TmplAttr->getKind() == attr::DLLImport) { 523 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) { 524 continue; 525 } 526 } 527 528 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) { 529 AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI()); 530 continue; 531 } 532 533 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) || 534 isa<CFConsumedAttr>(TmplAttr)) { 535 AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr), 536 /*template instantiation=*/true); 537 continue; 538 } 539 540 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) { 541 if (!New->hasAttr<PointerAttr>()) 542 New->addAttr(A->clone(Context)); 543 continue; 544 } 545 546 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) { 547 if (!New->hasAttr<OwnerAttr>()) 548 New->addAttr(A->clone(Context)); 549 continue; 550 } 551 552 assert(!TmplAttr->isPackExpansion()); 553 if (TmplAttr->isLateParsed() && LateAttrs) { 554 // Late parsed attributes must be instantiated and attached after the 555 // enclosing class has been instantiated. See Sema::InstantiateClass. 556 LocalInstantiationScope *Saved = nullptr; 557 if (CurrentInstantiationScope) 558 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); 559 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); 560 } else { 561 // Allow 'this' within late-parsed attributes. 562 NamedDecl *ND = dyn_cast<NamedDecl>(New); 563 CXXRecordDecl *ThisContext = 564 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); 565 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), 566 ND && ND->isCXXInstanceMember()); 567 568 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, 569 *this, TemplateArgs); 570 if (NewAttr) 571 New->addAttr(NewAttr); 572 } 573 } 574 } 575 576 /// Get the previous declaration of a declaration for the purposes of template 577 /// instantiation. If this finds a previous declaration, then the previous 578 /// declaration of the instantiation of D should be an instantiation of the 579 /// result of this function. 580 template<typename DeclT> 581 static DeclT *getPreviousDeclForInstantiation(DeclT *D) { 582 DeclT *Result = D->getPreviousDecl(); 583 584 // If the declaration is within a class, and the previous declaration was 585 // merged from a different definition of that class, then we don't have a 586 // previous declaration for the purpose of template instantiation. 587 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) && 588 D->getLexicalDeclContext() != Result->getLexicalDeclContext()) 589 return nullptr; 590 591 return Result; 592 } 593 594 Decl * 595 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 596 llvm_unreachable("Translation units cannot be instantiated"); 597 } 598 599 Decl * 600 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) { 601 llvm_unreachable("pragma comment cannot be instantiated"); 602 } 603 604 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl( 605 PragmaDetectMismatchDecl *D) { 606 llvm_unreachable("pragma comment cannot be instantiated"); 607 } 608 609 Decl * 610 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) { 611 llvm_unreachable("extern \"C\" context cannot be instantiated"); 612 } 613 614 Decl * 615 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 616 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 617 D->getIdentifier()); 618 Owner->addDecl(Inst); 619 return Inst; 620 } 621 622 Decl * 623 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 624 llvm_unreachable("Namespaces cannot be instantiated"); 625 } 626 627 Decl * 628 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 629 NamespaceAliasDecl *Inst 630 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 631 D->getNamespaceLoc(), 632 D->getAliasLoc(), 633 D->getIdentifier(), 634 D->getQualifierLoc(), 635 D->getTargetNameLoc(), 636 D->getNamespace()); 637 Owner->addDecl(Inst); 638 return Inst; 639 } 640 641 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 642 bool IsTypeAlias) { 643 bool Invalid = false; 644 TypeSourceInfo *DI = D->getTypeSourceInfo(); 645 if (DI->getType()->isInstantiationDependentType() || 646 DI->getType()->isVariablyModifiedType()) { 647 DI = SemaRef.SubstType(DI, TemplateArgs, 648 D->getLocation(), D->getDeclName()); 649 if (!DI) { 650 Invalid = true; 651 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 652 } 653 } else { 654 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 655 } 656 657 // HACK: g++ has a bug where it gets the value kind of ?: wrong. 658 // libstdc++ relies upon this bug in its implementation of common_type. 659 // If we happen to be processing that implementation, fake up the g++ ?: 660 // semantics. See LWG issue 2141 for more information on the bug. 661 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>(); 662 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 663 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) && 664 DT->isReferenceType() && 665 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() && 666 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") && 667 D->getIdentifier() && D->getIdentifier()->isStr("type") && 668 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc())) 669 // Fold it to the (non-reference) type which g++ would have produced. 670 DI = SemaRef.Context.getTrivialTypeSourceInfo( 671 DI->getType().getNonReferenceType()); 672 673 // Create the new typedef 674 TypedefNameDecl *Typedef; 675 if (IsTypeAlias) 676 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(), 677 D->getLocation(), D->getIdentifier(), DI); 678 else 679 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(), 680 D->getLocation(), D->getIdentifier(), DI); 681 if (Invalid) 682 Typedef->setInvalidDecl(); 683 684 // If the old typedef was the name for linkage purposes of an anonymous 685 // tag decl, re-establish that relationship for the new typedef. 686 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 687 TagDecl *oldTag = oldTagType->getDecl(); 688 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) { 689 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 690 assert(!newTag->hasNameForLinkage()); 691 newTag->setTypedefNameForAnonDecl(Typedef); 692 } 693 } 694 695 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) { 696 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 697 TemplateArgs); 698 if (!InstPrev) 699 return nullptr; 700 701 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev); 702 703 // If the typedef types are not identical, reject them. 704 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); 705 706 Typedef->setPreviousDecl(InstPrevTypedef); 707 } 708 709 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); 710 711 if (D->getUnderlyingType()->getAs<DependentNameType>()) 712 SemaRef.inferGslPointerAttribute(Typedef); 713 714 Typedef->setAccess(D->getAccess()); 715 716 return Typedef; 717 } 718 719 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { 720 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); 721 if (Typedef) 722 Owner->addDecl(Typedef); 723 return Typedef; 724 } 725 726 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { 727 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); 728 if (Typedef) 729 Owner->addDecl(Typedef); 730 return Typedef; 731 } 732 733 Decl * 734 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 735 // Create a local instantiation scope for this type alias template, which 736 // will contain the instantiations of the template parameters. 737 LocalInstantiationScope Scope(SemaRef); 738 739 TemplateParameterList *TempParams = D->getTemplateParameters(); 740 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 741 if (!InstParams) 742 return nullptr; 743 744 TypeAliasDecl *Pattern = D->getTemplatedDecl(); 745 746 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr; 747 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) { 748 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 749 if (!Found.empty()) { 750 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front()); 751 } 752 } 753 754 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( 755 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); 756 if (!AliasInst) 757 return nullptr; 758 759 TypeAliasTemplateDecl *Inst 760 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(), 761 D->getDeclName(), InstParams, AliasInst); 762 AliasInst->setDescribedAliasTemplate(Inst); 763 if (PrevAliasTemplate) 764 Inst->setPreviousDecl(PrevAliasTemplate); 765 766 Inst->setAccess(D->getAccess()); 767 768 if (!PrevAliasTemplate) 769 Inst->setInstantiatedFromMemberTemplate(D); 770 771 Owner->addDecl(Inst); 772 773 return Inst; 774 } 775 776 Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) { 777 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(), 778 D->getIdentifier()); 779 NewBD->setReferenced(D->isReferenced()); 780 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD); 781 return NewBD; 782 } 783 784 Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) { 785 // Transform the bindings first. 786 SmallVector<BindingDecl*, 16> NewBindings; 787 for (auto *OldBD : D->bindings()) 788 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD))); 789 ArrayRef<BindingDecl*> NewBindingArray = NewBindings; 790 791 auto *NewDD = cast_or_null<DecompositionDecl>( 792 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray)); 793 794 if (!NewDD || NewDD->isInvalidDecl()) 795 for (auto *NewBD : NewBindings) 796 NewBD->setInvalidDecl(); 797 798 return NewDD; 799 } 800 801 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { 802 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false); 803 } 804 805 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, 806 bool InstantiatingVarTemplate, 807 ArrayRef<BindingDecl*> *Bindings) { 808 809 // Do substitution on the type of the declaration 810 TypeSourceInfo *DI = SemaRef.SubstType( 811 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(), 812 D->getDeclName(), /*AllowDeducedTST*/true); 813 if (!DI) 814 return nullptr; 815 816 if (DI->getType()->isFunctionType()) { 817 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 818 << D->isStaticDataMember() << DI->getType(); 819 return nullptr; 820 } 821 822 DeclContext *DC = Owner; 823 if (D->isLocalExternDecl()) 824 SemaRef.adjustContextForLocalExternDecl(DC); 825 826 // Build the instantiated declaration. 827 VarDecl *Var; 828 if (Bindings) 829 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 830 D->getLocation(), DI->getType(), DI, 831 D->getStorageClass(), *Bindings); 832 else 833 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(), 834 D->getLocation(), D->getIdentifier(), DI->getType(), 835 DI, D->getStorageClass()); 836 837 // In ARC, infer 'retaining' for variables of retainable type. 838 if (SemaRef.getLangOpts().ObjCAutoRefCount && 839 SemaRef.inferObjCARCLifetime(Var)) 840 Var->setInvalidDecl(); 841 842 // Substitute the nested name specifier, if any. 843 if (SubstQualifier(D, Var)) 844 return nullptr; 845 846 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 847 StartingScope, InstantiatingVarTemplate); 848 849 if (D->isNRVOVariable()) { 850 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType(); 851 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, Sema::CES_Strict)) 852 Var->setNRVOVariable(true); 853 } 854 855 Var->setImplicit(D->isImplicit()); 856 857 if (Var->isStaticLocal()) 858 SemaRef.CheckStaticLocalForDllExport(Var); 859 860 return Var; 861 } 862 863 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { 864 AccessSpecDecl* AD 865 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner, 866 D->getAccessSpecifierLoc(), D->getColonLoc()); 867 Owner->addHiddenDecl(AD); 868 return AD; 869 } 870 871 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { 872 bool Invalid = false; 873 TypeSourceInfo *DI = D->getTypeSourceInfo(); 874 if (DI->getType()->isInstantiationDependentType() || 875 DI->getType()->isVariablyModifiedType()) { 876 DI = SemaRef.SubstType(DI, TemplateArgs, 877 D->getLocation(), D->getDeclName()); 878 if (!DI) { 879 DI = D->getTypeSourceInfo(); 880 Invalid = true; 881 } else if (DI->getType()->isFunctionType()) { 882 // C++ [temp.arg.type]p3: 883 // If a declaration acquires a function type through a type 884 // dependent on a template-parameter and this causes a 885 // declaration that does not use the syntactic form of a 886 // function declarator to have function type, the program is 887 // ill-formed. 888 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 889 << DI->getType(); 890 Invalid = true; 891 } 892 } else { 893 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 894 } 895 896 Expr *BitWidth = D->getBitWidth(); 897 if (Invalid) 898 BitWidth = nullptr; 899 else if (BitWidth) { 900 // The bit-width expression is a constant expression. 901 EnterExpressionEvaluationContext Unevaluated( 902 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 903 904 ExprResult InstantiatedBitWidth 905 = SemaRef.SubstExpr(BitWidth, TemplateArgs); 906 if (InstantiatedBitWidth.isInvalid()) { 907 Invalid = true; 908 BitWidth = nullptr; 909 } else 910 BitWidth = InstantiatedBitWidth.getAs<Expr>(); 911 } 912 913 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(), 914 DI->getType(), DI, 915 cast<RecordDecl>(Owner), 916 D->getLocation(), 917 D->isMutable(), 918 BitWidth, 919 D->getInClassInitStyle(), 920 D->getInnerLocStart(), 921 D->getAccess(), 922 nullptr); 923 if (!Field) { 924 cast<Decl>(Owner)->setInvalidDecl(); 925 return nullptr; 926 } 927 928 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope); 929 930 if (Field->hasAttrs()) 931 SemaRef.CheckAlignasUnderalignment(Field); 932 933 if (Invalid) 934 Field->setInvalidDecl(); 935 936 if (!Field->getDeclName()) { 937 // Keep track of where this decl came from. 938 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D); 939 } 940 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { 941 if (Parent->isAnonymousStructOrUnion() && 942 Parent->getRedeclContext()->isFunctionOrMethod()) 943 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); 944 } 945 946 Field->setImplicit(D->isImplicit()); 947 Field->setAccess(D->getAccess()); 948 Owner->addDecl(Field); 949 950 return Field; 951 } 952 953 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) { 954 bool Invalid = false; 955 TypeSourceInfo *DI = D->getTypeSourceInfo(); 956 957 if (DI->getType()->isVariablyModifiedType()) { 958 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified) 959 << D; 960 Invalid = true; 961 } else if (DI->getType()->isInstantiationDependentType()) { 962 DI = SemaRef.SubstType(DI, TemplateArgs, 963 D->getLocation(), D->getDeclName()); 964 if (!DI) { 965 DI = D->getTypeSourceInfo(); 966 Invalid = true; 967 } else if (DI->getType()->isFunctionType()) { 968 // C++ [temp.arg.type]p3: 969 // If a declaration acquires a function type through a type 970 // dependent on a template-parameter and this causes a 971 // declaration that does not use the syntactic form of a 972 // function declarator to have function type, the program is 973 // ill-formed. 974 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) 975 << DI->getType(); 976 Invalid = true; 977 } 978 } else { 979 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 980 } 981 982 MSPropertyDecl *Property = MSPropertyDecl::Create( 983 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(), 984 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId()); 985 986 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs, 987 StartingScope); 988 989 if (Invalid) 990 Property->setInvalidDecl(); 991 992 Property->setAccess(D->getAccess()); 993 Owner->addDecl(Property); 994 995 return Property; 996 } 997 998 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 999 NamedDecl **NamedChain = 1000 new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; 1001 1002 int i = 0; 1003 for (auto *PI : D->chain()) { 1004 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI, 1005 TemplateArgs); 1006 if (!Next) 1007 return nullptr; 1008 1009 NamedChain[i++] = Next; 1010 } 1011 1012 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType(); 1013 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 1014 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T, 1015 {NamedChain, D->getChainingSize()}); 1016 1017 for (const auto *Attr : D->attrs()) 1018 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 1019 1020 IndirectField->setImplicit(D->isImplicit()); 1021 IndirectField->setAccess(D->getAccess()); 1022 Owner->addDecl(IndirectField); 1023 return IndirectField; 1024 } 1025 1026 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { 1027 // Handle friend type expressions by simply substituting template 1028 // parameters into the pattern type and checking the result. 1029 if (TypeSourceInfo *Ty = D->getFriendType()) { 1030 TypeSourceInfo *InstTy; 1031 // If this is an unsupported friend, don't bother substituting template 1032 // arguments into it. The actual type referred to won't be used by any 1033 // parts of Clang, and may not be valid for instantiating. Just use the 1034 // same info for the instantiated friend. 1035 if (D->isUnsupportedFriend()) { 1036 InstTy = Ty; 1037 } else { 1038 InstTy = SemaRef.SubstType(Ty, TemplateArgs, 1039 D->getLocation(), DeclarationName()); 1040 } 1041 if (!InstTy) 1042 return nullptr; 1043 1044 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(), 1045 D->getFriendLoc(), InstTy); 1046 if (!FD) 1047 return nullptr; 1048 1049 FD->setAccess(AS_public); 1050 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 1051 Owner->addDecl(FD); 1052 return FD; 1053 } 1054 1055 NamedDecl *ND = D->getFriendDecl(); 1056 assert(ND && "friend decl must be a decl or a type!"); 1057 1058 // All of the Visit implementations for the various potential friend 1059 // declarations have to be carefully written to work for friend 1060 // objects, with the most important detail being that the target 1061 // decl should almost certainly not be placed in Owner. 1062 Decl *NewND = Visit(ND); 1063 if (!NewND) return nullptr; 1064 1065 FriendDecl *FD = 1066 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), 1067 cast<NamedDecl>(NewND), D->getFriendLoc()); 1068 FD->setAccess(AS_public); 1069 FD->setUnsupportedFriend(D->isUnsupportedFriend()); 1070 Owner->addDecl(FD); 1071 return FD; 1072 } 1073 1074 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { 1075 Expr *AssertExpr = D->getAssertExpr(); 1076 1077 // The expression in a static assertion is a constant expression. 1078 EnterExpressionEvaluationContext Unevaluated( 1079 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1080 1081 ExprResult InstantiatedAssertExpr 1082 = SemaRef.SubstExpr(AssertExpr, TemplateArgs); 1083 if (InstantiatedAssertExpr.isInvalid()) 1084 return nullptr; 1085 1086 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(), 1087 InstantiatedAssertExpr.get(), 1088 D->getMessage(), 1089 D->getRParenLoc(), 1090 D->isFailed()); 1091 } 1092 1093 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { 1094 EnumDecl *PrevDecl = nullptr; 1095 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { 1096 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 1097 PatternPrev, 1098 TemplateArgs); 1099 if (!Prev) return nullptr; 1100 PrevDecl = cast<EnumDecl>(Prev); 1101 } 1102 1103 EnumDecl *Enum = 1104 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(), 1105 D->getLocation(), D->getIdentifier(), PrevDecl, 1106 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed()); 1107 if (D->isFixed()) { 1108 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { 1109 // If we have type source information for the underlying type, it means it 1110 // has been explicitly set by the user. Perform substitution on it before 1111 // moving on. 1112 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 1113 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc, 1114 DeclarationName()); 1115 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI)) 1116 Enum->setIntegerType(SemaRef.Context.IntTy); 1117 else 1118 Enum->setIntegerTypeSourceInfo(NewTI); 1119 } else { 1120 assert(!D->getIntegerType()->isDependentType() 1121 && "Dependent type without type source info"); 1122 Enum->setIntegerType(D->getIntegerType()); 1123 } 1124 } 1125 1126 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); 1127 1128 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation); 1129 Enum->setAccess(D->getAccess()); 1130 // Forward the mangling number from the template to the instantiated decl. 1131 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D)); 1132 // See if the old tag was defined along with a declarator. 1133 // If it did, mark the new tag as being associated with that declarator. 1134 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D)) 1135 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD); 1136 // See if the old tag was defined along with a typedef. 1137 // If it did, mark the new tag as being associated with that typedef. 1138 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D)) 1139 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND); 1140 if (SubstQualifier(D, Enum)) return nullptr; 1141 Owner->addDecl(Enum); 1142 1143 EnumDecl *Def = D->getDefinition(); 1144 if (Def && Def != D) { 1145 // If this is an out-of-line definition of an enum member template, check 1146 // that the underlying types match in the instantiation of both 1147 // declarations. 1148 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { 1149 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 1150 QualType DefnUnderlying = 1151 SemaRef.SubstType(TI->getType(), TemplateArgs, 1152 UnderlyingLoc, DeclarationName()); 1153 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(), 1154 DefnUnderlying, /*IsFixed=*/true, Enum); 1155 } 1156 } 1157 1158 // C++11 [temp.inst]p1: The implicit instantiation of a class template 1159 // specialization causes the implicit instantiation of the declarations, but 1160 // not the definitions of scoped member enumerations. 1161 // 1162 // DR1484 clarifies that enumeration definitions inside of a template 1163 // declaration aren't considered entities that can be separately instantiated 1164 // from the rest of the entity they are declared inside of. 1165 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) { 1166 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); 1167 InstantiateEnumDefinition(Enum, Def); 1168 } 1169 1170 return Enum; 1171 } 1172 1173 void TemplateDeclInstantiator::InstantiateEnumDefinition( 1174 EnumDecl *Enum, EnumDecl *Pattern) { 1175 Enum->startDefinition(); 1176 1177 // Update the location to refer to the definition. 1178 Enum->setLocation(Pattern->getLocation()); 1179 1180 SmallVector<Decl*, 4> Enumerators; 1181 1182 EnumConstantDecl *LastEnumConst = nullptr; 1183 for (auto *EC : Pattern->enumerators()) { 1184 // The specified value for the enumerator. 1185 ExprResult Value((Expr *)nullptr); 1186 if (Expr *UninstValue = EC->getInitExpr()) { 1187 // The enumerator's value expression is a constant expression. 1188 EnterExpressionEvaluationContext Unevaluated( 1189 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1190 1191 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs); 1192 } 1193 1194 // Drop the initial value and continue. 1195 bool isInvalid = false; 1196 if (Value.isInvalid()) { 1197 Value = nullptr; 1198 isInvalid = true; 1199 } 1200 1201 EnumConstantDecl *EnumConst 1202 = SemaRef.CheckEnumConstant(Enum, LastEnumConst, 1203 EC->getLocation(), EC->getIdentifier(), 1204 Value.get()); 1205 1206 if (isInvalid) { 1207 if (EnumConst) 1208 EnumConst->setInvalidDecl(); 1209 Enum->setInvalidDecl(); 1210 } 1211 1212 if (EnumConst) { 1213 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst); 1214 1215 EnumConst->setAccess(Enum->getAccess()); 1216 Enum->addDecl(EnumConst); 1217 Enumerators.push_back(EnumConst); 1218 LastEnumConst = EnumConst; 1219 1220 if (Pattern->getDeclContext()->isFunctionOrMethod() && 1221 !Enum->isScoped()) { 1222 // If the enumeration is within a function or method, record the enum 1223 // constant as a local. 1224 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst); 1225 } 1226 } 1227 } 1228 1229 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum, 1230 Enumerators, nullptr, ParsedAttributesView()); 1231 } 1232 1233 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { 1234 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls."); 1235 } 1236 1237 Decl * 1238 TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) { 1239 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated."); 1240 } 1241 1242 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { 1243 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1244 1245 // Create a local instantiation scope for this class template, which 1246 // will contain the instantiations of the template parameters. 1247 LocalInstantiationScope Scope(SemaRef); 1248 TemplateParameterList *TempParams = D->getTemplateParameters(); 1249 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1250 if (!InstParams) 1251 return nullptr; 1252 1253 CXXRecordDecl *Pattern = D->getTemplatedDecl(); 1254 1255 // Instantiate the qualifier. We have to do this first in case 1256 // we're a friend declaration, because if we are then we need to put 1257 // the new declaration in the appropriate context. 1258 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); 1259 if (QualifierLoc) { 1260 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1261 TemplateArgs); 1262 if (!QualifierLoc) 1263 return nullptr; 1264 } 1265 1266 CXXRecordDecl *PrevDecl = nullptr; 1267 ClassTemplateDecl *PrevClassTemplate = nullptr; 1268 1269 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) { 1270 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 1271 if (!Found.empty()) { 1272 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front()); 1273 if (PrevClassTemplate) 1274 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 1275 } 1276 } 1277 1278 // If this isn't a friend, then it's a member template, in which 1279 // case we just want to build the instantiation in the 1280 // specialization. If it is a friend, we want to build it in 1281 // the appropriate context. 1282 DeclContext *DC = Owner; 1283 if (isFriend) { 1284 if (QualifierLoc) { 1285 CXXScopeSpec SS; 1286 SS.Adopt(QualifierLoc); 1287 DC = SemaRef.computeDeclContext(SS); 1288 if (!DC) return nullptr; 1289 } else { 1290 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(), 1291 Pattern->getDeclContext(), 1292 TemplateArgs); 1293 } 1294 1295 // Look for a previous declaration of the template in the owning 1296 // context. 1297 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), 1298 Sema::LookupOrdinaryName, 1299 SemaRef.forRedeclarationInCurContext()); 1300 SemaRef.LookupQualifiedName(R, DC); 1301 1302 if (R.isSingleResult()) { 1303 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); 1304 if (PrevClassTemplate) 1305 PrevDecl = PrevClassTemplate->getTemplatedDecl(); 1306 } 1307 1308 if (!PrevClassTemplate && QualifierLoc) { 1309 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) 1310 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC 1311 << QualifierLoc.getSourceRange(); 1312 return nullptr; 1313 } 1314 1315 bool AdoptedPreviousTemplateParams = false; 1316 if (PrevClassTemplate) { 1317 bool Complain = true; 1318 1319 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class 1320 // template for struct std::tr1::__detail::_Map_base, where the 1321 // template parameters of the friend declaration don't match the 1322 // template parameters of the original declaration. In this one 1323 // case, we don't complain about the ill-formed friend 1324 // declaration. 1325 if (isFriend && Pattern->getIdentifier() && 1326 Pattern->getIdentifier()->isStr("_Map_base") && 1327 DC->isNamespace() && 1328 cast<NamespaceDecl>(DC)->getIdentifier() && 1329 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) { 1330 DeclContext *DCParent = DC->getParent(); 1331 if (DCParent->isNamespace() && 1332 cast<NamespaceDecl>(DCParent)->getIdentifier() && 1333 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) { 1334 if (cast<Decl>(DCParent)->isInStdNamespace()) 1335 Complain = false; 1336 } 1337 } 1338 1339 TemplateParameterList *PrevParams 1340 = PrevClassTemplate->getMostRecentDecl()->getTemplateParameters(); 1341 1342 // Make sure the parameter lists match. 1343 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams, 1344 Complain, 1345 Sema::TPL_TemplateMatch)) { 1346 if (Complain) 1347 return nullptr; 1348 1349 AdoptedPreviousTemplateParams = true; 1350 InstParams = PrevParams; 1351 } 1352 1353 // Do some additional validation, then merge default arguments 1354 // from the existing declarations. 1355 if (!AdoptedPreviousTemplateParams && 1356 SemaRef.CheckTemplateParameterList(InstParams, PrevParams, 1357 Sema::TPC_ClassTemplate)) 1358 return nullptr; 1359 } 1360 } 1361 1362 CXXRecordDecl *RecordInst = CXXRecordDecl::Create( 1363 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(), 1364 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl, 1365 /*DelayTypeCreation=*/true); 1366 1367 if (QualifierLoc) 1368 RecordInst->setQualifierInfo(QualifierLoc); 1369 1370 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs, 1371 StartingScope); 1372 1373 ClassTemplateDecl *Inst 1374 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(), 1375 D->getIdentifier(), InstParams, RecordInst); 1376 assert(!(isFriend && Owner->isDependentContext())); 1377 Inst->setPreviousDecl(PrevClassTemplate); 1378 1379 RecordInst->setDescribedClassTemplate(Inst); 1380 1381 if (isFriend) { 1382 if (PrevClassTemplate) 1383 Inst->setAccess(PrevClassTemplate->getAccess()); 1384 else 1385 Inst->setAccess(D->getAccess()); 1386 1387 Inst->setObjectOfFriendDecl(); 1388 // TODO: do we want to track the instantiation progeny of this 1389 // friend target decl? 1390 } else { 1391 Inst->setAccess(D->getAccess()); 1392 if (!PrevClassTemplate) 1393 Inst->setInstantiatedFromMemberTemplate(D); 1394 } 1395 1396 // Trigger creation of the type for the instantiation. 1397 SemaRef.Context.getInjectedClassNameType(RecordInst, 1398 Inst->getInjectedClassNameSpecialization()); 1399 1400 // Finish handling of friends. 1401 if (isFriend) { 1402 DC->makeDeclVisibleInContext(Inst); 1403 Inst->setLexicalDeclContext(Owner); 1404 RecordInst->setLexicalDeclContext(Owner); 1405 return Inst; 1406 } 1407 1408 if (D->isOutOfLine()) { 1409 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 1410 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); 1411 } 1412 1413 Owner->addDecl(Inst); 1414 1415 if (!PrevClassTemplate) { 1416 // Queue up any out-of-line partial specializations of this member 1417 // class template; the client will force their instantiation once 1418 // the enclosing class has been instantiated. 1419 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; 1420 D->getPartialSpecializations(PartialSpecs); 1421 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 1422 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 1423 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I])); 1424 } 1425 1426 return Inst; 1427 } 1428 1429 Decl * 1430 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( 1431 ClassTemplatePartialSpecializationDecl *D) { 1432 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 1433 1434 // Lookup the already-instantiated declaration in the instantiation 1435 // of the class template and return that. 1436 DeclContext::lookup_result Found 1437 = Owner->lookup(ClassTemplate->getDeclName()); 1438 if (Found.empty()) 1439 return nullptr; 1440 1441 ClassTemplateDecl *InstClassTemplate 1442 = dyn_cast<ClassTemplateDecl>(Found.front()); 1443 if (!InstClassTemplate) 1444 return nullptr; 1445 1446 if (ClassTemplatePartialSpecializationDecl *Result 1447 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) 1448 return Result; 1449 1450 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D); 1451 } 1452 1453 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) { 1454 assert(D->getTemplatedDecl()->isStaticDataMember() && 1455 "Only static data member templates are allowed."); 1456 1457 // Create a local instantiation scope for this variable template, which 1458 // will contain the instantiations of the template parameters. 1459 LocalInstantiationScope Scope(SemaRef); 1460 TemplateParameterList *TempParams = D->getTemplateParameters(); 1461 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1462 if (!InstParams) 1463 return nullptr; 1464 1465 VarDecl *Pattern = D->getTemplatedDecl(); 1466 VarTemplateDecl *PrevVarTemplate = nullptr; 1467 1468 if (getPreviousDeclForInstantiation(Pattern)) { 1469 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName()); 1470 if (!Found.empty()) 1471 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 1472 } 1473 1474 VarDecl *VarInst = 1475 cast_or_null<VarDecl>(VisitVarDecl(Pattern, 1476 /*InstantiatingVarTemplate=*/true)); 1477 if (!VarInst) return nullptr; 1478 1479 DeclContext *DC = Owner; 1480 1481 VarTemplateDecl *Inst = VarTemplateDecl::Create( 1482 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams, 1483 VarInst); 1484 VarInst->setDescribedVarTemplate(Inst); 1485 Inst->setPreviousDecl(PrevVarTemplate); 1486 1487 Inst->setAccess(D->getAccess()); 1488 if (!PrevVarTemplate) 1489 Inst->setInstantiatedFromMemberTemplate(D); 1490 1491 if (D->isOutOfLine()) { 1492 Inst->setLexicalDeclContext(D->getLexicalDeclContext()); 1493 VarInst->setLexicalDeclContext(D->getLexicalDeclContext()); 1494 } 1495 1496 Owner->addDecl(Inst); 1497 1498 if (!PrevVarTemplate) { 1499 // Queue up any out-of-line partial specializations of this member 1500 // variable template; the client will force their instantiation once 1501 // the enclosing class has been instantiated. 1502 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 1503 D->getPartialSpecializations(PartialSpecs); 1504 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) 1505 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) 1506 OutOfLineVarPartialSpecs.push_back( 1507 std::make_pair(Inst, PartialSpecs[I])); 1508 } 1509 1510 return Inst; 1511 } 1512 1513 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl( 1514 VarTemplatePartialSpecializationDecl *D) { 1515 assert(D->isStaticDataMember() && 1516 "Only static data member templates are allowed."); 1517 1518 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 1519 1520 // Lookup the already-instantiated declaration and return that. 1521 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName()); 1522 assert(!Found.empty() && "Instantiation found nothing?"); 1523 1524 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front()); 1525 assert(InstVarTemplate && "Instantiation did not find a variable template?"); 1526 1527 if (VarTemplatePartialSpecializationDecl *Result = 1528 InstVarTemplate->findPartialSpecInstantiatedFromMember(D)) 1529 return Result; 1530 1531 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D); 1532 } 1533 1534 Decl * 1535 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 1536 // Create a local instantiation scope for this function template, which 1537 // will contain the instantiations of the template parameters and then get 1538 // merged with the local instantiation scope for the function template 1539 // itself. 1540 LocalInstantiationScope Scope(SemaRef); 1541 1542 TemplateParameterList *TempParams = D->getTemplateParameters(); 1543 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 1544 if (!InstParams) 1545 return nullptr; 1546 1547 FunctionDecl *Instantiated = nullptr; 1548 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl())) 1549 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod, 1550 InstParams)); 1551 else 1552 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl( 1553 D->getTemplatedDecl(), 1554 InstParams)); 1555 1556 if (!Instantiated) 1557 return nullptr; 1558 1559 // Link the instantiated function template declaration to the function 1560 // template from which it was instantiated. 1561 FunctionTemplateDecl *InstTemplate 1562 = Instantiated->getDescribedFunctionTemplate(); 1563 InstTemplate->setAccess(D->getAccess()); 1564 assert(InstTemplate && 1565 "VisitFunctionDecl/CXXMethodDecl didn't create a template!"); 1566 1567 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); 1568 1569 // Link the instantiation back to the pattern *unless* this is a 1570 // non-definition friend declaration. 1571 if (!InstTemplate->getInstantiatedFromMemberTemplate() && 1572 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) 1573 InstTemplate->setInstantiatedFromMemberTemplate(D); 1574 1575 // Make declarations visible in the appropriate context. 1576 if (!isFriend) { 1577 Owner->addDecl(InstTemplate); 1578 } else if (InstTemplate->getDeclContext()->isRecord() && 1579 !getPreviousDeclForInstantiation(D)) { 1580 SemaRef.CheckFriendAccess(InstTemplate); 1581 } 1582 1583 return InstTemplate; 1584 } 1585 1586 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { 1587 CXXRecordDecl *PrevDecl = nullptr; 1588 if (D->isInjectedClassName()) 1589 PrevDecl = cast<CXXRecordDecl>(Owner); 1590 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { 1591 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(), 1592 PatternPrev, 1593 TemplateArgs); 1594 if (!Prev) return nullptr; 1595 PrevDecl = cast<CXXRecordDecl>(Prev); 1596 } 1597 1598 CXXRecordDecl *Record = CXXRecordDecl::Create( 1599 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(), 1600 D->getLocation(), D->getIdentifier(), PrevDecl); 1601 1602 // Substitute the nested name specifier, if any. 1603 if (SubstQualifier(D, Record)) 1604 return nullptr; 1605 1606 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs, 1607 StartingScope); 1608 1609 Record->setImplicit(D->isImplicit()); 1610 // FIXME: Check against AS_none is an ugly hack to work around the issue that 1611 // the tag decls introduced by friend class declarations don't have an access 1612 // specifier. Remove once this area of the code gets sorted out. 1613 if (D->getAccess() != AS_none) 1614 Record->setAccess(D->getAccess()); 1615 if (!D->isInjectedClassName()) 1616 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 1617 1618 // If the original function was part of a friend declaration, 1619 // inherit its namespace state. 1620 if (D->getFriendObjectKind()) 1621 Record->setObjectOfFriendDecl(); 1622 1623 // Make sure that anonymous structs and unions are recorded. 1624 if (D->isAnonymousStructOrUnion()) 1625 Record->setAnonymousStructOrUnion(true); 1626 1627 if (D->isLocalClass()) 1628 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); 1629 1630 // Forward the mangling number from the template to the instantiated decl. 1631 SemaRef.Context.setManglingNumber(Record, 1632 SemaRef.Context.getManglingNumber(D)); 1633 1634 // See if the old tag was defined along with a declarator. 1635 // If it did, mark the new tag as being associated with that declarator. 1636 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D)) 1637 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD); 1638 1639 // See if the old tag was defined along with a typedef. 1640 // If it did, mark the new tag as being associated with that typedef. 1641 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D)) 1642 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND); 1643 1644 Owner->addDecl(Record); 1645 1646 // DR1484 clarifies that the members of a local class are instantiated as part 1647 // of the instantiation of their enclosing entity. 1648 if (D->isCompleteDefinition() && D->isLocalClass()) { 1649 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef); 1650 1651 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs, 1652 TSK_ImplicitInstantiation, 1653 /*Complain=*/true); 1654 1655 // For nested local classes, we will instantiate the members when we 1656 // reach the end of the outermost (non-nested) local class. 1657 if (!D->isCXXClassMember()) 1658 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs, 1659 TSK_ImplicitInstantiation); 1660 1661 // This class may have local implicit instantiations that need to be 1662 // performed within this scope. 1663 LocalInstantiations.perform(); 1664 } 1665 1666 SemaRef.DiagnoseUnusedNestedTypedefs(Record); 1667 1668 return Record; 1669 } 1670 1671 /// Adjust the given function type for an instantiation of the 1672 /// given declaration, to cope with modifications to the function's type that 1673 /// aren't reflected in the type-source information. 1674 /// 1675 /// \param D The declaration we're instantiating. 1676 /// \param TInfo The already-instantiated type. 1677 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, 1678 FunctionDecl *D, 1679 TypeSourceInfo *TInfo) { 1680 const FunctionProtoType *OrigFunc 1681 = D->getType()->castAs<FunctionProtoType>(); 1682 const FunctionProtoType *NewFunc 1683 = TInfo->getType()->castAs<FunctionProtoType>(); 1684 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo()) 1685 return TInfo->getType(); 1686 1687 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo(); 1688 NewEPI.ExtInfo = OrigFunc->getExtInfo(); 1689 return Context.getFunctionType(NewFunc->getReturnType(), 1690 NewFunc->getParamTypes(), NewEPI); 1691 } 1692 1693 /// Normal class members are of more specific types and therefore 1694 /// don't make it here. This function serves three purposes: 1695 /// 1) instantiating function templates 1696 /// 2) substituting friend declarations 1697 /// 3) substituting deduction guide declarations for nested class templates 1698 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D, 1699 TemplateParameterList *TemplateParams) { 1700 // Check whether there is already a function template specialization for 1701 // this declaration. 1702 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 1703 if (FunctionTemplate && !TemplateParams) { 1704 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1705 1706 void *InsertPos = nullptr; 1707 FunctionDecl *SpecFunc 1708 = FunctionTemplate->findSpecialization(Innermost, InsertPos); 1709 1710 // If we already have a function template specialization, return it. 1711 if (SpecFunc) 1712 return SpecFunc; 1713 } 1714 1715 bool isFriend; 1716 if (FunctionTemplate) 1717 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 1718 else 1719 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 1720 1721 bool MergeWithParentScope = (TemplateParams != nullptr) || 1722 Owner->isFunctionOrMethod() || 1723 !(isa<Decl>(Owner) && 1724 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 1725 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 1726 1727 ExplicitSpecifier InstantiatedExplicitSpecifier; 1728 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) { 1729 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier( 1730 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide); 1731 if (InstantiatedExplicitSpecifier.isInvalid()) 1732 return nullptr; 1733 } 1734 1735 SmallVector<ParmVarDecl *, 4> Params; 1736 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 1737 if (!TInfo) 1738 return nullptr; 1739 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 1740 1741 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 1742 if (QualifierLoc) { 1743 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 1744 TemplateArgs); 1745 if (!QualifierLoc) 1746 return nullptr; 1747 } 1748 1749 // If we're instantiating a local function declaration, put the result 1750 // in the enclosing namespace; otherwise we need to find the instantiated 1751 // context. 1752 DeclContext *DC; 1753 if (D->isLocalExternDecl()) { 1754 DC = Owner; 1755 SemaRef.adjustContextForLocalExternDecl(DC); 1756 } else if (isFriend && QualifierLoc) { 1757 CXXScopeSpec SS; 1758 SS.Adopt(QualifierLoc); 1759 DC = SemaRef.computeDeclContext(SS); 1760 if (!DC) return nullptr; 1761 } else { 1762 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 1763 TemplateArgs); 1764 } 1765 1766 DeclarationNameInfo NameInfo 1767 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 1768 1769 FunctionDecl *Function; 1770 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) { 1771 Function = CXXDeductionGuideDecl::Create( 1772 SemaRef.Context, DC, D->getInnerLocStart(), 1773 InstantiatedExplicitSpecifier, NameInfo, T, TInfo, 1774 D->getSourceRange().getEnd()); 1775 if (DGuide->isCopyDeductionCandidate()) 1776 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate(); 1777 Function->setAccess(D->getAccess()); 1778 } else { 1779 Function = FunctionDecl::Create( 1780 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo, 1781 D->getCanonicalDecl()->getStorageClass(), D->isInlineSpecified(), 1782 D->hasWrittenPrototype(), D->getConstexprKind()); 1783 Function->setRangeEnd(D->getSourceRange().getEnd()); 1784 } 1785 1786 if (D->isInlined()) 1787 Function->setImplicitlyInline(); 1788 1789 if (QualifierLoc) 1790 Function->setQualifierInfo(QualifierLoc); 1791 1792 if (D->isLocalExternDecl()) 1793 Function->setLocalExternDecl(); 1794 1795 DeclContext *LexicalDC = Owner; 1796 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) { 1797 assert(D->getDeclContext()->isFileContext()); 1798 LexicalDC = D->getDeclContext(); 1799 } 1800 1801 Function->setLexicalDeclContext(LexicalDC); 1802 1803 // Attach the parameters 1804 for (unsigned P = 0; P < Params.size(); ++P) 1805 if (Params[P]) 1806 Params[P]->setOwningFunction(Function); 1807 Function->setParams(Params); 1808 1809 if (TemplateParams) { 1810 // Our resulting instantiation is actually a function template, since we 1811 // are substituting only the outer template parameters. For example, given 1812 // 1813 // template<typename T> 1814 // struct X { 1815 // template<typename U> friend void f(T, U); 1816 // }; 1817 // 1818 // X<int> x; 1819 // 1820 // We are instantiating the friend function template "f" within X<int>, 1821 // which means substituting int for T, but leaving "f" as a friend function 1822 // template. 1823 // Build the function template itself. 1824 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 1825 Function->getLocation(), 1826 Function->getDeclName(), 1827 TemplateParams, Function); 1828 Function->setDescribedFunctionTemplate(FunctionTemplate); 1829 1830 FunctionTemplate->setLexicalDeclContext(LexicalDC); 1831 1832 if (isFriend && D->isThisDeclarationADefinition()) { 1833 FunctionTemplate->setInstantiatedFromMemberTemplate( 1834 D->getDescribedFunctionTemplate()); 1835 } 1836 } else if (FunctionTemplate) { 1837 // Record this function template specialization. 1838 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 1839 Function->setFunctionTemplateSpecialization(FunctionTemplate, 1840 TemplateArgumentList::CreateCopy(SemaRef.Context, 1841 Innermost), 1842 /*InsertPos=*/nullptr); 1843 } else if (isFriend && D->isThisDeclarationADefinition()) { 1844 // Do not connect the friend to the template unless it's actually a 1845 // definition. We don't want non-template functions to be marked as being 1846 // template instantiations. 1847 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 1848 } 1849 1850 if (isFriend) 1851 Function->setObjectOfFriendDecl(); 1852 1853 if (InitFunctionInstantiation(Function, D)) 1854 Function->setInvalidDecl(); 1855 1856 bool IsExplicitSpecialization = false; 1857 1858 LookupResult Previous( 1859 SemaRef, Function->getDeclName(), SourceLocation(), 1860 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 1861 : Sema::LookupOrdinaryName, 1862 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration 1863 : SemaRef.forRedeclarationInCurContext()); 1864 1865 if (DependentFunctionTemplateSpecializationInfo *Info 1866 = D->getDependentSpecializationInfo()) { 1867 assert(isFriend && "non-friend has dependent specialization info?"); 1868 1869 // Instantiate the explicit template arguments. 1870 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1871 Info->getRAngleLoc()); 1872 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1873 ExplicitArgs, TemplateArgs)) 1874 return nullptr; 1875 1876 // Map the candidate templates to their instantiations. 1877 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 1878 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 1879 Info->getTemplate(I), 1880 TemplateArgs); 1881 if (!Temp) return nullptr; 1882 1883 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 1884 } 1885 1886 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1887 &ExplicitArgs, 1888 Previous)) 1889 Function->setInvalidDecl(); 1890 1891 IsExplicitSpecialization = true; 1892 } else if (const ASTTemplateArgumentListInfo *Info = 1893 D->getTemplateSpecializationArgsAsWritten()) { 1894 // The name of this function was written as a template-id. 1895 SemaRef.LookupQualifiedName(Previous, DC); 1896 1897 // Instantiate the explicit template arguments. 1898 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 1899 Info->getRAngleLoc()); 1900 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 1901 ExplicitArgs, TemplateArgs)) 1902 return nullptr; 1903 1904 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 1905 &ExplicitArgs, 1906 Previous)) 1907 Function->setInvalidDecl(); 1908 1909 IsExplicitSpecialization = true; 1910 } else if (TemplateParams || !FunctionTemplate) { 1911 // Look only into the namespace where the friend would be declared to 1912 // find a previous declaration. This is the innermost enclosing namespace, 1913 // as described in ActOnFriendFunctionDecl. 1914 SemaRef.LookupQualifiedName(Previous, DC); 1915 1916 // In C++, the previous declaration we find might be a tag type 1917 // (class or enum). In this case, the new declaration will hide the 1918 // tag type. Note that this does does not apply if we're declaring a 1919 // typedef (C++ [dcl.typedef]p4). 1920 if (Previous.isSingleTagDecl()) 1921 Previous.clear(); 1922 } 1923 1924 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous, 1925 IsExplicitSpecialization); 1926 1927 NamedDecl *PrincipalDecl = (TemplateParams 1928 ? cast<NamedDecl>(FunctionTemplate) 1929 : Function); 1930 1931 // If the original function was part of a friend declaration, 1932 // inherit its namespace state and add it to the owner. 1933 if (isFriend) { 1934 Function->setObjectOfFriendDecl(); 1935 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate()) 1936 FT->setObjectOfFriendDecl(); 1937 DC->makeDeclVisibleInContext(PrincipalDecl); 1938 1939 bool QueuedInstantiation = false; 1940 1941 // C++11 [temp.friend]p4 (DR329): 1942 // When a function is defined in a friend function declaration in a class 1943 // template, the function is instantiated when the function is odr-used. 1944 // The same restrictions on multiple declarations and definitions that 1945 // apply to non-template function declarations and definitions also apply 1946 // to these implicit definitions. 1947 if (D->isThisDeclarationADefinition()) { 1948 SemaRef.CheckForFunctionRedefinition(Function); 1949 if (!Function->isInvalidDecl()) { 1950 for (auto R : Function->redecls()) { 1951 if (R == Function) 1952 continue; 1953 1954 // If some prior declaration of this function has been used, we need 1955 // to instantiate its definition. 1956 if (!QueuedInstantiation && R->isUsed(false)) { 1957 if (MemberSpecializationInfo *MSInfo = 1958 Function->getMemberSpecializationInfo()) { 1959 if (MSInfo->getPointOfInstantiation().isInvalid()) { 1960 SourceLocation Loc = R->getLocation(); // FIXME 1961 MSInfo->setPointOfInstantiation(Loc); 1962 SemaRef.PendingLocalImplicitInstantiations.push_back( 1963 std::make_pair(Function, Loc)); 1964 QueuedInstantiation = true; 1965 } 1966 } 1967 } 1968 } 1969 } 1970 } 1971 1972 // Check the template parameter list against the previous declaration. The 1973 // goal here is to pick up default arguments added since the friend was 1974 // declared; we know the template parameter lists match, since otherwise 1975 // we would not have picked this template as the previous declaration. 1976 if (TemplateParams && FunctionTemplate->getPreviousDecl()) { 1977 SemaRef.CheckTemplateParameterList( 1978 TemplateParams, 1979 FunctionTemplate->getPreviousDecl()->getTemplateParameters(), 1980 Function->isThisDeclarationADefinition() 1981 ? Sema::TPC_FriendFunctionTemplateDefinition 1982 : Sema::TPC_FriendFunctionTemplate); 1983 } 1984 } 1985 1986 if (Function->isLocalExternDecl() && !Function->getPreviousDecl()) 1987 DC->makeDeclVisibleInContext(PrincipalDecl); 1988 1989 if (Function->isOverloadedOperator() && !DC->isRecord() && 1990 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 1991 PrincipalDecl->setNonMemberOperator(); 1992 1993 assert(!D->isDefaulted() && "only methods should be defaulted"); 1994 return Function; 1995 } 1996 1997 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl( 1998 CXXMethodDecl *D, TemplateParameterList *TemplateParams, 1999 Optional<const ASTTemplateArgumentListInfo *> 2000 ClassScopeSpecializationArgs) { 2001 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 2002 if (FunctionTemplate && !TemplateParams) { 2003 // We are creating a function template specialization from a function 2004 // template. Check whether there is already a function template 2005 // specialization for this particular set of template arguments. 2006 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 2007 2008 void *InsertPos = nullptr; 2009 FunctionDecl *SpecFunc 2010 = FunctionTemplate->findSpecialization(Innermost, InsertPos); 2011 2012 // If we already have a function template specialization, return it. 2013 if (SpecFunc) 2014 return SpecFunc; 2015 } 2016 2017 bool isFriend; 2018 if (FunctionTemplate) 2019 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 2020 else 2021 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 2022 2023 bool MergeWithParentScope = (TemplateParams != nullptr) || 2024 !(isa<Decl>(Owner) && 2025 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 2026 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 2027 2028 // Instantiate enclosing template arguments for friends. 2029 SmallVector<TemplateParameterList *, 4> TempParamLists; 2030 unsigned NumTempParamLists = 0; 2031 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 2032 TempParamLists.resize(NumTempParamLists); 2033 for (unsigned I = 0; I != NumTempParamLists; ++I) { 2034 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 2035 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2036 if (!InstParams) 2037 return nullptr; 2038 TempParamLists[I] = InstParams; 2039 } 2040 } 2041 2042 ExplicitSpecifier InstantiatedExplicitSpecifier = 2043 instantiateExplicitSpecifier(SemaRef, TemplateArgs, 2044 ExplicitSpecifier::getFromDecl(D), D); 2045 if (InstantiatedExplicitSpecifier.isInvalid()) 2046 return nullptr; 2047 2048 SmallVector<ParmVarDecl *, 4> Params; 2049 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 2050 if (!TInfo) 2051 return nullptr; 2052 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 2053 2054 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 2055 if (QualifierLoc) { 2056 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 2057 TemplateArgs); 2058 if (!QualifierLoc) 2059 return nullptr; 2060 } 2061 2062 DeclContext *DC = Owner; 2063 if (isFriend) { 2064 if (QualifierLoc) { 2065 CXXScopeSpec SS; 2066 SS.Adopt(QualifierLoc); 2067 DC = SemaRef.computeDeclContext(SS); 2068 2069 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 2070 return nullptr; 2071 } else { 2072 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 2073 D->getDeclContext(), 2074 TemplateArgs); 2075 } 2076 if (!DC) return nullptr; 2077 } 2078 2079 // Build the instantiated method declaration. 2080 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 2081 CXXMethodDecl *Method = nullptr; 2082 2083 SourceLocation StartLoc = D->getInnerLocStart(); 2084 DeclarationNameInfo NameInfo 2085 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2086 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 2087 Method = CXXConstructorDecl::Create( 2088 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2089 InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false, 2090 Constructor->getConstexprKind()); 2091 Method->setRangeEnd(Constructor->getEndLoc()); 2092 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 2093 Method = CXXDestructorDecl::Create(SemaRef.Context, Record, 2094 StartLoc, NameInfo, T, TInfo, 2095 Destructor->isInlineSpecified(), 2096 false); 2097 Method->setRangeEnd(Destructor->getEndLoc()); 2098 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 2099 Method = CXXConversionDecl::Create( 2100 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2101 Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier, 2102 Conversion->getConstexprKind(), Conversion->getEndLoc()); 2103 } else { 2104 StorageClass SC = D->isStatic() ? SC_Static : SC_None; 2105 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo, 2106 T, TInfo, SC, D->isInlineSpecified(), 2107 D->getConstexprKind(), D->getEndLoc()); 2108 } 2109 2110 if (D->isInlined()) 2111 Method->setImplicitlyInline(); 2112 2113 if (QualifierLoc) 2114 Method->setQualifierInfo(QualifierLoc); 2115 2116 if (TemplateParams) { 2117 // Our resulting instantiation is actually a function template, since we 2118 // are substituting only the outer template parameters. For example, given 2119 // 2120 // template<typename T> 2121 // struct X { 2122 // template<typename U> void f(T, U); 2123 // }; 2124 // 2125 // X<int> x; 2126 // 2127 // We are instantiating the member template "f" within X<int>, which means 2128 // substituting int for T, but leaving "f" as a member function template. 2129 // Build the function template itself. 2130 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 2131 Method->getLocation(), 2132 Method->getDeclName(), 2133 TemplateParams, Method); 2134 if (isFriend) { 2135 FunctionTemplate->setLexicalDeclContext(Owner); 2136 FunctionTemplate->setObjectOfFriendDecl(); 2137 } else if (D->isOutOfLine()) 2138 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 2139 Method->setDescribedFunctionTemplate(FunctionTemplate); 2140 } else if (FunctionTemplate) { 2141 // Record this function template specialization. 2142 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 2143 Method->setFunctionTemplateSpecialization(FunctionTemplate, 2144 TemplateArgumentList::CreateCopy(SemaRef.Context, 2145 Innermost), 2146 /*InsertPos=*/nullptr); 2147 } else if (!isFriend) { 2148 // Record that this is an instantiation of a member function. 2149 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 2150 } 2151 2152 // If we are instantiating a member function defined 2153 // out-of-line, the instantiation will have the same lexical 2154 // context (which will be a namespace scope) as the template. 2155 if (isFriend) { 2156 if (NumTempParamLists) 2157 Method->setTemplateParameterListsInfo( 2158 SemaRef.Context, 2159 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists)); 2160 2161 Method->setLexicalDeclContext(Owner); 2162 Method->setObjectOfFriendDecl(); 2163 } else if (D->isOutOfLine()) 2164 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 2165 2166 // Attach the parameters 2167 for (unsigned P = 0; P < Params.size(); ++P) 2168 Params[P]->setOwningFunction(Method); 2169 Method->setParams(Params); 2170 2171 if (InitMethodInstantiation(Method, D)) 2172 Method->setInvalidDecl(); 2173 2174 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 2175 Sema::ForExternalRedeclaration); 2176 2177 bool IsExplicitSpecialization = false; 2178 2179 // If the name of this function was written as a template-id, instantiate 2180 // the explicit template arguments. 2181 if (DependentFunctionTemplateSpecializationInfo *Info 2182 = D->getDependentSpecializationInfo()) { 2183 assert(isFriend && "non-friend has dependent specialization info?"); 2184 2185 // Instantiate the explicit template arguments. 2186 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2187 Info->getRAngleLoc()); 2188 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 2189 ExplicitArgs, TemplateArgs)) 2190 return nullptr; 2191 2192 // Map the candidate templates to their instantiations. 2193 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 2194 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 2195 Info->getTemplate(I), 2196 TemplateArgs); 2197 if (!Temp) return nullptr; 2198 2199 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 2200 } 2201 2202 if (SemaRef.CheckFunctionTemplateSpecialization(Method, 2203 &ExplicitArgs, 2204 Previous)) 2205 Method->setInvalidDecl(); 2206 2207 IsExplicitSpecialization = true; 2208 } else if (const ASTTemplateArgumentListInfo *Info = 2209 ClassScopeSpecializationArgs.getValueOr( 2210 D->getTemplateSpecializationArgsAsWritten())) { 2211 SemaRef.LookupQualifiedName(Previous, DC); 2212 2213 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2214 Info->getRAngleLoc()); 2215 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 2216 ExplicitArgs, TemplateArgs)) 2217 return nullptr; 2218 2219 if (SemaRef.CheckFunctionTemplateSpecialization(Method, 2220 &ExplicitArgs, 2221 Previous)) 2222 Method->setInvalidDecl(); 2223 2224 IsExplicitSpecialization = true; 2225 } else if (ClassScopeSpecializationArgs) { 2226 // Class-scope explicit specialization written without explicit template 2227 // arguments. 2228 SemaRef.LookupQualifiedName(Previous, DC); 2229 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous)) 2230 Method->setInvalidDecl(); 2231 2232 IsExplicitSpecialization = true; 2233 } else if (!FunctionTemplate || TemplateParams || isFriend) { 2234 SemaRef.LookupQualifiedName(Previous, Record); 2235 2236 // In C++, the previous declaration we find might be a tag type 2237 // (class or enum). In this case, the new declaration will hide the 2238 // tag type. Note that this does does not apply if we're declaring a 2239 // typedef (C++ [dcl.typedef]p4). 2240 if (Previous.isSingleTagDecl()) 2241 Previous.clear(); 2242 } 2243 2244 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, 2245 IsExplicitSpecialization); 2246 2247 if (D->isPure()) 2248 SemaRef.CheckPureMethod(Method, SourceRange()); 2249 2250 // Propagate access. For a non-friend declaration, the access is 2251 // whatever we're propagating from. For a friend, it should be the 2252 // previous declaration we just found. 2253 if (isFriend && Method->getPreviousDecl()) 2254 Method->setAccess(Method->getPreviousDecl()->getAccess()); 2255 else 2256 Method->setAccess(D->getAccess()); 2257 if (FunctionTemplate) 2258 FunctionTemplate->setAccess(Method->getAccess()); 2259 2260 SemaRef.CheckOverrideControl(Method); 2261 2262 // If a function is defined as defaulted or deleted, mark it as such now. 2263 if (D->isExplicitlyDefaulted()) 2264 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 2265 if (D->isDeletedAsWritten()) 2266 SemaRef.SetDeclDeleted(Method, Method->getLocation()); 2267 2268 // If this is an explicit specialization, mark the implicitly-instantiated 2269 // template specialization as being an explicit specialization too. 2270 // FIXME: Is this necessary? 2271 if (IsExplicitSpecialization && !isFriend) 2272 SemaRef.CompleteMemberSpecialization(Method, Previous); 2273 2274 // If there's a function template, let our caller handle it. 2275 if (FunctionTemplate) { 2276 // do nothing 2277 2278 // Don't hide a (potentially) valid declaration with an invalid one. 2279 } else if (Method->isInvalidDecl() && !Previous.empty()) { 2280 // do nothing 2281 2282 // Otherwise, check access to friends and make them visible. 2283 } else if (isFriend) { 2284 // We only need to re-check access for methods which we didn't 2285 // manage to match during parsing. 2286 if (!D->getPreviousDecl()) 2287 SemaRef.CheckFriendAccess(Method); 2288 2289 Record->makeDeclVisibleInContext(Method); 2290 2291 // Otherwise, add the declaration. We don't need to do this for 2292 // class-scope specializations because we'll have matched them with 2293 // the appropriate template. 2294 } else { 2295 Owner->addDecl(Method); 2296 } 2297 2298 // PR17480: Honor the used attribute to instantiate member function 2299 // definitions 2300 if (Method->hasAttr<UsedAttr>()) { 2301 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) { 2302 SourceLocation Loc; 2303 if (const MemberSpecializationInfo *MSInfo = 2304 A->getMemberSpecializationInfo()) 2305 Loc = MSInfo->getPointOfInstantiation(); 2306 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A)) 2307 Loc = Spec->getPointOfInstantiation(); 2308 SemaRef.MarkFunctionReferenced(Loc, Method); 2309 } 2310 } 2311 2312 return Method; 2313 } 2314 2315 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 2316 return VisitCXXMethodDecl(D); 2317 } 2318 2319 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 2320 return VisitCXXMethodDecl(D); 2321 } 2322 2323 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 2324 return VisitCXXMethodDecl(D); 2325 } 2326 2327 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 2328 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None, 2329 /*ExpectParameterPack=*/ false); 2330 } 2331 2332 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 2333 TemplateTypeParmDecl *D) { 2334 // TODO: don't always clone when decls are refcounted. 2335 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 2336 2337 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create( 2338 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(), 2339 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(), 2340 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack()); 2341 Inst->setAccess(AS_public); 2342 Inst->setImplicit(D->isImplicit()); 2343 2344 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2345 TypeSourceInfo *InstantiatedDefaultArg = 2346 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, 2347 D->getDefaultArgumentLoc(), D->getDeclName()); 2348 if (InstantiatedDefaultArg) 2349 Inst->setDefaultArgument(InstantiatedDefaultArg); 2350 } 2351 2352 // Introduce this template parameter's instantiation into the instantiation 2353 // scope. 2354 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 2355 2356 return Inst; 2357 } 2358 2359 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 2360 NonTypeTemplateParmDecl *D) { 2361 // Substitute into the type of the non-type template parameter. 2362 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 2363 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 2364 SmallVector<QualType, 4> ExpandedParameterPackTypes; 2365 bool IsExpandedParameterPack = false; 2366 TypeSourceInfo *DI; 2367 QualType T; 2368 bool Invalid = false; 2369 2370 if (D->isExpandedParameterPack()) { 2371 // The non-type template parameter pack is an already-expanded pack 2372 // expansion of types. Substitute into each of the expanded types. 2373 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 2374 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 2375 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 2376 TypeSourceInfo *NewDI = 2377 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs, 2378 D->getLocation(), D->getDeclName()); 2379 if (!NewDI) 2380 return nullptr; 2381 2382 QualType NewT = 2383 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2384 if (NewT.isNull()) 2385 return nullptr; 2386 2387 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2388 ExpandedParameterPackTypes.push_back(NewT); 2389 } 2390 2391 IsExpandedParameterPack = true; 2392 DI = D->getTypeSourceInfo(); 2393 T = DI->getType(); 2394 } else if (D->isPackExpansion()) { 2395 // The non-type template parameter pack's type is a pack expansion of types. 2396 // Determine whether we need to expand this parameter pack into separate 2397 // types. 2398 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); 2399 TypeLoc Pattern = Expansion.getPatternLoc(); 2400 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2401 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 2402 2403 // Determine whether the set of unexpanded parameter packs can and should 2404 // be expanded. 2405 bool Expand = true; 2406 bool RetainExpansion = false; 2407 Optional<unsigned> OrigNumExpansions 2408 = Expansion.getTypePtr()->getNumExpansions(); 2409 Optional<unsigned> NumExpansions = OrigNumExpansions; 2410 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 2411 Pattern.getSourceRange(), 2412 Unexpanded, 2413 TemplateArgs, 2414 Expand, RetainExpansion, 2415 NumExpansions)) 2416 return nullptr; 2417 2418 if (Expand) { 2419 for (unsigned I = 0; I != *NumExpansions; ++I) { 2420 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2421 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 2422 D->getLocation(), 2423 D->getDeclName()); 2424 if (!NewDI) 2425 return nullptr; 2426 2427 QualType NewT = 2428 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2429 if (NewT.isNull()) 2430 return nullptr; 2431 2432 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2433 ExpandedParameterPackTypes.push_back(NewT); 2434 } 2435 2436 // Note that we have an expanded parameter pack. The "type" of this 2437 // expanded parameter pack is the original expansion type, but callers 2438 // will end up using the expanded parameter pack types for type-checking. 2439 IsExpandedParameterPack = true; 2440 DI = D->getTypeSourceInfo(); 2441 T = DI->getType(); 2442 } else { 2443 // We cannot fully expand the pack expansion now, so substitute into the 2444 // pattern and create a new pack expansion type. 2445 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2446 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 2447 D->getLocation(), 2448 D->getDeclName()); 2449 if (!NewPattern) 2450 return nullptr; 2451 2452 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation()); 2453 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 2454 NumExpansions); 2455 if (!DI) 2456 return nullptr; 2457 2458 T = DI->getType(); 2459 } 2460 } else { 2461 // Simple case: substitution into a parameter that is not a parameter pack. 2462 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 2463 D->getLocation(), D->getDeclName()); 2464 if (!DI) 2465 return nullptr; 2466 2467 // Check that this type is acceptable for a non-type template parameter. 2468 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation()); 2469 if (T.isNull()) { 2470 T = SemaRef.Context.IntTy; 2471 Invalid = true; 2472 } 2473 } 2474 2475 NonTypeTemplateParmDecl *Param; 2476 if (IsExpandedParameterPack) 2477 Param = NonTypeTemplateParmDecl::Create( 2478 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2479 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2480 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes, 2481 ExpandedParameterPackTypesAsWritten); 2482 else 2483 Param = NonTypeTemplateParmDecl::Create( 2484 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2485 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2486 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI); 2487 2488 Param->setAccess(AS_public); 2489 Param->setImplicit(D->isImplicit()); 2490 if (Invalid) 2491 Param->setInvalidDecl(); 2492 2493 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2494 EnterExpressionEvaluationContext ConstantEvaluated( 2495 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 2496 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs); 2497 if (!Value.isInvalid()) 2498 Param->setDefaultArgument(Value.get()); 2499 } 2500 2501 // Introduce this template parameter's instantiation into the instantiation 2502 // scope. 2503 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2504 return Param; 2505 } 2506 2507 static void collectUnexpandedParameterPacks( 2508 Sema &S, 2509 TemplateParameterList *Params, 2510 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 2511 for (const auto &P : *Params) { 2512 if (P->isTemplateParameterPack()) 2513 continue; 2514 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) 2515 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), 2516 Unexpanded); 2517 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P)) 2518 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), 2519 Unexpanded); 2520 } 2521 } 2522 2523 Decl * 2524 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 2525 TemplateTemplateParmDecl *D) { 2526 // Instantiate the template parameter list of the template template parameter. 2527 TemplateParameterList *TempParams = D->getTemplateParameters(); 2528 TemplateParameterList *InstParams; 2529 SmallVector<TemplateParameterList*, 8> ExpandedParams; 2530 2531 bool IsExpandedParameterPack = false; 2532 2533 if (D->isExpandedParameterPack()) { 2534 // The template template parameter pack is an already-expanded pack 2535 // expansion of template parameters. Substitute into each of the expanded 2536 // parameters. 2537 ExpandedParams.reserve(D->getNumExpansionTemplateParameters()); 2538 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 2539 I != N; ++I) { 2540 LocalInstantiationScope Scope(SemaRef); 2541 TemplateParameterList *Expansion = 2542 SubstTemplateParams(D->getExpansionTemplateParameters(I)); 2543 if (!Expansion) 2544 return nullptr; 2545 ExpandedParams.push_back(Expansion); 2546 } 2547 2548 IsExpandedParameterPack = true; 2549 InstParams = TempParams; 2550 } else if (D->isPackExpansion()) { 2551 // The template template parameter pack expands to a pack of template 2552 // template parameters. Determine whether we need to expand this parameter 2553 // pack into separate parameters. 2554 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2555 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), 2556 Unexpanded); 2557 2558 // Determine whether the set of unexpanded parameter packs can and should 2559 // be expanded. 2560 bool Expand = true; 2561 bool RetainExpansion = false; 2562 Optional<unsigned> NumExpansions; 2563 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), 2564 TempParams->getSourceRange(), 2565 Unexpanded, 2566 TemplateArgs, 2567 Expand, RetainExpansion, 2568 NumExpansions)) 2569 return nullptr; 2570 2571 if (Expand) { 2572 for (unsigned I = 0; I != *NumExpansions; ++I) { 2573 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2574 LocalInstantiationScope Scope(SemaRef); 2575 TemplateParameterList *Expansion = SubstTemplateParams(TempParams); 2576 if (!Expansion) 2577 return nullptr; 2578 ExpandedParams.push_back(Expansion); 2579 } 2580 2581 // Note that we have an expanded parameter pack. The "type" of this 2582 // expanded parameter pack is the original expansion type, but callers 2583 // will end up using the expanded parameter pack types for type-checking. 2584 IsExpandedParameterPack = true; 2585 InstParams = TempParams; 2586 } else { 2587 // We cannot fully expand the pack expansion now, so just substitute 2588 // into the pattern. 2589 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2590 2591 LocalInstantiationScope Scope(SemaRef); 2592 InstParams = SubstTemplateParams(TempParams); 2593 if (!InstParams) 2594 return nullptr; 2595 } 2596 } else { 2597 // Perform the actual substitution of template parameters within a new, 2598 // local instantiation scope. 2599 LocalInstantiationScope Scope(SemaRef); 2600 InstParams = SubstTemplateParams(TempParams); 2601 if (!InstParams) 2602 return nullptr; 2603 } 2604 2605 // Build the template template parameter. 2606 TemplateTemplateParmDecl *Param; 2607 if (IsExpandedParameterPack) 2608 Param = TemplateTemplateParmDecl::Create( 2609 SemaRef.Context, Owner, D->getLocation(), 2610 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2611 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams); 2612 else 2613 Param = TemplateTemplateParmDecl::Create( 2614 SemaRef.Context, Owner, D->getLocation(), 2615 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2616 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams); 2617 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2618 NestedNameSpecifierLoc QualifierLoc = 2619 D->getDefaultArgument().getTemplateQualifierLoc(); 2620 QualifierLoc = 2621 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs); 2622 TemplateName TName = SemaRef.SubstTemplateName( 2623 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(), 2624 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); 2625 if (!TName.isNull()) 2626 Param->setDefaultArgument( 2627 SemaRef.Context, 2628 TemplateArgumentLoc(TemplateArgument(TName), 2629 D->getDefaultArgument().getTemplateQualifierLoc(), 2630 D->getDefaultArgument().getTemplateNameLoc())); 2631 } 2632 Param->setAccess(AS_public); 2633 Param->setImplicit(D->isImplicit()); 2634 2635 // Introduce this template parameter's instantiation into the instantiation 2636 // scope. 2637 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2638 2639 return Param; 2640 } 2641 2642 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 2643 // Using directives are never dependent (and never contain any types or 2644 // expressions), so they require no explicit instantiation work. 2645 2646 UsingDirectiveDecl *Inst 2647 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 2648 D->getNamespaceKeyLocation(), 2649 D->getQualifierLoc(), 2650 D->getIdentLocation(), 2651 D->getNominatedNamespace(), 2652 D->getCommonAncestor()); 2653 2654 // Add the using directive to its declaration context 2655 // only if this is not a function or method. 2656 if (!Owner->isFunctionOrMethod()) 2657 Owner->addDecl(Inst); 2658 2659 return Inst; 2660 } 2661 2662 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 2663 2664 // The nested name specifier may be dependent, for example 2665 // template <typename T> struct t { 2666 // struct s1 { T f1(); }; 2667 // struct s2 : s1 { using s1::f1; }; 2668 // }; 2669 // template struct t<int>; 2670 // Here, in using s1::f1, s1 refers to t<T>::s1; 2671 // we need to substitute for t<int>::s1. 2672 NestedNameSpecifierLoc QualifierLoc 2673 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2674 TemplateArgs); 2675 if (!QualifierLoc) 2676 return nullptr; 2677 2678 // For an inheriting constructor declaration, the name of the using 2679 // declaration is the name of a constructor in this class, not in the 2680 // base class. 2681 DeclarationNameInfo NameInfo = D->getNameInfo(); 2682 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 2683 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext)) 2684 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName( 2685 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD)))); 2686 2687 // We only need to do redeclaration lookups if we're in a class 2688 // scope (in fact, it's not really even possible in non-class 2689 // scopes). 2690 bool CheckRedeclaration = Owner->isRecord(); 2691 2692 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 2693 Sema::ForVisibleRedeclaration); 2694 2695 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 2696 D->getUsingLoc(), 2697 QualifierLoc, 2698 NameInfo, 2699 D->hasTypename()); 2700 2701 CXXScopeSpec SS; 2702 SS.Adopt(QualifierLoc); 2703 if (CheckRedeclaration) { 2704 Prev.setHideTags(false); 2705 SemaRef.LookupQualifiedName(Prev, Owner); 2706 2707 // Check for invalid redeclarations. 2708 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(), 2709 D->hasTypename(), SS, 2710 D->getLocation(), Prev)) 2711 NewUD->setInvalidDecl(); 2712 2713 } 2714 2715 if (!NewUD->isInvalidDecl() && 2716 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), 2717 SS, NameInfo, D->getLocation())) 2718 NewUD->setInvalidDecl(); 2719 2720 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 2721 NewUD->setAccess(D->getAccess()); 2722 Owner->addDecl(NewUD); 2723 2724 // Don't process the shadow decls for an invalid decl. 2725 if (NewUD->isInvalidDecl()) 2726 return NewUD; 2727 2728 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 2729 SemaRef.CheckInheritingConstructorUsingDecl(NewUD); 2730 2731 bool isFunctionScope = Owner->isFunctionOrMethod(); 2732 2733 // Process the shadow decls. 2734 for (auto *Shadow : D->shadows()) { 2735 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so 2736 // reconstruct it in the case where it matters. 2737 NamedDecl *OldTarget = Shadow->getTargetDecl(); 2738 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow)) 2739 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl()) 2740 OldTarget = BaseShadow; 2741 2742 NamedDecl *InstTarget = 2743 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 2744 Shadow->getLocation(), OldTarget, TemplateArgs)); 2745 if (!InstTarget) 2746 return nullptr; 2747 2748 UsingShadowDecl *PrevDecl = nullptr; 2749 if (CheckRedeclaration) { 2750 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl)) 2751 continue; 2752 } else if (UsingShadowDecl *OldPrev = 2753 getPreviousDeclForInstantiation(Shadow)) { 2754 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( 2755 Shadow->getLocation(), OldPrev, TemplateArgs)); 2756 } 2757 2758 UsingShadowDecl *InstShadow = 2759 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget, 2760 PrevDecl); 2761 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 2762 2763 if (isFunctionScope) 2764 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 2765 } 2766 2767 return NewUD; 2768 } 2769 2770 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 2771 // Ignore these; we handle them in bulk when processing the UsingDecl. 2772 return nullptr; 2773 } 2774 2775 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl( 2776 ConstructorUsingShadowDecl *D) { 2777 // Ignore these; we handle them in bulk when processing the UsingDecl. 2778 return nullptr; 2779 } 2780 2781 template <typename T> 2782 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl( 2783 T *D, bool InstantiatingPackElement) { 2784 // If this is a pack expansion, expand it now. 2785 if (D->isPackExpansion() && !InstantiatingPackElement) { 2786 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2787 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded); 2788 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded); 2789 2790 // Determine whether the set of unexpanded parameter packs can and should 2791 // be expanded. 2792 bool Expand = true; 2793 bool RetainExpansion = false; 2794 Optional<unsigned> NumExpansions; 2795 if (SemaRef.CheckParameterPacksForExpansion( 2796 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs, 2797 Expand, RetainExpansion, NumExpansions)) 2798 return nullptr; 2799 2800 // This declaration cannot appear within a function template signature, 2801 // so we can't have a partial argument list for a parameter pack. 2802 assert(!RetainExpansion && 2803 "should never need to retain an expansion for UsingPackDecl"); 2804 2805 if (!Expand) { 2806 // We cannot fully expand the pack expansion now, so substitute into the 2807 // pattern and create a new pack expansion. 2808 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2809 return instantiateUnresolvedUsingDecl(D, true); 2810 } 2811 2812 // Within a function, we don't have any normal way to check for conflicts 2813 // between shadow declarations from different using declarations in the 2814 // same pack expansion, but this is always ill-formed because all expansions 2815 // must produce (conflicting) enumerators. 2816 // 2817 // Sadly we can't just reject this in the template definition because it 2818 // could be valid if the pack is empty or has exactly one expansion. 2819 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) { 2820 SemaRef.Diag(D->getEllipsisLoc(), 2821 diag::err_using_decl_redeclaration_expansion); 2822 return nullptr; 2823 } 2824 2825 // Instantiate the slices of this pack and build a UsingPackDecl. 2826 SmallVector<NamedDecl*, 8> Expansions; 2827 for (unsigned I = 0; I != *NumExpansions; ++I) { 2828 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2829 Decl *Slice = instantiateUnresolvedUsingDecl(D, true); 2830 if (!Slice) 2831 return nullptr; 2832 // Note that we can still get unresolved using declarations here, if we 2833 // had arguments for all packs but the pattern also contained other 2834 // template arguments (this only happens during partial substitution, eg 2835 // into the body of a generic lambda in a function template). 2836 Expansions.push_back(cast<NamedDecl>(Slice)); 2837 } 2838 2839 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 2840 if (isDeclWithinFunction(D)) 2841 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 2842 return NewD; 2843 } 2844 2845 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D); 2846 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation(); 2847 2848 NestedNameSpecifierLoc QualifierLoc 2849 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2850 TemplateArgs); 2851 if (!QualifierLoc) 2852 return nullptr; 2853 2854 CXXScopeSpec SS; 2855 SS.Adopt(QualifierLoc); 2856 2857 DeclarationNameInfo NameInfo 2858 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2859 2860 // Produce a pack expansion only if we're not instantiating a particular 2861 // slice of a pack expansion. 2862 bool InstantiatingSlice = D->getEllipsisLoc().isValid() && 2863 SemaRef.ArgumentPackSubstitutionIndex != -1; 2864 SourceLocation EllipsisLoc = 2865 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc(); 2866 2867 NamedDecl *UD = SemaRef.BuildUsingDeclaration( 2868 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(), 2869 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc, 2870 ParsedAttributesView(), 2871 /*IsInstantiation*/ true); 2872 if (UD) 2873 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D); 2874 2875 return UD; 2876 } 2877 2878 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl( 2879 UnresolvedUsingTypenameDecl *D) { 2880 return instantiateUnresolvedUsingDecl(D); 2881 } 2882 2883 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl( 2884 UnresolvedUsingValueDecl *D) { 2885 return instantiateUnresolvedUsingDecl(D); 2886 } 2887 2888 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) { 2889 SmallVector<NamedDecl*, 8> Expansions; 2890 for (auto *UD : D->expansions()) { 2891 if (NamedDecl *NewUD = 2892 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs)) 2893 Expansions.push_back(NewUD); 2894 else 2895 return nullptr; 2896 } 2897 2898 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 2899 if (isDeclWithinFunction(D)) 2900 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 2901 return NewD; 2902 } 2903 2904 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 2905 ClassScopeFunctionSpecializationDecl *Decl) { 2906 CXXMethodDecl *OldFD = Decl->getSpecialization(); 2907 return cast_or_null<CXXMethodDecl>( 2908 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten())); 2909 } 2910 2911 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( 2912 OMPThreadPrivateDecl *D) { 2913 SmallVector<Expr *, 5> Vars; 2914 for (auto *I : D->varlists()) { 2915 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 2916 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"); 2917 Vars.push_back(Var); 2918 } 2919 2920 OMPThreadPrivateDecl *TD = 2921 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars); 2922 2923 TD->setAccess(AS_public); 2924 Owner->addDecl(TD); 2925 2926 return TD; 2927 } 2928 2929 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) { 2930 SmallVector<Expr *, 5> Vars; 2931 for (auto *I : D->varlists()) { 2932 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 2933 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr"); 2934 Vars.push_back(Var); 2935 } 2936 SmallVector<OMPClause *, 4> Clauses; 2937 // Copy map clauses from the original mapper. 2938 for (OMPClause *C : D->clauselists()) { 2939 auto *AC = cast<OMPAllocatorClause>(C); 2940 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs); 2941 if (!NewE.isUsable()) 2942 continue; 2943 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause( 2944 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc()); 2945 Clauses.push_back(IC); 2946 } 2947 2948 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective( 2949 D->getLocation(), Vars, Clauses, Owner); 2950 if (Res.get().isNull()) 2951 return nullptr; 2952 return Res.get().getSingleDecl(); 2953 } 2954 2955 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) { 2956 llvm_unreachable( 2957 "Requires directive cannot be instantiated within a dependent context"); 2958 } 2959 2960 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl( 2961 OMPDeclareReductionDecl *D) { 2962 // Instantiate type and check if it is allowed. 2963 const bool RequiresInstantiation = 2964 D->getType()->isDependentType() || 2965 D->getType()->isInstantiationDependentType() || 2966 D->getType()->containsUnexpandedParameterPack(); 2967 QualType SubstReductionType; 2968 if (RequiresInstantiation) { 2969 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType( 2970 D->getLocation(), 2971 ParsedType::make(SemaRef.SubstType( 2972 D->getType(), TemplateArgs, D->getLocation(), DeclarationName()))); 2973 } else { 2974 SubstReductionType = D->getType(); 2975 } 2976 if (SubstReductionType.isNull()) 2977 return nullptr; 2978 bool IsCorrect = !SubstReductionType.isNull(); 2979 // Create instantiated copy. 2980 std::pair<QualType, SourceLocation> ReductionTypes[] = { 2981 std::make_pair(SubstReductionType, D->getLocation())}; 2982 auto *PrevDeclInScope = D->getPrevDeclInScope(); 2983 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 2984 PrevDeclInScope = cast<OMPDeclareReductionDecl>( 2985 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 2986 ->get<Decl *>()); 2987 } 2988 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart( 2989 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(), 2990 PrevDeclInScope); 2991 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl()); 2992 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD); 2993 if (!RequiresInstantiation) { 2994 if (Expr *Combiner = D->getCombiner()) { 2995 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut()); 2996 NewDRD->setCombiner(Combiner); 2997 if (Expr *Init = D->getInitializer()) { 2998 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv()); 2999 NewDRD->setInitializer(Init, D->getInitializerKind()); 3000 } 3001 } 3002 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd( 3003 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl()); 3004 return NewDRD; 3005 } 3006 Expr *SubstCombiner = nullptr; 3007 Expr *SubstInitializer = nullptr; 3008 // Combiners instantiation sequence. 3009 if (D->getCombiner()) { 3010 SemaRef.ActOnOpenMPDeclareReductionCombinerStart( 3011 /*S=*/nullptr, NewDRD); 3012 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3013 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(), 3014 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl()); 3015 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3016 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(), 3017 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl()); 3018 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3019 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3020 ThisContext); 3021 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get(); 3022 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner); 3023 // Initializers instantiation sequence. 3024 if (D->getInitializer()) { 3025 VarDecl *OmpPrivParm = 3026 SemaRef.ActOnOpenMPDeclareReductionInitializerStart( 3027 /*S=*/nullptr, NewDRD); 3028 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3029 cast<DeclRefExpr>(D->getInitOrig())->getDecl(), 3030 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl()); 3031 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3032 cast<DeclRefExpr>(D->getInitPriv())->getDecl(), 3033 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl()); 3034 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) { 3035 SubstInitializer = 3036 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get(); 3037 } else { 3038 IsCorrect = IsCorrect && OmpPrivParm->hasInit(); 3039 } 3040 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd( 3041 NewDRD, SubstInitializer, OmpPrivParm); 3042 } 3043 IsCorrect = 3044 IsCorrect && SubstCombiner && 3045 (!D->getInitializer() || 3046 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit && 3047 SubstInitializer) || 3048 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit && 3049 !SubstInitializer && !SubstInitializer)); 3050 } else { 3051 IsCorrect = false; 3052 } 3053 3054 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD, 3055 IsCorrect); 3056 3057 return NewDRD; 3058 } 3059 3060 Decl * 3061 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) { 3062 // Instantiate type and check if it is allowed. 3063 const bool RequiresInstantiation = 3064 D->getType()->isDependentType() || 3065 D->getType()->isInstantiationDependentType() || 3066 D->getType()->containsUnexpandedParameterPack(); 3067 QualType SubstMapperTy; 3068 DeclarationName VN = D->getVarName(); 3069 if (RequiresInstantiation) { 3070 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType( 3071 D->getLocation(), 3072 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs, 3073 D->getLocation(), VN))); 3074 } else { 3075 SubstMapperTy = D->getType(); 3076 } 3077 if (SubstMapperTy.isNull()) 3078 return nullptr; 3079 // Create an instantiated copy of mapper. 3080 auto *PrevDeclInScope = D->getPrevDeclInScope(); 3081 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 3082 PrevDeclInScope = cast<OMPDeclareMapperDecl>( 3083 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 3084 ->get<Decl *>()); 3085 } 3086 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart( 3087 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(), 3088 VN, D->getAccess(), PrevDeclInScope); 3089 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD); 3090 SmallVector<OMPClause *, 6> Clauses; 3091 bool IsCorrect = true; 3092 if (!RequiresInstantiation) { 3093 // Copy the mapper variable. 3094 NewDMD->setMapperVarRef(D->getMapperVarRef()); 3095 // Copy map clauses from the original mapper. 3096 for (OMPClause *C : D->clauselists()) 3097 Clauses.push_back(C); 3098 } else { 3099 // Instantiate the mapper variable. 3100 DeclarationNameInfo DirName; 3101 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr, 3102 (*D->clauselist_begin())->getBeginLoc()); 3103 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl( 3104 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN); 3105 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3106 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(), 3107 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl()); 3108 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3109 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3110 ThisContext); 3111 // Instantiate map clauses. 3112 for (OMPClause *C : D->clauselists()) { 3113 auto *OldC = cast<OMPMapClause>(C); 3114 SmallVector<Expr *, 4> NewVars; 3115 for (Expr *OE : OldC->varlists()) { 3116 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get(); 3117 if (!NE) { 3118 IsCorrect = false; 3119 break; 3120 } 3121 NewVars.push_back(NE); 3122 } 3123 if (!IsCorrect) 3124 break; 3125 NestedNameSpecifierLoc NewQualifierLoc = 3126 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(), 3127 TemplateArgs); 3128 CXXScopeSpec SS; 3129 SS.Adopt(NewQualifierLoc); 3130 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo( 3131 OldC->getMapperIdInfo(), TemplateArgs); 3132 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(), 3133 OldC->getEndLoc()); 3134 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause( 3135 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS, 3136 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(), 3137 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs); 3138 Clauses.push_back(NewC); 3139 } 3140 SemaRef.EndOpenMPDSABlock(nullptr); 3141 } 3142 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr, 3143 Clauses); 3144 if (!IsCorrect) 3145 return nullptr; 3146 return NewDMD; 3147 } 3148 3149 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl( 3150 OMPCapturedExprDecl * /*D*/) { 3151 llvm_unreachable("Should not be met in templates"); 3152 } 3153 3154 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 3155 return VisitFunctionDecl(D, nullptr); 3156 } 3157 3158 Decl * 3159 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { 3160 Decl *Inst = VisitFunctionDecl(D, nullptr); 3161 if (Inst && !D->getDescribedFunctionTemplate()) 3162 Owner->addDecl(Inst); 3163 return Inst; 3164 } 3165 3166 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 3167 return VisitCXXMethodDecl(D, nullptr); 3168 } 3169 3170 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 3171 llvm_unreachable("There are only CXXRecordDecls in C++"); 3172 } 3173 3174 Decl * 3175 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 3176 ClassTemplateSpecializationDecl *D) { 3177 // As a MS extension, we permit class-scope explicit specialization 3178 // of member class templates. 3179 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 3180 assert(ClassTemplate->getDeclContext()->isRecord() && 3181 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 3182 "can only instantiate an explicit specialization " 3183 "for a member class template"); 3184 3185 // Lookup the already-instantiated declaration in the instantiation 3186 // of the class template. 3187 ClassTemplateDecl *InstClassTemplate = 3188 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl( 3189 D->getLocation(), ClassTemplate, TemplateArgs)); 3190 if (!InstClassTemplate) 3191 return nullptr; 3192 3193 // Substitute into the template arguments of the class template explicit 3194 // specialization. 3195 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). 3196 castAs<TemplateSpecializationTypeLoc>(); 3197 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), 3198 Loc.getRAngleLoc()); 3199 SmallVector<TemplateArgumentLoc, 4> ArgLocs; 3200 for (unsigned I = 0; I != Loc.getNumArgs(); ++I) 3201 ArgLocs.push_back(Loc.getArgLoc(I)); 3202 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(), 3203 InstTemplateArgs, TemplateArgs)) 3204 return nullptr; 3205 3206 // Check that the template argument list is well-formed for this 3207 // class template. 3208 SmallVector<TemplateArgument, 4> Converted; 3209 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, 3210 D->getLocation(), 3211 InstTemplateArgs, 3212 false, 3213 Converted)) 3214 return nullptr; 3215 3216 // Figure out where to insert this class template explicit specialization 3217 // in the member template's set of class template explicit specializations. 3218 void *InsertPos = nullptr; 3219 ClassTemplateSpecializationDecl *PrevDecl = 3220 InstClassTemplate->findSpecialization(Converted, InsertPos); 3221 3222 // Check whether we've already seen a conflicting instantiation of this 3223 // declaration (for instance, if there was a prior implicit instantiation). 3224 bool Ignored; 3225 if (PrevDecl && 3226 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(), 3227 D->getSpecializationKind(), 3228 PrevDecl, 3229 PrevDecl->getSpecializationKind(), 3230 PrevDecl->getPointOfInstantiation(), 3231 Ignored)) 3232 return nullptr; 3233 3234 // If PrevDecl was a definition and D is also a definition, diagnose. 3235 // This happens in cases like: 3236 // 3237 // template<typename T, typename U> 3238 // struct Outer { 3239 // template<typename X> struct Inner; 3240 // template<> struct Inner<T> {}; 3241 // template<> struct Inner<U> {}; 3242 // }; 3243 // 3244 // Outer<int, int> outer; // error: the explicit specializations of Inner 3245 // // have the same signature. 3246 if (PrevDecl && PrevDecl->getDefinition() && 3247 D->isThisDeclarationADefinition()) { 3248 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; 3249 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), 3250 diag::note_previous_definition); 3251 return nullptr; 3252 } 3253 3254 // Create the class template partial specialization declaration. 3255 ClassTemplateSpecializationDecl *InstD = 3256 ClassTemplateSpecializationDecl::Create( 3257 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(), 3258 D->getLocation(), InstClassTemplate, Converted, PrevDecl); 3259 3260 // Add this partial specialization to the set of class template partial 3261 // specializations. 3262 if (!PrevDecl) 3263 InstClassTemplate->AddSpecialization(InstD, InsertPos); 3264 3265 // Substitute the nested name specifier, if any. 3266 if (SubstQualifier(D, InstD)) 3267 return nullptr; 3268 3269 // Build the canonical type that describes the converted template 3270 // arguments of the class template explicit specialization. 3271 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3272 TemplateName(InstClassTemplate), Converted, 3273 SemaRef.Context.getRecordType(InstD)); 3274 3275 // Build the fully-sugared type for this class template 3276 // specialization as the user wrote in the specialization 3277 // itself. This means that we'll pretty-print the type retrieved 3278 // from the specialization's declaration the way that the user 3279 // actually wrote the specialization, rather than formatting the 3280 // name based on the "canonical" representation used to store the 3281 // template arguments in the specialization. 3282 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3283 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs, 3284 CanonType); 3285 3286 InstD->setAccess(D->getAccess()); 3287 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 3288 InstD->setSpecializationKind(D->getSpecializationKind()); 3289 InstD->setTypeAsWritten(WrittenTy); 3290 InstD->setExternLoc(D->getExternLoc()); 3291 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); 3292 3293 Owner->addDecl(InstD); 3294 3295 // Instantiate the members of the class-scope explicit specialization eagerly. 3296 // We don't have support for lazy instantiation of an explicit specialization 3297 // yet, and MSVC eagerly instantiates in this case. 3298 // FIXME: This is wrong in standard C++. 3299 if (D->isThisDeclarationADefinition() && 3300 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs, 3301 TSK_ImplicitInstantiation, 3302 /*Complain=*/true)) 3303 return nullptr; 3304 3305 return InstD; 3306 } 3307 3308 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3309 VarTemplateSpecializationDecl *D) { 3310 3311 TemplateArgumentListInfo VarTemplateArgsInfo; 3312 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 3313 assert(VarTemplate && 3314 "A template specialization without specialized template?"); 3315 3316 VarTemplateDecl *InstVarTemplate = 3317 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl( 3318 D->getLocation(), VarTemplate, TemplateArgs)); 3319 if (!InstVarTemplate) 3320 return nullptr; 3321 3322 // Substitute the current template arguments. 3323 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 3324 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 3325 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 3326 3327 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(), 3328 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs)) 3329 return nullptr; 3330 3331 // Check that the template argument list is well-formed for this template. 3332 SmallVector<TemplateArgument, 4> Converted; 3333 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(), 3334 VarTemplateArgsInfo, false, Converted)) 3335 return nullptr; 3336 3337 // Check whether we've already seen a declaration of this specialization. 3338 void *InsertPos = nullptr; 3339 VarTemplateSpecializationDecl *PrevDecl = 3340 InstVarTemplate->findSpecialization(Converted, InsertPos); 3341 3342 // Check whether we've already seen a conflicting instantiation of this 3343 // declaration (for instance, if there was a prior implicit instantiation). 3344 bool Ignored; 3345 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl( 3346 D->getLocation(), D->getSpecializationKind(), PrevDecl, 3347 PrevDecl->getSpecializationKind(), 3348 PrevDecl->getPointOfInstantiation(), Ignored)) 3349 return nullptr; 3350 3351 return VisitVarTemplateSpecializationDecl( 3352 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl); 3353 } 3354 3355 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3356 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos, 3357 const TemplateArgumentListInfo &TemplateArgsInfo, 3358 ArrayRef<TemplateArgument> Converted, 3359 VarTemplateSpecializationDecl *PrevDecl) { 3360 3361 // Do substitution on the type of the declaration 3362 TypeSourceInfo *DI = 3363 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 3364 D->getTypeSpecStartLoc(), D->getDeclName()); 3365 if (!DI) 3366 return nullptr; 3367 3368 if (DI->getType()->isFunctionType()) { 3369 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 3370 << D->isStaticDataMember() << DI->getType(); 3371 return nullptr; 3372 } 3373 3374 // Build the instantiated declaration 3375 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 3376 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 3377 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted); 3378 Var->setTemplateArgsInfo(TemplateArgsInfo); 3379 if (InsertPos) 3380 VarTemplate->AddSpecialization(Var, InsertPos); 3381 3382 // Substitute the nested name specifier, if any. 3383 if (SubstQualifier(D, Var)) 3384 return nullptr; 3385 3386 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 3387 StartingScope, false, PrevDecl); 3388 3389 return Var; 3390 } 3391 3392 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 3393 llvm_unreachable("@defs is not supported in Objective-C++"); 3394 } 3395 3396 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 3397 // FIXME: We need to be able to instantiate FriendTemplateDecls. 3398 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 3399 DiagnosticsEngine::Error, 3400 "cannot instantiate %0 yet"); 3401 SemaRef.Diag(D->getLocation(), DiagID) 3402 << D->getDeclKindName(); 3403 3404 return nullptr; 3405 } 3406 3407 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) { 3408 llvm_unreachable("Concept definitions cannot reside inside a template"); 3409 } 3410 3411 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 3412 llvm_unreachable("Unexpected decl"); 3413 } 3414 3415 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 3416 const MultiLevelTemplateArgumentList &TemplateArgs) { 3417 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3418 if (D->isInvalidDecl()) 3419 return nullptr; 3420 3421 Decl *SubstD; 3422 runWithSufficientStackSpace(D->getLocation(), [&] { 3423 SubstD = Instantiator.Visit(D); 3424 }); 3425 return SubstD; 3426 } 3427 3428 /// Instantiates a nested template parameter list in the current 3429 /// instantiation context. 3430 /// 3431 /// \param L The parameter list to instantiate 3432 /// 3433 /// \returns NULL if there was an error 3434 TemplateParameterList * 3435 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 3436 // Get errors for all the parameters before bailing out. 3437 bool Invalid = false; 3438 3439 unsigned N = L->size(); 3440 typedef SmallVector<NamedDecl *, 8> ParamVector; 3441 ParamVector Params; 3442 Params.reserve(N); 3443 for (auto &P : *L) { 3444 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P)); 3445 Params.push_back(D); 3446 Invalid = Invalid || !D || D->isInvalidDecl(); 3447 } 3448 3449 // Clean up if we had an error. 3450 if (Invalid) 3451 return nullptr; 3452 3453 // Note: we substitute into associated constraints later 3454 Expr *const UninstantiatedRequiresClause = L->getRequiresClause(); 3455 3456 TemplateParameterList *InstL 3457 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 3458 L->getLAngleLoc(), Params, 3459 L->getRAngleLoc(), 3460 UninstantiatedRequiresClause); 3461 return InstL; 3462 } 3463 3464 TemplateParameterList * 3465 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 3466 const MultiLevelTemplateArgumentList &TemplateArgs) { 3467 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3468 return Instantiator.SubstTemplateParams(Params); 3469 } 3470 3471 /// Instantiate the declaration of a class template partial 3472 /// specialization. 3473 /// 3474 /// \param ClassTemplate the (instantiated) class template that is partially 3475 // specialized by the instantiation of \p PartialSpec. 3476 /// 3477 /// \param PartialSpec the (uninstantiated) class template partial 3478 /// specialization that we are instantiating. 3479 /// 3480 /// \returns The instantiated partial specialization, if successful; otherwise, 3481 /// NULL to indicate an error. 3482 ClassTemplatePartialSpecializationDecl * 3483 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 3484 ClassTemplateDecl *ClassTemplate, 3485 ClassTemplatePartialSpecializationDecl *PartialSpec) { 3486 // Create a local instantiation scope for this class template partial 3487 // specialization, which will contain the instantiations of the template 3488 // parameters. 3489 LocalInstantiationScope Scope(SemaRef); 3490 3491 // Substitute into the template parameters of the class template partial 3492 // specialization. 3493 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 3494 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 3495 if (!InstParams) 3496 return nullptr; 3497 3498 // Substitute into the template arguments of the class template partial 3499 // specialization. 3500 const ASTTemplateArgumentListInfo *TemplArgInfo 3501 = PartialSpec->getTemplateArgsAsWritten(); 3502 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 3503 TemplArgInfo->RAngleLoc); 3504 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 3505 TemplArgInfo->NumTemplateArgs, 3506 InstTemplateArgs, TemplateArgs)) 3507 return nullptr; 3508 3509 // Check that the template argument list is well-formed for this 3510 // class template. 3511 SmallVector<TemplateArgument, 4> Converted; 3512 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 3513 PartialSpec->getLocation(), 3514 InstTemplateArgs, 3515 false, 3516 Converted)) 3517 return nullptr; 3518 3519 // Check these arguments are valid for a template partial specialization. 3520 if (SemaRef.CheckTemplatePartialSpecializationArgs( 3521 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(), 3522 Converted)) 3523 return nullptr; 3524 3525 // Figure out where to insert this class template partial specialization 3526 // in the member template's set of class template partial specializations. 3527 void *InsertPos = nullptr; 3528 ClassTemplateSpecializationDecl *PrevDecl 3529 = ClassTemplate->findPartialSpecialization(Converted, InsertPos); 3530 3531 // Build the canonical type that describes the converted template 3532 // arguments of the class template partial specialization. 3533 QualType CanonType 3534 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 3535 Converted); 3536 3537 // Build the fully-sugared type for this class template 3538 // specialization as the user wrote in the specialization 3539 // itself. This means that we'll pretty-print the type retrieved 3540 // from the specialization's declaration the way that the user 3541 // actually wrote the specialization, rather than formatting the 3542 // name based on the "canonical" representation used to store the 3543 // template arguments in the specialization. 3544 TypeSourceInfo *WrittenTy 3545 = SemaRef.Context.getTemplateSpecializationTypeInfo( 3546 TemplateName(ClassTemplate), 3547 PartialSpec->getLocation(), 3548 InstTemplateArgs, 3549 CanonType); 3550 3551 if (PrevDecl) { 3552 // We've already seen a partial specialization with the same template 3553 // parameters and template arguments. This can happen, for example, when 3554 // substituting the outer template arguments ends up causing two 3555 // class template partial specializations of a member class template 3556 // to have identical forms, e.g., 3557 // 3558 // template<typename T, typename U> 3559 // struct Outer { 3560 // template<typename X, typename Y> struct Inner; 3561 // template<typename Y> struct Inner<T, Y>; 3562 // template<typename Y> struct Inner<U, Y>; 3563 // }; 3564 // 3565 // Outer<int, int> outer; // error: the partial specializations of Inner 3566 // // have the same signature. 3567 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 3568 << WrittenTy->getType(); 3569 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 3570 << SemaRef.Context.getTypeDeclType(PrevDecl); 3571 return nullptr; 3572 } 3573 3574 3575 // Create the class template partial specialization declaration. 3576 ClassTemplatePartialSpecializationDecl *InstPartialSpec = 3577 ClassTemplatePartialSpecializationDecl::Create( 3578 SemaRef.Context, PartialSpec->getTagKind(), Owner, 3579 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams, 3580 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr); 3581 // Substitute the nested name specifier, if any. 3582 if (SubstQualifier(PartialSpec, InstPartialSpec)) 3583 return nullptr; 3584 3585 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 3586 InstPartialSpec->setTypeAsWritten(WrittenTy); 3587 3588 // Check the completed partial specialization. 3589 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 3590 3591 // Add this partial specialization to the set of class template partial 3592 // specializations. 3593 ClassTemplate->AddPartialSpecialization(InstPartialSpec, 3594 /*InsertPos=*/nullptr); 3595 return InstPartialSpec; 3596 } 3597 3598 /// Instantiate the declaration of a variable template partial 3599 /// specialization. 3600 /// 3601 /// \param VarTemplate the (instantiated) variable template that is partially 3602 /// specialized by the instantiation of \p PartialSpec. 3603 /// 3604 /// \param PartialSpec the (uninstantiated) variable template partial 3605 /// specialization that we are instantiating. 3606 /// 3607 /// \returns The instantiated partial specialization, if successful; otherwise, 3608 /// NULL to indicate an error. 3609 VarTemplatePartialSpecializationDecl * 3610 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 3611 VarTemplateDecl *VarTemplate, 3612 VarTemplatePartialSpecializationDecl *PartialSpec) { 3613 // Create a local instantiation scope for this variable template partial 3614 // specialization, which will contain the instantiations of the template 3615 // parameters. 3616 LocalInstantiationScope Scope(SemaRef); 3617 3618 // Substitute into the template parameters of the variable template partial 3619 // specialization. 3620 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 3621 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 3622 if (!InstParams) 3623 return nullptr; 3624 3625 // Substitute into the template arguments of the variable template partial 3626 // specialization. 3627 const ASTTemplateArgumentListInfo *TemplArgInfo 3628 = PartialSpec->getTemplateArgsAsWritten(); 3629 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 3630 TemplArgInfo->RAngleLoc); 3631 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 3632 TemplArgInfo->NumTemplateArgs, 3633 InstTemplateArgs, TemplateArgs)) 3634 return nullptr; 3635 3636 // Check that the template argument list is well-formed for this 3637 // class template. 3638 SmallVector<TemplateArgument, 4> Converted; 3639 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 3640 InstTemplateArgs, false, Converted)) 3641 return nullptr; 3642 3643 // Check these arguments are valid for a template partial specialization. 3644 if (SemaRef.CheckTemplatePartialSpecializationArgs( 3645 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(), 3646 Converted)) 3647 return nullptr; 3648 3649 // Figure out where to insert this variable template partial specialization 3650 // in the member template's set of variable template partial specializations. 3651 void *InsertPos = nullptr; 3652 VarTemplateSpecializationDecl *PrevDecl = 3653 VarTemplate->findPartialSpecialization(Converted, InsertPos); 3654 3655 // Build the canonical type that describes the converted template 3656 // arguments of the variable template partial specialization. 3657 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3658 TemplateName(VarTemplate), Converted); 3659 3660 // Build the fully-sugared type for this variable template 3661 // specialization as the user wrote in the specialization 3662 // itself. This means that we'll pretty-print the type retrieved 3663 // from the specialization's declaration the way that the user 3664 // actually wrote the specialization, rather than formatting the 3665 // name based on the "canonical" representation used to store the 3666 // template arguments in the specialization. 3667 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3668 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 3669 CanonType); 3670 3671 if (PrevDecl) { 3672 // We've already seen a partial specialization with the same template 3673 // parameters and template arguments. This can happen, for example, when 3674 // substituting the outer template arguments ends up causing two 3675 // variable template partial specializations of a member variable template 3676 // to have identical forms, e.g., 3677 // 3678 // template<typename T, typename U> 3679 // struct Outer { 3680 // template<typename X, typename Y> pair<X,Y> p; 3681 // template<typename Y> pair<T, Y> p; 3682 // template<typename Y> pair<U, Y> p; 3683 // }; 3684 // 3685 // Outer<int, int> outer; // error: the partial specializations of Inner 3686 // // have the same signature. 3687 SemaRef.Diag(PartialSpec->getLocation(), 3688 diag::err_var_partial_spec_redeclared) 3689 << WrittenTy->getType(); 3690 SemaRef.Diag(PrevDecl->getLocation(), 3691 diag::note_var_prev_partial_spec_here); 3692 return nullptr; 3693 } 3694 3695 // Do substitution on the type of the declaration 3696 TypeSourceInfo *DI = SemaRef.SubstType( 3697 PartialSpec->getTypeSourceInfo(), TemplateArgs, 3698 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 3699 if (!DI) 3700 return nullptr; 3701 3702 if (DI->getType()->isFunctionType()) { 3703 SemaRef.Diag(PartialSpec->getLocation(), 3704 diag::err_variable_instantiates_to_function) 3705 << PartialSpec->isStaticDataMember() << DI->getType(); 3706 return nullptr; 3707 } 3708 3709 // Create the variable template partial specialization declaration. 3710 VarTemplatePartialSpecializationDecl *InstPartialSpec = 3711 VarTemplatePartialSpecializationDecl::Create( 3712 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 3713 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 3714 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs); 3715 3716 // Substitute the nested name specifier, if any. 3717 if (SubstQualifier(PartialSpec, InstPartialSpec)) 3718 return nullptr; 3719 3720 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 3721 InstPartialSpec->setTypeAsWritten(WrittenTy); 3722 3723 // Check the completed partial specialization. 3724 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 3725 3726 // Add this partial specialization to the set of variable template partial 3727 // specializations. The instantiation of the initializer is not necessary. 3728 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr); 3729 3730 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 3731 LateAttrs, Owner, StartingScope); 3732 3733 return InstPartialSpec; 3734 } 3735 3736 TypeSourceInfo* 3737 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 3738 SmallVectorImpl<ParmVarDecl *> &Params) { 3739 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 3740 assert(OldTInfo && "substituting function without type source info"); 3741 assert(Params.empty() && "parameter vector is non-empty at start"); 3742 3743 CXXRecordDecl *ThisContext = nullptr; 3744 Qualifiers ThisTypeQuals; 3745 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 3746 ThisContext = cast<CXXRecordDecl>(Owner); 3747 ThisTypeQuals = Method->getMethodQualifiers(); 3748 } 3749 3750 TypeSourceInfo *NewTInfo 3751 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 3752 D->getTypeSpecStartLoc(), 3753 D->getDeclName(), 3754 ThisContext, ThisTypeQuals); 3755 if (!NewTInfo) 3756 return nullptr; 3757 3758 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 3759 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 3760 if (NewTInfo != OldTInfo) { 3761 // Get parameters from the new type info. 3762 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 3763 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 3764 unsigned NewIdx = 0; 3765 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); 3766 OldIdx != NumOldParams; ++OldIdx) { 3767 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); 3768 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 3769 3770 Optional<unsigned> NumArgumentsInExpansion; 3771 if (OldParam->isParameterPack()) 3772 NumArgumentsInExpansion = 3773 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 3774 TemplateArgs); 3775 if (!NumArgumentsInExpansion) { 3776 // Simple case: normal parameter, or a parameter pack that's 3777 // instantiated to a (still-dependent) parameter pack. 3778 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 3779 Params.push_back(NewParam); 3780 Scope->InstantiatedLocal(OldParam, NewParam); 3781 } else { 3782 // Parameter pack expansion: make the instantiation an argument pack. 3783 Scope->MakeInstantiatedLocalArgPack(OldParam); 3784 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 3785 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 3786 Params.push_back(NewParam); 3787 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 3788 } 3789 } 3790 } 3791 } else { 3792 // The function type itself was not dependent and therefore no 3793 // substitution occurred. However, we still need to instantiate 3794 // the function parameters themselves. 3795 const FunctionProtoType *OldProto = 3796 cast<FunctionProtoType>(OldProtoLoc.getType()); 3797 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; 3798 ++i) { 3799 ParmVarDecl *OldParam = OldProtoLoc.getParam(i); 3800 if (!OldParam) { 3801 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 3802 D, D->getLocation(), OldProto->getParamType(i))); 3803 continue; 3804 } 3805 3806 ParmVarDecl *Parm = 3807 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 3808 if (!Parm) 3809 return nullptr; 3810 Params.push_back(Parm); 3811 } 3812 } 3813 } else { 3814 // If the type of this function, after ignoring parentheses, is not 3815 // *directly* a function type, then we're instantiating a function that 3816 // was declared via a typedef or with attributes, e.g., 3817 // 3818 // typedef int functype(int, int); 3819 // functype func; 3820 // int __cdecl meth(int, int); 3821 // 3822 // In this case, we'll just go instantiate the ParmVarDecls that we 3823 // synthesized in the method declaration. 3824 SmallVector<QualType, 4> ParamTypes; 3825 Sema::ExtParameterInfoBuilder ExtParamInfos; 3826 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr, 3827 TemplateArgs, ParamTypes, &Params, 3828 ExtParamInfos)) 3829 return nullptr; 3830 } 3831 3832 return NewTInfo; 3833 } 3834 3835 /// Introduce the instantiated function parameters into the local 3836 /// instantiation scope, and set the parameter names to those used 3837 /// in the template. 3838 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 3839 const FunctionDecl *PatternDecl, 3840 LocalInstantiationScope &Scope, 3841 const MultiLevelTemplateArgumentList &TemplateArgs) { 3842 unsigned FParamIdx = 0; 3843 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 3844 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 3845 if (!PatternParam->isParameterPack()) { 3846 // Simple case: not a parameter pack. 3847 assert(FParamIdx < Function->getNumParams()); 3848 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 3849 FunctionParam->setDeclName(PatternParam->getDeclName()); 3850 // If the parameter's type is not dependent, update it to match the type 3851 // in the pattern. They can differ in top-level cv-qualifiers, and we want 3852 // the pattern's type here. If the type is dependent, they can't differ, 3853 // per core issue 1668. Substitute into the type from the pattern, in case 3854 // it's instantiation-dependent. 3855 // FIXME: Updating the type to work around this is at best fragile. 3856 if (!PatternDecl->getType()->isDependentType()) { 3857 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs, 3858 FunctionParam->getLocation(), 3859 FunctionParam->getDeclName()); 3860 if (T.isNull()) 3861 return true; 3862 FunctionParam->setType(T); 3863 } 3864 3865 Scope.InstantiatedLocal(PatternParam, FunctionParam); 3866 ++FParamIdx; 3867 continue; 3868 } 3869 3870 // Expand the parameter pack. 3871 Scope.MakeInstantiatedLocalArgPack(PatternParam); 3872 Optional<unsigned> NumArgumentsInExpansion 3873 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 3874 if (NumArgumentsInExpansion) { 3875 QualType PatternType = 3876 PatternParam->getType()->castAs<PackExpansionType>()->getPattern(); 3877 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 3878 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 3879 FunctionParam->setDeclName(PatternParam->getDeclName()); 3880 if (!PatternDecl->getType()->isDependentType()) { 3881 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg); 3882 QualType T = S.SubstType(PatternType, TemplateArgs, 3883 FunctionParam->getLocation(), 3884 FunctionParam->getDeclName()); 3885 if (T.isNull()) 3886 return true; 3887 FunctionParam->setType(T); 3888 } 3889 3890 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 3891 ++FParamIdx; 3892 } 3893 } 3894 } 3895 3896 return false; 3897 } 3898 3899 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 3900 FunctionDecl *Decl) { 3901 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 3902 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 3903 return; 3904 3905 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 3906 InstantiatingTemplate::ExceptionSpecification()); 3907 if (Inst.isInvalid()) { 3908 // We hit the instantiation depth limit. Clear the exception specification 3909 // so that our callers don't have to cope with EST_Uninstantiated. 3910 UpdateExceptionSpec(Decl, EST_None); 3911 return; 3912 } 3913 if (Inst.isAlreadyInstantiating()) { 3914 // This exception specification indirectly depends on itself. Reject. 3915 // FIXME: Corresponding rule in the standard? 3916 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl; 3917 UpdateExceptionSpec(Decl, EST_None); 3918 return; 3919 } 3920 3921 // Enter the scope of this instantiation. We don't use 3922 // PushDeclContext because we don't have a scope. 3923 Sema::ContextRAII savedContext(*this, Decl); 3924 LocalInstantiationScope Scope(*this); 3925 3926 MultiLevelTemplateArgumentList TemplateArgs = 3927 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true); 3928 3929 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 3930 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope, 3931 TemplateArgs)) { 3932 UpdateExceptionSpec(Decl, EST_None); 3933 return; 3934 } 3935 3936 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(), 3937 TemplateArgs); 3938 } 3939 3940 /// Initializes the common fields of an instantiation function 3941 /// declaration (New) from the corresponding fields of its template (Tmpl). 3942 /// 3943 /// \returns true if there was an error 3944 bool 3945 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 3946 FunctionDecl *Tmpl) { 3947 if (Tmpl->isDeleted()) 3948 New->setDeletedAsWritten(); 3949 3950 New->setImplicit(Tmpl->isImplicit()); 3951 3952 // Forward the mangling number from the template to the instantiated decl. 3953 SemaRef.Context.setManglingNumber(New, 3954 SemaRef.Context.getManglingNumber(Tmpl)); 3955 3956 // If we are performing substituting explicitly-specified template arguments 3957 // or deduced template arguments into a function template and we reach this 3958 // point, we are now past the point where SFINAE applies and have committed 3959 // to keeping the new function template specialization. We therefore 3960 // convert the active template instantiation for the function template 3961 // into a template instantiation for this specific function template 3962 // specialization, which is not a SFINAE context, so that we diagnose any 3963 // further errors in the declaration itself. 3964 typedef Sema::CodeSynthesisContext ActiveInstType; 3965 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back(); 3966 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 3967 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 3968 if (FunctionTemplateDecl *FunTmpl 3969 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 3970 assert(FunTmpl->getTemplatedDecl() == Tmpl && 3971 "Deduction from the wrong function template?"); 3972 (void) FunTmpl; 3973 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 3974 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 3975 ActiveInst.Entity = New; 3976 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 3977 } 3978 } 3979 3980 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 3981 assert(Proto && "Function template without prototype?"); 3982 3983 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 3984 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3985 3986 // DR1330: In C++11, defer instantiation of a non-trivial 3987 // exception specification. 3988 // DR1484: Local classes and their members are instantiated along with the 3989 // containing function. 3990 if (SemaRef.getLangOpts().CPlusPlus11 && 3991 EPI.ExceptionSpec.Type != EST_None && 3992 EPI.ExceptionSpec.Type != EST_DynamicNone && 3993 EPI.ExceptionSpec.Type != EST_BasicNoexcept && 3994 !Tmpl->isLexicallyWithinFunctionOrMethod()) { 3995 FunctionDecl *ExceptionSpecTemplate = Tmpl; 3996 if (EPI.ExceptionSpec.Type == EST_Uninstantiated) 3997 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; 3998 ExceptionSpecificationType NewEST = EST_Uninstantiated; 3999 if (EPI.ExceptionSpec.Type == EST_Unevaluated) 4000 NewEST = EST_Unevaluated; 4001 4002 // Mark the function has having an uninstantiated exception specification. 4003 const FunctionProtoType *NewProto 4004 = New->getType()->getAs<FunctionProtoType>(); 4005 assert(NewProto && "Template instantiation without function prototype?"); 4006 EPI = NewProto->getExtProtoInfo(); 4007 EPI.ExceptionSpec.Type = NewEST; 4008 EPI.ExceptionSpec.SourceDecl = New; 4009 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; 4010 New->setType(SemaRef.Context.getFunctionType( 4011 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 4012 } else { 4013 Sema::ContextRAII SwitchContext(SemaRef, New); 4014 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs); 4015 } 4016 } 4017 4018 // Get the definition. Leaves the variable unchanged if undefined. 4019 const FunctionDecl *Definition = Tmpl; 4020 Tmpl->isDefined(Definition); 4021 4022 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 4023 LateAttrs, StartingScope); 4024 4025 return false; 4026 } 4027 4028 /// Initializes common fields of an instantiated method 4029 /// declaration (New) from the corresponding fields of its template 4030 /// (Tmpl). 4031 /// 4032 /// \returns true if there was an error 4033 bool 4034 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 4035 CXXMethodDecl *Tmpl) { 4036 if (InitFunctionInstantiation(New, Tmpl)) 4037 return true; 4038 4039 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11) 4040 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New)); 4041 4042 New->setAccess(Tmpl->getAccess()); 4043 if (Tmpl->isVirtualAsWritten()) 4044 New->setVirtualAsWritten(true); 4045 4046 // FIXME: New needs a pointer to Tmpl 4047 return false; 4048 } 4049 4050 /// Instantiate (or find existing instantiation of) a function template with a 4051 /// given set of template arguments. 4052 /// 4053 /// Usually this should not be used, and template argument deduction should be 4054 /// used in its place. 4055 FunctionDecl * 4056 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 4057 const TemplateArgumentList *Args, 4058 SourceLocation Loc) { 4059 FunctionDecl *FD = FTD->getTemplatedDecl(); 4060 4061 sema::TemplateDeductionInfo Info(Loc); 4062 InstantiatingTemplate Inst( 4063 *this, Loc, FTD, Args->asArray(), 4064 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); 4065 if (Inst.isInvalid()) 4066 return nullptr; 4067 4068 ContextRAII SavedContext(*this, FD); 4069 MultiLevelTemplateArgumentList MArgs(*Args); 4070 4071 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs)); 4072 } 4073 4074 /// In the MS ABI, we need to instantiate default arguments of dllexported 4075 /// default constructors along with the constructor definition. This allows IR 4076 /// gen to emit a constructor closure which calls the default constructor with 4077 /// its default arguments. 4078 static void InstantiateDefaultCtorDefaultArgs(Sema &S, 4079 CXXConstructorDecl *Ctor) { 4080 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4081 Ctor->isDefaultConstructor()); 4082 unsigned NumParams = Ctor->getNumParams(); 4083 if (NumParams == 0) 4084 return; 4085 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>(); 4086 if (!Attr) 4087 return; 4088 for (unsigned I = 0; I != NumParams; ++I) { 4089 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor, 4090 Ctor->getParamDecl(I)); 4091 S.DiscardCleanupsInEvaluationContext(); 4092 } 4093 } 4094 4095 /// Instantiate the definition of the given function from its 4096 /// template. 4097 /// 4098 /// \param PointOfInstantiation the point at which the instantiation was 4099 /// required. Note that this is not precisely a "point of instantiation" 4100 /// for the function, but it's close. 4101 /// 4102 /// \param Function the already-instantiated declaration of a 4103 /// function template specialization or member function of a class template 4104 /// specialization. 4105 /// 4106 /// \param Recursive if true, recursively instantiates any functions that 4107 /// are required by this instantiation. 4108 /// 4109 /// \param DefinitionRequired if true, then we are performing an explicit 4110 /// instantiation where the body of the function is required. Complain if 4111 /// there is no such body. 4112 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 4113 FunctionDecl *Function, 4114 bool Recursive, 4115 bool DefinitionRequired, 4116 bool AtEndOfTU) { 4117 if (Function->isInvalidDecl() || Function->isDefined() || 4118 isa<CXXDeductionGuideDecl>(Function)) 4119 return; 4120 4121 // Never instantiate an explicit specialization except if it is a class scope 4122 // explicit specialization. 4123 TemplateSpecializationKind TSK = 4124 Function->getTemplateSpecializationKindForInstantiation(); 4125 if (TSK == TSK_ExplicitSpecialization) 4126 return; 4127 4128 // Find the function body that we'll be substituting. 4129 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 4130 assert(PatternDecl && "instantiating a non-template"); 4131 4132 const FunctionDecl *PatternDef = PatternDecl->getDefinition(); 4133 Stmt *Pattern = nullptr; 4134 if (PatternDef) { 4135 Pattern = PatternDef->getBody(PatternDef); 4136 PatternDecl = PatternDef; 4137 if (PatternDef->willHaveBody()) 4138 PatternDef = nullptr; 4139 } 4140 4141 // FIXME: We need to track the instantiation stack in order to know which 4142 // definitions should be visible within this instantiation. 4143 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function, 4144 Function->getInstantiatedFromMemberFunction(), 4145 PatternDecl, PatternDef, TSK, 4146 /*Complain*/DefinitionRequired)) { 4147 if (DefinitionRequired) 4148 Function->setInvalidDecl(); 4149 else if (TSK == TSK_ExplicitInstantiationDefinition) { 4150 // Try again at the end of the translation unit (at which point a 4151 // definition will be required). 4152 assert(!Recursive); 4153 Function->setInstantiationIsPending(true); 4154 PendingInstantiations.push_back( 4155 std::make_pair(Function, PointOfInstantiation)); 4156 } else if (TSK == TSK_ImplicitInstantiation) { 4157 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 4158 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 4159 Diag(PointOfInstantiation, diag::warn_func_template_missing) 4160 << Function; 4161 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 4162 if (getLangOpts().CPlusPlus11) 4163 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) 4164 << Function; 4165 } 4166 } 4167 4168 return; 4169 } 4170 4171 // Postpone late parsed template instantiations. 4172 if (PatternDecl->isLateTemplateParsed() && 4173 !LateTemplateParser) { 4174 Function->setInstantiationIsPending(true); 4175 LateParsedInstantiations.push_back( 4176 std::make_pair(Function, PointOfInstantiation)); 4177 return; 4178 } 4179 4180 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() { 4181 std::string Name; 4182 llvm::raw_string_ostream OS(Name); 4183 Function->getNameForDiagnostic(OS, getPrintingPolicy(), 4184 /*Qualified=*/true); 4185 return Name; 4186 }); 4187 4188 // If we're performing recursive template instantiation, create our own 4189 // queue of pending implicit instantiations that we will instantiate later, 4190 // while we're still within our own instantiation context. 4191 // This has to happen before LateTemplateParser below is called, so that 4192 // it marks vtables used in late parsed templates as used. 4193 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4194 /*Enabled=*/Recursive); 4195 LocalEagerInstantiationScope LocalInstantiations(*this); 4196 4197 // Call the LateTemplateParser callback if there is a need to late parse 4198 // a templated function definition. 4199 if (!Pattern && PatternDecl->isLateTemplateParsed() && 4200 LateTemplateParser) { 4201 // FIXME: Optimize to allow individual templates to be deserialized. 4202 if (PatternDecl->isFromASTFile()) 4203 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 4204 4205 auto LPTIter = LateParsedTemplateMap.find(PatternDecl); 4206 assert(LPTIter != LateParsedTemplateMap.end() && 4207 "missing LateParsedTemplate"); 4208 LateTemplateParser(OpaqueParser, *LPTIter->second); 4209 Pattern = PatternDecl->getBody(PatternDecl); 4210 } 4211 4212 // Note, we should never try to instantiate a deleted function template. 4213 assert((Pattern || PatternDecl->isDefaulted() || 4214 PatternDecl->hasSkippedBody()) && 4215 "unexpected kind of function template definition"); 4216 4217 // C++1y [temp.explicit]p10: 4218 // Except for inline functions, declarations with types deduced from their 4219 // initializer or return value, and class template specializations, other 4220 // explicit instantiation declarations have the effect of suppressing the 4221 // implicit instantiation of the entity to which they refer. 4222 if (TSK == TSK_ExplicitInstantiationDeclaration && 4223 !PatternDecl->isInlined() && 4224 !PatternDecl->getReturnType()->getContainedAutoType()) 4225 return; 4226 4227 if (PatternDecl->isInlined()) { 4228 // Function, and all later redeclarations of it (from imported modules, 4229 // for instance), are now implicitly inline. 4230 for (auto *D = Function->getMostRecentDecl(); /**/; 4231 D = D->getPreviousDecl()) { 4232 D->setImplicitlyInline(); 4233 if (D == Function) 4234 break; 4235 } 4236 } 4237 4238 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 4239 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4240 return; 4241 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(), 4242 "instantiating function definition"); 4243 4244 // The instantiation is visible here, even if it was first declared in an 4245 // unimported module. 4246 Function->setVisibleDespiteOwningModule(); 4247 4248 // Copy the inner loc start from the pattern. 4249 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 4250 4251 EnterExpressionEvaluationContext EvalContext( 4252 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 4253 4254 // Introduce a new scope where local variable instantiations will be 4255 // recorded, unless we're actually a member function within a local 4256 // class, in which case we need to merge our results with the parent 4257 // scope (of the enclosing function). 4258 bool MergeWithParentScope = false; 4259 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 4260 MergeWithParentScope = Rec->isLocalClass(); 4261 4262 LocalInstantiationScope Scope(*this, MergeWithParentScope); 4263 4264 if (PatternDecl->isDefaulted()) 4265 SetDeclDefaulted(Function, PatternDecl->getLocation()); 4266 else { 4267 MultiLevelTemplateArgumentList TemplateArgs = 4268 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl); 4269 4270 // Substitute into the qualifier; we can get a substitution failure here 4271 // through evil use of alias templates. 4272 // FIXME: Is CurContext correct for this? Should we go to the (instantiation 4273 // of the) lexical context of the pattern? 4274 SubstQualifier(*this, PatternDecl, Function, TemplateArgs); 4275 4276 ActOnStartOfFunctionDef(nullptr, Function); 4277 4278 // Enter the scope of this instantiation. We don't use 4279 // PushDeclContext because we don't have a scope. 4280 Sema::ContextRAII savedContext(*this, Function); 4281 4282 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 4283 TemplateArgs)) 4284 return; 4285 4286 StmtResult Body; 4287 if (PatternDecl->hasSkippedBody()) { 4288 ActOnSkippedFunctionBody(Function); 4289 Body = nullptr; 4290 } else { 4291 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) { 4292 // If this is a constructor, instantiate the member initializers. 4293 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl), 4294 TemplateArgs); 4295 4296 // If this is an MS ABI dllexport default constructor, instantiate any 4297 // default arguments. 4298 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 4299 Ctor->isDefaultConstructor()) { 4300 InstantiateDefaultCtorDefaultArgs(*this, Ctor); 4301 } 4302 } 4303 4304 // Instantiate the function body. 4305 Body = SubstStmt(Pattern, TemplateArgs); 4306 4307 if (Body.isInvalid()) 4308 Function->setInvalidDecl(); 4309 } 4310 // FIXME: finishing the function body while in an expression evaluation 4311 // context seems wrong. Investigate more. 4312 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true); 4313 4314 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 4315 4316 if (auto *Listener = getASTMutationListener()) 4317 Listener->FunctionDefinitionInstantiated(Function); 4318 4319 savedContext.pop(); 4320 } 4321 4322 DeclGroupRef DG(Function); 4323 Consumer.HandleTopLevelDecl(DG); 4324 4325 // This class may have local implicit instantiations that need to be 4326 // instantiation within this scope. 4327 LocalInstantiations.perform(); 4328 Scope.Exit(); 4329 GlobalInstantiations.perform(); 4330 } 4331 4332 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 4333 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 4334 const TemplateArgumentList &TemplateArgList, 4335 const TemplateArgumentListInfo &TemplateArgsInfo, 4336 SmallVectorImpl<TemplateArgument> &Converted, 4337 SourceLocation PointOfInstantiation, void *InsertPos, 4338 LateInstantiatedAttrVec *LateAttrs, 4339 LocalInstantiationScope *StartingScope) { 4340 if (FromVar->isInvalidDecl()) 4341 return nullptr; 4342 4343 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 4344 if (Inst.isInvalid()) 4345 return nullptr; 4346 4347 MultiLevelTemplateArgumentList TemplateArgLists; 4348 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 4349 4350 // Instantiate the first declaration of the variable template: for a partial 4351 // specialization of a static data member template, the first declaration may 4352 // or may not be the declaration in the class; if it's in the class, we want 4353 // to instantiate a member in the class (a declaration), and if it's outside, 4354 // we want to instantiate a definition. 4355 // 4356 // If we're instantiating an explicitly-specialized member template or member 4357 // partial specialization, don't do this. The member specialization completely 4358 // replaces the original declaration in this case. 4359 bool IsMemberSpec = false; 4360 if (VarTemplatePartialSpecializationDecl *PartialSpec = 4361 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) 4362 IsMemberSpec = PartialSpec->isMemberSpecialization(); 4363 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate()) 4364 IsMemberSpec = FromTemplate->isMemberSpecialization(); 4365 if (!IsMemberSpec) 4366 FromVar = FromVar->getFirstDecl(); 4367 4368 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 4369 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 4370 MultiLevelList); 4371 4372 // TODO: Set LateAttrs and StartingScope ... 4373 4374 return cast_or_null<VarTemplateSpecializationDecl>( 4375 Instantiator.VisitVarTemplateSpecializationDecl( 4376 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted)); 4377 } 4378 4379 /// Instantiates a variable template specialization by completing it 4380 /// with appropriate type information and initializer. 4381 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 4382 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 4383 const MultiLevelTemplateArgumentList &TemplateArgs) { 4384 assert(PatternDecl->isThisDeclarationADefinition() && 4385 "don't have a definition to instantiate from"); 4386 4387 // Do substitution on the type of the declaration 4388 TypeSourceInfo *DI = 4389 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 4390 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 4391 if (!DI) 4392 return nullptr; 4393 4394 // Update the type of this variable template specialization. 4395 VarSpec->setType(DI->getType()); 4396 4397 // Convert the declaration into a definition now. 4398 VarSpec->setCompleteDefinition(); 4399 4400 // Instantiate the initializer. 4401 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 4402 4403 return VarSpec; 4404 } 4405 4406 /// BuildVariableInstantiation - Used after a new variable has been created. 4407 /// Sets basic variable data and decides whether to postpone the 4408 /// variable instantiation. 4409 void Sema::BuildVariableInstantiation( 4410 VarDecl *NewVar, VarDecl *OldVar, 4411 const MultiLevelTemplateArgumentList &TemplateArgs, 4412 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 4413 LocalInstantiationScope *StartingScope, 4414 bool InstantiatingVarTemplate, 4415 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) { 4416 // Instantiating a partial specialization to produce a partial 4417 // specialization. 4418 bool InstantiatingVarTemplatePartialSpec = 4419 isa<VarTemplatePartialSpecializationDecl>(OldVar) && 4420 isa<VarTemplatePartialSpecializationDecl>(NewVar); 4421 // Instantiating from a variable template (or partial specialization) to 4422 // produce a variable template specialization. 4423 bool InstantiatingSpecFromTemplate = 4424 isa<VarTemplateSpecializationDecl>(NewVar) && 4425 (OldVar->getDescribedVarTemplate() || 4426 isa<VarTemplatePartialSpecializationDecl>(OldVar)); 4427 4428 // If we are instantiating a local extern declaration, the 4429 // instantiation belongs lexically to the containing function. 4430 // If we are instantiating a static data member defined 4431 // out-of-line, the instantiation will have the same lexical 4432 // context (which will be a namespace scope) as the template. 4433 if (OldVar->isLocalExternDecl()) { 4434 NewVar->setLocalExternDecl(); 4435 NewVar->setLexicalDeclContext(Owner); 4436 } else if (OldVar->isOutOfLine()) 4437 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 4438 NewVar->setTSCSpec(OldVar->getTSCSpec()); 4439 NewVar->setInitStyle(OldVar->getInitStyle()); 4440 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 4441 NewVar->setObjCForDecl(OldVar->isObjCForDecl()); 4442 NewVar->setConstexpr(OldVar->isConstexpr()); 4443 NewVar->setInitCapture(OldVar->isInitCapture()); 4444 NewVar->setPreviousDeclInSameBlockScope( 4445 OldVar->isPreviousDeclInSameBlockScope()); 4446 NewVar->setAccess(OldVar->getAccess()); 4447 4448 if (!OldVar->isStaticDataMember()) { 4449 if (OldVar->isUsed(false)) 4450 NewVar->setIsUsed(); 4451 NewVar->setReferenced(OldVar->isReferenced()); 4452 } 4453 4454 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 4455 4456 LookupResult Previous( 4457 *this, NewVar->getDeclName(), NewVar->getLocation(), 4458 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 4459 : Sema::LookupOrdinaryName, 4460 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration 4461 : forRedeclarationInCurContext()); 4462 4463 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 4464 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 4465 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 4466 // We have a previous declaration. Use that one, so we merge with the 4467 // right type. 4468 if (NamedDecl *NewPrev = FindInstantiatedDecl( 4469 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 4470 Previous.addDecl(NewPrev); 4471 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 4472 OldVar->hasLinkage()) { 4473 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 4474 } else if (PrevDeclForVarTemplateSpecialization) { 4475 Previous.addDecl(PrevDeclForVarTemplateSpecialization); 4476 } 4477 CheckVariableDeclaration(NewVar, Previous); 4478 4479 if (!InstantiatingVarTemplate) { 4480 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 4481 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 4482 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 4483 } 4484 4485 if (!OldVar->isOutOfLine()) { 4486 if (NewVar->getDeclContext()->isFunctionOrMethod()) 4487 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 4488 } 4489 4490 // Link instantiations of static data members back to the template from 4491 // which they were instantiated. 4492 // 4493 // Don't do this when instantiating a template (we link the template itself 4494 // back in that case) nor when instantiating a static data member template 4495 // (that's not a member specialization). 4496 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate && 4497 !InstantiatingSpecFromTemplate) 4498 NewVar->setInstantiationOfStaticDataMember(OldVar, 4499 TSK_ImplicitInstantiation); 4500 4501 // If the pattern is an (in-class) explicit specialization, then the result 4502 // is also an explicit specialization. 4503 if (VarTemplateSpecializationDecl *OldVTSD = 4504 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) { 4505 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization && 4506 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD)) 4507 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind( 4508 TSK_ExplicitSpecialization); 4509 } 4510 4511 // Forward the mangling number from the template to the instantiated decl. 4512 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 4513 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar)); 4514 4515 // Figure out whether to eagerly instantiate the initializer. 4516 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) { 4517 // We're producing a template. Don't instantiate the initializer yet. 4518 } else if (NewVar->getType()->isUndeducedType()) { 4519 // We need the type to complete the declaration of the variable. 4520 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 4521 } else if (InstantiatingSpecFromTemplate || 4522 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() && 4523 !NewVar->isThisDeclarationADefinition())) { 4524 // Delay instantiation of the initializer for variable template 4525 // specializations or inline static data members until a definition of the 4526 // variable is needed. 4527 } else { 4528 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 4529 } 4530 4531 // Diagnose unused local variables with dependent types, where the diagnostic 4532 // will have been deferred. 4533 if (!NewVar->isInvalidDecl() && 4534 NewVar->getDeclContext()->isFunctionOrMethod() && 4535 OldVar->getType()->isDependentType()) 4536 DiagnoseUnusedDecl(NewVar); 4537 } 4538 4539 /// Instantiate the initializer of a variable. 4540 void Sema::InstantiateVariableInitializer( 4541 VarDecl *Var, VarDecl *OldVar, 4542 const MultiLevelTemplateArgumentList &TemplateArgs) { 4543 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4544 L->VariableDefinitionInstantiated(Var); 4545 4546 // We propagate the 'inline' flag with the initializer, because it 4547 // would otherwise imply that the variable is a definition for a 4548 // non-static data member. 4549 if (OldVar->isInlineSpecified()) 4550 Var->setInlineSpecified(); 4551 else if (OldVar->isInline()) 4552 Var->setImplicitlyInline(); 4553 4554 if (OldVar->getInit()) { 4555 EnterExpressionEvaluationContext Evaluated( 4556 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var); 4557 4558 // Instantiate the initializer. 4559 ExprResult Init; 4560 4561 { 4562 ContextRAII SwitchContext(*this, Var->getDeclContext()); 4563 Init = SubstInitializer(OldVar->getInit(), TemplateArgs, 4564 OldVar->getInitStyle() == VarDecl::CallInit); 4565 } 4566 4567 if (!Init.isInvalid()) { 4568 Expr *InitExpr = Init.get(); 4569 4570 if (Var->hasAttr<DLLImportAttr>() && 4571 (!InitExpr || 4572 !InitExpr->isConstantInitializer(getASTContext(), false))) { 4573 // Do not dynamically initialize dllimport variables. 4574 } else if (InitExpr) { 4575 bool DirectInit = OldVar->isDirectInit(); 4576 AddInitializerToDecl(Var, InitExpr, DirectInit); 4577 } else 4578 ActOnUninitializedDecl(Var); 4579 } else { 4580 // FIXME: Not too happy about invalidating the declaration 4581 // because of a bogus initializer. 4582 Var->setInvalidDecl(); 4583 } 4584 } else { 4585 // `inline` variables are a definition and declaration all in one; we won't 4586 // pick up an initializer from anywhere else. 4587 if (Var->isStaticDataMember() && !Var->isInline()) { 4588 if (!Var->isOutOfLine()) 4589 return; 4590 4591 // If the declaration inside the class had an initializer, don't add 4592 // another one to the out-of-line definition. 4593 if (OldVar->getFirstDecl()->hasInit()) 4594 return; 4595 } 4596 4597 // We'll add an initializer to a for-range declaration later. 4598 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl()) 4599 return; 4600 4601 ActOnUninitializedDecl(Var); 4602 } 4603 4604 if (getLangOpts().CUDA) 4605 checkAllowedCUDAInitializer(Var); 4606 } 4607 4608 /// Instantiate the definition of the given variable from its 4609 /// template. 4610 /// 4611 /// \param PointOfInstantiation the point at which the instantiation was 4612 /// required. Note that this is not precisely a "point of instantiation" 4613 /// for the variable, but it's close. 4614 /// 4615 /// \param Var the already-instantiated declaration of a templated variable. 4616 /// 4617 /// \param Recursive if true, recursively instantiates any functions that 4618 /// are required by this instantiation. 4619 /// 4620 /// \param DefinitionRequired if true, then we are performing an explicit 4621 /// instantiation where a definition of the variable is required. Complain 4622 /// if there is no such definition. 4623 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 4624 VarDecl *Var, bool Recursive, 4625 bool DefinitionRequired, bool AtEndOfTU) { 4626 if (Var->isInvalidDecl()) 4627 return; 4628 4629 // Never instantiate an explicitly-specialized entity. 4630 TemplateSpecializationKind TSK = 4631 Var->getTemplateSpecializationKindForInstantiation(); 4632 if (TSK == TSK_ExplicitSpecialization) 4633 return; 4634 4635 // Find the pattern and the arguments to substitute into it. 4636 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern(); 4637 assert(PatternDecl && "no pattern for templated variable"); 4638 MultiLevelTemplateArgumentList TemplateArgs = 4639 getTemplateInstantiationArgs(Var); 4640 4641 VarTemplateSpecializationDecl *VarSpec = 4642 dyn_cast<VarTemplateSpecializationDecl>(Var); 4643 if (VarSpec) { 4644 // If this is a variable template specialization, make sure that it is 4645 // non-dependent. 4646 bool InstantiationDependent = false; 4647 assert(!TemplateSpecializationType::anyDependentTemplateArguments( 4648 VarSpec->getTemplateArgsInfo(), InstantiationDependent) && 4649 "Only instantiate variable template specializations that are " 4650 "not type-dependent"); 4651 (void)InstantiationDependent; 4652 4653 // If this is a static data member template, there might be an 4654 // uninstantiated initializer on the declaration. If so, instantiate 4655 // it now. 4656 // 4657 // FIXME: This largely duplicates what we would do below. The difference 4658 // is that along this path we may instantiate an initializer from an 4659 // in-class declaration of the template and instantiate the definition 4660 // from a separate out-of-class definition. 4661 if (PatternDecl->isStaticDataMember() && 4662 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 4663 !Var->hasInit()) { 4664 // FIXME: Factor out the duplicated instantiation context setup/tear down 4665 // code here. 4666 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 4667 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4668 return; 4669 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 4670 "instantiating variable initializer"); 4671 4672 // The instantiation is visible here, even if it was first declared in an 4673 // unimported module. 4674 Var->setVisibleDespiteOwningModule(); 4675 4676 // If we're performing recursive template instantiation, create our own 4677 // queue of pending implicit instantiations that we will instantiate 4678 // later, while we're still within our own instantiation context. 4679 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4680 /*Enabled=*/Recursive); 4681 LocalInstantiationScope Local(*this); 4682 LocalEagerInstantiationScope LocalInstantiations(*this); 4683 4684 // Enter the scope of this instantiation. We don't use 4685 // PushDeclContext because we don't have a scope. 4686 ContextRAII PreviousContext(*this, Var->getDeclContext()); 4687 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 4688 PreviousContext.pop(); 4689 4690 // This variable may have local implicit instantiations that need to be 4691 // instantiated within this scope. 4692 LocalInstantiations.perform(); 4693 Local.Exit(); 4694 GlobalInstantiations.perform(); 4695 } 4696 } else { 4697 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && 4698 "not a static data member?"); 4699 } 4700 4701 VarDecl *Def = PatternDecl->getDefinition(getASTContext()); 4702 4703 // If we don't have a definition of the variable template, we won't perform 4704 // any instantiation. Rather, we rely on the user to instantiate this 4705 // definition (or provide a specialization for it) in another translation 4706 // unit. 4707 if (!Def && !DefinitionRequired) { 4708 if (TSK == TSK_ExplicitInstantiationDefinition) { 4709 PendingInstantiations.push_back( 4710 std::make_pair(Var, PointOfInstantiation)); 4711 } else if (TSK == TSK_ImplicitInstantiation) { 4712 // Warn about missing definition at the end of translation unit. 4713 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 4714 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 4715 Diag(PointOfInstantiation, diag::warn_var_template_missing) 4716 << Var; 4717 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 4718 if (getLangOpts().CPlusPlus11) 4719 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var; 4720 } 4721 return; 4722 } 4723 } 4724 4725 // FIXME: We need to track the instantiation stack in order to know which 4726 // definitions should be visible within this instantiation. 4727 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember(). 4728 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var, 4729 /*InstantiatedFromMember*/false, 4730 PatternDecl, Def, TSK, 4731 /*Complain*/DefinitionRequired)) 4732 return; 4733 4734 // C++11 [temp.explicit]p10: 4735 // Except for inline functions, const variables of literal types, variables 4736 // of reference types, [...] explicit instantiation declarations 4737 // have the effect of suppressing the implicit instantiation of the entity 4738 // to which they refer. 4739 // 4740 // FIXME: That's not exactly the same as "might be usable in constant 4741 // expressions", which only allows constexpr variables and const integral 4742 // types, not arbitrary const literal types. 4743 if (TSK == TSK_ExplicitInstantiationDeclaration && 4744 !Var->mightBeUsableInConstantExpressions(getASTContext())) 4745 return; 4746 4747 // Make sure to pass the instantiated variable to the consumer at the end. 4748 struct PassToConsumerRAII { 4749 ASTConsumer &Consumer; 4750 VarDecl *Var; 4751 4752 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 4753 : Consumer(Consumer), Var(Var) { } 4754 4755 ~PassToConsumerRAII() { 4756 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 4757 } 4758 } PassToConsumerRAII(Consumer, Var); 4759 4760 // If we already have a definition, we're done. 4761 if (VarDecl *Def = Var->getDefinition()) { 4762 // We may be explicitly instantiating something we've already implicitly 4763 // instantiated. 4764 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 4765 PointOfInstantiation); 4766 return; 4767 } 4768 4769 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 4770 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4771 return; 4772 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 4773 "instantiating variable definition"); 4774 4775 // If we're performing recursive template instantiation, create our own 4776 // queue of pending implicit instantiations that we will instantiate later, 4777 // while we're still within our own instantiation context. 4778 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4779 /*Enabled=*/Recursive); 4780 4781 // Enter the scope of this instantiation. We don't use 4782 // PushDeclContext because we don't have a scope. 4783 ContextRAII PreviousContext(*this, Var->getDeclContext()); 4784 LocalInstantiationScope Local(*this); 4785 4786 LocalEagerInstantiationScope LocalInstantiations(*this); 4787 4788 VarDecl *OldVar = Var; 4789 if (Def->isStaticDataMember() && !Def->isOutOfLine()) { 4790 // We're instantiating an inline static data member whose definition was 4791 // provided inside the class. 4792 InstantiateVariableInitializer(Var, Def, TemplateArgs); 4793 } else if (!VarSpec) { 4794 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 4795 TemplateArgs)); 4796 } else if (Var->isStaticDataMember() && 4797 Var->getLexicalDeclContext()->isRecord()) { 4798 // We need to instantiate the definition of a static data member template, 4799 // and all we have is the in-class declaration of it. Instantiate a separate 4800 // declaration of the definition. 4801 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 4802 TemplateArgs); 4803 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 4804 VarSpec->getSpecializedTemplate(), Def, nullptr, 4805 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray())); 4806 if (Var) { 4807 llvm::PointerUnion<VarTemplateDecl *, 4808 VarTemplatePartialSpecializationDecl *> PatternPtr = 4809 VarSpec->getSpecializedTemplateOrPartial(); 4810 if (VarTemplatePartialSpecializationDecl *Partial = 4811 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 4812 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 4813 Partial, &VarSpec->getTemplateInstantiationArgs()); 4814 4815 // Merge the definition with the declaration. 4816 LookupResult R(*this, Var->getDeclName(), Var->getLocation(), 4817 LookupOrdinaryName, forRedeclarationInCurContext()); 4818 R.addDecl(OldVar); 4819 MergeVarDecl(Var, R); 4820 4821 // Attach the initializer. 4822 InstantiateVariableInitializer(Var, Def, TemplateArgs); 4823 } 4824 } else 4825 // Complete the existing variable's definition with an appropriately 4826 // substituted type and initializer. 4827 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 4828 4829 PreviousContext.pop(); 4830 4831 if (Var) { 4832 PassToConsumerRAII.Var = Var; 4833 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 4834 OldVar->getPointOfInstantiation()); 4835 } 4836 4837 // This variable may have local implicit instantiations that need to be 4838 // instantiated within this scope. 4839 LocalInstantiations.perform(); 4840 Local.Exit(); 4841 GlobalInstantiations.perform(); 4842 } 4843 4844 void 4845 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 4846 const CXXConstructorDecl *Tmpl, 4847 const MultiLevelTemplateArgumentList &TemplateArgs) { 4848 4849 SmallVector<CXXCtorInitializer*, 4> NewInits; 4850 bool AnyErrors = Tmpl->isInvalidDecl(); 4851 4852 // Instantiate all the initializers. 4853 for (const auto *Init : Tmpl->inits()) { 4854 // Only instantiate written initializers, let Sema re-construct implicit 4855 // ones. 4856 if (!Init->isWritten()) 4857 continue; 4858 4859 SourceLocation EllipsisLoc; 4860 4861 if (Init->isPackExpansion()) { 4862 // This is a pack expansion. We should expand it now. 4863 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 4864 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 4865 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 4866 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 4867 bool ShouldExpand = false; 4868 bool RetainExpansion = false; 4869 Optional<unsigned> NumExpansions; 4870 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 4871 BaseTL.getSourceRange(), 4872 Unexpanded, 4873 TemplateArgs, ShouldExpand, 4874 RetainExpansion, 4875 NumExpansions)) { 4876 AnyErrors = true; 4877 New->setInvalidDecl(); 4878 continue; 4879 } 4880 assert(ShouldExpand && "Partial instantiation of base initializer?"); 4881 4882 // Loop over all of the arguments in the argument pack(s), 4883 for (unsigned I = 0; I != *NumExpansions; ++I) { 4884 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 4885 4886 // Instantiate the initializer. 4887 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4888 /*CXXDirectInit=*/true); 4889 if (TempInit.isInvalid()) { 4890 AnyErrors = true; 4891 break; 4892 } 4893 4894 // Instantiate the base type. 4895 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 4896 TemplateArgs, 4897 Init->getSourceLocation(), 4898 New->getDeclName()); 4899 if (!BaseTInfo) { 4900 AnyErrors = true; 4901 break; 4902 } 4903 4904 // Build the initializer. 4905 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 4906 BaseTInfo, TempInit.get(), 4907 New->getParent(), 4908 SourceLocation()); 4909 if (NewInit.isInvalid()) { 4910 AnyErrors = true; 4911 break; 4912 } 4913 4914 NewInits.push_back(NewInit.get()); 4915 } 4916 4917 continue; 4918 } 4919 4920 // Instantiate the initializer. 4921 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4922 /*CXXDirectInit=*/true); 4923 if (TempInit.isInvalid()) { 4924 AnyErrors = true; 4925 continue; 4926 } 4927 4928 MemInitResult NewInit; 4929 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 4930 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 4931 TemplateArgs, 4932 Init->getSourceLocation(), 4933 New->getDeclName()); 4934 if (!TInfo) { 4935 AnyErrors = true; 4936 New->setInvalidDecl(); 4937 continue; 4938 } 4939 4940 if (Init->isBaseInitializer()) 4941 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(), 4942 New->getParent(), EllipsisLoc); 4943 else 4944 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(), 4945 cast<CXXRecordDecl>(CurContext->getParent())); 4946 } else if (Init->isMemberInitializer()) { 4947 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 4948 Init->getMemberLocation(), 4949 Init->getMember(), 4950 TemplateArgs)); 4951 if (!Member) { 4952 AnyErrors = true; 4953 New->setInvalidDecl(); 4954 continue; 4955 } 4956 4957 NewInit = BuildMemberInitializer(Member, TempInit.get(), 4958 Init->getSourceLocation()); 4959 } else if (Init->isIndirectMemberInitializer()) { 4960 IndirectFieldDecl *IndirectMember = 4961 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 4962 Init->getMemberLocation(), 4963 Init->getIndirectMember(), TemplateArgs)); 4964 4965 if (!IndirectMember) { 4966 AnyErrors = true; 4967 New->setInvalidDecl(); 4968 continue; 4969 } 4970 4971 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(), 4972 Init->getSourceLocation()); 4973 } 4974 4975 if (NewInit.isInvalid()) { 4976 AnyErrors = true; 4977 New->setInvalidDecl(); 4978 } else { 4979 NewInits.push_back(NewInit.get()); 4980 } 4981 } 4982 4983 // Assign all the initializers to the new constructor. 4984 ActOnMemInitializers(New, 4985 /*FIXME: ColonLoc */ 4986 SourceLocation(), 4987 NewInits, 4988 AnyErrors); 4989 } 4990 4991 // TODO: this could be templated if the various decl types used the 4992 // same method name. 4993 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 4994 ClassTemplateDecl *Instance) { 4995 Pattern = Pattern->getCanonicalDecl(); 4996 4997 do { 4998 Instance = Instance->getCanonicalDecl(); 4999 if (Pattern == Instance) return true; 5000 Instance = Instance->getInstantiatedFromMemberTemplate(); 5001 } while (Instance); 5002 5003 return false; 5004 } 5005 5006 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 5007 FunctionTemplateDecl *Instance) { 5008 Pattern = Pattern->getCanonicalDecl(); 5009 5010 do { 5011 Instance = Instance->getCanonicalDecl(); 5012 if (Pattern == Instance) return true; 5013 Instance = Instance->getInstantiatedFromMemberTemplate(); 5014 } while (Instance); 5015 5016 return false; 5017 } 5018 5019 static bool 5020 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 5021 ClassTemplatePartialSpecializationDecl *Instance) { 5022 Pattern 5023 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 5024 do { 5025 Instance = cast<ClassTemplatePartialSpecializationDecl>( 5026 Instance->getCanonicalDecl()); 5027 if (Pattern == Instance) 5028 return true; 5029 Instance = Instance->getInstantiatedFromMember(); 5030 } while (Instance); 5031 5032 return false; 5033 } 5034 5035 static bool isInstantiationOf(CXXRecordDecl *Pattern, 5036 CXXRecordDecl *Instance) { 5037 Pattern = Pattern->getCanonicalDecl(); 5038 5039 do { 5040 Instance = Instance->getCanonicalDecl(); 5041 if (Pattern == Instance) return true; 5042 Instance = Instance->getInstantiatedFromMemberClass(); 5043 } while (Instance); 5044 5045 return false; 5046 } 5047 5048 static bool isInstantiationOf(FunctionDecl *Pattern, 5049 FunctionDecl *Instance) { 5050 Pattern = Pattern->getCanonicalDecl(); 5051 5052 do { 5053 Instance = Instance->getCanonicalDecl(); 5054 if (Pattern == Instance) return true; 5055 Instance = Instance->getInstantiatedFromMemberFunction(); 5056 } while (Instance); 5057 5058 return false; 5059 } 5060 5061 static bool isInstantiationOf(EnumDecl *Pattern, 5062 EnumDecl *Instance) { 5063 Pattern = Pattern->getCanonicalDecl(); 5064 5065 do { 5066 Instance = Instance->getCanonicalDecl(); 5067 if (Pattern == Instance) return true; 5068 Instance = Instance->getInstantiatedFromMemberEnum(); 5069 } while (Instance); 5070 5071 return false; 5072 } 5073 5074 static bool isInstantiationOf(UsingShadowDecl *Pattern, 5075 UsingShadowDecl *Instance, 5076 ASTContext &C) { 5077 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance), 5078 Pattern); 5079 } 5080 5081 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance, 5082 ASTContext &C) { 5083 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 5084 } 5085 5086 template<typename T> 5087 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, 5088 ASTContext &Ctx) { 5089 // An unresolved using declaration can instantiate to an unresolved using 5090 // declaration, or to a using declaration or a using declaration pack. 5091 // 5092 // Multiple declarations can claim to be instantiated from an unresolved 5093 // using declaration if it's a pack expansion. We want the UsingPackDecl 5094 // in that case, not the individual UsingDecls within the pack. 5095 bool OtherIsPackExpansion; 5096 NamedDecl *OtherFrom; 5097 if (auto *OtherUUD = dyn_cast<T>(Other)) { 5098 OtherIsPackExpansion = OtherUUD->isPackExpansion(); 5099 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD); 5100 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) { 5101 OtherIsPackExpansion = true; 5102 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl(); 5103 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) { 5104 OtherIsPackExpansion = false; 5105 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD); 5106 } else { 5107 return false; 5108 } 5109 return Pattern->isPackExpansion() == OtherIsPackExpansion && 5110 declaresSameEntity(OtherFrom, Pattern); 5111 } 5112 5113 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 5114 VarDecl *Instance) { 5115 assert(Instance->isStaticDataMember()); 5116 5117 Pattern = Pattern->getCanonicalDecl(); 5118 5119 do { 5120 Instance = Instance->getCanonicalDecl(); 5121 if (Pattern == Instance) return true; 5122 Instance = Instance->getInstantiatedFromStaticDataMember(); 5123 } while (Instance); 5124 5125 return false; 5126 } 5127 5128 // Other is the prospective instantiation 5129 // D is the prospective pattern 5130 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 5131 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) 5132 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5133 5134 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D)) 5135 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5136 5137 if (D->getKind() != Other->getKind()) 5138 return false; 5139 5140 if (auto *Record = dyn_cast<CXXRecordDecl>(Other)) 5141 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 5142 5143 if (auto *Function = dyn_cast<FunctionDecl>(Other)) 5144 return isInstantiationOf(cast<FunctionDecl>(D), Function); 5145 5146 if (auto *Enum = dyn_cast<EnumDecl>(Other)) 5147 return isInstantiationOf(cast<EnumDecl>(D), Enum); 5148 5149 if (auto *Var = dyn_cast<VarDecl>(Other)) 5150 if (Var->isStaticDataMember()) 5151 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 5152 5153 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other)) 5154 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 5155 5156 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 5157 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 5158 5159 if (auto *PartialSpec = 5160 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 5161 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 5162 PartialSpec); 5163 5164 if (auto *Field = dyn_cast<FieldDecl>(Other)) { 5165 if (!Field->getDeclName()) { 5166 // This is an unnamed field. 5167 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field), 5168 cast<FieldDecl>(D)); 5169 } 5170 } 5171 5172 if (auto *Using = dyn_cast<UsingDecl>(Other)) 5173 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 5174 5175 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other)) 5176 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 5177 5178 return D->getDeclName() && 5179 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 5180 } 5181 5182 template<typename ForwardIterator> 5183 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 5184 NamedDecl *D, 5185 ForwardIterator first, 5186 ForwardIterator last) { 5187 for (; first != last; ++first) 5188 if (isInstantiationOf(Ctx, D, *first)) 5189 return cast<NamedDecl>(*first); 5190 5191 return nullptr; 5192 } 5193 5194 /// Finds the instantiation of the given declaration context 5195 /// within the current instantiation. 5196 /// 5197 /// \returns NULL if there was an error 5198 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 5199 const MultiLevelTemplateArgumentList &TemplateArgs) { 5200 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 5201 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true); 5202 return cast_or_null<DeclContext>(ID); 5203 } else return DC; 5204 } 5205 5206 /// Find the instantiation of the given declaration within the 5207 /// current instantiation. 5208 /// 5209 /// This routine is intended to be used when \p D is a declaration 5210 /// referenced from within a template, that needs to mapped into the 5211 /// corresponding declaration within an instantiation. For example, 5212 /// given: 5213 /// 5214 /// \code 5215 /// template<typename T> 5216 /// struct X { 5217 /// enum Kind { 5218 /// KnownValue = sizeof(T) 5219 /// }; 5220 /// 5221 /// bool getKind() const { return KnownValue; } 5222 /// }; 5223 /// 5224 /// template struct X<int>; 5225 /// \endcode 5226 /// 5227 /// In the instantiation of X<int>::getKind(), we need to map the \p 5228 /// EnumConstantDecl for \p KnownValue (which refers to 5229 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue). 5230 /// \p FindInstantiatedDecl performs this mapping from within the instantiation 5231 /// of X<int>. 5232 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 5233 const MultiLevelTemplateArgumentList &TemplateArgs, 5234 bool FindingInstantiatedContext) { 5235 DeclContext *ParentDC = D->getDeclContext(); 5236 // FIXME: Parmeters of pointer to functions (y below) that are themselves 5237 // parameters (p below) can have their ParentDC set to the translation-unit 5238 // - thus we can not consistently check if the ParentDC of such a parameter 5239 // is Dependent or/and a FunctionOrMethod. 5240 // For e.g. this code, during Template argument deduction tries to 5241 // find an instantiated decl for (T y) when the ParentDC for y is 5242 // the translation unit. 5243 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 5244 // float baz(float(*)()) { return 0.0; } 5245 // Foo(baz); 5246 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 5247 // it gets here, always has a FunctionOrMethod as its ParentDC?? 5248 // For now: 5249 // - as long as we have a ParmVarDecl whose parent is non-dependent and 5250 // whose type is not instantiation dependent, do nothing to the decl 5251 // - otherwise find its instantiated decl. 5252 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() && 5253 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 5254 return D; 5255 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 5256 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 5257 ((ParentDC->isFunctionOrMethod() || 5258 isa<OMPDeclareReductionDecl>(ParentDC) || 5259 isa<OMPDeclareMapperDecl>(ParentDC)) && 5260 ParentDC->isDependentContext()) || 5261 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 5262 // D is a local of some kind. Look into the map of local 5263 // declarations to their instantiations. 5264 if (CurrentInstantiationScope) { 5265 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) { 5266 if (Decl *FD = Found->dyn_cast<Decl *>()) 5267 return cast<NamedDecl>(FD); 5268 5269 int PackIdx = ArgumentPackSubstitutionIndex; 5270 assert(PackIdx != -1 && 5271 "found declaration pack but not pack expanding"); 5272 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 5273 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 5274 } 5275 } 5276 5277 // If we're performing a partial substitution during template argument 5278 // deduction, we may not have values for template parameters yet. They 5279 // just map to themselves. 5280 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 5281 isa<TemplateTemplateParmDecl>(D)) 5282 return D; 5283 5284 if (D->isInvalidDecl()) 5285 return nullptr; 5286 5287 // Normally this function only searches for already instantiated declaration 5288 // however we have to make an exclusion for local types used before 5289 // definition as in the code: 5290 // 5291 // template<typename T> void f1() { 5292 // void g1(struct x1); 5293 // struct x1 {}; 5294 // } 5295 // 5296 // In this case instantiation of the type of 'g1' requires definition of 5297 // 'x1', which is defined later. Error recovery may produce an enum used 5298 // before definition. In these cases we need to instantiate relevant 5299 // declarations here. 5300 bool NeedInstantiate = false; 5301 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 5302 NeedInstantiate = RD->isLocalClass(); 5303 else 5304 NeedInstantiate = isa<EnumDecl>(D); 5305 if (NeedInstantiate) { 5306 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 5307 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 5308 return cast<TypeDecl>(Inst); 5309 } 5310 5311 // If we didn't find the decl, then we must have a label decl that hasn't 5312 // been found yet. Lazily instantiate it and return it now. 5313 assert(isa<LabelDecl>(D)); 5314 5315 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 5316 assert(Inst && "Failed to instantiate label??"); 5317 5318 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 5319 return cast<LabelDecl>(Inst); 5320 } 5321 5322 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 5323 if (!Record->isDependentContext()) 5324 return D; 5325 5326 // Determine whether this record is the "templated" declaration describing 5327 // a class template or class template partial specialization. 5328 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 5329 if (ClassTemplate) 5330 ClassTemplate = ClassTemplate->getCanonicalDecl(); 5331 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5332 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 5333 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 5334 5335 // Walk the current context to find either the record or an instantiation of 5336 // it. 5337 DeclContext *DC = CurContext; 5338 while (!DC->isFileContext()) { 5339 // If we're performing substitution while we're inside the template 5340 // definition, we'll find our own context. We're done. 5341 if (DC->Equals(Record)) 5342 return Record; 5343 5344 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 5345 // Check whether we're in the process of instantiating a class template 5346 // specialization of the template we're mapping. 5347 if (ClassTemplateSpecializationDecl *InstSpec 5348 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 5349 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 5350 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 5351 return InstRecord; 5352 } 5353 5354 // Check whether we're in the process of instantiating a member class. 5355 if (isInstantiationOf(Record, InstRecord)) 5356 return InstRecord; 5357 } 5358 5359 // Move to the outer template scope. 5360 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 5361 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 5362 DC = FD->getLexicalDeclContext(); 5363 continue; 5364 } 5365 // An implicit deduction guide acts as if it's within the class template 5366 // specialization described by its name and first N template params. 5367 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD); 5368 if (Guide && Guide->isImplicit()) { 5369 TemplateDecl *TD = Guide->getDeducedTemplate(); 5370 // Convert the arguments to an "as-written" list. 5371 TemplateArgumentListInfo Args(Loc, Loc); 5372 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front( 5373 TD->getTemplateParameters()->size())) { 5374 ArrayRef<TemplateArgument> Unpacked(Arg); 5375 if (Arg.getKind() == TemplateArgument::Pack) 5376 Unpacked = Arg.pack_elements(); 5377 for (TemplateArgument UnpackedArg : Unpacked) 5378 Args.addArgument( 5379 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc)); 5380 } 5381 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args); 5382 if (T.isNull()) 5383 return nullptr; 5384 auto *SubstRecord = T->getAsCXXRecordDecl(); 5385 assert(SubstRecord && "class template id not a class type?"); 5386 // Check that this template-id names the primary template and not a 5387 // partial or explicit specialization. (In the latter cases, it's 5388 // meaningless to attempt to find an instantiation of D within the 5389 // specialization.) 5390 // FIXME: The standard doesn't say what should happen here. 5391 if (FindingInstantiatedContext && 5392 usesPartialOrExplicitSpecialization( 5393 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) { 5394 Diag(Loc, diag::err_specialization_not_primary_template) 5395 << T << (SubstRecord->getTemplateSpecializationKind() == 5396 TSK_ExplicitSpecialization); 5397 return nullptr; 5398 } 5399 DC = SubstRecord; 5400 continue; 5401 } 5402 } 5403 5404 DC = DC->getParent(); 5405 } 5406 5407 // Fall through to deal with other dependent record types (e.g., 5408 // anonymous unions in class templates). 5409 } 5410 5411 if (!ParentDC->isDependentContext()) 5412 return D; 5413 5414 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 5415 if (!ParentDC) 5416 return nullptr; 5417 5418 if (ParentDC != D->getDeclContext()) { 5419 // We performed some kind of instantiation in the parent context, 5420 // so now we need to look into the instantiated parent context to 5421 // find the instantiation of the declaration D. 5422 5423 // If our context used to be dependent, we may need to instantiate 5424 // it before performing lookup into that context. 5425 bool IsBeingInstantiated = false; 5426 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 5427 if (!Spec->isDependentContext()) { 5428 QualType T = Context.getTypeDeclType(Spec); 5429 const RecordType *Tag = T->getAs<RecordType>(); 5430 assert(Tag && "type of non-dependent record is not a RecordType"); 5431 if (Tag->isBeingDefined()) 5432 IsBeingInstantiated = true; 5433 if (!Tag->isBeingDefined() && 5434 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 5435 return nullptr; 5436 5437 ParentDC = Tag->getDecl(); 5438 } 5439 } 5440 5441 NamedDecl *Result = nullptr; 5442 // FIXME: If the name is a dependent name, this lookup won't necessarily 5443 // find it. Does that ever matter? 5444 if (auto Name = D->getDeclName()) { 5445 DeclarationNameInfo NameInfo(Name, D->getLocation()); 5446 DeclarationNameInfo NewNameInfo = 5447 SubstDeclarationNameInfo(NameInfo, TemplateArgs); 5448 Name = NewNameInfo.getName(); 5449 if (!Name) 5450 return nullptr; 5451 DeclContext::lookup_result Found = ParentDC->lookup(Name); 5452 5453 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) { 5454 VarTemplateDecl *Templ = cast_or_null<VarTemplateDecl>( 5455 findInstantiationOf(Context, VTSD->getSpecializedTemplate(), 5456 Found.begin(), Found.end())); 5457 if (!Templ) 5458 return nullptr; 5459 Result = getVarTemplateSpecialization( 5460 Templ, &VTSD->getTemplateArgsInfo(), NewNameInfo, SourceLocation()); 5461 } else 5462 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 5463 } else { 5464 // Since we don't have a name for the entity we're looking for, 5465 // our only option is to walk through all of the declarations to 5466 // find that name. This will occur in a few cases: 5467 // 5468 // - anonymous struct/union within a template 5469 // - unnamed class/struct/union/enum within a template 5470 // 5471 // FIXME: Find a better way to find these instantiations! 5472 Result = findInstantiationOf(Context, D, 5473 ParentDC->decls_begin(), 5474 ParentDC->decls_end()); 5475 } 5476 5477 if (!Result) { 5478 if (isa<UsingShadowDecl>(D)) { 5479 // UsingShadowDecls can instantiate to nothing because of using hiding. 5480 } else if (Diags.hasErrorOccurred()) { 5481 // We've already complained about something, so most likely this 5482 // declaration failed to instantiate. There's no point in complaining 5483 // further, since this is normal in invalid code. 5484 } else if (IsBeingInstantiated) { 5485 // The class in which this member exists is currently being 5486 // instantiated, and we haven't gotten around to instantiating this 5487 // member yet. This can happen when the code uses forward declarations 5488 // of member classes, and introduces ordering dependencies via 5489 // template instantiation. 5490 Diag(Loc, diag::err_member_not_yet_instantiated) 5491 << D->getDeclName() 5492 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 5493 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 5494 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 5495 // This enumeration constant was found when the template was defined, 5496 // but can't be found in the instantiation. This can happen if an 5497 // unscoped enumeration member is explicitly specialized. 5498 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 5499 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 5500 TemplateArgs)); 5501 assert(Spec->getTemplateSpecializationKind() == 5502 TSK_ExplicitSpecialization); 5503 Diag(Loc, diag::err_enumerator_does_not_exist) 5504 << D->getDeclName() 5505 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 5506 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 5507 << Context.getTypeDeclType(Spec); 5508 } else { 5509 // We should have found something, but didn't. 5510 llvm_unreachable("Unable to find instantiation of declaration!"); 5511 } 5512 } 5513 5514 D = Result; 5515 } 5516 5517 return D; 5518 } 5519 5520 /// Performs template instantiation for all implicit template 5521 /// instantiations we have seen until this point. 5522 void Sema::PerformPendingInstantiations(bool LocalOnly) { 5523 while (!PendingLocalImplicitInstantiations.empty() || 5524 (!LocalOnly && !PendingInstantiations.empty())) { 5525 PendingImplicitInstantiation Inst; 5526 5527 if (PendingLocalImplicitInstantiations.empty()) { 5528 Inst = PendingInstantiations.front(); 5529 PendingInstantiations.pop_front(); 5530 } else { 5531 Inst = PendingLocalImplicitInstantiations.front(); 5532 PendingLocalImplicitInstantiations.pop_front(); 5533 } 5534 5535 // Instantiate function definitions 5536 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 5537 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 5538 TSK_ExplicitInstantiationDefinition; 5539 if (Function->isMultiVersion()) { 5540 getASTContext().forEachMultiversionedFunctionVersion( 5541 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) { 5542 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true, 5543 DefinitionRequired, true); 5544 if (CurFD->isDefined()) 5545 CurFD->setInstantiationIsPending(false); 5546 }); 5547 } else { 5548 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true, 5549 DefinitionRequired, true); 5550 if (Function->isDefined()) 5551 Function->setInstantiationIsPending(false); 5552 } 5553 continue; 5554 } 5555 5556 // Instantiate variable definitions 5557 VarDecl *Var = cast<VarDecl>(Inst.first); 5558 5559 assert((Var->isStaticDataMember() || 5560 isa<VarTemplateSpecializationDecl>(Var)) && 5561 "Not a static data member, nor a variable template" 5562 " specialization?"); 5563 5564 // Don't try to instantiate declarations if the most recent redeclaration 5565 // is invalid. 5566 if (Var->getMostRecentDecl()->isInvalidDecl()) 5567 continue; 5568 5569 // Check if the most recent declaration has changed the specialization kind 5570 // and removed the need for implicit instantiation. 5571 switch (Var->getMostRecentDecl() 5572 ->getTemplateSpecializationKindForInstantiation()) { 5573 case TSK_Undeclared: 5574 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 5575 case TSK_ExplicitInstantiationDeclaration: 5576 case TSK_ExplicitSpecialization: 5577 continue; // No longer need to instantiate this type. 5578 case TSK_ExplicitInstantiationDefinition: 5579 // We only need an instantiation if the pending instantiation *is* the 5580 // explicit instantiation. 5581 if (Var != Var->getMostRecentDecl()) 5582 continue; 5583 break; 5584 case TSK_ImplicitInstantiation: 5585 break; 5586 } 5587 5588 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 5589 "instantiating variable definition"); 5590 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 5591 TSK_ExplicitInstantiationDefinition; 5592 5593 // Instantiate static data member definitions or variable template 5594 // specializations. 5595 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 5596 DefinitionRequired, true); 5597 } 5598 } 5599 5600 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 5601 const MultiLevelTemplateArgumentList &TemplateArgs) { 5602 for (auto DD : Pattern->ddiags()) { 5603 switch (DD->getKind()) { 5604 case DependentDiagnostic::Access: 5605 HandleDependentAccessCheck(*DD, TemplateArgs); 5606 break; 5607 } 5608 } 5609 } 5610