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 SemaRef.SetDeclDefaulted(Function, D->getLocation()); 2082 if (D->isDeleted()) 2083 SemaRef.SetDeclDeleted(Function, D->getLocation()); 2084 2085 if (Function->isLocalExternDecl() && !Function->getPreviousDecl()) 2086 DC->makeDeclVisibleInContext(PrincipalDecl); 2087 2088 if (Function->isOverloadedOperator() && !DC->isRecord() && 2089 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 2090 PrincipalDecl->setNonMemberOperator(); 2091 2092 return Function; 2093 } 2094 2095 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl( 2096 CXXMethodDecl *D, TemplateParameterList *TemplateParams, 2097 Optional<const ASTTemplateArgumentListInfo *> 2098 ClassScopeSpecializationArgs) { 2099 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 2100 if (FunctionTemplate && !TemplateParams) { 2101 // We are creating a function template specialization from a function 2102 // template. Check whether there is already a function template 2103 // specialization for this particular set of template arguments. 2104 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 2105 2106 void *InsertPos = nullptr; 2107 FunctionDecl *SpecFunc 2108 = FunctionTemplate->findSpecialization(Innermost, InsertPos); 2109 2110 // If we already have a function template specialization, return it. 2111 if (SpecFunc) 2112 return SpecFunc; 2113 } 2114 2115 bool isFriend; 2116 if (FunctionTemplate) 2117 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 2118 else 2119 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 2120 2121 bool MergeWithParentScope = (TemplateParams != nullptr) || 2122 !(isa<Decl>(Owner) && 2123 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 2124 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 2125 2126 // Instantiate enclosing template arguments for friends. 2127 SmallVector<TemplateParameterList *, 4> TempParamLists; 2128 unsigned NumTempParamLists = 0; 2129 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 2130 TempParamLists.resize(NumTempParamLists); 2131 for (unsigned I = 0; I != NumTempParamLists; ++I) { 2132 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 2133 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2134 if (!InstParams) 2135 return nullptr; 2136 TempParamLists[I] = InstParams; 2137 } 2138 } 2139 2140 ExplicitSpecifier InstantiatedExplicitSpecifier = 2141 instantiateExplicitSpecifier(SemaRef, TemplateArgs, 2142 ExplicitSpecifier::getFromDecl(D), D); 2143 if (InstantiatedExplicitSpecifier.isInvalid()) 2144 return nullptr; 2145 2146 SmallVector<ParmVarDecl *, 4> Params; 2147 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 2148 if (!TInfo) 2149 return nullptr; 2150 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 2151 2152 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 2153 if (QualifierLoc) { 2154 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 2155 TemplateArgs); 2156 if (!QualifierLoc) 2157 return nullptr; 2158 } 2159 2160 DeclContext *DC = Owner; 2161 if (isFriend) { 2162 if (QualifierLoc) { 2163 CXXScopeSpec SS; 2164 SS.Adopt(QualifierLoc); 2165 DC = SemaRef.computeDeclContext(SS); 2166 2167 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 2168 return nullptr; 2169 } else { 2170 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 2171 D->getDeclContext(), 2172 TemplateArgs); 2173 } 2174 if (!DC) return nullptr; 2175 } 2176 2177 // Build the instantiated method declaration. 2178 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 2179 CXXMethodDecl *Method = nullptr; 2180 2181 SourceLocation StartLoc = D->getInnerLocStart(); 2182 DeclarationNameInfo NameInfo 2183 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2184 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 2185 Method = CXXConstructorDecl::Create( 2186 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2187 InstantiatedExplicitSpecifier, Constructor->isInlineSpecified(), false, 2188 Constructor->getConstexprKind()); 2189 Method->setRangeEnd(Constructor->getEndLoc()); 2190 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 2191 Method = CXXDestructorDecl::Create( 2192 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2193 Destructor->isInlineSpecified(), false, Destructor->getConstexprKind()); 2194 Method->setRangeEnd(Destructor->getEndLoc()); 2195 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 2196 Method = CXXConversionDecl::Create( 2197 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2198 Conversion->isInlineSpecified(), InstantiatedExplicitSpecifier, 2199 Conversion->getConstexprKind(), Conversion->getEndLoc()); 2200 } else { 2201 StorageClass SC = D->isStatic() ? SC_Static : SC_None; 2202 Method = CXXMethodDecl::Create(SemaRef.Context, Record, StartLoc, NameInfo, 2203 T, TInfo, SC, D->isInlineSpecified(), 2204 D->getConstexprKind(), D->getEndLoc()); 2205 } 2206 2207 if (D->isInlined()) 2208 Method->setImplicitlyInline(); 2209 2210 if (QualifierLoc) 2211 Method->setQualifierInfo(QualifierLoc); 2212 2213 if (TemplateParams) { 2214 // Our resulting instantiation is actually a function template, since we 2215 // are substituting only the outer template parameters. For example, given 2216 // 2217 // template<typename T> 2218 // struct X { 2219 // template<typename U> void f(T, U); 2220 // }; 2221 // 2222 // X<int> x; 2223 // 2224 // We are instantiating the member template "f" within X<int>, which means 2225 // substituting int for T, but leaving "f" as a member function template. 2226 // Build the function template itself. 2227 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 2228 Method->getLocation(), 2229 Method->getDeclName(), 2230 TemplateParams, Method); 2231 if (isFriend) { 2232 FunctionTemplate->setLexicalDeclContext(Owner); 2233 FunctionTemplate->setObjectOfFriendDecl(); 2234 } else if (D->isOutOfLine()) 2235 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 2236 Method->setDescribedFunctionTemplate(FunctionTemplate); 2237 } else if (FunctionTemplate) { 2238 // Record this function template specialization. 2239 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 2240 Method->setFunctionTemplateSpecialization(FunctionTemplate, 2241 TemplateArgumentList::CreateCopy(SemaRef.Context, 2242 Innermost), 2243 /*InsertPos=*/nullptr); 2244 } else if (!isFriend) { 2245 // Record that this is an instantiation of a member function. 2246 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 2247 } 2248 2249 // If we are instantiating a member function defined 2250 // out-of-line, the instantiation will have the same lexical 2251 // context (which will be a namespace scope) as the template. 2252 if (isFriend) { 2253 if (NumTempParamLists) 2254 Method->setTemplateParameterListsInfo( 2255 SemaRef.Context, 2256 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists)); 2257 2258 Method->setLexicalDeclContext(Owner); 2259 Method->setObjectOfFriendDecl(); 2260 } else if (D->isOutOfLine()) 2261 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 2262 2263 // Attach the parameters 2264 for (unsigned P = 0; P < Params.size(); ++P) 2265 Params[P]->setOwningFunction(Method); 2266 Method->setParams(Params); 2267 2268 if (InitMethodInstantiation(Method, D)) 2269 Method->setInvalidDecl(); 2270 2271 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 2272 Sema::ForExternalRedeclaration); 2273 2274 bool IsExplicitSpecialization = false; 2275 2276 // If the name of this function was written as a template-id, instantiate 2277 // the explicit template arguments. 2278 if (DependentFunctionTemplateSpecializationInfo *Info 2279 = D->getDependentSpecializationInfo()) { 2280 assert(isFriend && "non-friend has dependent specialization info?"); 2281 2282 // Instantiate the explicit template arguments. 2283 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2284 Info->getRAngleLoc()); 2285 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 2286 ExplicitArgs, TemplateArgs)) 2287 return nullptr; 2288 2289 // Map the candidate templates to their instantiations. 2290 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 2291 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 2292 Info->getTemplate(I), 2293 TemplateArgs); 2294 if (!Temp) return nullptr; 2295 2296 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 2297 } 2298 2299 if (SemaRef.CheckFunctionTemplateSpecialization(Method, 2300 &ExplicitArgs, 2301 Previous)) 2302 Method->setInvalidDecl(); 2303 2304 IsExplicitSpecialization = true; 2305 } else if (const ASTTemplateArgumentListInfo *Info = 2306 ClassScopeSpecializationArgs.getValueOr( 2307 D->getTemplateSpecializationArgsAsWritten())) { 2308 SemaRef.LookupQualifiedName(Previous, DC); 2309 2310 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2311 Info->getRAngleLoc()); 2312 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(), 2313 ExplicitArgs, TemplateArgs)) 2314 return nullptr; 2315 2316 if (SemaRef.CheckFunctionTemplateSpecialization(Method, 2317 &ExplicitArgs, 2318 Previous)) 2319 Method->setInvalidDecl(); 2320 2321 IsExplicitSpecialization = true; 2322 } else if (ClassScopeSpecializationArgs) { 2323 // Class-scope explicit specialization written without explicit template 2324 // arguments. 2325 SemaRef.LookupQualifiedName(Previous, DC); 2326 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous)) 2327 Method->setInvalidDecl(); 2328 2329 IsExplicitSpecialization = true; 2330 } else if (!FunctionTemplate || TemplateParams || isFriend) { 2331 SemaRef.LookupQualifiedName(Previous, Record); 2332 2333 // In C++, the previous declaration we find might be a tag type 2334 // (class or enum). In this case, the new declaration will hide the 2335 // tag type. Note that this does does not apply if we're declaring a 2336 // typedef (C++ [dcl.typedef]p4). 2337 if (Previous.isSingleTagDecl()) 2338 Previous.clear(); 2339 } 2340 2341 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, 2342 IsExplicitSpecialization); 2343 2344 if (D->isPure()) 2345 SemaRef.CheckPureMethod(Method, SourceRange()); 2346 2347 // Propagate access. For a non-friend declaration, the access is 2348 // whatever we're propagating from. For a friend, it should be the 2349 // previous declaration we just found. 2350 if (isFriend && Method->getPreviousDecl()) 2351 Method->setAccess(Method->getPreviousDecl()->getAccess()); 2352 else 2353 Method->setAccess(D->getAccess()); 2354 if (FunctionTemplate) 2355 FunctionTemplate->setAccess(Method->getAccess()); 2356 2357 SemaRef.CheckOverrideControl(Method); 2358 2359 // If a function is defined as defaulted or deleted, mark it as such now. 2360 if (D->isExplicitlyDefaulted()) 2361 SemaRef.SetDeclDefaulted(Method, Method->getLocation()); 2362 if (D->isDeletedAsWritten()) 2363 SemaRef.SetDeclDeleted(Method, Method->getLocation()); 2364 2365 // If this is an explicit specialization, mark the implicitly-instantiated 2366 // template specialization as being an explicit specialization too. 2367 // FIXME: Is this necessary? 2368 if (IsExplicitSpecialization && !isFriend) 2369 SemaRef.CompleteMemberSpecialization(Method, Previous); 2370 2371 // If there's a function template, let our caller handle it. 2372 if (FunctionTemplate) { 2373 // do nothing 2374 2375 // Don't hide a (potentially) valid declaration with an invalid one. 2376 } else if (Method->isInvalidDecl() && !Previous.empty()) { 2377 // do nothing 2378 2379 // Otherwise, check access to friends and make them visible. 2380 } else if (isFriend) { 2381 // We only need to re-check access for methods which we didn't 2382 // manage to match during parsing. 2383 if (!D->getPreviousDecl()) 2384 SemaRef.CheckFriendAccess(Method); 2385 2386 Record->makeDeclVisibleInContext(Method); 2387 2388 // Otherwise, add the declaration. We don't need to do this for 2389 // class-scope specializations because we'll have matched them with 2390 // the appropriate template. 2391 } else { 2392 Owner->addDecl(Method); 2393 } 2394 2395 // PR17480: Honor the used attribute to instantiate member function 2396 // definitions 2397 if (Method->hasAttr<UsedAttr>()) { 2398 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) { 2399 SourceLocation Loc; 2400 if (const MemberSpecializationInfo *MSInfo = 2401 A->getMemberSpecializationInfo()) 2402 Loc = MSInfo->getPointOfInstantiation(); 2403 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A)) 2404 Loc = Spec->getPointOfInstantiation(); 2405 SemaRef.MarkFunctionReferenced(Loc, Method); 2406 } 2407 } 2408 2409 return Method; 2410 } 2411 2412 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 2413 return VisitCXXMethodDecl(D); 2414 } 2415 2416 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 2417 return VisitCXXMethodDecl(D); 2418 } 2419 2420 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 2421 return VisitCXXMethodDecl(D); 2422 } 2423 2424 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 2425 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None, 2426 /*ExpectParameterPack=*/ false); 2427 } 2428 2429 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 2430 TemplateTypeParmDecl *D) { 2431 // TODO: don't always clone when decls are refcounted. 2432 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 2433 2434 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create( 2435 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(), 2436 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(), 2437 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack()); 2438 Inst->setAccess(AS_public); 2439 Inst->setImplicit(D->isImplicit()); 2440 2441 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2442 TypeSourceInfo *InstantiatedDefaultArg = 2443 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, 2444 D->getDefaultArgumentLoc(), D->getDeclName()); 2445 if (InstantiatedDefaultArg) 2446 Inst->setDefaultArgument(InstantiatedDefaultArg); 2447 } 2448 2449 // Introduce this template parameter's instantiation into the instantiation 2450 // scope. 2451 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 2452 2453 return Inst; 2454 } 2455 2456 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 2457 NonTypeTemplateParmDecl *D) { 2458 // Substitute into the type of the non-type template parameter. 2459 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 2460 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 2461 SmallVector<QualType, 4> ExpandedParameterPackTypes; 2462 bool IsExpandedParameterPack = false; 2463 TypeSourceInfo *DI; 2464 QualType T; 2465 bool Invalid = false; 2466 2467 if (D->isExpandedParameterPack()) { 2468 // The non-type template parameter pack is an already-expanded pack 2469 // expansion of types. Substitute into each of the expanded types. 2470 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 2471 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 2472 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 2473 TypeSourceInfo *NewDI = 2474 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs, 2475 D->getLocation(), D->getDeclName()); 2476 if (!NewDI) 2477 return nullptr; 2478 2479 QualType NewT = 2480 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2481 if (NewT.isNull()) 2482 return nullptr; 2483 2484 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2485 ExpandedParameterPackTypes.push_back(NewT); 2486 } 2487 2488 IsExpandedParameterPack = true; 2489 DI = D->getTypeSourceInfo(); 2490 T = DI->getType(); 2491 } else if (D->isPackExpansion()) { 2492 // The non-type template parameter pack's type is a pack expansion of types. 2493 // Determine whether we need to expand this parameter pack into separate 2494 // types. 2495 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); 2496 TypeLoc Pattern = Expansion.getPatternLoc(); 2497 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2498 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 2499 2500 // Determine whether the set of unexpanded parameter packs can and should 2501 // be expanded. 2502 bool Expand = true; 2503 bool RetainExpansion = false; 2504 Optional<unsigned> OrigNumExpansions 2505 = Expansion.getTypePtr()->getNumExpansions(); 2506 Optional<unsigned> NumExpansions = OrigNumExpansions; 2507 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 2508 Pattern.getSourceRange(), 2509 Unexpanded, 2510 TemplateArgs, 2511 Expand, RetainExpansion, 2512 NumExpansions)) 2513 return nullptr; 2514 2515 if (Expand) { 2516 for (unsigned I = 0; I != *NumExpansions; ++I) { 2517 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2518 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 2519 D->getLocation(), 2520 D->getDeclName()); 2521 if (!NewDI) 2522 return nullptr; 2523 2524 QualType NewT = 2525 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2526 if (NewT.isNull()) 2527 return nullptr; 2528 2529 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2530 ExpandedParameterPackTypes.push_back(NewT); 2531 } 2532 2533 // Note that we have an expanded parameter pack. The "type" of this 2534 // expanded parameter pack is the original expansion type, but callers 2535 // will end up using the expanded parameter pack types for type-checking. 2536 IsExpandedParameterPack = true; 2537 DI = D->getTypeSourceInfo(); 2538 T = DI->getType(); 2539 } else { 2540 // We cannot fully expand the pack expansion now, so substitute into the 2541 // pattern and create a new pack expansion type. 2542 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2543 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 2544 D->getLocation(), 2545 D->getDeclName()); 2546 if (!NewPattern) 2547 return nullptr; 2548 2549 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation()); 2550 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 2551 NumExpansions); 2552 if (!DI) 2553 return nullptr; 2554 2555 T = DI->getType(); 2556 } 2557 } else { 2558 // Simple case: substitution into a parameter that is not a parameter pack. 2559 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 2560 D->getLocation(), D->getDeclName()); 2561 if (!DI) 2562 return nullptr; 2563 2564 // Check that this type is acceptable for a non-type template parameter. 2565 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation()); 2566 if (T.isNull()) { 2567 T = SemaRef.Context.IntTy; 2568 Invalid = true; 2569 } 2570 } 2571 2572 NonTypeTemplateParmDecl *Param; 2573 if (IsExpandedParameterPack) 2574 Param = NonTypeTemplateParmDecl::Create( 2575 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2576 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2577 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes, 2578 ExpandedParameterPackTypesAsWritten); 2579 else 2580 Param = NonTypeTemplateParmDecl::Create( 2581 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2582 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2583 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI); 2584 2585 Param->setAccess(AS_public); 2586 Param->setImplicit(D->isImplicit()); 2587 if (Invalid) 2588 Param->setInvalidDecl(); 2589 2590 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2591 EnterExpressionEvaluationContext ConstantEvaluated( 2592 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 2593 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs); 2594 if (!Value.isInvalid()) 2595 Param->setDefaultArgument(Value.get()); 2596 } 2597 2598 // Introduce this template parameter's instantiation into the instantiation 2599 // scope. 2600 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2601 return Param; 2602 } 2603 2604 static void collectUnexpandedParameterPacks( 2605 Sema &S, 2606 TemplateParameterList *Params, 2607 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 2608 for (const auto &P : *Params) { 2609 if (P->isTemplateParameterPack()) 2610 continue; 2611 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) 2612 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), 2613 Unexpanded); 2614 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P)) 2615 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), 2616 Unexpanded); 2617 } 2618 } 2619 2620 Decl * 2621 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 2622 TemplateTemplateParmDecl *D) { 2623 // Instantiate the template parameter list of the template template parameter. 2624 TemplateParameterList *TempParams = D->getTemplateParameters(); 2625 TemplateParameterList *InstParams; 2626 SmallVector<TemplateParameterList*, 8> ExpandedParams; 2627 2628 bool IsExpandedParameterPack = false; 2629 2630 if (D->isExpandedParameterPack()) { 2631 // The template template parameter pack is an already-expanded pack 2632 // expansion of template parameters. Substitute into each of the expanded 2633 // parameters. 2634 ExpandedParams.reserve(D->getNumExpansionTemplateParameters()); 2635 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 2636 I != N; ++I) { 2637 LocalInstantiationScope Scope(SemaRef); 2638 TemplateParameterList *Expansion = 2639 SubstTemplateParams(D->getExpansionTemplateParameters(I)); 2640 if (!Expansion) 2641 return nullptr; 2642 ExpandedParams.push_back(Expansion); 2643 } 2644 2645 IsExpandedParameterPack = true; 2646 InstParams = TempParams; 2647 } else if (D->isPackExpansion()) { 2648 // The template template parameter pack expands to a pack of template 2649 // template parameters. Determine whether we need to expand this parameter 2650 // pack into separate parameters. 2651 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2652 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), 2653 Unexpanded); 2654 2655 // Determine whether the set of unexpanded parameter packs can and should 2656 // be expanded. 2657 bool Expand = true; 2658 bool RetainExpansion = false; 2659 Optional<unsigned> NumExpansions; 2660 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), 2661 TempParams->getSourceRange(), 2662 Unexpanded, 2663 TemplateArgs, 2664 Expand, RetainExpansion, 2665 NumExpansions)) 2666 return nullptr; 2667 2668 if (Expand) { 2669 for (unsigned I = 0; I != *NumExpansions; ++I) { 2670 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2671 LocalInstantiationScope Scope(SemaRef); 2672 TemplateParameterList *Expansion = SubstTemplateParams(TempParams); 2673 if (!Expansion) 2674 return nullptr; 2675 ExpandedParams.push_back(Expansion); 2676 } 2677 2678 // Note that we have an expanded parameter pack. The "type" of this 2679 // expanded parameter pack is the original expansion type, but callers 2680 // will end up using the expanded parameter pack types for type-checking. 2681 IsExpandedParameterPack = true; 2682 InstParams = TempParams; 2683 } else { 2684 // We cannot fully expand the pack expansion now, so just substitute 2685 // into the pattern. 2686 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2687 2688 LocalInstantiationScope Scope(SemaRef); 2689 InstParams = SubstTemplateParams(TempParams); 2690 if (!InstParams) 2691 return nullptr; 2692 } 2693 } else { 2694 // Perform the actual substitution of template parameters within a new, 2695 // local instantiation scope. 2696 LocalInstantiationScope Scope(SemaRef); 2697 InstParams = SubstTemplateParams(TempParams); 2698 if (!InstParams) 2699 return nullptr; 2700 } 2701 2702 // Build the template template parameter. 2703 TemplateTemplateParmDecl *Param; 2704 if (IsExpandedParameterPack) 2705 Param = TemplateTemplateParmDecl::Create( 2706 SemaRef.Context, Owner, D->getLocation(), 2707 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2708 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams); 2709 else 2710 Param = TemplateTemplateParmDecl::Create( 2711 SemaRef.Context, Owner, D->getLocation(), 2712 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2713 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams); 2714 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2715 NestedNameSpecifierLoc QualifierLoc = 2716 D->getDefaultArgument().getTemplateQualifierLoc(); 2717 QualifierLoc = 2718 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs); 2719 TemplateName TName = SemaRef.SubstTemplateName( 2720 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(), 2721 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); 2722 if (!TName.isNull()) 2723 Param->setDefaultArgument( 2724 SemaRef.Context, 2725 TemplateArgumentLoc(TemplateArgument(TName), 2726 D->getDefaultArgument().getTemplateQualifierLoc(), 2727 D->getDefaultArgument().getTemplateNameLoc())); 2728 } 2729 Param->setAccess(AS_public); 2730 Param->setImplicit(D->isImplicit()); 2731 2732 // Introduce this template parameter's instantiation into the instantiation 2733 // scope. 2734 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2735 2736 return Param; 2737 } 2738 2739 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 2740 // Using directives are never dependent (and never contain any types or 2741 // expressions), so they require no explicit instantiation work. 2742 2743 UsingDirectiveDecl *Inst 2744 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 2745 D->getNamespaceKeyLocation(), 2746 D->getQualifierLoc(), 2747 D->getIdentLocation(), 2748 D->getNominatedNamespace(), 2749 D->getCommonAncestor()); 2750 2751 // Add the using directive to its declaration context 2752 // only if this is not a function or method. 2753 if (!Owner->isFunctionOrMethod()) 2754 Owner->addDecl(Inst); 2755 2756 return Inst; 2757 } 2758 2759 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 2760 2761 // The nested name specifier may be dependent, for example 2762 // template <typename T> struct t { 2763 // struct s1 { T f1(); }; 2764 // struct s2 : s1 { using s1::f1; }; 2765 // }; 2766 // template struct t<int>; 2767 // Here, in using s1::f1, s1 refers to t<T>::s1; 2768 // we need to substitute for t<int>::s1. 2769 NestedNameSpecifierLoc QualifierLoc 2770 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2771 TemplateArgs); 2772 if (!QualifierLoc) 2773 return nullptr; 2774 2775 // For an inheriting constructor declaration, the name of the using 2776 // declaration is the name of a constructor in this class, not in the 2777 // base class. 2778 DeclarationNameInfo NameInfo = D->getNameInfo(); 2779 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 2780 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext)) 2781 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName( 2782 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD)))); 2783 2784 // We only need to do redeclaration lookups if we're in a class 2785 // scope (in fact, it's not really even possible in non-class 2786 // scopes). 2787 bool CheckRedeclaration = Owner->isRecord(); 2788 2789 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 2790 Sema::ForVisibleRedeclaration); 2791 2792 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 2793 D->getUsingLoc(), 2794 QualifierLoc, 2795 NameInfo, 2796 D->hasTypename()); 2797 2798 CXXScopeSpec SS; 2799 SS.Adopt(QualifierLoc); 2800 if (CheckRedeclaration) { 2801 Prev.setHideTags(false); 2802 SemaRef.LookupQualifiedName(Prev, Owner); 2803 2804 // Check for invalid redeclarations. 2805 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(), 2806 D->hasTypename(), SS, 2807 D->getLocation(), Prev)) 2808 NewUD->setInvalidDecl(); 2809 2810 } 2811 2812 if (!NewUD->isInvalidDecl() && 2813 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), 2814 SS, NameInfo, D->getLocation())) 2815 NewUD->setInvalidDecl(); 2816 2817 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 2818 NewUD->setAccess(D->getAccess()); 2819 Owner->addDecl(NewUD); 2820 2821 // Don't process the shadow decls for an invalid decl. 2822 if (NewUD->isInvalidDecl()) 2823 return NewUD; 2824 2825 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 2826 SemaRef.CheckInheritingConstructorUsingDecl(NewUD); 2827 2828 bool isFunctionScope = Owner->isFunctionOrMethod(); 2829 2830 // Process the shadow decls. 2831 for (auto *Shadow : D->shadows()) { 2832 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so 2833 // reconstruct it in the case where it matters. 2834 NamedDecl *OldTarget = Shadow->getTargetDecl(); 2835 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow)) 2836 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl()) 2837 OldTarget = BaseShadow; 2838 2839 NamedDecl *InstTarget = 2840 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 2841 Shadow->getLocation(), OldTarget, TemplateArgs)); 2842 if (!InstTarget) 2843 return nullptr; 2844 2845 UsingShadowDecl *PrevDecl = nullptr; 2846 if (CheckRedeclaration) { 2847 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl)) 2848 continue; 2849 } else if (UsingShadowDecl *OldPrev = 2850 getPreviousDeclForInstantiation(Shadow)) { 2851 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( 2852 Shadow->getLocation(), OldPrev, TemplateArgs)); 2853 } 2854 2855 UsingShadowDecl *InstShadow = 2856 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget, 2857 PrevDecl); 2858 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 2859 2860 if (isFunctionScope) 2861 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 2862 } 2863 2864 return NewUD; 2865 } 2866 2867 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 2868 // Ignore these; we handle them in bulk when processing the UsingDecl. 2869 return nullptr; 2870 } 2871 2872 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl( 2873 ConstructorUsingShadowDecl *D) { 2874 // Ignore these; we handle them in bulk when processing the UsingDecl. 2875 return nullptr; 2876 } 2877 2878 template <typename T> 2879 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl( 2880 T *D, bool InstantiatingPackElement) { 2881 // If this is a pack expansion, expand it now. 2882 if (D->isPackExpansion() && !InstantiatingPackElement) { 2883 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2884 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded); 2885 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded); 2886 2887 // Determine whether the set of unexpanded parameter packs can and should 2888 // be expanded. 2889 bool Expand = true; 2890 bool RetainExpansion = false; 2891 Optional<unsigned> NumExpansions; 2892 if (SemaRef.CheckParameterPacksForExpansion( 2893 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs, 2894 Expand, RetainExpansion, NumExpansions)) 2895 return nullptr; 2896 2897 // This declaration cannot appear within a function template signature, 2898 // so we can't have a partial argument list for a parameter pack. 2899 assert(!RetainExpansion && 2900 "should never need to retain an expansion for UsingPackDecl"); 2901 2902 if (!Expand) { 2903 // We cannot fully expand the pack expansion now, so substitute into the 2904 // pattern and create a new pack expansion. 2905 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2906 return instantiateUnresolvedUsingDecl(D, true); 2907 } 2908 2909 // Within a function, we don't have any normal way to check for conflicts 2910 // between shadow declarations from different using declarations in the 2911 // same pack expansion, but this is always ill-formed because all expansions 2912 // must produce (conflicting) enumerators. 2913 // 2914 // Sadly we can't just reject this in the template definition because it 2915 // could be valid if the pack is empty or has exactly one expansion. 2916 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) { 2917 SemaRef.Diag(D->getEllipsisLoc(), 2918 diag::err_using_decl_redeclaration_expansion); 2919 return nullptr; 2920 } 2921 2922 // Instantiate the slices of this pack and build a UsingPackDecl. 2923 SmallVector<NamedDecl*, 8> Expansions; 2924 for (unsigned I = 0; I != *NumExpansions; ++I) { 2925 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2926 Decl *Slice = instantiateUnresolvedUsingDecl(D, true); 2927 if (!Slice) 2928 return nullptr; 2929 // Note that we can still get unresolved using declarations here, if we 2930 // had arguments for all packs but the pattern also contained other 2931 // template arguments (this only happens during partial substitution, eg 2932 // into the body of a generic lambda in a function template). 2933 Expansions.push_back(cast<NamedDecl>(Slice)); 2934 } 2935 2936 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 2937 if (isDeclWithinFunction(D)) 2938 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 2939 return NewD; 2940 } 2941 2942 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D); 2943 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation(); 2944 2945 NestedNameSpecifierLoc QualifierLoc 2946 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 2947 TemplateArgs); 2948 if (!QualifierLoc) 2949 return nullptr; 2950 2951 CXXScopeSpec SS; 2952 SS.Adopt(QualifierLoc); 2953 2954 DeclarationNameInfo NameInfo 2955 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2956 2957 // Produce a pack expansion only if we're not instantiating a particular 2958 // slice of a pack expansion. 2959 bool InstantiatingSlice = D->getEllipsisLoc().isValid() && 2960 SemaRef.ArgumentPackSubstitutionIndex != -1; 2961 SourceLocation EllipsisLoc = 2962 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc(); 2963 2964 NamedDecl *UD = SemaRef.BuildUsingDeclaration( 2965 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(), 2966 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc, 2967 ParsedAttributesView(), 2968 /*IsInstantiation*/ true); 2969 if (UD) 2970 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D); 2971 2972 return UD; 2973 } 2974 2975 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl( 2976 UnresolvedUsingTypenameDecl *D) { 2977 return instantiateUnresolvedUsingDecl(D); 2978 } 2979 2980 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl( 2981 UnresolvedUsingValueDecl *D) { 2982 return instantiateUnresolvedUsingDecl(D); 2983 } 2984 2985 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) { 2986 SmallVector<NamedDecl*, 8> Expansions; 2987 for (auto *UD : D->expansions()) { 2988 if (NamedDecl *NewUD = 2989 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs)) 2990 Expansions.push_back(NewUD); 2991 else 2992 return nullptr; 2993 } 2994 2995 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 2996 if (isDeclWithinFunction(D)) 2997 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 2998 return NewD; 2999 } 3000 3001 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 3002 ClassScopeFunctionSpecializationDecl *Decl) { 3003 CXXMethodDecl *OldFD = Decl->getSpecialization(); 3004 return cast_or_null<CXXMethodDecl>( 3005 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten())); 3006 } 3007 3008 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( 3009 OMPThreadPrivateDecl *D) { 3010 SmallVector<Expr *, 5> Vars; 3011 for (auto *I : D->varlists()) { 3012 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 3013 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"); 3014 Vars.push_back(Var); 3015 } 3016 3017 OMPThreadPrivateDecl *TD = 3018 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars); 3019 3020 TD->setAccess(AS_public); 3021 Owner->addDecl(TD); 3022 3023 return TD; 3024 } 3025 3026 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) { 3027 SmallVector<Expr *, 5> Vars; 3028 for (auto *I : D->varlists()) { 3029 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 3030 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr"); 3031 Vars.push_back(Var); 3032 } 3033 SmallVector<OMPClause *, 4> Clauses; 3034 // Copy map clauses from the original mapper. 3035 for (OMPClause *C : D->clauselists()) { 3036 auto *AC = cast<OMPAllocatorClause>(C); 3037 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs); 3038 if (!NewE.isUsable()) 3039 continue; 3040 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause( 3041 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc()); 3042 Clauses.push_back(IC); 3043 } 3044 3045 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective( 3046 D->getLocation(), Vars, Clauses, Owner); 3047 if (Res.get().isNull()) 3048 return nullptr; 3049 return Res.get().getSingleDecl(); 3050 } 3051 3052 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) { 3053 llvm_unreachable( 3054 "Requires directive cannot be instantiated within a dependent context"); 3055 } 3056 3057 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl( 3058 OMPDeclareReductionDecl *D) { 3059 // Instantiate type and check if it is allowed. 3060 const bool RequiresInstantiation = 3061 D->getType()->isDependentType() || 3062 D->getType()->isInstantiationDependentType() || 3063 D->getType()->containsUnexpandedParameterPack(); 3064 QualType SubstReductionType; 3065 if (RequiresInstantiation) { 3066 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType( 3067 D->getLocation(), 3068 ParsedType::make(SemaRef.SubstType( 3069 D->getType(), TemplateArgs, D->getLocation(), DeclarationName()))); 3070 } else { 3071 SubstReductionType = D->getType(); 3072 } 3073 Expr *Combiner = D->getCombiner(); 3074 Expr *Init = D->getInitializer(); 3075 const bool CombinerRequiresInstantiation = 3076 Combiner && 3077 (Combiner->isValueDependent() || Combiner->isInstantiationDependent() || 3078 Combiner->isTypeDependent() || 3079 Combiner->containsUnexpandedParameterPack()); 3080 const bool InitRequiresInstantiation = 3081 Init && 3082 (Init->isValueDependent() || Init->isInstantiationDependent() || 3083 Init->isTypeDependent() || Init->containsUnexpandedParameterPack()); 3084 if (SubstReductionType.isNull()) 3085 return nullptr; 3086 bool IsCorrect = !SubstReductionType.isNull(); 3087 // Create instantiated copy. 3088 std::pair<QualType, SourceLocation> ReductionTypes[] = { 3089 std::make_pair(SubstReductionType, D->getLocation())}; 3090 auto *PrevDeclInScope = D->getPrevDeclInScope(); 3091 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 3092 PrevDeclInScope = cast<OMPDeclareReductionDecl>( 3093 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 3094 ->get<Decl *>()); 3095 } 3096 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart( 3097 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(), 3098 PrevDeclInScope); 3099 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl()); 3100 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD); 3101 if (!RequiresInstantiation && !CombinerRequiresInstantiation && 3102 !InitRequiresInstantiation) { 3103 if (Combiner) { 3104 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut()); 3105 NewDRD->setCombiner(Combiner); 3106 if (Init) { 3107 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv()); 3108 NewDRD->setInitializer(Init, D->getInitializerKind()); 3109 } 3110 } 3111 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd( 3112 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl()); 3113 return NewDRD; 3114 } 3115 Expr *SubstCombiner = nullptr; 3116 Expr *SubstInitializer = nullptr; 3117 // Combiners instantiation sequence. 3118 if (Combiner) { 3119 if (!CombinerRequiresInstantiation) { 3120 NewDRD->setCombinerData(D->getCombinerIn(), D->getCombinerOut()); 3121 NewDRD->setCombiner(Combiner); 3122 } else { 3123 SemaRef.ActOnOpenMPDeclareReductionCombinerStart( 3124 /*S=*/nullptr, NewDRD); 3125 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3126 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(), 3127 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl()); 3128 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3129 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(), 3130 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl()); 3131 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3132 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3133 ThisContext); 3134 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get(); 3135 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner); 3136 } 3137 } 3138 // Initializers instantiation sequence. 3139 if (Init) { 3140 if (!InitRequiresInstantiation) { 3141 NewDRD->setInitializerData(D->getInitOrig(), D->getInitPriv()); 3142 NewDRD->setInitializer(Init, D->getInitializerKind()); 3143 } else { 3144 VarDecl *OmpPrivParm = 3145 SemaRef.ActOnOpenMPDeclareReductionInitializerStart( 3146 /*S=*/nullptr, NewDRD); 3147 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3148 cast<DeclRefExpr>(D->getInitOrig())->getDecl(), 3149 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl()); 3150 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3151 cast<DeclRefExpr>(D->getInitPriv())->getDecl(), 3152 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl()); 3153 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) { 3154 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get(); 3155 } else { 3156 auto *OldPrivParm = 3157 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()); 3158 IsCorrect = IsCorrect && OldPrivParm->hasInit(); 3159 if (IsCorrect) 3160 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm, 3161 TemplateArgs); 3162 } 3163 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd( 3164 NewDRD, SubstInitializer, OmpPrivParm); 3165 } 3166 } 3167 IsCorrect = IsCorrect && (!CombinerRequiresInstantiation || SubstCombiner) && 3168 (!InitRequiresInstantiation || 3169 (!Init || 3170 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit && 3171 SubstInitializer) || 3172 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit && 3173 !SubstInitializer))); 3174 3175 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd( 3176 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl()); 3177 3178 return NewDRD; 3179 } 3180 3181 Decl * 3182 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) { 3183 // Instantiate type and check if it is allowed. 3184 const bool RequiresInstantiation = 3185 D->getType()->isDependentType() || 3186 D->getType()->isInstantiationDependentType() || 3187 D->getType()->containsUnexpandedParameterPack(); 3188 QualType SubstMapperTy; 3189 DeclarationName VN = D->getVarName(); 3190 if (RequiresInstantiation) { 3191 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType( 3192 D->getLocation(), 3193 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs, 3194 D->getLocation(), VN))); 3195 } else { 3196 SubstMapperTy = D->getType(); 3197 } 3198 if (SubstMapperTy.isNull()) 3199 return nullptr; 3200 // Create an instantiated copy of mapper. 3201 auto *PrevDeclInScope = D->getPrevDeclInScope(); 3202 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 3203 PrevDeclInScope = cast<OMPDeclareMapperDecl>( 3204 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 3205 ->get<Decl *>()); 3206 } 3207 OMPDeclareMapperDecl *NewDMD = SemaRef.ActOnOpenMPDeclareMapperDirectiveStart( 3208 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(), 3209 VN, D->getAccess(), PrevDeclInScope); 3210 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD); 3211 SmallVector<OMPClause *, 6> Clauses; 3212 bool IsCorrect = true; 3213 if (!RequiresInstantiation) { 3214 // Copy the mapper variable. 3215 NewDMD->setMapperVarRef(D->getMapperVarRef()); 3216 // Copy map clauses from the original mapper. 3217 for (OMPClause *C : D->clauselists()) 3218 Clauses.push_back(C); 3219 } else { 3220 // Instantiate the mapper variable. 3221 DeclarationNameInfo DirName; 3222 SemaRef.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, /*S=*/nullptr, 3223 (*D->clauselist_begin())->getBeginLoc()); 3224 SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl( 3225 NewDMD, /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN); 3226 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3227 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(), 3228 cast<DeclRefExpr>(NewDMD->getMapperVarRef())->getDecl()); 3229 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3230 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3231 ThisContext); 3232 // Instantiate map clauses. 3233 for (OMPClause *C : D->clauselists()) { 3234 auto *OldC = cast<OMPMapClause>(C); 3235 SmallVector<Expr *, 4> NewVars; 3236 for (Expr *OE : OldC->varlists()) { 3237 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get(); 3238 if (!NE) { 3239 IsCorrect = false; 3240 break; 3241 } 3242 NewVars.push_back(NE); 3243 } 3244 if (!IsCorrect) 3245 break; 3246 NestedNameSpecifierLoc NewQualifierLoc = 3247 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(), 3248 TemplateArgs); 3249 CXXScopeSpec SS; 3250 SS.Adopt(NewQualifierLoc); 3251 DeclarationNameInfo NewNameInfo = SemaRef.SubstDeclarationNameInfo( 3252 OldC->getMapperIdInfo(), TemplateArgs); 3253 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(), 3254 OldC->getEndLoc()); 3255 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause( 3256 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS, 3257 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(), 3258 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs); 3259 Clauses.push_back(NewC); 3260 } 3261 SemaRef.EndOpenMPDSABlock(nullptr); 3262 } 3263 (void)SemaRef.ActOnOpenMPDeclareMapperDirectiveEnd(NewDMD, /*S=*/nullptr, 3264 Clauses); 3265 if (!IsCorrect) 3266 return nullptr; 3267 return NewDMD; 3268 } 3269 3270 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl( 3271 OMPCapturedExprDecl * /*D*/) { 3272 llvm_unreachable("Should not be met in templates"); 3273 } 3274 3275 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 3276 return VisitFunctionDecl(D, nullptr); 3277 } 3278 3279 Decl * 3280 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { 3281 Decl *Inst = VisitFunctionDecl(D, nullptr); 3282 if (Inst && !D->getDescribedFunctionTemplate()) 3283 Owner->addDecl(Inst); 3284 return Inst; 3285 } 3286 3287 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 3288 return VisitCXXMethodDecl(D, nullptr); 3289 } 3290 3291 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 3292 llvm_unreachable("There are only CXXRecordDecls in C++"); 3293 } 3294 3295 Decl * 3296 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 3297 ClassTemplateSpecializationDecl *D) { 3298 // As a MS extension, we permit class-scope explicit specialization 3299 // of member class templates. 3300 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 3301 assert(ClassTemplate->getDeclContext()->isRecord() && 3302 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 3303 "can only instantiate an explicit specialization " 3304 "for a member class template"); 3305 3306 // Lookup the already-instantiated declaration in the instantiation 3307 // of the class template. 3308 ClassTemplateDecl *InstClassTemplate = 3309 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl( 3310 D->getLocation(), ClassTemplate, TemplateArgs)); 3311 if (!InstClassTemplate) 3312 return nullptr; 3313 3314 // Substitute into the template arguments of the class template explicit 3315 // specialization. 3316 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). 3317 castAs<TemplateSpecializationTypeLoc>(); 3318 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), 3319 Loc.getRAngleLoc()); 3320 SmallVector<TemplateArgumentLoc, 4> ArgLocs; 3321 for (unsigned I = 0; I != Loc.getNumArgs(); ++I) 3322 ArgLocs.push_back(Loc.getArgLoc(I)); 3323 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(), 3324 InstTemplateArgs, TemplateArgs)) 3325 return nullptr; 3326 3327 // Check that the template argument list is well-formed for this 3328 // class template. 3329 SmallVector<TemplateArgument, 4> Converted; 3330 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, 3331 D->getLocation(), 3332 InstTemplateArgs, 3333 false, 3334 Converted)) 3335 return nullptr; 3336 3337 // Figure out where to insert this class template explicit specialization 3338 // in the member template's set of class template explicit specializations. 3339 void *InsertPos = nullptr; 3340 ClassTemplateSpecializationDecl *PrevDecl = 3341 InstClassTemplate->findSpecialization(Converted, InsertPos); 3342 3343 // Check whether we've already seen a conflicting instantiation of this 3344 // declaration (for instance, if there was a prior implicit instantiation). 3345 bool Ignored; 3346 if (PrevDecl && 3347 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(), 3348 D->getSpecializationKind(), 3349 PrevDecl, 3350 PrevDecl->getSpecializationKind(), 3351 PrevDecl->getPointOfInstantiation(), 3352 Ignored)) 3353 return nullptr; 3354 3355 // If PrevDecl was a definition and D is also a definition, diagnose. 3356 // This happens in cases like: 3357 // 3358 // template<typename T, typename U> 3359 // struct Outer { 3360 // template<typename X> struct Inner; 3361 // template<> struct Inner<T> {}; 3362 // template<> struct Inner<U> {}; 3363 // }; 3364 // 3365 // Outer<int, int> outer; // error: the explicit specializations of Inner 3366 // // have the same signature. 3367 if (PrevDecl && PrevDecl->getDefinition() && 3368 D->isThisDeclarationADefinition()) { 3369 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; 3370 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), 3371 diag::note_previous_definition); 3372 return nullptr; 3373 } 3374 3375 // Create the class template partial specialization declaration. 3376 ClassTemplateSpecializationDecl *InstD = 3377 ClassTemplateSpecializationDecl::Create( 3378 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(), 3379 D->getLocation(), InstClassTemplate, Converted, PrevDecl); 3380 3381 // Add this partial specialization to the set of class template partial 3382 // specializations. 3383 if (!PrevDecl) 3384 InstClassTemplate->AddSpecialization(InstD, InsertPos); 3385 3386 // Substitute the nested name specifier, if any. 3387 if (SubstQualifier(D, InstD)) 3388 return nullptr; 3389 3390 // Build the canonical type that describes the converted template 3391 // arguments of the class template explicit specialization. 3392 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3393 TemplateName(InstClassTemplate), Converted, 3394 SemaRef.Context.getRecordType(InstD)); 3395 3396 // Build the fully-sugared type for this class template 3397 // specialization as the user wrote in the specialization 3398 // itself. This means that we'll pretty-print the type retrieved 3399 // from the specialization's declaration the way that the user 3400 // actually wrote the specialization, rather than formatting the 3401 // name based on the "canonical" representation used to store the 3402 // template arguments in the specialization. 3403 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3404 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs, 3405 CanonType); 3406 3407 InstD->setAccess(D->getAccess()); 3408 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 3409 InstD->setSpecializationKind(D->getSpecializationKind()); 3410 InstD->setTypeAsWritten(WrittenTy); 3411 InstD->setExternLoc(D->getExternLoc()); 3412 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); 3413 3414 Owner->addDecl(InstD); 3415 3416 // Instantiate the members of the class-scope explicit specialization eagerly. 3417 // We don't have support for lazy instantiation of an explicit specialization 3418 // yet, and MSVC eagerly instantiates in this case. 3419 // FIXME: This is wrong in standard C++. 3420 if (D->isThisDeclarationADefinition() && 3421 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs, 3422 TSK_ImplicitInstantiation, 3423 /*Complain=*/true)) 3424 return nullptr; 3425 3426 return InstD; 3427 } 3428 3429 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3430 VarTemplateSpecializationDecl *D) { 3431 3432 TemplateArgumentListInfo VarTemplateArgsInfo; 3433 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 3434 assert(VarTemplate && 3435 "A template specialization without specialized template?"); 3436 3437 VarTemplateDecl *InstVarTemplate = 3438 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl( 3439 D->getLocation(), VarTemplate, TemplateArgs)); 3440 if (!InstVarTemplate) 3441 return nullptr; 3442 3443 // Substitute the current template arguments. 3444 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 3445 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 3446 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 3447 3448 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(), 3449 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs)) 3450 return nullptr; 3451 3452 // Check that the template argument list is well-formed for this template. 3453 SmallVector<TemplateArgument, 4> Converted; 3454 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(), 3455 VarTemplateArgsInfo, false, Converted)) 3456 return nullptr; 3457 3458 // Check whether we've already seen a declaration of this specialization. 3459 void *InsertPos = nullptr; 3460 VarTemplateSpecializationDecl *PrevDecl = 3461 InstVarTemplate->findSpecialization(Converted, InsertPos); 3462 3463 // Check whether we've already seen a conflicting instantiation of this 3464 // declaration (for instance, if there was a prior implicit instantiation). 3465 bool Ignored; 3466 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl( 3467 D->getLocation(), D->getSpecializationKind(), PrevDecl, 3468 PrevDecl->getSpecializationKind(), 3469 PrevDecl->getPointOfInstantiation(), Ignored)) 3470 return nullptr; 3471 3472 return VisitVarTemplateSpecializationDecl( 3473 InstVarTemplate, D, InsertPos, VarTemplateArgsInfo, Converted, PrevDecl); 3474 } 3475 3476 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3477 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos, 3478 const TemplateArgumentListInfo &TemplateArgsInfo, 3479 ArrayRef<TemplateArgument> Converted, 3480 VarTemplateSpecializationDecl *PrevDecl) { 3481 3482 // Do substitution on the type of the declaration 3483 TypeSourceInfo *DI = 3484 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 3485 D->getTypeSpecStartLoc(), D->getDeclName()); 3486 if (!DI) 3487 return nullptr; 3488 3489 if (DI->getType()->isFunctionType()) { 3490 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 3491 << D->isStaticDataMember() << DI->getType(); 3492 return nullptr; 3493 } 3494 3495 // Build the instantiated declaration 3496 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 3497 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 3498 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted); 3499 Var->setTemplateArgsInfo(TemplateArgsInfo); 3500 if (InsertPos) 3501 VarTemplate->AddSpecialization(Var, InsertPos); 3502 3503 // Substitute the nested name specifier, if any. 3504 if (SubstQualifier(D, Var)) 3505 return nullptr; 3506 3507 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 3508 StartingScope, false, PrevDecl); 3509 3510 return Var; 3511 } 3512 3513 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 3514 llvm_unreachable("@defs is not supported in Objective-C++"); 3515 } 3516 3517 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 3518 // FIXME: We need to be able to instantiate FriendTemplateDecls. 3519 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 3520 DiagnosticsEngine::Error, 3521 "cannot instantiate %0 yet"); 3522 SemaRef.Diag(D->getLocation(), DiagID) 3523 << D->getDeclKindName(); 3524 3525 return nullptr; 3526 } 3527 3528 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) { 3529 llvm_unreachable("Concept definitions cannot reside inside a template"); 3530 } 3531 3532 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 3533 llvm_unreachable("Unexpected decl"); 3534 } 3535 3536 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 3537 const MultiLevelTemplateArgumentList &TemplateArgs) { 3538 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3539 if (D->isInvalidDecl()) 3540 return nullptr; 3541 3542 Decl *SubstD; 3543 runWithSufficientStackSpace(D->getLocation(), [&] { 3544 SubstD = Instantiator.Visit(D); 3545 }); 3546 return SubstD; 3547 } 3548 3549 /// Instantiates a nested template parameter list in the current 3550 /// instantiation context. 3551 /// 3552 /// \param L The parameter list to instantiate 3553 /// 3554 /// \returns NULL if there was an error 3555 TemplateParameterList * 3556 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 3557 // Get errors for all the parameters before bailing out. 3558 bool Invalid = false; 3559 3560 unsigned N = L->size(); 3561 typedef SmallVector<NamedDecl *, 8> ParamVector; 3562 ParamVector Params; 3563 Params.reserve(N); 3564 for (auto &P : *L) { 3565 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P)); 3566 Params.push_back(D); 3567 Invalid = Invalid || !D || D->isInvalidDecl(); 3568 } 3569 3570 // Clean up if we had an error. 3571 if (Invalid) 3572 return nullptr; 3573 3574 // FIXME: Concepts: Substitution into requires clause should only happen when 3575 // checking satisfaction. 3576 Expr *InstRequiresClause = nullptr; 3577 if (Expr *E = L->getRequiresClause()) { 3578 ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs); 3579 if (Res.isInvalid() || !Res.isUsable()) { 3580 return nullptr; 3581 } 3582 InstRequiresClause = Res.get(); 3583 } 3584 3585 TemplateParameterList *InstL 3586 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 3587 L->getLAngleLoc(), Params, 3588 L->getRAngleLoc(), InstRequiresClause); 3589 return InstL; 3590 } 3591 3592 TemplateParameterList * 3593 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 3594 const MultiLevelTemplateArgumentList &TemplateArgs) { 3595 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3596 return Instantiator.SubstTemplateParams(Params); 3597 } 3598 3599 /// Instantiate the declaration of a class template partial 3600 /// specialization. 3601 /// 3602 /// \param ClassTemplate the (instantiated) class template that is partially 3603 // specialized by the instantiation of \p PartialSpec. 3604 /// 3605 /// \param PartialSpec the (uninstantiated) class template partial 3606 /// specialization that we are instantiating. 3607 /// 3608 /// \returns The instantiated partial specialization, if successful; otherwise, 3609 /// NULL to indicate an error. 3610 ClassTemplatePartialSpecializationDecl * 3611 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 3612 ClassTemplateDecl *ClassTemplate, 3613 ClassTemplatePartialSpecializationDecl *PartialSpec) { 3614 // Create a local instantiation scope for this class template partial 3615 // specialization, which will contain the instantiations of the template 3616 // parameters. 3617 LocalInstantiationScope Scope(SemaRef); 3618 3619 // Substitute into the template parameters of the class template partial 3620 // specialization. 3621 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 3622 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 3623 if (!InstParams) 3624 return nullptr; 3625 3626 // Substitute into the template arguments of the class template partial 3627 // specialization. 3628 const ASTTemplateArgumentListInfo *TemplArgInfo 3629 = PartialSpec->getTemplateArgsAsWritten(); 3630 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 3631 TemplArgInfo->RAngleLoc); 3632 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 3633 TemplArgInfo->NumTemplateArgs, 3634 InstTemplateArgs, TemplateArgs)) 3635 return nullptr; 3636 3637 // Check that the template argument list is well-formed for this 3638 // class template. 3639 SmallVector<TemplateArgument, 4> Converted; 3640 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 3641 PartialSpec->getLocation(), 3642 InstTemplateArgs, 3643 false, 3644 Converted)) 3645 return nullptr; 3646 3647 // Check these arguments are valid for a template partial specialization. 3648 if (SemaRef.CheckTemplatePartialSpecializationArgs( 3649 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(), 3650 Converted)) 3651 return nullptr; 3652 3653 // Figure out where to insert this class template partial specialization 3654 // in the member template's set of class template partial specializations. 3655 void *InsertPos = nullptr; 3656 ClassTemplateSpecializationDecl *PrevDecl 3657 = ClassTemplate->findPartialSpecialization(Converted, InsertPos); 3658 3659 // Build the canonical type that describes the converted template 3660 // arguments of the class template partial specialization. 3661 QualType CanonType 3662 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 3663 Converted); 3664 3665 // Build the fully-sugared type for this class template 3666 // specialization as the user wrote in the specialization 3667 // itself. This means that we'll pretty-print the type retrieved 3668 // from the specialization's declaration the way that the user 3669 // actually wrote the specialization, rather than formatting the 3670 // name based on the "canonical" representation used to store the 3671 // template arguments in the specialization. 3672 TypeSourceInfo *WrittenTy 3673 = SemaRef.Context.getTemplateSpecializationTypeInfo( 3674 TemplateName(ClassTemplate), 3675 PartialSpec->getLocation(), 3676 InstTemplateArgs, 3677 CanonType); 3678 3679 if (PrevDecl) { 3680 // We've already seen a partial specialization with the same template 3681 // parameters and template arguments. This can happen, for example, when 3682 // substituting the outer template arguments ends up causing two 3683 // class template partial specializations of a member class template 3684 // to have identical forms, e.g., 3685 // 3686 // template<typename T, typename U> 3687 // struct Outer { 3688 // template<typename X, typename Y> struct Inner; 3689 // template<typename Y> struct Inner<T, Y>; 3690 // template<typename Y> struct Inner<U, Y>; 3691 // }; 3692 // 3693 // Outer<int, int> outer; // error: the partial specializations of Inner 3694 // // have the same signature. 3695 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 3696 << WrittenTy->getType(); 3697 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 3698 << SemaRef.Context.getTypeDeclType(PrevDecl); 3699 return nullptr; 3700 } 3701 3702 3703 // Create the class template partial specialization declaration. 3704 ClassTemplatePartialSpecializationDecl *InstPartialSpec = 3705 ClassTemplatePartialSpecializationDecl::Create( 3706 SemaRef.Context, PartialSpec->getTagKind(), Owner, 3707 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams, 3708 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr); 3709 // Substitute the nested name specifier, if any. 3710 if (SubstQualifier(PartialSpec, InstPartialSpec)) 3711 return nullptr; 3712 3713 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 3714 InstPartialSpec->setTypeAsWritten(WrittenTy); 3715 3716 // Check the completed partial specialization. 3717 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 3718 3719 // Add this partial specialization to the set of class template partial 3720 // specializations. 3721 ClassTemplate->AddPartialSpecialization(InstPartialSpec, 3722 /*InsertPos=*/nullptr); 3723 return InstPartialSpec; 3724 } 3725 3726 /// Instantiate the declaration of a variable template partial 3727 /// specialization. 3728 /// 3729 /// \param VarTemplate the (instantiated) variable template that is partially 3730 /// specialized by the instantiation of \p PartialSpec. 3731 /// 3732 /// \param PartialSpec the (uninstantiated) variable template partial 3733 /// specialization that we are instantiating. 3734 /// 3735 /// \returns The instantiated partial specialization, if successful; otherwise, 3736 /// NULL to indicate an error. 3737 VarTemplatePartialSpecializationDecl * 3738 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 3739 VarTemplateDecl *VarTemplate, 3740 VarTemplatePartialSpecializationDecl *PartialSpec) { 3741 // Create a local instantiation scope for this variable template partial 3742 // specialization, which will contain the instantiations of the template 3743 // parameters. 3744 LocalInstantiationScope Scope(SemaRef); 3745 3746 // Substitute into the template parameters of the variable template partial 3747 // specialization. 3748 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 3749 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 3750 if (!InstParams) 3751 return nullptr; 3752 3753 // Substitute into the template arguments of the variable template partial 3754 // specialization. 3755 const ASTTemplateArgumentListInfo *TemplArgInfo 3756 = PartialSpec->getTemplateArgsAsWritten(); 3757 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 3758 TemplArgInfo->RAngleLoc); 3759 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(), 3760 TemplArgInfo->NumTemplateArgs, 3761 InstTemplateArgs, TemplateArgs)) 3762 return nullptr; 3763 3764 // Check that the template argument list is well-formed for this 3765 // class template. 3766 SmallVector<TemplateArgument, 4> Converted; 3767 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 3768 InstTemplateArgs, false, Converted)) 3769 return nullptr; 3770 3771 // Check these arguments are valid for a template partial specialization. 3772 if (SemaRef.CheckTemplatePartialSpecializationArgs( 3773 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(), 3774 Converted)) 3775 return nullptr; 3776 3777 // Figure out where to insert this variable template partial specialization 3778 // in the member template's set of variable template partial specializations. 3779 void *InsertPos = nullptr; 3780 VarTemplateSpecializationDecl *PrevDecl = 3781 VarTemplate->findPartialSpecialization(Converted, InsertPos); 3782 3783 // Build the canonical type that describes the converted template 3784 // arguments of the variable template partial specialization. 3785 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3786 TemplateName(VarTemplate), Converted); 3787 3788 // Build the fully-sugared type for this variable template 3789 // specialization as the user wrote in the specialization 3790 // itself. This means that we'll pretty-print the type retrieved 3791 // from the specialization's declaration the way that the user 3792 // actually wrote the specialization, rather than formatting the 3793 // name based on the "canonical" representation used to store the 3794 // template arguments in the specialization. 3795 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3796 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 3797 CanonType); 3798 3799 if (PrevDecl) { 3800 // We've already seen a partial specialization with the same template 3801 // parameters and template arguments. This can happen, for example, when 3802 // substituting the outer template arguments ends up causing two 3803 // variable template partial specializations of a member variable template 3804 // to have identical forms, e.g., 3805 // 3806 // template<typename T, typename U> 3807 // struct Outer { 3808 // template<typename X, typename Y> pair<X,Y> p; 3809 // template<typename Y> pair<T, Y> p; 3810 // template<typename Y> pair<U, Y> p; 3811 // }; 3812 // 3813 // Outer<int, int> outer; // error: the partial specializations of Inner 3814 // // have the same signature. 3815 SemaRef.Diag(PartialSpec->getLocation(), 3816 diag::err_var_partial_spec_redeclared) 3817 << WrittenTy->getType(); 3818 SemaRef.Diag(PrevDecl->getLocation(), 3819 diag::note_var_prev_partial_spec_here); 3820 return nullptr; 3821 } 3822 3823 // Do substitution on the type of the declaration 3824 TypeSourceInfo *DI = SemaRef.SubstType( 3825 PartialSpec->getTypeSourceInfo(), TemplateArgs, 3826 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 3827 if (!DI) 3828 return nullptr; 3829 3830 if (DI->getType()->isFunctionType()) { 3831 SemaRef.Diag(PartialSpec->getLocation(), 3832 diag::err_variable_instantiates_to_function) 3833 << PartialSpec->isStaticDataMember() << DI->getType(); 3834 return nullptr; 3835 } 3836 3837 // Create the variable template partial specialization declaration. 3838 VarTemplatePartialSpecializationDecl *InstPartialSpec = 3839 VarTemplatePartialSpecializationDecl::Create( 3840 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 3841 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 3842 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs); 3843 3844 // Substitute the nested name specifier, if any. 3845 if (SubstQualifier(PartialSpec, InstPartialSpec)) 3846 return nullptr; 3847 3848 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 3849 InstPartialSpec->setTypeAsWritten(WrittenTy); 3850 3851 // Check the completed partial specialization. 3852 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 3853 3854 // Add this partial specialization to the set of variable template partial 3855 // specializations. The instantiation of the initializer is not necessary. 3856 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr); 3857 3858 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 3859 LateAttrs, Owner, StartingScope); 3860 3861 return InstPartialSpec; 3862 } 3863 3864 TypeSourceInfo* 3865 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 3866 SmallVectorImpl<ParmVarDecl *> &Params) { 3867 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 3868 assert(OldTInfo && "substituting function without type source info"); 3869 assert(Params.empty() && "parameter vector is non-empty at start"); 3870 3871 CXXRecordDecl *ThisContext = nullptr; 3872 Qualifiers ThisTypeQuals; 3873 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 3874 ThisContext = cast<CXXRecordDecl>(Owner); 3875 ThisTypeQuals = Method->getMethodQualifiers(); 3876 } 3877 3878 TypeSourceInfo *NewTInfo 3879 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 3880 D->getTypeSpecStartLoc(), 3881 D->getDeclName(), 3882 ThisContext, ThisTypeQuals); 3883 if (!NewTInfo) 3884 return nullptr; 3885 3886 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 3887 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 3888 if (NewTInfo != OldTInfo) { 3889 // Get parameters from the new type info. 3890 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 3891 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 3892 unsigned NewIdx = 0; 3893 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); 3894 OldIdx != NumOldParams; ++OldIdx) { 3895 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); 3896 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 3897 3898 Optional<unsigned> NumArgumentsInExpansion; 3899 if (OldParam->isParameterPack()) 3900 NumArgumentsInExpansion = 3901 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 3902 TemplateArgs); 3903 if (!NumArgumentsInExpansion) { 3904 // Simple case: normal parameter, or a parameter pack that's 3905 // instantiated to a (still-dependent) parameter pack. 3906 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 3907 Params.push_back(NewParam); 3908 Scope->InstantiatedLocal(OldParam, NewParam); 3909 } else { 3910 // Parameter pack expansion: make the instantiation an argument pack. 3911 Scope->MakeInstantiatedLocalArgPack(OldParam); 3912 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 3913 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 3914 Params.push_back(NewParam); 3915 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 3916 } 3917 } 3918 } 3919 } else { 3920 // The function type itself was not dependent and therefore no 3921 // substitution occurred. However, we still need to instantiate 3922 // the function parameters themselves. 3923 const FunctionProtoType *OldProto = 3924 cast<FunctionProtoType>(OldProtoLoc.getType()); 3925 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; 3926 ++i) { 3927 ParmVarDecl *OldParam = OldProtoLoc.getParam(i); 3928 if (!OldParam) { 3929 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 3930 D, D->getLocation(), OldProto->getParamType(i))); 3931 continue; 3932 } 3933 3934 ParmVarDecl *Parm = 3935 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 3936 if (!Parm) 3937 return nullptr; 3938 Params.push_back(Parm); 3939 } 3940 } 3941 } else { 3942 // If the type of this function, after ignoring parentheses, is not 3943 // *directly* a function type, then we're instantiating a function that 3944 // was declared via a typedef or with attributes, e.g., 3945 // 3946 // typedef int functype(int, int); 3947 // functype func; 3948 // int __cdecl meth(int, int); 3949 // 3950 // In this case, we'll just go instantiate the ParmVarDecls that we 3951 // synthesized in the method declaration. 3952 SmallVector<QualType, 4> ParamTypes; 3953 Sema::ExtParameterInfoBuilder ExtParamInfos; 3954 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr, 3955 TemplateArgs, ParamTypes, &Params, 3956 ExtParamInfos)) 3957 return nullptr; 3958 } 3959 3960 return NewTInfo; 3961 } 3962 3963 /// Introduce the instantiated function parameters into the local 3964 /// instantiation scope, and set the parameter names to those used 3965 /// in the template. 3966 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 3967 const FunctionDecl *PatternDecl, 3968 LocalInstantiationScope &Scope, 3969 const MultiLevelTemplateArgumentList &TemplateArgs) { 3970 unsigned FParamIdx = 0; 3971 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 3972 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 3973 if (!PatternParam->isParameterPack()) { 3974 // Simple case: not a parameter pack. 3975 assert(FParamIdx < Function->getNumParams()); 3976 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 3977 FunctionParam->setDeclName(PatternParam->getDeclName()); 3978 // If the parameter's type is not dependent, update it to match the type 3979 // in the pattern. They can differ in top-level cv-qualifiers, and we want 3980 // the pattern's type here. If the type is dependent, they can't differ, 3981 // per core issue 1668. Substitute into the type from the pattern, in case 3982 // it's instantiation-dependent. 3983 // FIXME: Updating the type to work around this is at best fragile. 3984 if (!PatternDecl->getType()->isDependentType()) { 3985 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs, 3986 FunctionParam->getLocation(), 3987 FunctionParam->getDeclName()); 3988 if (T.isNull()) 3989 return true; 3990 FunctionParam->setType(T); 3991 } 3992 3993 Scope.InstantiatedLocal(PatternParam, FunctionParam); 3994 ++FParamIdx; 3995 continue; 3996 } 3997 3998 // Expand the parameter pack. 3999 Scope.MakeInstantiatedLocalArgPack(PatternParam); 4000 Optional<unsigned> NumArgumentsInExpansion 4001 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 4002 if (NumArgumentsInExpansion) { 4003 QualType PatternType = 4004 PatternParam->getType()->castAs<PackExpansionType>()->getPattern(); 4005 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 4006 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 4007 FunctionParam->setDeclName(PatternParam->getDeclName()); 4008 if (!PatternDecl->getType()->isDependentType()) { 4009 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg); 4010 QualType T = S.SubstType(PatternType, TemplateArgs, 4011 FunctionParam->getLocation(), 4012 FunctionParam->getDeclName()); 4013 if (T.isNull()) 4014 return true; 4015 FunctionParam->setType(T); 4016 } 4017 4018 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 4019 ++FParamIdx; 4020 } 4021 } 4022 } 4023 4024 return false; 4025 } 4026 4027 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 4028 FunctionDecl *Decl) { 4029 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 4030 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 4031 return; 4032 4033 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 4034 InstantiatingTemplate::ExceptionSpecification()); 4035 if (Inst.isInvalid()) { 4036 // We hit the instantiation depth limit. Clear the exception specification 4037 // so that our callers don't have to cope with EST_Uninstantiated. 4038 UpdateExceptionSpec(Decl, EST_None); 4039 return; 4040 } 4041 if (Inst.isAlreadyInstantiating()) { 4042 // This exception specification indirectly depends on itself. Reject. 4043 // FIXME: Corresponding rule in the standard? 4044 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl; 4045 UpdateExceptionSpec(Decl, EST_None); 4046 return; 4047 } 4048 4049 // Enter the scope of this instantiation. We don't use 4050 // PushDeclContext because we don't have a scope. 4051 Sema::ContextRAII savedContext(*this, Decl); 4052 LocalInstantiationScope Scope(*this); 4053 4054 MultiLevelTemplateArgumentList TemplateArgs = 4055 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true); 4056 4057 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 4058 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope, 4059 TemplateArgs)) { 4060 UpdateExceptionSpec(Decl, EST_None); 4061 return; 4062 } 4063 4064 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(), 4065 TemplateArgs); 4066 } 4067 4068 /// Initializes the common fields of an instantiation function 4069 /// declaration (New) from the corresponding fields of its template (Tmpl). 4070 /// 4071 /// \returns true if there was an error 4072 bool 4073 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 4074 FunctionDecl *Tmpl) { 4075 New->setImplicit(Tmpl->isImplicit()); 4076 4077 // Forward the mangling number from the template to the instantiated decl. 4078 SemaRef.Context.setManglingNumber(New, 4079 SemaRef.Context.getManglingNumber(Tmpl)); 4080 4081 // If we are performing substituting explicitly-specified template arguments 4082 // or deduced template arguments into a function template and we reach this 4083 // point, we are now past the point where SFINAE applies and have committed 4084 // to keeping the new function template specialization. We therefore 4085 // convert the active template instantiation for the function template 4086 // into a template instantiation for this specific function template 4087 // specialization, which is not a SFINAE context, so that we diagnose any 4088 // further errors in the declaration itself. 4089 typedef Sema::CodeSynthesisContext ActiveInstType; 4090 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back(); 4091 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 4092 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 4093 if (FunctionTemplateDecl *FunTmpl 4094 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 4095 assert(FunTmpl->getTemplatedDecl() == Tmpl && 4096 "Deduction from the wrong function template?"); 4097 (void) FunTmpl; 4098 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 4099 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 4100 ActiveInst.Entity = New; 4101 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 4102 } 4103 } 4104 4105 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 4106 assert(Proto && "Function template without prototype?"); 4107 4108 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 4109 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 4110 4111 // DR1330: In C++11, defer instantiation of a non-trivial 4112 // exception specification. 4113 // DR1484: Local classes and their members are instantiated along with the 4114 // containing function. 4115 if (SemaRef.getLangOpts().CPlusPlus11 && 4116 EPI.ExceptionSpec.Type != EST_None && 4117 EPI.ExceptionSpec.Type != EST_DynamicNone && 4118 EPI.ExceptionSpec.Type != EST_BasicNoexcept && 4119 !Tmpl->isLexicallyWithinFunctionOrMethod()) { 4120 FunctionDecl *ExceptionSpecTemplate = Tmpl; 4121 if (EPI.ExceptionSpec.Type == EST_Uninstantiated) 4122 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; 4123 ExceptionSpecificationType NewEST = EST_Uninstantiated; 4124 if (EPI.ExceptionSpec.Type == EST_Unevaluated) 4125 NewEST = EST_Unevaluated; 4126 4127 // Mark the function has having an uninstantiated exception specification. 4128 const FunctionProtoType *NewProto 4129 = New->getType()->getAs<FunctionProtoType>(); 4130 assert(NewProto && "Template instantiation without function prototype?"); 4131 EPI = NewProto->getExtProtoInfo(); 4132 EPI.ExceptionSpec.Type = NewEST; 4133 EPI.ExceptionSpec.SourceDecl = New; 4134 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; 4135 New->setType(SemaRef.Context.getFunctionType( 4136 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 4137 } else { 4138 Sema::ContextRAII SwitchContext(SemaRef, New); 4139 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs); 4140 } 4141 } 4142 4143 // Get the definition. Leaves the variable unchanged if undefined. 4144 const FunctionDecl *Definition = Tmpl; 4145 Tmpl->isDefined(Definition); 4146 4147 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 4148 LateAttrs, StartingScope); 4149 4150 return false; 4151 } 4152 4153 /// Initializes common fields of an instantiated method 4154 /// declaration (New) from the corresponding fields of its template 4155 /// (Tmpl). 4156 /// 4157 /// \returns true if there was an error 4158 bool 4159 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 4160 CXXMethodDecl *Tmpl) { 4161 if (InitFunctionInstantiation(New, Tmpl)) 4162 return true; 4163 4164 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11) 4165 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New)); 4166 4167 New->setAccess(Tmpl->getAccess()); 4168 if (Tmpl->isVirtualAsWritten()) 4169 New->setVirtualAsWritten(true); 4170 4171 // FIXME: New needs a pointer to Tmpl 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