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