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