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(Aligned->getLocation(), New, Result.getAs<Expr>(), 90 Aligned->getSpellingListIndex(), IsPackExpansion); 91 } else { 92 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(), 93 TemplateArgs, Aligned->getLocation(), 94 DeclarationName()); 95 if (Result) 96 S.AddAlignedAttr(Aligned->getLocation(), New, Result, 97 Aligned->getSpellingListIndex(), IsPackExpansion); 98 } 99 } 100 101 static void instantiateDependentAlignedAttr( 102 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 103 const AlignedAttr *Aligned, Decl *New) { 104 if (!Aligned->isPackExpansion()) { 105 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 106 return; 107 } 108 109 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 110 if (Aligned->isAlignmentExpr()) 111 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(), 112 Unexpanded); 113 else 114 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(), 115 Unexpanded); 116 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); 117 118 // Determine whether we can expand this attribute pack yet. 119 bool Expand = true, RetainExpansion = false; 120 Optional<unsigned> NumExpansions; 121 // FIXME: Use the actual location of the ellipsis. 122 SourceLocation EllipsisLoc = Aligned->getLocation(); 123 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(), 124 Unexpanded, TemplateArgs, Expand, 125 RetainExpansion, NumExpansions)) 126 return; 127 128 if (!Expand) { 129 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1); 130 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true); 131 } else { 132 for (unsigned I = 0; I != *NumExpansions; ++I) { 133 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I); 134 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); 135 } 136 } 137 } 138 139 static void instantiateDependentAssumeAlignedAttr( 140 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 141 const AssumeAlignedAttr *Aligned, Decl *New) { 142 // The alignment expression is a constant expression. 143 EnterExpressionEvaluationContext Unevaluated( 144 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 145 146 Expr *E, *OE = nullptr; 147 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs); 148 if (Result.isInvalid()) 149 return; 150 E = Result.getAs<Expr>(); 151 152 if (Aligned->getOffset()) { 153 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs); 154 if (Result.isInvalid()) 155 return; 156 OE = Result.getAs<Expr>(); 157 } 158 159 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE, 160 Aligned->getSpellingListIndex()); 161 } 162 163 static void instantiateDependentAlignValueAttr( 164 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 165 const AlignValueAttr *Aligned, Decl *New) { 166 // The alignment expression is a constant expression. 167 EnterExpressionEvaluationContext Unevaluated( 168 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 169 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs); 170 if (!Result.isInvalid()) 171 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(), 172 Aligned->getSpellingListIndex()); 173 } 174 175 static void instantiateDependentAllocAlignAttr( 176 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 177 const AllocAlignAttr *Align, Decl *New) { 178 Expr *Param = IntegerLiteral::Create( 179 S.getASTContext(), 180 llvm::APInt(64, Align->getParamIndex().getSourceIndex()), 181 S.getASTContext().UnsignedLongLongTy, Align->getLocation()); 182 S.AddAllocAlignAttr(Align->getLocation(), New, Param, 183 Align->getSpellingListIndex()); 184 } 185 186 static Expr *instantiateDependentFunctionAttrCondition( 187 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 188 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) { 189 Expr *Cond = nullptr; 190 { 191 Sema::ContextRAII SwitchContext(S, New); 192 EnterExpressionEvaluationContext Unevaluated( 193 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 194 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs); 195 if (Result.isInvalid()) 196 return nullptr; 197 Cond = Result.getAs<Expr>(); 198 } 199 if (!Cond->isTypeDependent()) { 200 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 201 if (Converted.isInvalid()) 202 return nullptr; 203 Cond = Converted.get(); 204 } 205 206 SmallVector<PartialDiagnosticAt, 8> Diags; 207 if (OldCond->isValueDependent() && !Cond->isValueDependent() && 208 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) { 209 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A; 210 for (const auto &P : Diags) 211 S.Diag(P.first, P.second); 212 return nullptr; 213 } 214 return Cond; 215 } 216 217 static void instantiateDependentEnableIfAttr( 218 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 219 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) { 220 Expr *Cond = instantiateDependentFunctionAttrCondition( 221 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New); 222 223 if (Cond) 224 New->addAttr(new (S.getASTContext()) EnableIfAttr( 225 EIA->getLocation(), S.getASTContext(), Cond, EIA->getMessage(), 226 EIA->getSpellingListIndex())); 227 } 228 229 static void instantiateDependentDiagnoseIfAttr( 230 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 231 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) { 232 Expr *Cond = instantiateDependentFunctionAttrCondition( 233 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New); 234 235 if (Cond) 236 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr( 237 DIA->getLocation(), S.getASTContext(), Cond, DIA->getMessage(), 238 DIA->getDiagnosticType(), DIA->getArgDependent(), New, 239 DIA->getSpellingListIndex())); 240 } 241 242 // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using 243 // template A as the base and arguments from TemplateArgs. 244 static void instantiateDependentCUDALaunchBoundsAttr( 245 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 246 const CUDALaunchBoundsAttr &Attr, Decl *New) { 247 // The alignment expression is a constant expression. 248 EnterExpressionEvaluationContext Unevaluated( 249 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 250 251 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs); 252 if (Result.isInvalid()) 253 return; 254 Expr *MaxThreads = Result.getAs<Expr>(); 255 256 Expr *MinBlocks = nullptr; 257 if (Attr.getMinBlocks()) { 258 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs); 259 if (Result.isInvalid()) 260 return; 261 MinBlocks = Result.getAs<Expr>(); 262 } 263 264 S.AddLaunchBoundsAttr(Attr.getLocation(), New, MaxThreads, MinBlocks, 265 Attr.getSpellingListIndex()); 266 } 267 268 static void 269 instantiateDependentModeAttr(Sema &S, 270 const MultiLevelTemplateArgumentList &TemplateArgs, 271 const ModeAttr &Attr, Decl *New) { 272 S.AddModeAttr(Attr.getRange(), New, Attr.getMode(), 273 Attr.getSpellingListIndex(), /*InInstantiation=*/true); 274 } 275 276 /// Instantiation of 'declare simd' attribute and its arguments. 277 static void instantiateOMPDeclareSimdDeclAttr( 278 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 279 const OMPDeclareSimdDeclAttr &Attr, Decl *New) { 280 // Allow 'this' in clauses with varlists. 281 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New)) 282 New = FTD->getTemplatedDecl(); 283 auto *FD = cast<FunctionDecl>(New); 284 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext()); 285 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps; 286 SmallVector<unsigned, 4> LinModifiers; 287 288 auto SubstExpr = [&](Expr *E) -> ExprResult { 289 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 290 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 291 Sema::ContextRAII SavedContext(S, FD); 292 LocalInstantiationScope Local(S); 293 if (FD->getNumParams() > PVD->getFunctionScopeIndex()) 294 Local.InstantiatedLocal( 295 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex())); 296 return S.SubstExpr(E, TemplateArgs); 297 } 298 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(), 299 FD->isCXXInstanceMember()); 300 return S.SubstExpr(E, TemplateArgs); 301 }; 302 303 // Substitute a single OpenMP clause, which is a potentially-evaluated 304 // full-expression. 305 auto Subst = [&](Expr *E) -> ExprResult { 306 EnterExpressionEvaluationContext Evaluated( 307 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 308 ExprResult Res = SubstExpr(E); 309 if (Res.isInvalid()) 310 return Res; 311 return S.ActOnFinishFullExpr(Res.get(), false); 312 }; 313 314 ExprResult Simdlen; 315 if (auto *E = Attr.getSimdlen()) 316 Simdlen = Subst(E); 317 318 if (Attr.uniforms_size() > 0) { 319 for(auto *E : Attr.uniforms()) { 320 ExprResult Inst = Subst(E); 321 if (Inst.isInvalid()) 322 continue; 323 Uniforms.push_back(Inst.get()); 324 } 325 } 326 327 auto AI = Attr.alignments_begin(); 328 for (auto *E : Attr.aligneds()) { 329 ExprResult Inst = Subst(E); 330 if (Inst.isInvalid()) 331 continue; 332 Aligneds.push_back(Inst.get()); 333 Inst = ExprEmpty(); 334 if (*AI) 335 Inst = S.SubstExpr(*AI, TemplateArgs); 336 Alignments.push_back(Inst.get()); 337 ++AI; 338 } 339 340 auto SI = Attr.steps_begin(); 341 for (auto *E : Attr.linears()) { 342 ExprResult Inst = Subst(E); 343 if (Inst.isInvalid()) 344 continue; 345 Linears.push_back(Inst.get()); 346 Inst = ExprEmpty(); 347 if (*SI) 348 Inst = S.SubstExpr(*SI, TemplateArgs); 349 Steps.push_back(Inst.get()); 350 ++SI; 351 } 352 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end()); 353 (void)S.ActOnOpenMPDeclareSimdDirective( 354 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(), 355 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps, 356 Attr.getRange()); 357 } 358 359 static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr( 360 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 361 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) { 362 // Both min and max expression are constant expressions. 363 EnterExpressionEvaluationContext Unevaluated( 364 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 365 366 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs); 367 if (Result.isInvalid()) 368 return; 369 Expr *MinExpr = Result.getAs<Expr>(); 370 371 Result = S.SubstExpr(Attr.getMax(), TemplateArgs); 372 if (Result.isInvalid()) 373 return; 374 Expr *MaxExpr = Result.getAs<Expr>(); 375 376 S.addAMDGPUFlatWorkGroupSizeAttr(Attr.getLocation(), New, MinExpr, MaxExpr, 377 Attr.getSpellingListIndex()); 378 } 379 380 static ExplicitSpecifier 381 instantiateExplicitSpecifier(Sema &S, 382 const MultiLevelTemplateArgumentList &TemplateArgs, 383 ExplicitSpecifier ES, FunctionDecl *New) { 384 if (!ES.getExpr()) 385 return ES; 386 Expr *OldCond = ES.getExpr(); 387 Expr *Cond = nullptr; 388 { 389 EnterExpressionEvaluationContext Unevaluated( 390 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 391 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs); 392 if (SubstResult.isInvalid()) { 393 return ExplicitSpecifier::Invalid(); 394 } 395 Cond = SubstResult.get(); 396 } 397 ExplicitSpecifier Result(Cond, ES.getKind()); 398 if (!Cond->isTypeDependent()) 399 S.tryResolveExplicitSpecifier(Result); 400 return Result; 401 } 402 403 static void instantiateDependentAMDGPUWavesPerEUAttr( 404 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, 405 const AMDGPUWavesPerEUAttr &Attr, Decl *New) { 406 // Both min and max expression are constant expressions. 407 EnterExpressionEvaluationContext Unevaluated( 408 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 409 410 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs); 411 if (Result.isInvalid()) 412 return; 413 Expr *MinExpr = Result.getAs<Expr>(); 414 415 Expr *MaxExpr = nullptr; 416 if (auto Max = Attr.getMax()) { 417 Result = S.SubstExpr(Max, TemplateArgs); 418 if (Result.isInvalid()) 419 return; 420 MaxExpr = Result.getAs<Expr>(); 421 } 422 423 S.addAMDGPUWavesPerEUAttr(Attr.getLocation(), New, MinExpr, MaxExpr, 424 Attr.getSpellingListIndex()); 425 } 426 427 void Sema::InstantiateAttrsForDecl( 428 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl, 429 Decl *New, LateInstantiatedAttrVec *LateAttrs, 430 LocalInstantiationScope *OuterMostScope) { 431 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) { 432 for (const auto *TmplAttr : Tmpl->attrs()) { 433 // FIXME: If any of the special case versions from InstantiateAttrs become 434 // applicable to template declaration, we'll need to add them here. 435 CXXThisScopeRAII ThisScope( 436 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()), 437 Qualifiers(), ND->isCXXInstanceMember()); 438 439 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl( 440 TmplAttr, Context, *this, TemplateArgs); 441 if (NewAttr) 442 New->addAttr(NewAttr); 443 } 444 } 445 } 446 447 static Sema::RetainOwnershipKind 448 attrToRetainOwnershipKind(const Attr *A) { 449 switch (A->getKind()) { 450 case clang::attr::CFConsumed: 451 return Sema::RetainOwnershipKind::CF; 452 case clang::attr::OSConsumed: 453 return Sema::RetainOwnershipKind::OS; 454 case clang::attr::NSConsumed: 455 return Sema::RetainOwnershipKind::NS; 456 default: 457 llvm_unreachable("Wrong argument supplied"); 458 } 459 } 460 461 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 462 const Decl *Tmpl, Decl *New, 463 LateInstantiatedAttrVec *LateAttrs, 464 LocalInstantiationScope *OuterMostScope) { 465 for (const auto *TmplAttr : Tmpl->attrs()) { 466 // FIXME: This should be generalized to more than just the AlignedAttr. 467 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr); 468 if (Aligned && Aligned->isAlignmentDependent()) { 469 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New); 470 continue; 471 } 472 473 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr); 474 if (AssumeAligned) { 475 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New); 476 continue; 477 } 478 479 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr); 480 if (AlignValue) { 481 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New); 482 continue; 483 } 484 485 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) { 486 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New); 487 continue; 488 } 489 490 491 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) { 492 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl, 493 cast<FunctionDecl>(New)); 494 continue; 495 } 496 497 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) { 498 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl, 499 cast<FunctionDecl>(New)); 500 continue; 501 } 502 503 if (const CUDALaunchBoundsAttr *CUDALaunchBounds = 504 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) { 505 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs, 506 *CUDALaunchBounds, New); 507 continue; 508 } 509 510 if (const ModeAttr *Mode = dyn_cast<ModeAttr>(TmplAttr)) { 511 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New); 512 continue; 513 } 514 515 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) { 516 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New); 517 continue; 518 } 519 520 if (const AMDGPUFlatWorkGroupSizeAttr *AMDGPUFlatWorkGroupSize = 521 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) { 522 instantiateDependentAMDGPUFlatWorkGroupSizeAttr( 523 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New); 524 } 525 526 if (const AMDGPUWavesPerEUAttr *AMDGPUFlatWorkGroupSize = 527 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) { 528 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs, 529 *AMDGPUFlatWorkGroupSize, New); 530 } 531 532 // Existing DLL attribute on the instantiation takes precedence. 533 if (TmplAttr->getKind() == attr::DLLExport || 534 TmplAttr->getKind() == attr::DLLImport) { 535 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) { 536 continue; 537 } 538 } 539 540 if (auto ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) { 541 AddParameterABIAttr(ABIAttr->getRange(), New, ABIAttr->getABI(), 542 ABIAttr->getSpellingListIndex()); 543 continue; 544 } 545 546 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) || 547 isa<CFConsumedAttr>(TmplAttr)) { 548 AddXConsumedAttr(New, TmplAttr->getRange(), 549 TmplAttr->getSpellingListIndex(), 550 attrToRetainOwnershipKind(TmplAttr), 551 /*template instantiation=*/true); 552 continue; 553 } 554 555 assert(!TmplAttr->isPackExpansion()); 556 if (TmplAttr->isLateParsed() && LateAttrs) { 557 // Late parsed attributes must be instantiated and attached after the 558 // enclosing class has been instantiated. See Sema::InstantiateClass. 559 LocalInstantiationScope *Saved = nullptr; 560 if (CurrentInstantiationScope) 561 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); 562 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); 563 } else { 564 // Allow 'this' within late-parsed attributes. 565 NamedDecl *ND = dyn_cast<NamedDecl>(New); 566 CXXRecordDecl *ThisContext = 567 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); 568 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), 569 ND && ND->isCXXInstanceMember()); 570 571 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, 572 *this, TemplateArgs); 573 if (NewAttr) 574 New->addAttr(NewAttr); 575 } 576 } 577 } 578 579 /// Get the previous declaration of a declaration for the purposes of template 580 /// instantiation. If this finds a previous declaration, then the previous 581 /// declaration of the instantiation of D should be an instantiation of the 582 /// result of this function. 583 template<typename DeclT> 584 static DeclT *getPreviousDeclForInstantiation(DeclT *D) { 585 DeclT *Result = D->getPreviousDecl(); 586 587 // If the declaration is within a class, and the previous declaration was 588 // merged from a different definition of that class, then we don't have a 589 // previous declaration for the purpose of template instantiation. 590 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) && 591 D->getLexicalDeclContext() != Result->getLexicalDeclContext()) 592 return nullptr; 593 594 return Result; 595 } 596 597 Decl * 598 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 599 llvm_unreachable("Translation units cannot be instantiated"); 600 } 601 602 Decl * 603 TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) { 604 llvm_unreachable("pragma comment cannot be instantiated"); 605 } 606 607 Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl( 608 PragmaDetectMismatchDecl *D) { 609 llvm_unreachable("pragma comment cannot be instantiated"); 610 } 611 612 Decl * 613 TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) { 614 llvm_unreachable("extern \"C\" context cannot be instantiated"); 615 } 616 617 Decl * 618 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { 619 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), 620 D->getIdentifier()); 621 Owner->addDecl(Inst); 622 return Inst; 623 } 624 625 Decl * 626 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { 627 llvm_unreachable("Namespaces cannot be instantiated"); 628 } 629 630 Decl * 631 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 632 NamespaceAliasDecl *Inst 633 = NamespaceAliasDecl::Create(SemaRef.Context, Owner, 634 D->getNamespaceLoc(), 635 D->getAliasLoc(), 636 D->getIdentifier(), 637 D->getQualifierLoc(), 638 D->getTargetNameLoc(), 639 D->getNamespace()); 640 Owner->addDecl(Inst); 641 return Inst; 642 } 643 644 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, 645 bool IsTypeAlias) { 646 bool Invalid = false; 647 TypeSourceInfo *DI = D->getTypeSourceInfo(); 648 if (DI->getType()->isInstantiationDependentType() || 649 DI->getType()->isVariablyModifiedType()) { 650 DI = SemaRef.SubstType(DI, TemplateArgs, 651 D->getLocation(), D->getDeclName()); 652 if (!DI) { 653 Invalid = true; 654 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy); 655 } 656 } else { 657 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType()); 658 } 659 660 // HACK: g++ has a bug where it gets the value kind of ?: wrong. 661 // libstdc++ relies upon this bug in its implementation of common_type. 662 // If we happen to be processing that implementation, fake up the g++ ?: 663 // semantics. See LWG issue 2141 for more information on the bug. 664 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>(); 665 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 666 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) && 667 DT->isReferenceType() && 668 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() && 669 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") && 670 D->getIdentifier() && D->getIdentifier()->isStr("type") && 671 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc())) 672 // Fold it to the (non-reference) type which g++ would have produced. 673 DI = SemaRef.Context.getTrivialTypeSourceInfo( 674 DI->getType().getNonReferenceType()); 675 676 // Create the new typedef 677 TypedefNameDecl *Typedef; 678 if (IsTypeAlias) 679 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(), 680 D->getLocation(), D->getIdentifier(), DI); 681 else 682 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(), 683 D->getLocation(), D->getIdentifier(), DI); 684 if (Invalid) 685 Typedef->setInvalidDecl(); 686 687 // If the old typedef was the name for linkage purposes of an anonymous 688 // tag decl, re-establish that relationship for the new typedef. 689 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { 690 TagDecl *oldTag = oldTagType->getDecl(); 691 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) { 692 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); 693 assert(!newTag->hasNameForLinkage()); 694 newTag->setTypedefNameForAnonDecl(Typedef); 695 } 696 } 697 698 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) { 699 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev, 700 TemplateArgs); 701 if (!InstPrev) 702 return nullptr; 703 704 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev); 705 706 // If the typedef types are not identical, reject them. 707 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); 708 709 Typedef->setPreviousDecl(InstPrevTypedef); 710 } 711 712 SemaRef.InstantiateAttrs(TemplateArgs, D, 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 2343 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2344 TypeSourceInfo *InstantiatedDefaultArg = 2345 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, 2346 D->getDefaultArgumentLoc(), D->getDeclName()); 2347 if (InstantiatedDefaultArg) 2348 Inst->setDefaultArgument(InstantiatedDefaultArg); 2349 } 2350 2351 // Introduce this template parameter's instantiation into the instantiation 2352 // scope. 2353 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 2354 2355 return Inst; 2356 } 2357 2358 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 2359 NonTypeTemplateParmDecl *D) { 2360 // Substitute into the type of the non-type template parameter. 2361 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 2362 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 2363 SmallVector<QualType, 4> ExpandedParameterPackTypes; 2364 bool IsExpandedParameterPack = false; 2365 TypeSourceInfo *DI; 2366 QualType T; 2367 bool Invalid = false; 2368 2369 if (D->isExpandedParameterPack()) { 2370 // The non-type template parameter pack is an already-expanded pack 2371 // expansion of types. Substitute into each of the expanded types. 2372 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 2373 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 2374 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 2375 TypeSourceInfo *NewDI = 2376 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs, 2377 D->getLocation(), D->getDeclName()); 2378 if (!NewDI) 2379 return nullptr; 2380 2381 QualType NewT = 2382 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2383 if (NewT.isNull()) 2384 return nullptr; 2385 2386 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2387 ExpandedParameterPackTypes.push_back(NewT); 2388 } 2389 2390 IsExpandedParameterPack = true; 2391 DI = D->getTypeSourceInfo(); 2392 T = DI->getType(); 2393 } else if (D->isPackExpansion()) { 2394 // The non-type template parameter pack's type is a pack expansion of types. 2395 // Determine whether we need to expand this parameter pack into separate 2396 // types. 2397 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); 2398 TypeLoc Pattern = Expansion.getPatternLoc(); 2399 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2400 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 2401 2402 // Determine whether the set of unexpanded parameter packs can and should 2403 // be expanded. 2404 bool Expand = true; 2405 bool RetainExpansion = false; 2406 Optional<unsigned> OrigNumExpansions 2407 = Expansion.getTypePtr()->getNumExpansions(); 2408 Optional<unsigned> NumExpansions = OrigNumExpansions; 2409 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 2410 Pattern.getSourceRange(), 2411 Unexpanded, 2412 TemplateArgs, 2413 Expand, RetainExpansion, 2414 NumExpansions)) 2415 return nullptr; 2416 2417 if (Expand) { 2418 for (unsigned I = 0; I != *NumExpansions; ++I) { 2419 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2420 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 2421 D->getLocation(), 2422 D->getDeclName()); 2423 if (!NewDI) 2424 return nullptr; 2425 2426 QualType NewT = 2427 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2428 if (NewT.isNull()) 2429 return nullptr; 2430 2431 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2432 ExpandedParameterPackTypes.push_back(NewT); 2433 } 2434 2435 // Note that we have an expanded parameter pack. The "type" of this 2436 // expanded parameter pack is the original expansion type, but callers 2437 // will end up using the expanded parameter pack types for type-checking. 2438 IsExpandedParameterPack = true; 2439 DI = D->getTypeSourceInfo(); 2440 T = DI->getType(); 2441 } else { 2442 // We cannot fully expand the pack expansion now, so substitute into the 2443 // pattern and create a new pack expansion type. 2444 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2445 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 2446 D->getLocation(), 2447 D->getDeclName()); 2448 if (!NewPattern) 2449 return nullptr; 2450 2451 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation()); 2452 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 2453 NumExpansions); 2454 if (!DI) 2455 return nullptr; 2456 2457 T = DI->getType(); 2458 } 2459 } else { 2460 // Simple case: substitution into a parameter that is not a parameter pack. 2461 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 2462 D->getLocation(), D->getDeclName()); 2463 if (!DI) 2464 return nullptr; 2465 2466 // Check that this type is acceptable for a non-type template parameter. 2467 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation()); 2468 if (T.isNull()) { 2469 T = SemaRef.Context.IntTy; 2470 Invalid = true; 2471 } 2472 } 2473 2474 NonTypeTemplateParmDecl *Param; 2475 if (IsExpandedParameterPack) 2476 Param = NonTypeTemplateParmDecl::Create( 2477 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2478 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2479 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes, 2480 ExpandedParameterPackTypesAsWritten); 2481 else 2482 Param = NonTypeTemplateParmDecl::Create( 2483 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2484 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2485 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI); 2486 2487 Param->setAccess(AS_public); 2488 if (Invalid) 2489 Param->setInvalidDecl(); 2490 2491 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2492 EnterExpressionEvaluationContext ConstantEvaluated( 2493 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 2494 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs); 2495 if (!Value.isInvalid()) 2496 Param->setDefaultArgument(Value.get()); 2497 } 2498 2499 // Introduce this template parameter's instantiation into the instantiation 2500 // scope. 2501 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2502 return Param; 2503 } 2504 2505 static void collectUnexpandedParameterPacks( 2506 Sema &S, 2507 TemplateParameterList *Params, 2508 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 2509 for (const auto &P : *Params) { 2510 if (P->isTemplateParameterPack()) 2511 continue; 2512 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) 2513 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), 2514 Unexpanded); 2515 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P)) 2516 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), 2517 Unexpanded); 2518 } 2519 } 2520 2521 Decl * 2522 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 2523 TemplateTemplateParmDecl *D) { 2524 // Instantiate the template parameter list of the template template parameter. 2525 TemplateParameterList *TempParams = D->getTemplateParameters(); 2526 TemplateParameterList *InstParams; 2527 SmallVector<TemplateParameterList*, 8> ExpandedParams; 2528 2529 bool IsExpandedParameterPack = false; 2530 2531 if (D->isExpandedParameterPack()) { 2532 // The template template parameter pack is an already-expanded pack 2533 // expansion of template parameters. Substitute into each of the expanded 2534 // parameters. 2535 ExpandedParams.reserve(D->getNumExpansionTemplateParameters()); 2536 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 2537 I != N; ++I) { 2538 LocalInstantiationScope Scope(SemaRef); 2539 TemplateParameterList *Expansion = 2540 SubstTemplateParams(D->getExpansionTemplateParameters(I)); 2541 if (!Expansion) 2542 return nullptr; 2543 ExpandedParams.push_back(Expansion); 2544 } 2545 2546 IsExpandedParameterPack = true; 2547 InstParams = TempParams; 2548 } else if (D->isPackExpansion()) { 2549 // The template template parameter pack expands to a pack of template 2550 // template parameters. Determine whether we need to expand this parameter 2551 // pack into separate parameters. 2552 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2553 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), 2554 Unexpanded); 2555 2556 // Determine whether the set of unexpanded parameter packs can and should 2557 // be expanded. 2558 bool Expand = true; 2559 bool RetainExpansion = false; 2560 Optional<unsigned> NumExpansions; 2561 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), 2562 TempParams->getSourceRange(), 2563 Unexpanded, 2564 TemplateArgs, 2565 Expand, RetainExpansion, 2566 NumExpansions)) 2567 return nullptr; 2568 2569 if (Expand) { 2570 for (unsigned I = 0; I != *NumExpansions; ++I) { 2571 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2572 LocalInstantiationScope Scope(SemaRef); 2573 TemplateParameterList *Expansion = SubstTemplateParams(TempParams); 2574 if (!Expansion) 2575 return nullptr; 2576 ExpandedParams.push_back(Expansion); 2577 } 2578 2579 // Note that we have an expanded parameter pack. The "type" of this 2580 // expanded parameter pack is the original expansion type, but callers 2581 // will end up using the expanded parameter pack types for type-checking. 2582 IsExpandedParameterPack = true; 2583 InstParams = TempParams; 2584 } else { 2585 // We cannot fully expand the pack expansion now, so just substitute 2586 // into the pattern. 2587 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2588 2589 LocalInstantiationScope Scope(SemaRef); 2590 InstParams = SubstTemplateParams(TempParams); 2591 if (!InstParams) 2592 return nullptr; 2593 } 2594 } else { 2595 // Perform the actual substitution of template parameters within a new, 2596 // local instantiation scope. 2597 LocalInstantiationScope Scope(SemaRef); 2598 InstParams = SubstTemplateParams(TempParams); 2599 if (!InstParams) 2600 return nullptr; 2601 } 2602 2603 // Build the template template parameter. 2604 TemplateTemplateParmDecl *Param; 2605 if (IsExpandedParameterPack) 2606 Param = TemplateTemplateParmDecl::Create( 2607 SemaRef.Context, Owner, D->getLocation(), 2608 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2609 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams); 2610 else 2611 Param = TemplateTemplateParmDecl::Create( 2612 SemaRef.Context, Owner, D->getLocation(), 2613 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2614 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams); 2615 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2616 NestedNameSpecifierLoc QualifierLoc = 2617 D->getDefaultArgument().getTemplateQualifierLoc(); 2618 QualifierLoc = 2619 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs); 2620 TemplateName TName = SemaRef.SubstTemplateName( 2621 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(), 2622 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); 2623 if (!TName.isNull()) 2624 Param->setDefaultArgument( 2625 SemaRef.Context, 2626 TemplateArgumentLoc(TemplateArgument(TName), 2627 D->getDefaultArgument().getTemplateQualifierLoc(), 2628 D->getDefaultArgument().getTemplateNameLoc())); 2629 } 2630 Param->setAccess(AS_public); 2631 2632 // Introduce this template parameter's instantiation into the instantiation 2633 // scope. 2634 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2635 2636 return Param; 2637 } 2638 2639 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 2640 // Using directives are never dependent (and never contain any types or 2641 // expressions), so they require no explicit instantiation work. 2642 2643 UsingDirectiveDecl *Inst 2644 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 2645 D->getNamespaceKeyLocation(), 2646 D->getQualifierLoc(), 2647 D->getIdentLocation(), 2648 D->getNominatedNamespace(), 2649 D->getCommonAncestor()); 2650 2651 // Add the using directive to its declaration context 2652 // only if this is not a function or method. 2653 if (!Owner->isFunctionOrMethod()) 2654 Owner->addDecl(Inst); 2655 2656 return Inst; 2657 } 2658 2659 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 2660 2661 // The nested name specifier may be dependent, for example 2662 // template <typename T> struct t { 2663 // struct s1 { T f1(); }; 2664 // struct s2 : s1 { using s1::f1; }; 2665 // }; 2666 // template struct t<int>; 2667 // Here, in using s1::f1, s1 refers to t<T>::s1; 2668 // we need to substitute for t<int>::s1. 2669 NestedNameSpecifierLoc QualifierLoc 2670 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2671 TemplateArgs); 2672 if (!QualifierLoc) 2673 return nullptr; 2674 2675 // For an inheriting constructor declaration, the name of the using 2676 // declaration is the name of a constructor in this class, not in the 2677 // base class. 2678 DeclarationNameInfo NameInfo = D->getNameInfo(); 2679 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 2680 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext)) 2681 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName( 2682 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD)))); 2683 2684 // We only need to do redeclaration lookups if we're in a class 2685 // scope (in fact, it's not really even possible in non-class 2686 // scopes). 2687 bool CheckRedeclaration = Owner->isRecord(); 2688 2689 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 2690 Sema::ForVisibleRedeclaration); 2691 2692 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 2693 D->getUsingLoc(), 2694 QualifierLoc, 2695 NameInfo, 2696 D->hasTypename()); 2697 2698 CXXScopeSpec SS; 2699 SS.Adopt(QualifierLoc); 2700 if (CheckRedeclaration) { 2701 Prev.setHideTags(false); 2702 SemaRef.LookupQualifiedName(Prev, Owner); 2703 2704 // Check for invalid redeclarations. 2705 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(), 2706 D->hasTypename(), SS, 2707 D->getLocation(), Prev)) 2708 NewUD->setInvalidDecl(); 2709 2710 } 2711 2712 if (!NewUD->isInvalidDecl() && 2713 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), 2714 SS, NameInfo, D->getLocation())) 2715 NewUD->setInvalidDecl(); 2716 2717 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 2718 NewUD->setAccess(D->getAccess()); 2719 Owner->addDecl(NewUD); 2720 2721 // Don't process the shadow decls for an invalid decl. 2722 if (NewUD->isInvalidDecl()) 2723 return NewUD; 2724 2725 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 2726 SemaRef.CheckInheritingConstructorUsingDecl(NewUD); 2727 2728 bool isFunctionScope = Owner->isFunctionOrMethod(); 2729 2730 // Process the shadow decls. 2731 for (auto *Shadow : D->shadows()) { 2732 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so 2733 // reconstruct it in the case where it matters. 2734 NamedDecl *OldTarget = Shadow->getTargetDecl(); 2735 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow)) 2736 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl()) 2737 OldTarget = BaseShadow; 2738 2739 NamedDecl *InstTarget = 2740 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 2741 Shadow->getLocation(), OldTarget, TemplateArgs)); 2742 if (!InstTarget) 2743 return nullptr; 2744 2745 UsingShadowDecl *PrevDecl = nullptr; 2746 if (CheckRedeclaration) { 2747 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl)) 2748 continue; 2749 } else if (UsingShadowDecl *OldPrev = 2750 getPreviousDeclForInstantiation(Shadow)) { 2751 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( 2752 Shadow->getLocation(), OldPrev, TemplateArgs)); 2753 } 2754 2755 UsingShadowDecl *InstShadow = 2756 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget, 2757 PrevDecl); 2758 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 2759 2760 if (isFunctionScope) 2761 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 2762 } 2763 2764 return NewUD; 2765 } 2766 2767 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 2768 // Ignore these; we handle them in bulk when processing the UsingDecl. 2769 return nullptr; 2770 } 2771 2772 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl( 2773 ConstructorUsingShadowDecl *D) { 2774 // Ignore these; we handle them in bulk when processing the UsingDecl. 2775 return nullptr; 2776 } 2777 2778 template <typename T> 2779 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl( 2780 T *D, bool InstantiatingPackElement) { 2781 // If this is a pack expansion, expand it now. 2782 if (D->isPackExpansion() && !InstantiatingPackElement) { 2783 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2784 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded); 2785 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded); 2786 2787 // Determine whether the set of unexpanded parameter packs can and should 2788 // be expanded. 2789 bool Expand = true; 2790 bool RetainExpansion = false; 2791 Optional<unsigned> NumExpansions; 2792 if (SemaRef.CheckParameterPacksForExpansion( 2793 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs, 2794 Expand, RetainExpansion, NumExpansions)) 2795 return nullptr; 2796 2797 // This declaration cannot appear within a function template signature, 2798 // so we can't have a partial argument list for a parameter pack. 2799 assert(!RetainExpansion && 2800 "should never need to retain an expansion for UsingPackDecl"); 2801 2802 if (!Expand) { 2803 // We cannot fully expand the pack expansion now, so substitute into the 2804 // pattern and create a new pack expansion. 2805 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2806 return instantiateUnresolvedUsingDecl(D, true); 2807 } 2808 2809 // Within a function, we don't have any normal way to check for conflicts 2810 // between shadow declarations from different using declarations in the 2811 // same pack expansion, but this is always ill-formed because all expansions 2812 // must produce (conflicting) enumerators. 2813 // 2814 // Sadly we can't just reject this in the template definition because it 2815 // could be valid if the pack is empty or has exactly one expansion. 2816 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) { 2817 SemaRef.Diag(D->getEllipsisLoc(), 2818 diag::err_using_decl_redeclaration_expansion); 2819 return nullptr; 2820 } 2821 2822 // Instantiate the slices of this pack and build a UsingPackDecl. 2823 SmallVector<NamedDecl*, 8> Expansions; 2824 for (unsigned I = 0; I != *NumExpansions; ++I) { 2825 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2826 Decl *Slice = instantiateUnresolvedUsingDecl(D, true); 2827 if (!Slice) 2828 return nullptr; 2829 // Note that we can still get unresolved using declarations here, if we 2830 // had arguments for all packs but the pattern also contained other 2831 // template arguments (this only happens during partial substitution, eg 2832 // into the body of a generic lambda in a function template). 2833 Expansions.push_back(cast<NamedDecl>(Slice)); 2834 } 2835 2836 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 2837 if (isDeclWithinFunction(D)) 2838 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 2839 return NewD; 2840 } 2841 2842 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D); 2843 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation(); 2844 2845 NestedNameSpecifierLoc QualifierLoc 2846 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2847 TemplateArgs); 2848 if (!QualifierLoc) 2849 return nullptr; 2850 2851 CXXScopeSpec SS; 2852 SS.Adopt(QualifierLoc); 2853 2854 DeclarationNameInfo NameInfo 2855 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2856 2857 // Produce a pack expansion only if we're not instantiating a particular 2858 // slice of a pack expansion. 2859 bool InstantiatingSlice = D->getEllipsisLoc().isValid() && 2860 SemaRef.ArgumentPackSubstitutionIndex != -1; 2861 SourceLocation EllipsisLoc = 2862 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc(); 2863 2864 NamedDecl *UD = SemaRef.BuildUsingDeclaration( 2865 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(), 2866 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc, 2867 ParsedAttributesView(), 2868 /*IsInstantiation*/ true); 2869 if (UD) 2870 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D); 2871 2872 return UD; 2873 } 2874 2875 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl( 2876 UnresolvedUsingTypenameDecl *D) { 2877 return instantiateUnresolvedUsingDecl(D); 2878 } 2879 2880 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl( 2881 UnresolvedUsingValueDecl *D) { 2882 return instantiateUnresolvedUsingDecl(D); 2883 } 2884 2885 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) { 2886 SmallVector<NamedDecl*, 8> Expansions; 2887 for (auto *UD : D->expansions()) { 2888 if (NamedDecl *NewUD = 2889 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs)) 2890 Expansions.push_back(NewUD); 2891 else 2892 return nullptr; 2893 } 2894 2895 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 2896 if (isDeclWithinFunction(D)) 2897 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 2898 return NewD; 2899 } 2900 2901 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 2902 ClassScopeFunctionSpecializationDecl *Decl) { 2903 CXXMethodDecl *OldFD = Decl->getSpecialization(); 2904 return cast_or_null<CXXMethodDecl>( 2905 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten())); 2906 } 2907 2908 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( 2909 OMPThreadPrivateDecl *D) { 2910 SmallVector<Expr *, 5> Vars; 2911 for (auto *I : D->varlists()) { 2912 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 2913 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"); 2914 Vars.push_back(Var); 2915 } 2916 2917 OMPThreadPrivateDecl *TD = 2918 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars); 2919 2920 TD->setAccess(AS_public); 2921 Owner->addDecl(TD); 2922 2923 return TD; 2924 } 2925 2926 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) { 2927 SmallVector<Expr *, 5> Vars; 2928 for (auto *I : D->varlists()) { 2929 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 2930 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr"); 2931 Vars.push_back(Var); 2932 } 2933 SmallVector<OMPClause *, 4> Clauses; 2934 // Copy map clauses from the original mapper. 2935 for (OMPClause *C : D->clauselists()) { 2936 auto *AC = cast<OMPAllocatorClause>(C); 2937 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs); 2938 if (!NewE.isUsable()) 2939 continue; 2940 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause( 2941 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc()); 2942 Clauses.push_back(IC); 2943 } 2944 2945 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective( 2946 D->getLocation(), Vars, Clauses, Owner); 2947 if (Res.get().isNull()) 2948 return nullptr; 2949 return Res.get().getSingleDecl(); 2950 } 2951 2952 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) { 2953 llvm_unreachable( 2954 "Requires directive cannot be instantiated within a dependent context"); 2955 } 2956 2957 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl( 2958 OMPDeclareReductionDecl *D) { 2959 // Instantiate type and check if it is allowed. 2960 const bool RequiresInstantiation = 2961 D->getType()->isDependentType() || 2962 D->getType()->isInstantiationDependentType() || 2963 D->getType()->containsUnexpandedParameterPack(); 2964 QualType SubstReductionType; 2965 if (RequiresInstantiation) { 2966 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType( 2967 D->getLocation(), 2968 ParsedType::make(SemaRef.SubstType( 2969 D->getType(), TemplateArgs, D->getLocation(), DeclarationName()))); 2970 } else { 2971 SubstReductionType = D->getType(); 2972 } 2973 if (SubstReductionType.isNull()) 2974 return nullptr; 2975 bool IsCorrect = !SubstReductionType.isNull(); 2976 // Create instantiated copy. 2977 std::pair<QualType, SourceLocation> ReductionTypes[] = { 2978 std::make_pair(SubstReductionType, D->getLocation())}; 2979 auto *PrevDeclInScope = D->getPrevDeclInScope(); 2980 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 2981 PrevDeclInScope = cast<OMPDeclareReductionDecl>( 2982 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 2983 ->get<Decl *>()); 2984 } 2985 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart( 2986 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(), 2987 PrevDeclInScope); 2988 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl()); 2989 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD); 2990 if (!RequiresInstantiation) { 2991 if (Expr *Combiner = D->getCombiner()) { 2992 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut()); 2993 NewDRD->setCombiner(Combiner); 2994 if (Expr *Init = D->getInitializer()) { 2995 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv()); 2996 NewDRD->setInitializer(Init, D->getInitializerKind()); 2997 } 2998 } 2999 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd( 3000 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl()); 3001 return NewDRD; 3002 } 3003 Expr *SubstCombiner = nullptr; 3004 Expr *SubstInitializer = nullptr; 3005 // Combiners instantiation sequence. 3006 if (D->getCombiner()) { 3007 SemaRef.ActOnOpenMPDeclareReductionCombinerStart( 3008 /*S=*/nullptr, NewDRD); 3009 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3010 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(), 3011 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl()); 3012 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3013 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(), 3014 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl()); 3015 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3016 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3017 ThisContext); 3018 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get(); 3019 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner); 3020 // Initializers instantiation sequence. 3021 if (D->getInitializer()) { 3022 VarDecl *OmpPrivParm = 3023 SemaRef.ActOnOpenMPDeclareReductionInitializerStart( 3024 /*S=*/nullptr, NewDRD); 3025 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3026 cast<DeclRefExpr>(D->getInitOrig())->getDecl(), 3027 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl()); 3028 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3029 cast<DeclRefExpr>(D->getInitPriv())->getDecl(), 3030 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl()); 3031 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) { 3032 SubstInitializer = 3033 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get(); 3034 } else { 3035 IsCorrect = IsCorrect && OmpPrivParm->hasInit(); 3036 } 3037 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd( 3038 NewDRD, SubstInitializer, OmpPrivParm); 3039 } 3040 IsCorrect = 3041 IsCorrect && SubstCombiner && 3042 (!D->getInitializer() || 3043 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit && 3044 SubstInitializer) || 3045 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit && 3046 !SubstInitializer && !SubstInitializer)); 3047 } else { 3048 IsCorrect = false; 3049 } 3050 3051 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD, 3052 IsCorrect); 3053 3054 return NewDRD; 3055 } 3056 3057 Decl * 3058 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) { 3059 // Instantiate type and check if it is allowed. 3060 const bool RequiresInstantiation = 3061 D->getType()->isDependentType() || 3062 D->getType()->isInstantiationDependentType() || 3063 D->getType()->containsUnexpandedParameterPack(); 3064 QualType SubstMapperTy; 3065 DeclarationName VN = D->getVarName(); 3066 if (RequiresInstantiation) { 3067 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType( 3068 D->getLocation(), 3069 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs, 3070 D->getLocation(), VN))); 3071 } else { 3072 SubstMapperTy = D->getType(); 3073 } 3074 if (SubstMapperTy.isNull()) 3075 return nullptr; 3076 // Create an instantiated copy of mapper. 3077 auto *PrevDeclInScope = D->getPrevDeclInScope(); 3078 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 3079 PrevDeclInScope = cast<OMPDeclareMapperDecl>( 3080 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 3081 ->get<Decl *>()); 3082 } 3083 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart( 3084 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(), 3085 VN, D->getAccess(), PrevDeclInScope); 3086 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD); 3087 SmallVector<OMPClause *, 6> Clauses; 3088 bool IsCorrect = true; 3089 if (!RequiresInstantiation) { 3090 // Copy the mapper variable. 3091 NewDMD->setMapperVarRef(D->getMapperVarRef()); 3092 // Copy map clauses from the original mapper. 3093 for (OMPClause *C : D->clauselists()) 3094 Clauses.push_back(C); 3095 } else { 3096 // Instantiate the mapper variable. 3097 DeclarationNameInfo DirName; 3098 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr, 3099 (*D->clauselist_begin())->getBeginLoc()); 3100 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl( 3101 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN); 3102 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3103 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(), 3104 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl()); 3105 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3106 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3107 ThisContext); 3108 // Instantiate map clauses. 3109 for (OMPClause *C : D->clauselists()) { 3110 auto *OldC = cast<OMPMapClause>(C); 3111 SmallVector<Expr *, 4> NewVars; 3112 for (Expr *OE : OldC->varlists()) { 3113 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get(); 3114 if (!NE) { 3115 IsCorrect = false; 3116 break; 3117 } 3118 NewVars.push_back(NE); 3119 } 3120 if (!IsCorrect) 3121 break; 3122 NestedNameSpecifierLoc NewQualifierLoc = 3123 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(), 3124 TemplateArgs); 3125 CXXScopeSpec SS; 3126 SS.Adopt(NewQualifierLoc); 3127 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo( 3128 OldC->getMapperIdInfo(), TemplateArgs); 3129 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(), 3130 OldC->getEndLoc()); 3131 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause( 3132 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS, 3133 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(), 3134 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs); 3135 Clauses.push_back(NewC); 3136 } 3137 SemaRef.EndOpenMPDSABlock(nullptr); 3138 } 3139 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr, 3140 Clauses); 3141 if (!IsCorrect) 3142 return nullptr; 3143 return NewDMD; 3144 } 3145 3146 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl( 3147 OMPCapturedExprDecl * /*D*/) { 3148 llvm_unreachable("Should not be met in templates"); 3149 } 3150 3151 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 3152 return VisitFunctionDecl(D, nullptr); 3153 } 3154 3155 Decl * 3156 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { 3157 Decl *Inst = VisitFunctionDecl(D, nullptr); 3158 if (Inst && !D->getDescribedFunctionTemplate()) 3159 Owner->addDecl(Inst); 3160 return Inst; 3161 } 3162 3163 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 3164 return VisitCXXMethodDecl(D, nullptr); 3165 } 3166 3167 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 3168 llvm_unreachable("There are only CXXRecordDecls in C++"); 3169 } 3170 3171 Decl * 3172 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 3173 ClassTemplateSpecializationDecl *D) { 3174 // As a MS extension, we permit class-scope explicit specialization 3175 // of member class templates. 3176 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 3177 assert(ClassTemplate->getDeclContext()->isRecord() && 3178 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 3179 "can only instantiate an explicit specialization " 3180 "for a member class template"); 3181 3182 // Lookup the already-instantiated declaration in the instantiation 3183 // of the class template. 3184 ClassTemplateDecl *InstClassTemplate = 3185 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl( 3186 D->getLocation(), ClassTemplate, TemplateArgs)); 3187 if (!InstClassTemplate) 3188 return nullptr; 3189 3190 // Substitute into the template arguments of the class template explicit 3191 // specialization. 3192 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). 3193 castAs<TemplateSpecializationTypeLoc>(); 3194 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), 3195 Loc.getRAngleLoc()); 3196 SmallVector<TemplateArgumentLoc, 4> ArgLocs; 3197 for (unsigned I = 0; I != Loc.getNumArgs(); ++I) 3198 ArgLocs.push_back(Loc.getArgLoc(I)); 3199 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(), 3200 InstTemplateArgs, TemplateArgs)) 3201 return nullptr; 3202 3203 // Check that the template argument list is well-formed for this 3204 // class template. 3205 SmallVector<TemplateArgument, 4> Converted; 3206 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, 3207 D->getLocation(), 3208 InstTemplateArgs, 3209 false, 3210 Converted)) 3211 return nullptr; 3212 3213 // Figure out where to insert this class template explicit specialization 3214 // in the member template's set of class template explicit specializations. 3215 void *InsertPos = nullptr; 3216 ClassTemplateSpecializationDecl *PrevDecl = 3217 InstClassTemplate->findSpecialization(Converted, InsertPos); 3218 3219 // Check whether we've already seen a conflicting instantiation of this 3220 // declaration (for instance, if there was a prior implicit instantiation). 3221 bool Ignored; 3222 if (PrevDecl && 3223 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(), 3224 D->getSpecializationKind(), 3225 PrevDecl, 3226 PrevDecl->getSpecializationKind(), 3227 PrevDecl->getPointOfInstantiation(), 3228 Ignored)) 3229 return nullptr; 3230 3231 // If PrevDecl was a definition and D is also a definition, diagnose. 3232 // This happens in cases like: 3233 // 3234 // template<typename T, typename U> 3235 // struct Outer { 3236 // template<typename X> struct Inner; 3237 // template<> struct Inner<T> {}; 3238 // template<> struct Inner<U> {}; 3239 // }; 3240 // 3241 // Outer<int, int> outer; // error: the explicit specializations of Inner 3242 // // have the same signature. 3243 if (PrevDecl && PrevDecl->getDefinition() && 3244 D->isThisDeclarationADefinition()) { 3245 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; 3246 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), 3247 diag::note_previous_definition); 3248 return nullptr; 3249 } 3250 3251 // Create the class template partial specialization declaration. 3252 ClassTemplateSpecializationDecl *InstD = 3253 ClassTemplateSpecializationDecl::Create( 3254 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(), 3255 D->getLocation(), InstClassTemplate, Converted, PrevDecl); 3256 3257 // Add this partial specialization to the set of class template partial 3258 // specializations. 3259 if (!PrevDecl) 3260 InstClassTemplate->AddSpecialization(InstD, InsertPos); 3261 3262 // Substitute the nested name specifier, if any. 3263 if (SubstQualifier(D, InstD)) 3264 return nullptr; 3265 3266 // Build the canonical type that describes the converted template 3267 // arguments of the class template explicit specialization. 3268 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3269 TemplateName(InstClassTemplate), Converted, 3270 SemaRef.Context.getRecordType(InstD)); 3271 3272 // Build the fully-sugared type for this class template 3273 // specialization as the user wrote in the specialization 3274 // itself. This means that we'll pretty-print the type retrieved 3275 // from the specialization's declaration the way that the user 3276 // actually wrote the specialization, rather than formatting the 3277 // name based on the "canonical" representation used to store the 3278 // template arguments in the specialization. 3279 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3280 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs, 3281 CanonType); 3282 3283 InstD->setAccess(D->getAccess()); 3284 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 3285 InstD->setSpecializationKind(D->getSpecializationKind()); 3286 InstD->setTypeAsWritten(WrittenTy); 3287 InstD->setExternLoc(D->getExternLoc()); 3288 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); 3289 3290 Owner->addDecl(InstD); 3291 3292 // Instantiate the members of the class-scope explicit specialization eagerly. 3293 // We don't have support for lazy instantiation of an explicit specialization 3294 // yet, and MSVC eagerly instantiates in this case. 3295 // FIXME: This is wrong in standard C++. 3296 if (D->isThisDeclarationADefinition() && 3297 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs, 3298 TSK_ImplicitInstantiation, 3299 /*Complain=*/true)) 3300 return nullptr; 3301 3302 return InstD; 3303 } 3304 3305 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3306 VarTemplateSpecializationDecl *D) { 3307 3308 TemplateArgumentListInfo VarTemplateArgsInfo; 3309 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 3310 assert(VarTemplate && 3311 "A template specialization without specialized template?"); 3312 3313 VarTemplateDecl *InstVarTemplate = 3314 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl( 3315 D->getLocation(), VarTemplate, TemplateArgs)); 3316 if (!InstVarTemplate) 3317 return nullptr; 3318 3319 // Substitute the current template arguments. 3320 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 3321 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 3322 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 3323 3324 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(), 3325 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs)) 3326 return nullptr; 3327 3328 // Check that the template argument list is well-formed for this template. 3329 SmallVector<TemplateArgument, 4> Converted; 3330 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(), 3331 VarTemplateArgsInfo, false, Converted)) 3332 return nullptr; 3333 3334 // Check whether we've already seen a declaration of this specialization. 3335 void *InsertPos = nullptr; 3336 VarTemplateSpecializationDecl *PrevDecl = 3337 InstVarTemplate->findSpecialization(Converted, InsertPos); 3338 3339 // Check whether we've already seen a conflicting instantiation of this 3340 // declaration (for instance, if there was a prior implicit instantiation). 3341 bool Ignored; 3342 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl( 3343 D->getLocation(), D->getSpecializationKind(), PrevDecl, 3344 PrevDecl->getSpecializationKind(), 3345 PrevDecl->getPointOfInstantiation(), Ignored)) 3346 return nullptr; 3347 3348 return VisitVarTemplateSpecializationDecl( 3349 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl); 3350 } 3351 3352 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3353 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos, 3354 const TemplateArgumentListInfo &TemplateArgsInfo, 3355 ArrayRef<TemplateArgument> Converted, 3356 VarTemplateSpecializationDecl *PrevDecl) { 3357 3358 // Do substitution on the type of the declaration 3359 TypeSourceInfo *DI = 3360 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 3361 D->getTypeSpecStartLoc(), D->getDeclName()); 3362 if (!DI) 3363 return nullptr; 3364 3365 if (DI->getType()->isFunctionType()) { 3366 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 3367 << D->isStaticDataMember() << DI->getType(); 3368 return nullptr; 3369 } 3370 3371 // Build the instantiated declaration 3372 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 3373 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 3374 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted); 3375 Var->setTemplateArgsInfo(TemplateArgsInfo); 3376 if (InsertPos) 3377 VarTemplate->AddSpecialization(Var, InsertPos); 3378 3379 // Substitute the nested name specifier, if any. 3380 if (SubstQualifier(D, Var)) 3381 return nullptr; 3382 3383 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 3384 StartingScope, false, PrevDecl); 3385 3386 return Var; 3387 } 3388 3389 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 3390 llvm_unreachable("@defs is not supported in Objective-C++"); 3391 } 3392 3393 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 3394 // FIXME: We need to be able to instantiate FriendTemplateDecls. 3395 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 3396 DiagnosticsEngine::Error, 3397 "cannot instantiate %0 yet"); 3398 SemaRef.Diag(D->getLocation(), DiagID) 3399 << D->getDeclKindName(); 3400 3401 return nullptr; 3402 } 3403 3404 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) { 3405 llvm_unreachable("Concept definitions cannot reside inside a template"); 3406 } 3407 3408 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 3409 llvm_unreachable("Unexpected decl"); 3410 } 3411 3412 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 3413 const MultiLevelTemplateArgumentList &TemplateArgs) { 3414 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3415 if (D->isInvalidDecl()) 3416 return nullptr; 3417 3418 return Instantiator.Visit(D); 3419 } 3420 3421 /// Instantiates a nested template parameter list in the current 3422 /// instantiation context. 3423 /// 3424 /// \param L The parameter list to instantiate 3425 /// 3426 /// \returns NULL if there was an error 3427 TemplateParameterList * 3428 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 3429 // Get errors for all the parameters before bailing out. 3430 bool Invalid = false; 3431 3432 unsigned N = L->size(); 3433 typedef SmallVector<NamedDecl *, 8> ParamVector; 3434 ParamVector Params; 3435 Params.reserve(N); 3436 for (auto &P : *L) { 3437 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P)); 3438 Params.push_back(D); 3439 Invalid = Invalid || !D || D->isInvalidDecl(); 3440 } 3441 3442 // Clean up if we had an error. 3443 if (Invalid) 3444 return nullptr; 3445 3446 // Note: we substitute into associated constraints later 3447 Expr *const UninstantiatedRequiresClause = L->getRequiresClause(); 3448 3449 TemplateParameterList *InstL 3450 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 3451 L->getLAngleLoc(), Params, 3452 L->getRAngleLoc(), 3453 UninstantiatedRequiresClause); 3454 return InstL; 3455 } 3456 3457 TemplateParameterList * 3458 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 3459 const MultiLevelTemplateArgumentList &TemplateArgs) { 3460 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3461 return Instantiator.SubstTemplateParams(Params); 3462 } 3463 3464 /// Instantiate the declaration of a class template partial 3465 /// specialization. 3466 /// 3467 /// \param ClassTemplate the (instantiated) class template that is partially 3468 // specialized by the instantiation of \p PartialSpec. 3469 /// 3470 /// \param PartialSpec the (uninstantiated) class template partial 3471 /// specialization that we are instantiating. 3472 /// 3473 /// \returns The instantiated partial specialization, if successful; otherwise, 3474 /// NULL to indicate an error. 3475 ClassTemplatePartialSpecializationDecl * 3476 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 3477 ClassTemplateDecl *ClassTemplate, 3478 ClassTemplatePartialSpecializationDecl *PartialSpec) { 3479 // Create a local instantiation scope for this class template partial 3480 // specialization, which will contain the instantiations of the template 3481 // parameters. 3482 LocalInstantiationScope Scope(SemaRef); 3483 3484 // Substitute into the template parameters of the class template partial 3485 // specialization. 3486 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 3487 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 3488 if (!InstParams) 3489 return nullptr; 3490 3491 // Substitute into the template arguments of the class template partial 3492 // specialization. 3493 const ASTTemplateArgumentListInfo *TemplArgInfo 3494 = PartialSpec->getTemplateArgsAsWritten(); 3495 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 3496 TemplArgInfo->RAngleLoc); 3497 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 3498 TemplArgInfo->NumTemplateArgs, 3499 InstTemplateArgs, TemplateArgs)) 3500 return nullptr; 3501 3502 // Check that the template argument list is well-formed for this 3503 // class template. 3504 SmallVector<TemplateArgument, 4> Converted; 3505 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 3506 PartialSpec->getLocation(), 3507 InstTemplateArgs, 3508 false, 3509 Converted)) 3510 return nullptr; 3511 3512 // Check these arguments are valid for a template partial specialization. 3513 if (SemaRef.CheckTemplatePartialSpecializationArgs( 3514 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(), 3515 Converted)) 3516 return nullptr; 3517 3518 // Figure out where to insert this class template partial specialization 3519 // in the member template's set of class template partial specializations. 3520 void *InsertPos = nullptr; 3521 ClassTemplateSpecializationDecl *PrevDecl 3522 = ClassTemplate->findPartialSpecialization(Converted, InsertPos); 3523 3524 // Build the canonical type that describes the converted template 3525 // arguments of the class template partial specialization. 3526 QualType CanonType 3527 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 3528 Converted); 3529 3530 // Build the fully-sugared type for this class template 3531 // specialization as the user wrote in the specialization 3532 // itself. This means that we'll pretty-print the type retrieved 3533 // from the specialization's declaration the way that the user 3534 // actually wrote the specialization, rather than formatting the 3535 // name based on the "canonical" representation used to store the 3536 // template arguments in the specialization. 3537 TypeSourceInfo *WrittenTy 3538 = SemaRef.Context.getTemplateSpecializationTypeInfo( 3539 TemplateName(ClassTemplate), 3540 PartialSpec->getLocation(), 3541 InstTemplateArgs, 3542 CanonType); 3543 3544 if (PrevDecl) { 3545 // We've already seen a partial specialization with the same template 3546 // parameters and template arguments. This can happen, for example, when 3547 // substituting the outer template arguments ends up causing two 3548 // class template partial specializations of a member class template 3549 // to have identical forms, e.g., 3550 // 3551 // template<typename T, typename U> 3552 // struct Outer { 3553 // template<typename X, typename Y> struct Inner; 3554 // template<typename Y> struct Inner<T, Y>; 3555 // template<typename Y> struct Inner<U, Y>; 3556 // }; 3557 // 3558 // Outer<int, int> outer; // error: the partial specializations of Inner 3559 // // have the same signature. 3560 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 3561 << WrittenTy->getType(); 3562 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 3563 << SemaRef.Context.getTypeDeclType(PrevDecl); 3564 return nullptr; 3565 } 3566 3567 3568 // Create the class template partial specialization declaration. 3569 ClassTemplatePartialSpecializationDecl *InstPartialSpec = 3570 ClassTemplatePartialSpecializationDecl::Create( 3571 SemaRef.Context, PartialSpec->getTagKind(), Owner, 3572 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams, 3573 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr); 3574 // Substitute the nested name specifier, if any. 3575 if (SubstQualifier(PartialSpec, InstPartialSpec)) 3576 return nullptr; 3577 3578 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 3579 InstPartialSpec->setTypeAsWritten(WrittenTy); 3580 3581 // Check the completed partial specialization. 3582 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 3583 3584 // Add this partial specialization to the set of class template partial 3585 // specializations. 3586 ClassTemplate->AddPartialSpecialization(InstPartialSpec, 3587 /*InsertPos=*/nullptr); 3588 return InstPartialSpec; 3589 } 3590 3591 /// Instantiate the declaration of a variable template partial 3592 /// specialization. 3593 /// 3594 /// \param VarTemplate the (instantiated) variable template that is partially 3595 /// specialized by the instantiation of \p PartialSpec. 3596 /// 3597 /// \param PartialSpec the (uninstantiated) variable template partial 3598 /// specialization that we are instantiating. 3599 /// 3600 /// \returns The instantiated partial specialization, if successful; otherwise, 3601 /// NULL to indicate an error. 3602 VarTemplatePartialSpecializationDecl * 3603 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 3604 VarTemplateDecl *VarTemplate, 3605 VarTemplatePartialSpecializationDecl *PartialSpec) { 3606 // Create a local instantiation scope for this variable template partial 3607 // specialization, which will contain the instantiations of the template 3608 // parameters. 3609 LocalInstantiationScope Scope(SemaRef); 3610 3611 // Substitute into the template parameters of the variable template partial 3612 // specialization. 3613 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 3614 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 3615 if (!InstParams) 3616 return nullptr; 3617 3618 // Substitute into the template arguments of the variable template partial 3619 // specialization. 3620 const ASTTemplateArgumentListInfo *TemplArgInfo 3621 = PartialSpec->getTemplateArgsAsWritten(); 3622 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 3623 TemplArgInfo->RAngleLoc); 3624 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 3625 TemplArgInfo->NumTemplateArgs, 3626 InstTemplateArgs, TemplateArgs)) 3627 return nullptr; 3628 3629 // Check that the template argument list is well-formed for this 3630 // class template. 3631 SmallVector<TemplateArgument, 4> Converted; 3632 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 3633 InstTemplateArgs, false, Converted)) 3634 return nullptr; 3635 3636 // Check these arguments are valid for a template partial specialization. 3637 if (SemaRef.CheckTemplatePartialSpecializationArgs( 3638 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(), 3639 Converted)) 3640 return nullptr; 3641 3642 // Figure out where to insert this variable template partial specialization 3643 // in the member template's set of variable template partial specializations. 3644 void *InsertPos = nullptr; 3645 VarTemplateSpecializationDecl *PrevDecl = 3646 VarTemplate->findPartialSpecialization(Converted, InsertPos); 3647 3648 // Build the canonical type that describes the converted template 3649 // arguments of the variable template partial specialization. 3650 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3651 TemplateName(VarTemplate), Converted); 3652 3653 // Build the fully-sugared type for this variable template 3654 // specialization as the user wrote in the specialization 3655 // itself. This means that we'll pretty-print the type retrieved 3656 // from the specialization's declaration the way that the user 3657 // actually wrote the specialization, rather than formatting the 3658 // name based on the "canonical" representation used to store the 3659 // template arguments in the specialization. 3660 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3661 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 3662 CanonType); 3663 3664 if (PrevDecl) { 3665 // We've already seen a partial specialization with the same template 3666 // parameters and template arguments. This can happen, for example, when 3667 // substituting the outer template arguments ends up causing two 3668 // variable template partial specializations of a member variable template 3669 // to have identical forms, e.g., 3670 // 3671 // template<typename T, typename U> 3672 // struct Outer { 3673 // template<typename X, typename Y> pair<X,Y> p; 3674 // template<typename Y> pair<T, Y> p; 3675 // template<typename Y> pair<U, Y> p; 3676 // }; 3677 // 3678 // Outer<int, int> outer; // error: the partial specializations of Inner 3679 // // have the same signature. 3680 SemaRef.Diag(PartialSpec->getLocation(), 3681 diag::err_var_partial_spec_redeclared) 3682 << WrittenTy->getType(); 3683 SemaRef.Diag(PrevDecl->getLocation(), 3684 diag::note_var_prev_partial_spec_here); 3685 return nullptr; 3686 } 3687 3688 // Do substitution on the type of the declaration 3689 TypeSourceInfo *DI = SemaRef.SubstType( 3690 PartialSpec->getTypeSourceInfo(), TemplateArgs, 3691 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 3692 if (!DI) 3693 return nullptr; 3694 3695 if (DI->getType()->isFunctionType()) { 3696 SemaRef.Diag(PartialSpec->getLocation(), 3697 diag::err_variable_instantiates_to_function) 3698 << PartialSpec->isStaticDataMember() << DI->getType(); 3699 return nullptr; 3700 } 3701 3702 // Create the variable template partial specialization declaration. 3703 VarTemplatePartialSpecializationDecl *InstPartialSpec = 3704 VarTemplatePartialSpecializationDecl::Create( 3705 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 3706 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 3707 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs); 3708 3709 // Substitute the nested name specifier, if any. 3710 if (SubstQualifier(PartialSpec, InstPartialSpec)) 3711 return nullptr; 3712 3713 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 3714 InstPartialSpec->setTypeAsWritten(WrittenTy); 3715 3716 // Check the completed partial specialization. 3717 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 3718 3719 // Add this partial specialization to the set of variable template partial 3720 // specializations. The instantiation of the initializer is not necessary. 3721 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr); 3722 3723 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 3724 LateAttrs, Owner, StartingScope); 3725 3726 return InstPartialSpec; 3727 } 3728 3729 TypeSourceInfo* 3730 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 3731 SmallVectorImpl<ParmVarDecl *> &Params) { 3732 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 3733 assert(OldTInfo && "substituting function without type source info"); 3734 assert(Params.empty() && "parameter vector is non-empty at start"); 3735 3736 CXXRecordDecl *ThisContext = nullptr; 3737 Qualifiers ThisTypeQuals; 3738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 3739 ThisContext = cast<CXXRecordDecl>(Owner); 3740 ThisTypeQuals = Method->getMethodQualifiers(); 3741 } 3742 3743 TypeSourceInfo *NewTInfo 3744 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 3745 D->getTypeSpecStartLoc(), 3746 D->getDeclName(), 3747 ThisContext, ThisTypeQuals); 3748 if (!NewTInfo) 3749 return nullptr; 3750 3751 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 3752 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 3753 if (NewTInfo != OldTInfo) { 3754 // Get parameters from the new type info. 3755 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 3756 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 3757 unsigned NewIdx = 0; 3758 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); 3759 OldIdx != NumOldParams; ++OldIdx) { 3760 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); 3761 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 3762 3763 Optional<unsigned> NumArgumentsInExpansion; 3764 if (OldParam->isParameterPack()) 3765 NumArgumentsInExpansion = 3766 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 3767 TemplateArgs); 3768 if (!NumArgumentsInExpansion) { 3769 // Simple case: normal parameter, or a parameter pack that's 3770 // instantiated to a (still-dependent) parameter pack. 3771 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 3772 Params.push_back(NewParam); 3773 Scope->InstantiatedLocal(OldParam, NewParam); 3774 } else { 3775 // Parameter pack expansion: make the instantiation an argument pack. 3776 Scope->MakeInstantiatedLocalArgPack(OldParam); 3777 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 3778 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 3779 Params.push_back(NewParam); 3780 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 3781 } 3782 } 3783 } 3784 } else { 3785 // The function type itself was not dependent and therefore no 3786 // substitution occurred. However, we still need to instantiate 3787 // the function parameters themselves. 3788 const FunctionProtoType *OldProto = 3789 cast<FunctionProtoType>(OldProtoLoc.getType()); 3790 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; 3791 ++i) { 3792 ParmVarDecl *OldParam = OldProtoLoc.getParam(i); 3793 if (!OldParam) { 3794 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 3795 D, D->getLocation(), OldProto->getParamType(i))); 3796 continue; 3797 } 3798 3799 ParmVarDecl *Parm = 3800 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 3801 if (!Parm) 3802 return nullptr; 3803 Params.push_back(Parm); 3804 } 3805 } 3806 } else { 3807 // If the type of this function, after ignoring parentheses, is not 3808 // *directly* a function type, then we're instantiating a function that 3809 // was declared via a typedef or with attributes, e.g., 3810 // 3811 // typedef int functype(int, int); 3812 // functype func; 3813 // int __cdecl meth(int, int); 3814 // 3815 // In this case, we'll just go instantiate the ParmVarDecls that we 3816 // synthesized in the method declaration. 3817 SmallVector<QualType, 4> ParamTypes; 3818 Sema::ExtParameterInfoBuilder ExtParamInfos; 3819 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr, 3820 TemplateArgs, ParamTypes, &Params, 3821 ExtParamInfos)) 3822 return nullptr; 3823 } 3824 3825 return NewTInfo; 3826 } 3827 3828 /// Introduce the instantiated function parameters into the local 3829 /// instantiation scope, and set the parameter names to those used 3830 /// in the template. 3831 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 3832 const FunctionDecl *PatternDecl, 3833 LocalInstantiationScope &Scope, 3834 const MultiLevelTemplateArgumentList &TemplateArgs) { 3835 unsigned FParamIdx = 0; 3836 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 3837 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 3838 if (!PatternParam->isParameterPack()) { 3839 // Simple case: not a parameter pack. 3840 assert(FParamIdx < Function->getNumParams()); 3841 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 3842 FunctionParam->setDeclName(PatternParam->getDeclName()); 3843 // If the parameter's type is not dependent, update it to match the type 3844 // in the pattern. They can differ in top-level cv-qualifiers, and we want 3845 // the pattern's type here. If the type is dependent, they can't differ, 3846 // per core issue 1668. Substitute into the type from the pattern, in case 3847 // it's instantiation-dependent. 3848 // FIXME: Updating the type to work around this is at best fragile. 3849 if (!PatternDecl->getType()->isDependentType()) { 3850 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs, 3851 FunctionParam->getLocation(), 3852 FunctionParam->getDeclName()); 3853 if (T.isNull()) 3854 return true; 3855 FunctionParam->setType(T); 3856 } 3857 3858 Scope.InstantiatedLocal(PatternParam, FunctionParam); 3859 ++FParamIdx; 3860 continue; 3861 } 3862 3863 // Expand the parameter pack. 3864 Scope.MakeInstantiatedLocalArgPack(PatternParam); 3865 Optional<unsigned> NumArgumentsInExpansion 3866 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 3867 if (NumArgumentsInExpansion) { 3868 QualType PatternType = 3869 PatternParam->getType()->castAs<PackExpansionType>()->getPattern(); 3870 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 3871 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 3872 FunctionParam->setDeclName(PatternParam->getDeclName()); 3873 if (!PatternDecl->getType()->isDependentType()) { 3874 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg); 3875 QualType T = S.SubstType(PatternType, TemplateArgs, 3876 FunctionParam->getLocation(), 3877 FunctionParam->getDeclName()); 3878 if (T.isNull()) 3879 return true; 3880 FunctionParam->setType(T); 3881 } 3882 3883 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 3884 ++FParamIdx; 3885 } 3886 } 3887 } 3888 3889 return false; 3890 } 3891 3892 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 3893 FunctionDecl *Decl) { 3894 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 3895 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 3896 return; 3897 3898 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 3899 InstantiatingTemplate::ExceptionSpecification()); 3900 if (Inst.isInvalid()) { 3901 // We hit the instantiation depth limit. Clear the exception specification 3902 // so that our callers don't have to cope with EST_Uninstantiated. 3903 UpdateExceptionSpec(Decl, EST_None); 3904 return; 3905 } 3906 if (Inst.isAlreadyInstantiating()) { 3907 // This exception specification indirectly depends on itself. Reject. 3908 // FIXME: Corresponding rule in the standard? 3909 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl; 3910 UpdateExceptionSpec(Decl, EST_None); 3911 return; 3912 } 3913 3914 // Enter the scope of this instantiation. We don't use 3915 // PushDeclContext because we don't have a scope. 3916 Sema::ContextRAII savedContext(*this, Decl); 3917 LocalInstantiationScope Scope(*this); 3918 3919 MultiLevelTemplateArgumentList TemplateArgs = 3920 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true); 3921 3922 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 3923 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope, 3924 TemplateArgs)) { 3925 UpdateExceptionSpec(Decl, EST_None); 3926 return; 3927 } 3928 3929 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(), 3930 TemplateArgs); 3931 } 3932 3933 /// Initializes the common fields of an instantiation function 3934 /// declaration (New) from the corresponding fields of its template (Tmpl). 3935 /// 3936 /// \returns true if there was an error 3937 bool 3938 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 3939 FunctionDecl *Tmpl) { 3940 if (Tmpl->isDeleted()) 3941 New->setDeletedAsWritten(); 3942 3943 New->setImplicit(Tmpl->isImplicit()); 3944 3945 // Forward the mangling number from the template to the instantiated decl. 3946 SemaRef.Context.setManglingNumber(New, 3947 SemaRef.Context.getManglingNumber(Tmpl)); 3948 3949 // If we are performing substituting explicitly-specified template arguments 3950 // or deduced template arguments into a function template and we reach this 3951 // point, we are now past the point where SFINAE applies and have committed 3952 // to keeping the new function template specialization. We therefore 3953 // convert the active template instantiation for the function template 3954 // into a template instantiation for this specific function template 3955 // specialization, which is not a SFINAE context, so that we diagnose any 3956 // further errors in the declaration itself. 3957 typedef Sema::CodeSynthesisContext ActiveInstType; 3958 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back(); 3959 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 3960 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 3961 if (FunctionTemplateDecl *FunTmpl 3962 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 3963 assert(FunTmpl->getTemplatedDecl() == Tmpl && 3964 "Deduction from the wrong function template?"); 3965 (void) FunTmpl; 3966 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 3967 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 3968 ActiveInst.Entity = New; 3969 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 3970 } 3971 } 3972 3973 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 3974 assert(Proto && "Function template without prototype?"); 3975 3976 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 3977 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3978 3979 // DR1330: In C++11, defer instantiation of a non-trivial 3980 // exception specification. 3981 // DR1484: Local classes and their members are instantiated along with the 3982 // containing function. 3983 if (SemaRef.getLangOpts().CPlusPlus11 && 3984 EPI.ExceptionSpec.Type != EST_None && 3985 EPI.ExceptionSpec.Type != EST_DynamicNone && 3986 EPI.ExceptionSpec.Type != EST_BasicNoexcept && 3987 !Tmpl->isLexicallyWithinFunctionOrMethod()) { 3988 FunctionDecl *ExceptionSpecTemplate = Tmpl; 3989 if (EPI.ExceptionSpec.Type == EST_Uninstantiated) 3990 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; 3991 ExceptionSpecificationType NewEST = EST_Uninstantiated; 3992 if (EPI.ExceptionSpec.Type == EST_Unevaluated) 3993 NewEST = EST_Unevaluated; 3994 3995 // Mark the function has having an uninstantiated exception specification. 3996 const FunctionProtoType *NewProto 3997 = New->getType()->getAs<FunctionProtoType>(); 3998 assert(NewProto && "Template instantiation without function prototype?"); 3999 EPI = NewProto->getExtProtoInfo(); 4000 EPI.ExceptionSpec.Type = NewEST; 4001 EPI.ExceptionSpec.SourceDecl = New; 4002 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; 4003 New->setType(SemaRef.Context.getFunctionType( 4004 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 4005 } else { 4006 Sema::ContextRAII SwitchContext(SemaRef, New); 4007 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs); 4008 } 4009 } 4010 4011 // Get the definition. Leaves the variable unchanged if undefined. 4012 const FunctionDecl *Definition = Tmpl; 4013 Tmpl->isDefined(Definition); 4014 4015 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 4016 LateAttrs, StartingScope); 4017 4018 return false; 4019 } 4020 4021 /// Initializes common fields of an instantiated method 4022 /// declaration (New) from the corresponding fields of its template 4023 /// (Tmpl). 4024 /// 4025 /// \returns true if there was an error 4026 bool 4027 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 4028 CXXMethodDecl *Tmpl) { 4029 if (InitFunctionInstantiation(New, Tmpl)) 4030 return true; 4031 4032 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11) 4033 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New)); 4034 4035 New->setAccess(Tmpl->getAccess()); 4036 if (Tmpl->isVirtualAsWritten()) 4037 New->setVirtualAsWritten(true); 4038 4039 // FIXME: New needs a pointer to Tmpl 4040 return false; 4041 } 4042 4043 /// Instantiate (or find existing instantiation of) a function template with a 4044 /// given set of template arguments. 4045 /// 4046 /// Usually this should not be used, and template argument deduction should be 4047 /// used in its place. 4048 FunctionDecl * 4049 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 4050 const TemplateArgumentList *Args, 4051 SourceLocation Loc) { 4052 FunctionDecl *FD = FTD->getTemplatedDecl(); 4053 4054 sema::TemplateDeductionInfo Info(Loc); 4055 InstantiatingTemplate Inst( 4056 *this, Loc, FTD, Args->asArray(), 4057 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); 4058 if (Inst.isInvalid()) 4059 return nullptr; 4060 4061 ContextRAII SavedContext(*this, FD); 4062 MultiLevelTemplateArgumentList MArgs(*Args); 4063 4064 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs)); 4065 } 4066 4067 /// In the MS ABI, we need to instantiate default arguments of dllexported 4068 /// default constructors along with the constructor definition. This allows IR 4069 /// gen to emit a constructor closure which calls the default constructor with 4070 /// its default arguments. 4071 static void InstantiateDefaultCtorDefaultArgs(Sema &S, 4072 CXXConstructorDecl *Ctor) { 4073 assert(S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 4074 Ctor->isDefaultConstructor()); 4075 unsigned NumParams = Ctor->getNumParams(); 4076 if (NumParams == 0) 4077 return; 4078 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>(); 4079 if (!Attr) 4080 return; 4081 for (unsigned I = 0; I != NumParams; ++I) { 4082 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor, 4083 Ctor->getParamDecl(I)); 4084 S.DiscardCleanupsInEvaluationContext(); 4085 } 4086 } 4087 4088 /// Instantiate the definition of the given function from its 4089 /// template. 4090 /// 4091 /// \param PointOfInstantiation the point at which the instantiation was 4092 /// required. Note that this is not precisely a "point of instantiation" 4093 /// for the function, but it's close. 4094 /// 4095 /// \param Function the already-instantiated declaration of a 4096 /// function template specialization or member function of a class template 4097 /// specialization. 4098 /// 4099 /// \param Recursive if true, recursively instantiates any functions that 4100 /// are required by this instantiation. 4101 /// 4102 /// \param DefinitionRequired if true, then we are performing an explicit 4103 /// instantiation where the body of the function is required. Complain if 4104 /// there is no such body. 4105 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 4106 FunctionDecl *Function, 4107 bool Recursive, 4108 bool DefinitionRequired, 4109 bool AtEndOfTU) { 4110 if (Function->isInvalidDecl() || Function->isDefined() || 4111 isa<CXXDeductionGuideDecl>(Function)) 4112 return; 4113 4114 // Never instantiate an explicit specialization except if it is a class scope 4115 // explicit specialization. 4116 TemplateSpecializationKind TSK = 4117 Function->getTemplateSpecializationKindForInstantiation(); 4118 if (TSK == TSK_ExplicitSpecialization) 4119 return; 4120 4121 // Find the function body that we'll be substituting. 4122 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 4123 assert(PatternDecl && "instantiating a non-template"); 4124 4125 const FunctionDecl *PatternDef = PatternDecl->getDefinition(); 4126 Stmt *Pattern = nullptr; 4127 if (PatternDef) { 4128 Pattern = PatternDef->getBody(PatternDef); 4129 PatternDecl = PatternDef; 4130 if (PatternDef->willHaveBody()) 4131 PatternDef = nullptr; 4132 } 4133 4134 // FIXME: We need to track the instantiation stack in order to know which 4135 // definitions should be visible within this instantiation. 4136 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function, 4137 Function->getInstantiatedFromMemberFunction(), 4138 PatternDecl, PatternDef, TSK, 4139 /*Complain*/DefinitionRequired)) { 4140 if (DefinitionRequired) 4141 Function->setInvalidDecl(); 4142 else if (TSK == TSK_ExplicitInstantiationDefinition) { 4143 // Try again at the end of the translation unit (at which point a 4144 // definition will be required). 4145 assert(!Recursive); 4146 Function->setInstantiationIsPending(true); 4147 PendingInstantiations.push_back( 4148 std::make_pair(Function, PointOfInstantiation)); 4149 } else if (TSK == TSK_ImplicitInstantiation) { 4150 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 4151 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 4152 Diag(PointOfInstantiation, diag::warn_func_template_missing) 4153 << Function; 4154 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 4155 if (getLangOpts().CPlusPlus11) 4156 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) 4157 << Function; 4158 } 4159 } 4160 4161 return; 4162 } 4163 4164 // Postpone late parsed template instantiations. 4165 if (PatternDecl->isLateTemplateParsed() && 4166 !LateTemplateParser) { 4167 Function->setInstantiationIsPending(true); 4168 LateParsedInstantiations.push_back( 4169 std::make_pair(Function, PointOfInstantiation)); 4170 return; 4171 } 4172 4173 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() { 4174 std::string Name; 4175 llvm::raw_string_ostream OS(Name); 4176 Function->getNameForDiagnostic(OS, getPrintingPolicy(), 4177 /*Qualified=*/true); 4178 return Name; 4179 }); 4180 4181 // If we're performing recursive template instantiation, create our own 4182 // queue of pending implicit instantiations that we will instantiate later, 4183 // while we're still within our own instantiation context. 4184 // This has to happen before LateTemplateParser below is called, so that 4185 // it marks vtables used in late parsed templates as used. 4186 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4187 /*Enabled=*/Recursive); 4188 LocalEagerInstantiationScope LocalInstantiations(*this); 4189 4190 // Call the LateTemplateParser callback if there is a need to late parse 4191 // a templated function definition. 4192 if (!Pattern && PatternDecl->isLateTemplateParsed() && 4193 LateTemplateParser) { 4194 // FIXME: Optimize to allow individual templates to be deserialized. 4195 if (PatternDecl->isFromASTFile()) 4196 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 4197 4198 auto LPTIter = LateParsedTemplateMap.find(PatternDecl); 4199 assert(LPTIter != LateParsedTemplateMap.end() && 4200 "missing LateParsedTemplate"); 4201 LateTemplateParser(OpaqueParser, *LPTIter->second); 4202 Pattern = PatternDecl->getBody(PatternDecl); 4203 } 4204 4205 // Note, we should never try to instantiate a deleted function template. 4206 assert((Pattern || PatternDecl->isDefaulted() || 4207 PatternDecl->hasSkippedBody()) && 4208 "unexpected kind of function template definition"); 4209 4210 // C++1y [temp.explicit]p10: 4211 // Except for inline functions, declarations with types deduced from their 4212 // initializer or return value, and class template specializations, other 4213 // explicit instantiation declarations have the effect of suppressing the 4214 // implicit instantiation of the entity to which they refer. 4215 if (TSK == TSK_ExplicitInstantiationDeclaration && 4216 !PatternDecl->isInlined() && 4217 !PatternDecl->getReturnType()->getContainedAutoType()) 4218 return; 4219 4220 if (PatternDecl->isInlined()) { 4221 // Function, and all later redeclarations of it (from imported modules, 4222 // for instance), are now implicitly inline. 4223 for (auto *D = Function->getMostRecentDecl(); /**/; 4224 D = D->getPreviousDecl()) { 4225 D->setImplicitlyInline(); 4226 if (D == Function) 4227 break; 4228 } 4229 } 4230 4231 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 4232 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4233 return; 4234 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(), 4235 "instantiating function definition"); 4236 4237 // The instantiation is visible here, even if it was first declared in an 4238 // unimported module. 4239 Function->setVisibleDespiteOwningModule(); 4240 4241 // Copy the inner loc start from the pattern. 4242 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 4243 4244 EnterExpressionEvaluationContext EvalContext( 4245 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 4246 4247 // Introduce a new scope where local variable instantiations will be 4248 // recorded, unless we're actually a member function within a local 4249 // class, in which case we need to merge our results with the parent 4250 // scope (of the enclosing function). 4251 bool MergeWithParentScope = false; 4252 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 4253 MergeWithParentScope = Rec->isLocalClass(); 4254 4255 LocalInstantiationScope Scope(*this, MergeWithParentScope); 4256 4257 if (PatternDecl->isDefaulted()) 4258 SetDeclDefaulted(Function, PatternDecl->getLocation()); 4259 else { 4260 MultiLevelTemplateArgumentList TemplateArgs = 4261 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl); 4262 4263 // Substitute into the qualifier; we can get a substitution failure here 4264 // through evil use of alias templates. 4265 // FIXME: Is CurContext correct for this? Should we go to the (instantiation 4266 // of the) lexical context of the pattern? 4267 SubstQualifier(*this, PatternDecl, Function, TemplateArgs); 4268 4269 ActOnStartOfFunctionDef(nullptr, Function); 4270 4271 // Enter the scope of this instantiation. We don't use 4272 // PushDeclContext because we don't have a scope. 4273 Sema::ContextRAII savedContext(*this, Function); 4274 4275 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 4276 TemplateArgs)) 4277 return; 4278 4279 StmtResult Body; 4280 if (PatternDecl->hasSkippedBody()) { 4281 ActOnSkippedFunctionBody(Function); 4282 Body = nullptr; 4283 } else { 4284 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) { 4285 // If this is a constructor, instantiate the member initializers. 4286 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl), 4287 TemplateArgs); 4288 4289 // If this is an MS ABI dllexport default constructor, instantiate any 4290 // default arguments. 4291 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 4292 Ctor->isDefaultConstructor()) { 4293 InstantiateDefaultCtorDefaultArgs(*this, Ctor); 4294 } 4295 } 4296 4297 // Instantiate the function body. 4298 Body = SubstStmt(Pattern, TemplateArgs); 4299 4300 if (Body.isInvalid()) 4301 Function->setInvalidDecl(); 4302 } 4303 // FIXME: finishing the function body while in an expression evaluation 4304 // context seems wrong. Investigate more. 4305 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true); 4306 4307 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 4308 4309 if (auto *Listener = getASTMutationListener()) 4310 Listener->FunctionDefinitionInstantiated(Function); 4311 4312 savedContext.pop(); 4313 } 4314 4315 DeclGroupRef DG(Function); 4316 Consumer.HandleTopLevelDecl(DG); 4317 4318 // This class may have local implicit instantiations that need to be 4319 // instantiation within this scope. 4320 LocalInstantiations.perform(); 4321 Scope.Exit(); 4322 GlobalInstantiations.perform(); 4323 } 4324 4325 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 4326 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 4327 const TemplateArgumentList &TemplateArgList, 4328 const TemplateArgumentListInfo &TemplateArgsInfo, 4329 SmallVectorImpl<TemplateArgument> &Converted, 4330 SourceLocation PointOfInstantiation, void *InsertPos, 4331 LateInstantiatedAttrVec *LateAttrs, 4332 LocalInstantiationScope *StartingScope) { 4333 if (FromVar->isInvalidDecl()) 4334 return nullptr; 4335 4336 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 4337 if (Inst.isInvalid()) 4338 return nullptr; 4339 4340 MultiLevelTemplateArgumentList TemplateArgLists; 4341 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 4342 4343 // Instantiate the first declaration of the variable template: for a partial 4344 // specialization of a static data member template, the first declaration may 4345 // or may not be the declaration in the class; if it's in the class, we want 4346 // to instantiate a member in the class (a declaration), and if it's outside, 4347 // we want to instantiate a definition. 4348 // 4349 // If we're instantiating an explicitly-specialized member template or member 4350 // partial specialization, don't do this. The member specialization completely 4351 // replaces the original declaration in this case. 4352 bool IsMemberSpec = false; 4353 if (VarTemplatePartialSpecializationDecl *PartialSpec = 4354 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) 4355 IsMemberSpec = PartialSpec->isMemberSpecialization(); 4356 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate()) 4357 IsMemberSpec = FromTemplate->isMemberSpecialization(); 4358 if (!IsMemberSpec) 4359 FromVar = FromVar->getFirstDecl(); 4360 4361 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 4362 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 4363 MultiLevelList); 4364 4365 // TODO: Set LateAttrs and StartingScope ... 4366 4367 return cast_or_null<VarTemplateSpecializationDecl>( 4368 Instantiator.VisitVarTemplateSpecializationDecl( 4369 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted)); 4370 } 4371 4372 /// Instantiates a variable template specialization by completing it 4373 /// with appropriate type information and initializer. 4374 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 4375 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 4376 const MultiLevelTemplateArgumentList &TemplateArgs) { 4377 assert(PatternDecl->isThisDeclarationADefinition() && 4378 "don't have a definition to instantiate from"); 4379 4380 // Do substitution on the type of the declaration 4381 TypeSourceInfo *DI = 4382 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 4383 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 4384 if (!DI) 4385 return nullptr; 4386 4387 // Update the type of this variable template specialization. 4388 VarSpec->setType(DI->getType()); 4389 4390 // Convert the declaration into a definition now. 4391 VarSpec->setCompleteDefinition(); 4392 4393 // Instantiate the initializer. 4394 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 4395 4396 return VarSpec; 4397 } 4398 4399 /// BuildVariableInstantiation - Used after a new variable has been created. 4400 /// Sets basic variable data and decides whether to postpone the 4401 /// variable instantiation. 4402 void Sema::BuildVariableInstantiation( 4403 VarDecl *NewVar, VarDecl *OldVar, 4404 const MultiLevelTemplateArgumentList &TemplateArgs, 4405 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 4406 LocalInstantiationScope *StartingScope, 4407 bool InstantiatingVarTemplate, 4408 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) { 4409 // Instantiating a partial specialization to produce a partial 4410 // specialization. 4411 bool InstantiatingVarTemplatePartialSpec = 4412 isa<VarTemplatePartialSpecializationDecl>(OldVar) && 4413 isa<VarTemplatePartialSpecializationDecl>(NewVar); 4414 // Instantiating from a variable template (or partial specialization) to 4415 // produce a variable template specialization. 4416 bool InstantiatingSpecFromTemplate = 4417 isa<VarTemplateSpecializationDecl>(NewVar) && 4418 (OldVar->getDescribedVarTemplate() || 4419 isa<VarTemplatePartialSpecializationDecl>(OldVar)); 4420 4421 // If we are instantiating a local extern declaration, the 4422 // instantiation belongs lexically to the containing function. 4423 // If we are instantiating a static data member defined 4424 // out-of-line, the instantiation will have the same lexical 4425 // context (which will be a namespace scope) as the template. 4426 if (OldVar->isLocalExternDecl()) { 4427 NewVar->setLocalExternDecl(); 4428 NewVar->setLexicalDeclContext(Owner); 4429 } else if (OldVar->isOutOfLine()) 4430 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 4431 NewVar->setTSCSpec(OldVar->getTSCSpec()); 4432 NewVar->setInitStyle(OldVar->getInitStyle()); 4433 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 4434 NewVar->setObjCForDecl(OldVar->isObjCForDecl()); 4435 NewVar->setConstexpr(OldVar->isConstexpr()); 4436 NewVar->setInitCapture(OldVar->isInitCapture()); 4437 NewVar->setPreviousDeclInSameBlockScope( 4438 OldVar->isPreviousDeclInSameBlockScope()); 4439 NewVar->setAccess(OldVar->getAccess()); 4440 4441 if (!OldVar->isStaticDataMember()) { 4442 if (OldVar->isUsed(false)) 4443 NewVar->setIsUsed(); 4444 NewVar->setReferenced(OldVar->isReferenced()); 4445 } 4446 4447 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 4448 4449 LookupResult Previous( 4450 *this, NewVar->getDeclName(), NewVar->getLocation(), 4451 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 4452 : Sema::LookupOrdinaryName, 4453 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration 4454 : forRedeclarationInCurContext()); 4455 4456 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 4457 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 4458 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 4459 // We have a previous declaration. Use that one, so we merge with the 4460 // right type. 4461 if (NamedDecl *NewPrev = FindInstantiatedDecl( 4462 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 4463 Previous.addDecl(NewPrev); 4464 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 4465 OldVar->hasLinkage()) { 4466 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 4467 } else if (PrevDeclForVarTemplateSpecialization) { 4468 Previous.addDecl(PrevDeclForVarTemplateSpecialization); 4469 } 4470 CheckVariableDeclaration(NewVar, Previous); 4471 4472 if (!InstantiatingVarTemplate) { 4473 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 4474 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 4475 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 4476 } 4477 4478 if (!OldVar->isOutOfLine()) { 4479 if (NewVar->getDeclContext()->isFunctionOrMethod()) 4480 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 4481 } 4482 4483 // Link instantiations of static data members back to the template from 4484 // which they were instantiated. 4485 // 4486 // Don't do this when instantiating a template (we link the template itself 4487 // back in that case) nor when instantiating a static data member template 4488 // (that's not a member specialization). 4489 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate && 4490 !InstantiatingSpecFromTemplate) 4491 NewVar->setInstantiationOfStaticDataMember(OldVar, 4492 TSK_ImplicitInstantiation); 4493 4494 // If the pattern is an (in-class) explicit specialization, then the result 4495 // is also an explicit specialization. 4496 if (VarTemplateSpecializationDecl *OldVTSD = 4497 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) { 4498 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization && 4499 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD)) 4500 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind( 4501 TSK_ExplicitSpecialization); 4502 } 4503 4504 // Forward the mangling number from the template to the instantiated decl. 4505 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 4506 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar)); 4507 4508 // Figure out whether to eagerly instantiate the initializer. 4509 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) { 4510 // We're producing a template. Don't instantiate the initializer yet. 4511 } else if (NewVar->getType()->isUndeducedType()) { 4512 // We need the type to complete the declaration of the variable. 4513 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 4514 } else if (InstantiatingSpecFromTemplate || 4515 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() && 4516 !NewVar->isThisDeclarationADefinition())) { 4517 // Delay instantiation of the initializer for variable template 4518 // specializations or inline static data members until a definition of the 4519 // variable is needed. 4520 } else { 4521 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 4522 } 4523 4524 // Diagnose unused local variables with dependent types, where the diagnostic 4525 // will have been deferred. 4526 if (!NewVar->isInvalidDecl() && 4527 NewVar->getDeclContext()->isFunctionOrMethod() && 4528 OldVar->getType()->isDependentType()) 4529 DiagnoseUnusedDecl(NewVar); 4530 } 4531 4532 /// Instantiate the initializer of a variable. 4533 void Sema::InstantiateVariableInitializer( 4534 VarDecl *Var, VarDecl *OldVar, 4535 const MultiLevelTemplateArgumentList &TemplateArgs) { 4536 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 4537 L->VariableDefinitionInstantiated(Var); 4538 4539 // We propagate the 'inline' flag with the initializer, because it 4540 // would otherwise imply that the variable is a definition for a 4541 // non-static data member. 4542 if (OldVar->isInlineSpecified()) 4543 Var->setInlineSpecified(); 4544 else if (OldVar->isInline()) 4545 Var->setImplicitlyInline(); 4546 4547 if (OldVar->getInit()) { 4548 EnterExpressionEvaluationContext Evaluated( 4549 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var); 4550 4551 // Instantiate the initializer. 4552 ExprResult Init; 4553 4554 { 4555 ContextRAII SwitchContext(*this, Var->getDeclContext()); 4556 Init = SubstInitializer(OldVar->getInit(), TemplateArgs, 4557 OldVar->getInitStyle() == VarDecl::CallInit); 4558 } 4559 4560 if (!Init.isInvalid()) { 4561 Expr *InitExpr = Init.get(); 4562 4563 if (Var->hasAttr<DLLImportAttr>() && 4564 (!InitExpr || 4565 !InitExpr->isConstantInitializer(getASTContext(), false))) { 4566 // Do not dynamically initialize dllimport variables. 4567 } else if (InitExpr) { 4568 bool DirectInit = OldVar->isDirectInit(); 4569 AddInitializerToDecl(Var, InitExpr, DirectInit); 4570 } else 4571 ActOnUninitializedDecl(Var); 4572 } else { 4573 // FIXME: Not too happy about invalidating the declaration 4574 // because of a bogus initializer. 4575 Var->setInvalidDecl(); 4576 } 4577 } else { 4578 // `inline` variables are a definition and declaration all in one; we won't 4579 // pick up an initializer from anywhere else. 4580 if (Var->isStaticDataMember() && !Var->isInline()) { 4581 if (!Var->isOutOfLine()) 4582 return; 4583 4584 // If the declaration inside the class had an initializer, don't add 4585 // another one to the out-of-line definition. 4586 if (OldVar->getFirstDecl()->hasInit()) 4587 return; 4588 } 4589 4590 // We'll add an initializer to a for-range declaration later. 4591 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl()) 4592 return; 4593 4594 ActOnUninitializedDecl(Var); 4595 } 4596 4597 if (getLangOpts().CUDA) 4598 checkAllowedCUDAInitializer(Var); 4599 } 4600 4601 /// Instantiate the definition of the given variable from its 4602 /// template. 4603 /// 4604 /// \param PointOfInstantiation the point at which the instantiation was 4605 /// required. Note that this is not precisely a "point of instantiation" 4606 /// for the variable, but it's close. 4607 /// 4608 /// \param Var the already-instantiated declaration of a templated variable. 4609 /// 4610 /// \param Recursive if true, recursively instantiates any functions that 4611 /// are required by this instantiation. 4612 /// 4613 /// \param DefinitionRequired if true, then we are performing an explicit 4614 /// instantiation where a definition of the variable is required. Complain 4615 /// if there is no such definition. 4616 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 4617 VarDecl *Var, bool Recursive, 4618 bool DefinitionRequired, bool AtEndOfTU) { 4619 if (Var->isInvalidDecl()) 4620 return; 4621 4622 // Never instantiate an explicitly-specialized entity. 4623 TemplateSpecializationKind TSK = 4624 Var->getTemplateSpecializationKindForInstantiation(); 4625 if (TSK == TSK_ExplicitSpecialization) 4626 return; 4627 4628 // Find the pattern and the arguments to substitute into it. 4629 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern(); 4630 assert(PatternDecl && "no pattern for templated variable"); 4631 MultiLevelTemplateArgumentList TemplateArgs = 4632 getTemplateInstantiationArgs(Var); 4633 4634 VarTemplateSpecializationDecl *VarSpec = 4635 dyn_cast<VarTemplateSpecializationDecl>(Var); 4636 if (VarSpec) { 4637 // If this is a variable template specialization, make sure that it is 4638 // non-dependent. 4639 bool InstantiationDependent = false; 4640 assert(!TemplateSpecializationType::anyDependentTemplateArguments( 4641 VarSpec->getTemplateArgsInfo(), InstantiationDependent) && 4642 "Only instantiate variable template specializations that are " 4643 "not type-dependent"); 4644 (void)InstantiationDependent; 4645 4646 // If this is a static data member template, there might be an 4647 // uninstantiated initializer on the declaration. If so, instantiate 4648 // it now. 4649 // 4650 // FIXME: This largely duplicates what we would do below. The difference 4651 // is that along this path we may instantiate an initializer from an 4652 // in-class declaration of the template and instantiate the definition 4653 // from a separate out-of-class definition. 4654 if (PatternDecl->isStaticDataMember() && 4655 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 4656 !Var->hasInit()) { 4657 // FIXME: Factor out the duplicated instantiation context setup/tear down 4658 // code here. 4659 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 4660 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4661 return; 4662 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 4663 "instantiating variable initializer"); 4664 4665 // The instantiation is visible here, even if it was first declared in an 4666 // unimported module. 4667 Var->setVisibleDespiteOwningModule(); 4668 4669 // If we're performing recursive template instantiation, create our own 4670 // queue of pending implicit instantiations that we will instantiate 4671 // later, while we're still within our own instantiation context. 4672 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4673 /*Enabled=*/Recursive); 4674 LocalInstantiationScope Local(*this); 4675 LocalEagerInstantiationScope LocalInstantiations(*this); 4676 4677 // Enter the scope of this instantiation. We don't use 4678 // PushDeclContext because we don't have a scope. 4679 ContextRAII PreviousContext(*this, Var->getDeclContext()); 4680 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 4681 PreviousContext.pop(); 4682 4683 // This variable may have local implicit instantiations that need to be 4684 // instantiated within this scope. 4685 LocalInstantiations.perform(); 4686 Local.Exit(); 4687 GlobalInstantiations.perform(); 4688 } 4689 } else { 4690 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && 4691 "not a static data member?"); 4692 } 4693 4694 VarDecl *Def = PatternDecl->getDefinition(getASTContext()); 4695 4696 // If we don't have a definition of the variable template, we won't perform 4697 // any instantiation. Rather, we rely on the user to instantiate this 4698 // definition (or provide a specialization for it) in another translation 4699 // unit. 4700 if (!Def && !DefinitionRequired) { 4701 if (TSK == TSK_ExplicitInstantiationDefinition) { 4702 PendingInstantiations.push_back( 4703 std::make_pair(Var, PointOfInstantiation)); 4704 } else if (TSK == TSK_ImplicitInstantiation) { 4705 // Warn about missing definition at the end of translation unit. 4706 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 4707 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 4708 Diag(PointOfInstantiation, diag::warn_var_template_missing) 4709 << Var; 4710 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 4711 if (getLangOpts().CPlusPlus11) 4712 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var; 4713 } 4714 return; 4715 } 4716 } 4717 4718 // FIXME: We need to track the instantiation stack in order to know which 4719 // definitions should be visible within this instantiation. 4720 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember(). 4721 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var, 4722 /*InstantiatedFromMember*/false, 4723 PatternDecl, Def, TSK, 4724 /*Complain*/DefinitionRequired)) 4725 return; 4726 4727 // C++11 [temp.explicit]p10: 4728 // Except for inline functions, const variables of literal types, variables 4729 // of reference types, [...] explicit instantiation declarations 4730 // have the effect of suppressing the implicit instantiation of the entity 4731 // to which they refer. 4732 // 4733 // FIXME: That's not exactly the same as "might be usable in constant 4734 // expressions", which only allows constexpr variables and const integral 4735 // types, not arbitrary const literal types. 4736 if (TSK == TSK_ExplicitInstantiationDeclaration && 4737 !Var->mightBeUsableInConstantExpressions(getASTContext())) 4738 return; 4739 4740 // Make sure to pass the instantiated variable to the consumer at the end. 4741 struct PassToConsumerRAII { 4742 ASTConsumer &Consumer; 4743 VarDecl *Var; 4744 4745 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 4746 : Consumer(Consumer), Var(Var) { } 4747 4748 ~PassToConsumerRAII() { 4749 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 4750 } 4751 } PassToConsumerRAII(Consumer, Var); 4752 4753 // If we already have a definition, we're done. 4754 if (VarDecl *Def = Var->getDefinition()) { 4755 // We may be explicitly instantiating something we've already implicitly 4756 // instantiated. 4757 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 4758 PointOfInstantiation); 4759 return; 4760 } 4761 4762 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 4763 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4764 return; 4765 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 4766 "instantiating variable definition"); 4767 4768 // If we're performing recursive template instantiation, create our own 4769 // queue of pending implicit instantiations that we will instantiate later, 4770 // while we're still within our own instantiation context. 4771 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4772 /*Enabled=*/Recursive); 4773 4774 // Enter the scope of this instantiation. We don't use 4775 // PushDeclContext because we don't have a scope. 4776 ContextRAII PreviousContext(*this, Var->getDeclContext()); 4777 LocalInstantiationScope Local(*this); 4778 4779 LocalEagerInstantiationScope LocalInstantiations(*this); 4780 4781 VarDecl *OldVar = Var; 4782 if (Def->isStaticDataMember() && !Def->isOutOfLine()) { 4783 // We're instantiating an inline static data member whose definition was 4784 // provided inside the class. 4785 InstantiateVariableInitializer(Var, Def, TemplateArgs); 4786 } else if (!VarSpec) { 4787 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 4788 TemplateArgs)); 4789 } else if (Var->isStaticDataMember() && 4790 Var->getLexicalDeclContext()->isRecord()) { 4791 // We need to instantiate the definition of a static data member template, 4792 // and all we have is the in-class declaration of it. Instantiate a separate 4793 // declaration of the definition. 4794 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 4795 TemplateArgs); 4796 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 4797 VarSpec->getSpecializedTemplate(), Def, nullptr, 4798 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray())); 4799 if (Var) { 4800 llvm::PointerUnion<VarTemplateDecl *, 4801 VarTemplatePartialSpecializationDecl *> PatternPtr = 4802 VarSpec->getSpecializedTemplateOrPartial(); 4803 if (VarTemplatePartialSpecializationDecl *Partial = 4804 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 4805 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 4806 Partial, &VarSpec->getTemplateInstantiationArgs()); 4807 4808 // Merge the definition with the declaration. 4809 LookupResult R(*this, Var->getDeclName(), Var->getLocation(), 4810 LookupOrdinaryName, forRedeclarationInCurContext()); 4811 R.addDecl(OldVar); 4812 MergeVarDecl(Var, R); 4813 4814 // Attach the initializer. 4815 InstantiateVariableInitializer(Var, Def, TemplateArgs); 4816 } 4817 } else 4818 // Complete the existing variable's definition with an appropriately 4819 // substituted type and initializer. 4820 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 4821 4822 PreviousContext.pop(); 4823 4824 if (Var) { 4825 PassToConsumerRAII.Var = Var; 4826 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 4827 OldVar->getPointOfInstantiation()); 4828 } 4829 4830 // This variable may have local implicit instantiations that need to be 4831 // instantiated within this scope. 4832 LocalInstantiations.perform(); 4833 Local.Exit(); 4834 GlobalInstantiations.perform(); 4835 } 4836 4837 void 4838 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 4839 const CXXConstructorDecl *Tmpl, 4840 const MultiLevelTemplateArgumentList &TemplateArgs) { 4841 4842 SmallVector<CXXCtorInitializer*, 4> NewInits; 4843 bool AnyErrors = Tmpl->isInvalidDecl(); 4844 4845 // Instantiate all the initializers. 4846 for (const auto *Init : Tmpl->inits()) { 4847 // Only instantiate written initializers, let Sema re-construct implicit 4848 // ones. 4849 if (!Init->isWritten()) 4850 continue; 4851 4852 SourceLocation EllipsisLoc; 4853 4854 if (Init->isPackExpansion()) { 4855 // This is a pack expansion. We should expand it now. 4856 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 4857 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 4858 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 4859 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 4860 bool ShouldExpand = false; 4861 bool RetainExpansion = false; 4862 Optional<unsigned> NumExpansions; 4863 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 4864 BaseTL.getSourceRange(), 4865 Unexpanded, 4866 TemplateArgs, ShouldExpand, 4867 RetainExpansion, 4868 NumExpansions)) { 4869 AnyErrors = true; 4870 New->setInvalidDecl(); 4871 continue; 4872 } 4873 assert(ShouldExpand && "Partial instantiation of base initializer?"); 4874 4875 // Loop over all of the arguments in the argument pack(s), 4876 for (unsigned I = 0; I != *NumExpansions; ++I) { 4877 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 4878 4879 // Instantiate the initializer. 4880 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4881 /*CXXDirectInit=*/true); 4882 if (TempInit.isInvalid()) { 4883 AnyErrors = true; 4884 break; 4885 } 4886 4887 // Instantiate the base type. 4888 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 4889 TemplateArgs, 4890 Init->getSourceLocation(), 4891 New->getDeclName()); 4892 if (!BaseTInfo) { 4893 AnyErrors = true; 4894 break; 4895 } 4896 4897 // Build the initializer. 4898 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 4899 BaseTInfo, TempInit.get(), 4900 New->getParent(), 4901 SourceLocation()); 4902 if (NewInit.isInvalid()) { 4903 AnyErrors = true; 4904 break; 4905 } 4906 4907 NewInits.push_back(NewInit.get()); 4908 } 4909 4910 continue; 4911 } 4912 4913 // Instantiate the initializer. 4914 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4915 /*CXXDirectInit=*/true); 4916 if (TempInit.isInvalid()) { 4917 AnyErrors = true; 4918 continue; 4919 } 4920 4921 MemInitResult NewInit; 4922 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 4923 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 4924 TemplateArgs, 4925 Init->getSourceLocation(), 4926 New->getDeclName()); 4927 if (!TInfo) { 4928 AnyErrors = true; 4929 New->setInvalidDecl(); 4930 continue; 4931 } 4932 4933 if (Init->isBaseInitializer()) 4934 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(), 4935 New->getParent(), EllipsisLoc); 4936 else 4937 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(), 4938 cast<CXXRecordDecl>(CurContext->getParent())); 4939 } else if (Init->isMemberInitializer()) { 4940 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 4941 Init->getMemberLocation(), 4942 Init->getMember(), 4943 TemplateArgs)); 4944 if (!Member) { 4945 AnyErrors = true; 4946 New->setInvalidDecl(); 4947 continue; 4948 } 4949 4950 NewInit = BuildMemberInitializer(Member, TempInit.get(), 4951 Init->getSourceLocation()); 4952 } else if (Init->isIndirectMemberInitializer()) { 4953 IndirectFieldDecl *IndirectMember = 4954 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 4955 Init->getMemberLocation(), 4956 Init->getIndirectMember(), TemplateArgs)); 4957 4958 if (!IndirectMember) { 4959 AnyErrors = true; 4960 New->setInvalidDecl(); 4961 continue; 4962 } 4963 4964 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(), 4965 Init->getSourceLocation()); 4966 } 4967 4968 if (NewInit.isInvalid()) { 4969 AnyErrors = true; 4970 New->setInvalidDecl(); 4971 } else { 4972 NewInits.push_back(NewInit.get()); 4973 } 4974 } 4975 4976 // Assign all the initializers to the new constructor. 4977 ActOnMemInitializers(New, 4978 /*FIXME: ColonLoc */ 4979 SourceLocation(), 4980 NewInits, 4981 AnyErrors); 4982 } 4983 4984 // TODO: this could be templated if the various decl types used the 4985 // same method name. 4986 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 4987 ClassTemplateDecl *Instance) { 4988 Pattern = Pattern->getCanonicalDecl(); 4989 4990 do { 4991 Instance = Instance->getCanonicalDecl(); 4992 if (Pattern == Instance) return true; 4993 Instance = Instance->getInstantiatedFromMemberTemplate(); 4994 } while (Instance); 4995 4996 return false; 4997 } 4998 4999 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 5000 FunctionTemplateDecl *Instance) { 5001 Pattern = Pattern->getCanonicalDecl(); 5002 5003 do { 5004 Instance = Instance->getCanonicalDecl(); 5005 if (Pattern == Instance) return true; 5006 Instance = Instance->getInstantiatedFromMemberTemplate(); 5007 } while (Instance); 5008 5009 return false; 5010 } 5011 5012 static bool 5013 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 5014 ClassTemplatePartialSpecializationDecl *Instance) { 5015 Pattern 5016 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 5017 do { 5018 Instance = cast<ClassTemplatePartialSpecializationDecl>( 5019 Instance->getCanonicalDecl()); 5020 if (Pattern == Instance) 5021 return true; 5022 Instance = Instance->getInstantiatedFromMember(); 5023 } while (Instance); 5024 5025 return false; 5026 } 5027 5028 static bool isInstantiationOf(CXXRecordDecl *Pattern, 5029 CXXRecordDecl *Instance) { 5030 Pattern = Pattern->getCanonicalDecl(); 5031 5032 do { 5033 Instance = Instance->getCanonicalDecl(); 5034 if (Pattern == Instance) return true; 5035 Instance = Instance->getInstantiatedFromMemberClass(); 5036 } while (Instance); 5037 5038 return false; 5039 } 5040 5041 static bool isInstantiationOf(FunctionDecl *Pattern, 5042 FunctionDecl *Instance) { 5043 Pattern = Pattern->getCanonicalDecl(); 5044 5045 do { 5046 Instance = Instance->getCanonicalDecl(); 5047 if (Pattern == Instance) return true; 5048 Instance = Instance->getInstantiatedFromMemberFunction(); 5049 } while (Instance); 5050 5051 return false; 5052 } 5053 5054 static bool isInstantiationOf(EnumDecl *Pattern, 5055 EnumDecl *Instance) { 5056 Pattern = Pattern->getCanonicalDecl(); 5057 5058 do { 5059 Instance = Instance->getCanonicalDecl(); 5060 if (Pattern == Instance) return true; 5061 Instance = Instance->getInstantiatedFromMemberEnum(); 5062 } while (Instance); 5063 5064 return false; 5065 } 5066 5067 static bool isInstantiationOf(UsingShadowDecl *Pattern, 5068 UsingShadowDecl *Instance, 5069 ASTContext &C) { 5070 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance), 5071 Pattern); 5072 } 5073 5074 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance, 5075 ASTContext &C) { 5076 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 5077 } 5078 5079 template<typename T> 5080 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, 5081 ASTContext &Ctx) { 5082 // An unresolved using declaration can instantiate to an unresolved using 5083 // declaration, or to a using declaration or a using declaration pack. 5084 // 5085 // Multiple declarations can claim to be instantiated from an unresolved 5086 // using declaration if it's a pack expansion. We want the UsingPackDecl 5087 // in that case, not the individual UsingDecls within the pack. 5088 bool OtherIsPackExpansion; 5089 NamedDecl *OtherFrom; 5090 if (auto *OtherUUD = dyn_cast<T>(Other)) { 5091 OtherIsPackExpansion = OtherUUD->isPackExpansion(); 5092 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD); 5093 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) { 5094 OtherIsPackExpansion = true; 5095 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl(); 5096 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) { 5097 OtherIsPackExpansion = false; 5098 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD); 5099 } else { 5100 return false; 5101 } 5102 return Pattern->isPackExpansion() == OtherIsPackExpansion && 5103 declaresSameEntity(OtherFrom, Pattern); 5104 } 5105 5106 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 5107 VarDecl *Instance) { 5108 assert(Instance->isStaticDataMember()); 5109 5110 Pattern = Pattern->getCanonicalDecl(); 5111 5112 do { 5113 Instance = Instance->getCanonicalDecl(); 5114 if (Pattern == Instance) return true; 5115 Instance = Instance->getInstantiatedFromStaticDataMember(); 5116 } while (Instance); 5117 5118 return false; 5119 } 5120 5121 // Other is the prospective instantiation 5122 // D is the prospective pattern 5123 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 5124 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) 5125 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5126 5127 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D)) 5128 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5129 5130 if (D->getKind() != Other->getKind()) 5131 return false; 5132 5133 if (auto *Record = dyn_cast<CXXRecordDecl>(Other)) 5134 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 5135 5136 if (auto *Function = dyn_cast<FunctionDecl>(Other)) 5137 return isInstantiationOf(cast<FunctionDecl>(D), Function); 5138 5139 if (auto *Enum = dyn_cast<EnumDecl>(Other)) 5140 return isInstantiationOf(cast<EnumDecl>(D), Enum); 5141 5142 if (auto *Var = dyn_cast<VarDecl>(Other)) 5143 if (Var->isStaticDataMember()) 5144 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 5145 5146 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other)) 5147 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 5148 5149 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 5150 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 5151 5152 if (auto *PartialSpec = 5153 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 5154 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 5155 PartialSpec); 5156 5157 if (auto *Field = dyn_cast<FieldDecl>(Other)) { 5158 if (!Field->getDeclName()) { 5159 // This is an unnamed field. 5160 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field), 5161 cast<FieldDecl>(D)); 5162 } 5163 } 5164 5165 if (auto *Using = dyn_cast<UsingDecl>(Other)) 5166 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 5167 5168 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other)) 5169 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 5170 5171 return D->getDeclName() && 5172 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 5173 } 5174 5175 template<typename ForwardIterator> 5176 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 5177 NamedDecl *D, 5178 ForwardIterator first, 5179 ForwardIterator last) { 5180 for (; first != last; ++first) 5181 if (isInstantiationOf(Ctx, D, *first)) 5182 return cast<NamedDecl>(*first); 5183 5184 return nullptr; 5185 } 5186 5187 /// Finds the instantiation of the given declaration context 5188 /// within the current instantiation. 5189 /// 5190 /// \returns NULL if there was an error 5191 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 5192 const MultiLevelTemplateArgumentList &TemplateArgs) { 5193 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 5194 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true); 5195 return cast_or_null<DeclContext>(ID); 5196 } else return DC; 5197 } 5198 5199 /// Find the instantiation of the given declaration within the 5200 /// current instantiation. 5201 /// 5202 /// This routine is intended to be used when \p D is a declaration 5203 /// referenced from within a template, that needs to mapped into the 5204 /// corresponding declaration within an instantiation. For example, 5205 /// given: 5206 /// 5207 /// \code 5208 /// template<typename T> 5209 /// struct X { 5210 /// enum Kind { 5211 /// KnownValue = sizeof(T) 5212 /// }; 5213 /// 5214 /// bool getKind() const { return KnownValue; } 5215 /// }; 5216 /// 5217 /// template struct X<int>; 5218 /// \endcode 5219 /// 5220 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the 5221 /// \p EnumConstantDecl for \p KnownValue (which refers to 5222 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation 5223 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs 5224 /// this mapping from within the instantiation of <tt>X<int></tt>. 5225 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 5226 const MultiLevelTemplateArgumentList &TemplateArgs, 5227 bool FindingInstantiatedContext) { 5228 DeclContext *ParentDC = D->getDeclContext(); 5229 // FIXME: Parmeters of pointer to functions (y below) that are themselves 5230 // parameters (p below) can have their ParentDC set to the translation-unit 5231 // - thus we can not consistently check if the ParentDC of such a parameter 5232 // is Dependent or/and a FunctionOrMethod. 5233 // For e.g. this code, during Template argument deduction tries to 5234 // find an instantiated decl for (T y) when the ParentDC for y is 5235 // the translation unit. 5236 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 5237 // float baz(float(*)()) { return 0.0; } 5238 // Foo(baz); 5239 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 5240 // it gets here, always has a FunctionOrMethod as its ParentDC?? 5241 // For now: 5242 // - as long as we have a ParmVarDecl whose parent is non-dependent and 5243 // whose type is not instantiation dependent, do nothing to the decl 5244 // - otherwise find its instantiated decl. 5245 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() && 5246 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 5247 return D; 5248 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 5249 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 5250 ((ParentDC->isFunctionOrMethod() || 5251 isa<OMPDeclareReductionDecl>(ParentDC) || 5252 isa<OMPDeclareMapperDecl>(ParentDC)) && 5253 ParentDC->isDependentContext()) || 5254 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 5255 // D is a local of some kind. Look into the map of local 5256 // declarations to their instantiations. 5257 if (CurrentInstantiationScope) { 5258 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) { 5259 if (Decl *FD = Found->dyn_cast<Decl *>()) 5260 return cast<NamedDecl>(FD); 5261 5262 int PackIdx = ArgumentPackSubstitutionIndex; 5263 assert(PackIdx != -1 && 5264 "found declaration pack but not pack expanding"); 5265 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 5266 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 5267 } 5268 } 5269 5270 // If we're performing a partial substitution during template argument 5271 // deduction, we may not have values for template parameters yet. They 5272 // just map to themselves. 5273 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 5274 isa<TemplateTemplateParmDecl>(D)) 5275 return D; 5276 5277 if (D->isInvalidDecl()) 5278 return nullptr; 5279 5280 // Normally this function only searches for already instantiated declaration 5281 // however we have to make an exclusion for local types used before 5282 // definition as in the code: 5283 // 5284 // template<typename T> void f1() { 5285 // void g1(struct x1); 5286 // struct x1 {}; 5287 // } 5288 // 5289 // In this case instantiation of the type of 'g1' requires definition of 5290 // 'x1', which is defined later. Error recovery may produce an enum used 5291 // before definition. In these cases we need to instantiate relevant 5292 // declarations here. 5293 bool NeedInstantiate = false; 5294 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 5295 NeedInstantiate = RD->isLocalClass(); 5296 else 5297 NeedInstantiate = isa<EnumDecl>(D); 5298 if (NeedInstantiate) { 5299 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 5300 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 5301 return cast<TypeDecl>(Inst); 5302 } 5303 5304 // If we didn't find the decl, then we must have a label decl that hasn't 5305 // been found yet. Lazily instantiate it and return it now. 5306 assert(isa<LabelDecl>(D)); 5307 5308 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 5309 assert(Inst && "Failed to instantiate label??"); 5310 5311 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 5312 return cast<LabelDecl>(Inst); 5313 } 5314 5315 // For variable template specializations, update those that are still 5316 // type-dependent. 5317 if (VarTemplateSpecializationDecl *VarSpec = 5318 dyn_cast<VarTemplateSpecializationDecl>(D)) { 5319 bool InstantiationDependent = false; 5320 const TemplateArgumentListInfo &VarTemplateArgs = 5321 VarSpec->getTemplateArgsInfo(); 5322 if (TemplateSpecializationType::anyDependentTemplateArguments( 5323 VarTemplateArgs, InstantiationDependent)) 5324 D = cast<NamedDecl>( 5325 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs)); 5326 return D; 5327 } 5328 5329 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 5330 if (!Record->isDependentContext()) 5331 return D; 5332 5333 // Determine whether this record is the "templated" declaration describing 5334 // a class template or class template partial specialization. 5335 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 5336 if (ClassTemplate) 5337 ClassTemplate = ClassTemplate->getCanonicalDecl(); 5338 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 5339 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 5340 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 5341 5342 // Walk the current context to find either the record or an instantiation of 5343 // it. 5344 DeclContext *DC = CurContext; 5345 while (!DC->isFileContext()) { 5346 // If we're performing substitution while we're inside the template 5347 // definition, we'll find our own context. We're done. 5348 if (DC->Equals(Record)) 5349 return Record; 5350 5351 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 5352 // Check whether we're in the process of instantiating a class template 5353 // specialization of the template we're mapping. 5354 if (ClassTemplateSpecializationDecl *InstSpec 5355 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 5356 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 5357 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 5358 return InstRecord; 5359 } 5360 5361 // Check whether we're in the process of instantiating a member class. 5362 if (isInstantiationOf(Record, InstRecord)) 5363 return InstRecord; 5364 } 5365 5366 // Move to the outer template scope. 5367 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 5368 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 5369 DC = FD->getLexicalDeclContext(); 5370 continue; 5371 } 5372 // An implicit deduction guide acts as if it's within the class template 5373 // specialization described by its name and first N template params. 5374 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD); 5375 if (Guide && Guide->isImplicit()) { 5376 TemplateDecl *TD = Guide->getDeducedTemplate(); 5377 // Convert the arguments to an "as-written" list. 5378 TemplateArgumentListInfo Args(Loc, Loc); 5379 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front( 5380 TD->getTemplateParameters()->size())) { 5381 ArrayRef<TemplateArgument> Unpacked(Arg); 5382 if (Arg.getKind() == TemplateArgument::Pack) 5383 Unpacked = Arg.pack_elements(); 5384 for (TemplateArgument UnpackedArg : Unpacked) 5385 Args.addArgument( 5386 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc)); 5387 } 5388 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args); 5389 if (T.isNull()) 5390 return nullptr; 5391 auto *SubstRecord = T->getAsCXXRecordDecl(); 5392 assert(SubstRecord && "class template id not a class type?"); 5393 // Check that this template-id names the primary template and not a 5394 // partial or explicit specialization. (In the latter cases, it's 5395 // meaningless to attempt to find an instantiation of D within the 5396 // specialization.) 5397 // FIXME: The standard doesn't say what should happen here. 5398 if (FindingInstantiatedContext && 5399 usesPartialOrExplicitSpecialization( 5400 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) { 5401 Diag(Loc, diag::err_specialization_not_primary_template) 5402 << T << (SubstRecord->getTemplateSpecializationKind() == 5403 TSK_ExplicitSpecialization); 5404 return nullptr; 5405 } 5406 DC = SubstRecord; 5407 continue; 5408 } 5409 } 5410 5411 DC = DC->getParent(); 5412 } 5413 5414 // Fall through to deal with other dependent record types (e.g., 5415 // anonymous unions in class templates). 5416 } 5417 5418 if (!ParentDC->isDependentContext()) 5419 return D; 5420 5421 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 5422 if (!ParentDC) 5423 return nullptr; 5424 5425 if (ParentDC != D->getDeclContext()) { 5426 // We performed some kind of instantiation in the parent context, 5427 // so now we need to look into the instantiated parent context to 5428 // find the instantiation of the declaration D. 5429 5430 // If our context used to be dependent, we may need to instantiate 5431 // it before performing lookup into that context. 5432 bool IsBeingInstantiated = false; 5433 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 5434 if (!Spec->isDependentContext()) { 5435 QualType T = Context.getTypeDeclType(Spec); 5436 const RecordType *Tag = T->getAs<RecordType>(); 5437 assert(Tag && "type of non-dependent record is not a RecordType"); 5438 if (Tag->isBeingDefined()) 5439 IsBeingInstantiated = true; 5440 if (!Tag->isBeingDefined() && 5441 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 5442 return nullptr; 5443 5444 ParentDC = Tag->getDecl(); 5445 } 5446 } 5447 5448 NamedDecl *Result = nullptr; 5449 // FIXME: If the name is a dependent name, this lookup won't necessarily 5450 // find it. Does that ever matter? 5451 if (auto Name = D->getDeclName()) { 5452 DeclarationNameInfo NameInfo(Name, D->getLocation()); 5453 Name = SubstDeclarationNameInfo(NameInfo, TemplateArgs).getName(); 5454 if (!Name) 5455 return nullptr; 5456 DeclContext::lookup_result Found = ParentDC->lookup(Name); 5457 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 5458 } else { 5459 // Since we don't have a name for the entity we're looking for, 5460 // our only option is to walk through all of the declarations to 5461 // find that name. This will occur in a few cases: 5462 // 5463 // - anonymous struct/union within a template 5464 // - unnamed class/struct/union/enum within a template 5465 // 5466 // FIXME: Find a better way to find these instantiations! 5467 Result = findInstantiationOf(Context, D, 5468 ParentDC->decls_begin(), 5469 ParentDC->decls_end()); 5470 } 5471 5472 if (!Result) { 5473 if (isa<UsingShadowDecl>(D)) { 5474 // UsingShadowDecls can instantiate to nothing because of using hiding. 5475 } else if (Diags.hasErrorOccurred()) { 5476 // We've already complained about something, so most likely this 5477 // declaration failed to instantiate. There's no point in complaining 5478 // further, since this is normal in invalid code. 5479 } else if (IsBeingInstantiated) { 5480 // The class in which this member exists is currently being 5481 // instantiated, and we haven't gotten around to instantiating this 5482 // member yet. This can happen when the code uses forward declarations 5483 // of member classes, and introduces ordering dependencies via 5484 // template instantiation. 5485 Diag(Loc, diag::err_member_not_yet_instantiated) 5486 << D->getDeclName() 5487 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 5488 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 5489 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 5490 // This enumeration constant was found when the template was defined, 5491 // but can't be found in the instantiation. This can happen if an 5492 // unscoped enumeration member is explicitly specialized. 5493 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 5494 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 5495 TemplateArgs)); 5496 assert(Spec->getTemplateSpecializationKind() == 5497 TSK_ExplicitSpecialization); 5498 Diag(Loc, diag::err_enumerator_does_not_exist) 5499 << D->getDeclName() 5500 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 5501 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 5502 << Context.getTypeDeclType(Spec); 5503 } else { 5504 // We should have found something, but didn't. 5505 llvm_unreachable("Unable to find instantiation of declaration!"); 5506 } 5507 } 5508 5509 D = Result; 5510 } 5511 5512 return D; 5513 } 5514 5515 /// Performs template instantiation for all implicit template 5516 /// instantiations we have seen until this point. 5517 void Sema::PerformPendingInstantiations(bool LocalOnly) { 5518 while (!PendingLocalImplicitInstantiations.empty() || 5519 (!LocalOnly && !PendingInstantiations.empty())) { 5520 PendingImplicitInstantiation Inst; 5521 5522 if (PendingLocalImplicitInstantiations.empty()) { 5523 Inst = PendingInstantiations.front(); 5524 PendingInstantiations.pop_front(); 5525 } else { 5526 Inst = PendingLocalImplicitInstantiations.front(); 5527 PendingLocalImplicitInstantiations.pop_front(); 5528 } 5529 5530 // Instantiate function definitions 5531 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 5532 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 5533 TSK_ExplicitInstantiationDefinition; 5534 if (Function->isMultiVersion()) { 5535 getASTContext().forEachMultiversionedFunctionVersion( 5536 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) { 5537 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true, 5538 DefinitionRequired, true); 5539 if (CurFD->isDefined()) 5540 CurFD->setInstantiationIsPending(false); 5541 }); 5542 } else { 5543 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true, 5544 DefinitionRequired, true); 5545 if (Function->isDefined()) 5546 Function->setInstantiationIsPending(false); 5547 } 5548 continue; 5549 } 5550 5551 // Instantiate variable definitions 5552 VarDecl *Var = cast<VarDecl>(Inst.first); 5553 5554 assert((Var->isStaticDataMember() || 5555 isa<VarTemplateSpecializationDecl>(Var)) && 5556 "Not a static data member, nor a variable template" 5557 " specialization?"); 5558 5559 // Don't try to instantiate declarations if the most recent redeclaration 5560 // is invalid. 5561 if (Var->getMostRecentDecl()->isInvalidDecl()) 5562 continue; 5563 5564 // Check if the most recent declaration has changed the specialization kind 5565 // and removed the need for implicit instantiation. 5566 switch (Var->getMostRecentDecl() 5567 ->getTemplateSpecializationKindForInstantiation()) { 5568 case TSK_Undeclared: 5569 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 5570 case TSK_ExplicitInstantiationDeclaration: 5571 case TSK_ExplicitSpecialization: 5572 continue; // No longer need to instantiate this type. 5573 case TSK_ExplicitInstantiationDefinition: 5574 // We only need an instantiation if the pending instantiation *is* the 5575 // explicit instantiation. 5576 if (Var != Var->getMostRecentDecl()) 5577 continue; 5578 break; 5579 case TSK_ImplicitInstantiation: 5580 break; 5581 } 5582 5583 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 5584 "instantiating variable definition"); 5585 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 5586 TSK_ExplicitInstantiationDefinition; 5587 5588 // Instantiate static data member definitions or variable template 5589 // specializations. 5590 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 5591 DefinitionRequired, true); 5592 } 5593 } 5594 5595 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 5596 const MultiLevelTemplateArgumentList &TemplateArgs) { 5597 for (auto DD : Pattern->ddiags()) { 5598 switch (DD->getKind()) { 5599 case DependentDiagnostic::Access: 5600 HandleDependentAccessCheck(*DD, TemplateArgs); 5601 break; 5602 } 5603 } 5604 } 5605