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 auto *AC = cast<OMPAllocatorClause>(C); 3375 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs); 3376 if (!NewE.isUsable()) 3377 continue; 3378 OMPClause *IC = SemaRef.ActOnOpenMPAllocatorClause( 3379 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc()); 3380 Clauses.push_back(IC); 3381 } 3382 3383 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective( 3384 D->getLocation(), Vars, Clauses, Owner); 3385 if (Res.get().isNull()) 3386 return nullptr; 3387 return Res.get().getSingleDecl(); 3388 } 3389 3390 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) { 3391 llvm_unreachable( 3392 "Requires directive cannot be instantiated within a dependent context"); 3393 } 3394 3395 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl( 3396 OMPDeclareReductionDecl *D) { 3397 // Instantiate type and check if it is allowed. 3398 const bool RequiresInstantiation = 3399 D->getType()->isDependentType() || 3400 D->getType()->isInstantiationDependentType() || 3401 D->getType()->containsUnexpandedParameterPack(); 3402 QualType SubstReductionType; 3403 if (RequiresInstantiation) { 3404 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType( 3405 D->getLocation(), 3406 ParsedType::make(SemaRef.SubstType( 3407 D->getType(), TemplateArgs, D->getLocation(), DeclarationName()))); 3408 } else { 3409 SubstReductionType = D->getType(); 3410 } 3411 if (SubstReductionType.isNull()) 3412 return nullptr; 3413 Expr *Combiner = D->getCombiner(); 3414 Expr *Init = D->getInitializer(); 3415 bool IsCorrect = true; 3416 // Create instantiated copy. 3417 std::pair<QualType, SourceLocation> ReductionTypes[] = { 3418 std::make_pair(SubstReductionType, D->getLocation())}; 3419 auto *PrevDeclInScope = D->getPrevDeclInScope(); 3420 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 3421 PrevDeclInScope = cast<OMPDeclareReductionDecl>( 3422 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 3423 ->get<Decl *>()); 3424 } 3425 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart( 3426 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(), 3427 PrevDeclInScope); 3428 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl()); 3429 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD); 3430 Expr *SubstCombiner = nullptr; 3431 Expr *SubstInitializer = nullptr; 3432 // Combiners instantiation sequence. 3433 if (Combiner) { 3434 SemaRef.ActOnOpenMPDeclareReductionCombinerStart( 3435 /*S=*/nullptr, NewDRD); 3436 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3437 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(), 3438 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl()); 3439 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3440 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(), 3441 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl()); 3442 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3443 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3444 ThisContext); 3445 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get(); 3446 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner); 3447 } 3448 // Initializers instantiation sequence. 3449 if (Init) { 3450 VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart( 3451 /*S=*/nullptr, NewDRD); 3452 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3453 cast<DeclRefExpr>(D->getInitOrig())->getDecl(), 3454 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl()); 3455 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3456 cast<DeclRefExpr>(D->getInitPriv())->getDecl(), 3457 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl()); 3458 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) { 3459 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get(); 3460 } else { 3461 auto *OldPrivParm = 3462 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()); 3463 IsCorrect = IsCorrect && OldPrivParm->hasInit(); 3464 if (IsCorrect) 3465 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm, 3466 TemplateArgs); 3467 } 3468 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer, 3469 OmpPrivParm); 3470 } 3471 IsCorrect = IsCorrect && SubstCombiner && 3472 (!Init || 3473 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit && 3474 SubstInitializer) || 3475 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit && 3476 !SubstInitializer)); 3477 3478 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd( 3479 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl()); 3480 3481 return NewDRD; 3482 } 3483 3484 Decl * 3485 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) { 3486 // Instantiate type and check if it is allowed. 3487 const bool RequiresInstantiation = 3488 D->getType()->isDependentType() || 3489 D->getType()->isInstantiationDependentType() || 3490 D->getType()->containsUnexpandedParameterPack(); 3491 QualType SubstMapperTy; 3492 DeclarationName VN = D->getVarName(); 3493 if (RequiresInstantiation) { 3494 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType( 3495 D->getLocation(), 3496 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs, 3497 D->getLocation(), VN))); 3498 } else { 3499 SubstMapperTy = D->getType(); 3500 } 3501 if (SubstMapperTy.isNull()) 3502 return nullptr; 3503 // Create an instantiated copy of mapper. 3504 auto *PrevDeclInScope = D->getPrevDeclInScope(); 3505 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 3506 PrevDeclInScope = cast<OMPDeclareMapperDecl>( 3507 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 3508 ->get<Decl *>()); 3509 } 3510 bool IsCorrect = true; 3511 SmallVector<OMPClause *, 6> Clauses; 3512 // Instantiate the mapper variable. 3513 DeclarationNameInfo DirName; 3514 SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName, 3515 /*S=*/nullptr, 3516 (*D->clauselist_begin())->getBeginLoc()); 3517 ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl( 3518 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN); 3519 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3520 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(), 3521 cast<DeclRefExpr>(MapperVarRef.get())->getDecl()); 3522 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3523 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3524 ThisContext); 3525 // Instantiate map clauses. 3526 for (OMPClause *C : D->clauselists()) { 3527 auto *OldC = cast<OMPMapClause>(C); 3528 SmallVector<Expr *, 4> NewVars; 3529 for (Expr *OE : OldC->varlists()) { 3530 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get(); 3531 if (!NE) { 3532 IsCorrect = false; 3533 break; 3534 } 3535 NewVars.push_back(NE); 3536 } 3537 if (!IsCorrect) 3538 break; 3539 NestedNameSpecifierLoc NewQualifierLoc = 3540 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(), 3541 TemplateArgs); 3542 CXXScopeSpec SS; 3543 SS.Adopt(NewQualifierLoc); 3544 DeclarationNameInfo NewNameInfo = 3545 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs); 3546 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(), 3547 OldC->getEndLoc()); 3548 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause( 3549 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS, 3550 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(), 3551 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs); 3552 Clauses.push_back(NewC); 3553 } 3554 SemaRef.EndOpenMPDSABlock(nullptr); 3555 if (!IsCorrect) 3556 return nullptr; 3557 Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective( 3558 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(), 3559 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope); 3560 Decl *NewDMD = DG.get().getSingleDecl(); 3561 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD); 3562 return NewDMD; 3563 } 3564 3565 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl( 3566 OMPCapturedExprDecl * /*D*/) { 3567 llvm_unreachable("Should not be met in templates"); 3568 } 3569 3570 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 3571 return VisitFunctionDecl(D, nullptr); 3572 } 3573 3574 Decl * 3575 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { 3576 Decl *Inst = VisitFunctionDecl(D, nullptr); 3577 if (Inst && !D->getDescribedFunctionTemplate()) 3578 Owner->addDecl(Inst); 3579 return Inst; 3580 } 3581 3582 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 3583 return VisitCXXMethodDecl(D, nullptr); 3584 } 3585 3586 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 3587 llvm_unreachable("There are only CXXRecordDecls in C++"); 3588 } 3589 3590 Decl * 3591 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 3592 ClassTemplateSpecializationDecl *D) { 3593 // As a MS extension, we permit class-scope explicit specialization 3594 // of member class templates. 3595 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 3596 assert(ClassTemplate->getDeclContext()->isRecord() && 3597 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 3598 "can only instantiate an explicit specialization " 3599 "for a member class template"); 3600 3601 // Lookup the already-instantiated declaration in the instantiation 3602 // of the class template. 3603 ClassTemplateDecl *InstClassTemplate = 3604 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl( 3605 D->getLocation(), ClassTemplate, TemplateArgs)); 3606 if (!InstClassTemplate) 3607 return nullptr; 3608 3609 // Substitute into the template arguments of the class template explicit 3610 // specialization. 3611 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). 3612 castAs<TemplateSpecializationTypeLoc>(); 3613 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), 3614 Loc.getRAngleLoc()); 3615 SmallVector<TemplateArgumentLoc, 4> ArgLocs; 3616 for (unsigned I = 0; I != Loc.getNumArgs(); ++I) 3617 ArgLocs.push_back(Loc.getArgLoc(I)); 3618 if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs)) 3619 return nullptr; 3620 3621 // Check that the template argument list is well-formed for this 3622 // class template. 3623 SmallVector<TemplateArgument, 4> Converted; 3624 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, 3625 D->getLocation(), 3626 InstTemplateArgs, 3627 false, 3628 Converted, 3629 /*UpdateArgsWithConversion=*/true)) 3630 return nullptr; 3631 3632 // Figure out where to insert this class template explicit specialization 3633 // in the member template's set of class template explicit specializations. 3634 void *InsertPos = nullptr; 3635 ClassTemplateSpecializationDecl *PrevDecl = 3636 InstClassTemplate->findSpecialization(Converted, InsertPos); 3637 3638 // Check whether we've already seen a conflicting instantiation of this 3639 // declaration (for instance, if there was a prior implicit instantiation). 3640 bool Ignored; 3641 if (PrevDecl && 3642 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(), 3643 D->getSpecializationKind(), 3644 PrevDecl, 3645 PrevDecl->getSpecializationKind(), 3646 PrevDecl->getPointOfInstantiation(), 3647 Ignored)) 3648 return nullptr; 3649 3650 // If PrevDecl was a definition and D is also a definition, diagnose. 3651 // This happens in cases like: 3652 // 3653 // template<typename T, typename U> 3654 // struct Outer { 3655 // template<typename X> struct Inner; 3656 // template<> struct Inner<T> {}; 3657 // template<> struct Inner<U> {}; 3658 // }; 3659 // 3660 // Outer<int, int> outer; // error: the explicit specializations of Inner 3661 // // have the same signature. 3662 if (PrevDecl && PrevDecl->getDefinition() && 3663 D->isThisDeclarationADefinition()) { 3664 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; 3665 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), 3666 diag::note_previous_definition); 3667 return nullptr; 3668 } 3669 3670 // Create the class template partial specialization declaration. 3671 ClassTemplateSpecializationDecl *InstD = 3672 ClassTemplateSpecializationDecl::Create( 3673 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(), 3674 D->getLocation(), InstClassTemplate, Converted, PrevDecl); 3675 3676 // Add this partial specialization to the set of class template partial 3677 // specializations. 3678 if (!PrevDecl) 3679 InstClassTemplate->AddSpecialization(InstD, InsertPos); 3680 3681 // Substitute the nested name specifier, if any. 3682 if (SubstQualifier(D, InstD)) 3683 return nullptr; 3684 3685 // Build the canonical type that describes the converted template 3686 // arguments of the class template explicit specialization. 3687 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3688 TemplateName(InstClassTemplate), Converted, 3689 SemaRef.Context.getRecordType(InstD)); 3690 3691 // Build the fully-sugared type for this class template 3692 // specialization as the user wrote in the specialization 3693 // itself. This means that we'll pretty-print the type retrieved 3694 // from the specialization's declaration the way that the user 3695 // actually wrote the specialization, rather than formatting the 3696 // name based on the "canonical" representation used to store the 3697 // template arguments in the specialization. 3698 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3699 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs, 3700 CanonType); 3701 3702 InstD->setAccess(D->getAccess()); 3703 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 3704 InstD->setSpecializationKind(D->getSpecializationKind()); 3705 InstD->setTypeAsWritten(WrittenTy); 3706 InstD->setExternLoc(D->getExternLoc()); 3707 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); 3708 3709 Owner->addDecl(InstD); 3710 3711 // Instantiate the members of the class-scope explicit specialization eagerly. 3712 // We don't have support for lazy instantiation of an explicit specialization 3713 // yet, and MSVC eagerly instantiates in this case. 3714 // FIXME: This is wrong in standard C++. 3715 if (D->isThisDeclarationADefinition() && 3716 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs, 3717 TSK_ImplicitInstantiation, 3718 /*Complain=*/true)) 3719 return nullptr; 3720 3721 return InstD; 3722 } 3723 3724 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3725 VarTemplateSpecializationDecl *D) { 3726 3727 TemplateArgumentListInfo VarTemplateArgsInfo; 3728 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 3729 assert(VarTemplate && 3730 "A template specialization without specialized template?"); 3731 3732 VarTemplateDecl *InstVarTemplate = 3733 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl( 3734 D->getLocation(), VarTemplate, TemplateArgs)); 3735 if (!InstVarTemplate) 3736 return nullptr; 3737 3738 // Substitute the current template arguments. 3739 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 3740 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 3741 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 3742 3743 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo.arguments(), TemplateArgs, 3744 VarTemplateArgsInfo)) 3745 return nullptr; 3746 3747 // Check that the template argument list is well-formed for this template. 3748 SmallVector<TemplateArgument, 4> Converted; 3749 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(), 3750 VarTemplateArgsInfo, false, Converted, 3751 /*UpdateArgsWithConversion=*/true)) 3752 return nullptr; 3753 3754 // Check whether we've already seen a declaration of this specialization. 3755 void *InsertPos = nullptr; 3756 VarTemplateSpecializationDecl *PrevDecl = 3757 InstVarTemplate->findSpecialization(Converted, InsertPos); 3758 3759 // Check whether we've already seen a conflicting instantiation of this 3760 // declaration (for instance, if there was a prior implicit instantiation). 3761 bool Ignored; 3762 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl( 3763 D->getLocation(), D->getSpecializationKind(), PrevDecl, 3764 PrevDecl->getSpecializationKind(), 3765 PrevDecl->getPointOfInstantiation(), Ignored)) 3766 return nullptr; 3767 3768 return VisitVarTemplateSpecializationDecl( 3769 InstVarTemplate, D, VarTemplateArgsInfo, Converted, PrevDecl); 3770 } 3771 3772 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3773 VarTemplateDecl *VarTemplate, VarDecl *D, 3774 const TemplateArgumentListInfo &TemplateArgsInfo, 3775 ArrayRef<TemplateArgument> Converted, 3776 VarTemplateSpecializationDecl *PrevDecl) { 3777 3778 // Do substitution on the type of the declaration 3779 TypeSourceInfo *DI = 3780 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 3781 D->getTypeSpecStartLoc(), D->getDeclName()); 3782 if (!DI) 3783 return nullptr; 3784 3785 if (DI->getType()->isFunctionType()) { 3786 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 3787 << D->isStaticDataMember() << DI->getType(); 3788 return nullptr; 3789 } 3790 3791 // Build the instantiated declaration 3792 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 3793 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 3794 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted); 3795 Var->setTemplateArgsInfo(TemplateArgsInfo); 3796 if (!PrevDecl) { 3797 void *InsertPos = nullptr; 3798 VarTemplate->findSpecialization(Converted, InsertPos); 3799 VarTemplate->AddSpecialization(Var, InsertPos); 3800 } 3801 3802 if (SemaRef.getLangOpts().OpenCL) 3803 SemaRef.deduceOpenCLAddressSpace(Var); 3804 3805 // Substitute the nested name specifier, if any. 3806 if (SubstQualifier(D, Var)) 3807 return nullptr; 3808 3809 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 3810 StartingScope, false, PrevDecl); 3811 3812 return Var; 3813 } 3814 3815 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 3816 llvm_unreachable("@defs is not supported in Objective-C++"); 3817 } 3818 3819 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 3820 // FIXME: We need to be able to instantiate FriendTemplateDecls. 3821 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 3822 DiagnosticsEngine::Error, 3823 "cannot instantiate %0 yet"); 3824 SemaRef.Diag(D->getLocation(), DiagID) 3825 << D->getDeclKindName(); 3826 3827 return nullptr; 3828 } 3829 3830 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) { 3831 llvm_unreachable("Concept definitions cannot reside inside a template"); 3832 } 3833 3834 Decl * 3835 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) { 3836 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(), 3837 D->getBeginLoc()); 3838 } 3839 3840 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 3841 llvm_unreachable("Unexpected decl"); 3842 } 3843 3844 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 3845 const MultiLevelTemplateArgumentList &TemplateArgs) { 3846 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3847 if (D->isInvalidDecl()) 3848 return nullptr; 3849 3850 Decl *SubstD; 3851 runWithSufficientStackSpace(D->getLocation(), [&] { 3852 SubstD = Instantiator.Visit(D); 3853 }); 3854 return SubstD; 3855 } 3856 3857 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK, 3858 FunctionDecl *Orig, QualType &T, 3859 TypeSourceInfo *&TInfo, 3860 DeclarationNameInfo &NameInfo) { 3861 assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual); 3862 3863 // C++2a [class.compare.default]p3: 3864 // the return type is replaced with bool 3865 auto *FPT = T->castAs<FunctionProtoType>(); 3866 T = SemaRef.Context.getFunctionType( 3867 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo()); 3868 3869 // Update the return type in the source info too. The most straightforward 3870 // way is to create new TypeSourceInfo for the new type. Use the location of 3871 // the '= default' as the location of the new type. 3872 // 3873 // FIXME: Set the correct return type when we initially transform the type, 3874 // rather than delaying it to now. 3875 TypeSourceInfo *NewTInfo = 3876 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc()); 3877 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>(); 3878 assert(OldLoc && "type of function is not a function type?"); 3879 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>(); 3880 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I) 3881 NewLoc.setParam(I, OldLoc.getParam(I)); 3882 TInfo = NewTInfo; 3883 3884 // and the declarator-id is replaced with operator== 3885 NameInfo.setName( 3886 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual)); 3887 } 3888 3889 FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, 3890 FunctionDecl *Spaceship) { 3891 if (Spaceship->isInvalidDecl()) 3892 return nullptr; 3893 3894 // C++2a [class.compare.default]p3: 3895 // an == operator function is declared implicitly [...] with the same 3896 // access and function-definition and in the same class scope as the 3897 // three-way comparison operator function 3898 MultiLevelTemplateArgumentList NoTemplateArgs; 3899 NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite); 3900 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth()); 3901 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs); 3902 Decl *R; 3903 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) { 3904 R = Instantiator.VisitCXXMethodDecl( 3905 MD, nullptr, None, 3906 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual); 3907 } else { 3908 assert(Spaceship->getFriendObjectKind() && 3909 "defaulted spaceship is neither a member nor a friend"); 3910 3911 R = Instantiator.VisitFunctionDecl( 3912 Spaceship, nullptr, 3913 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual); 3914 if (!R) 3915 return nullptr; 3916 3917 FriendDecl *FD = 3918 FriendDecl::Create(Context, RD, Spaceship->getLocation(), 3919 cast<NamedDecl>(R), Spaceship->getBeginLoc()); 3920 FD->setAccess(AS_public); 3921 RD->addDecl(FD); 3922 } 3923 return cast_or_null<FunctionDecl>(R); 3924 } 3925 3926 /// Instantiates a nested template parameter list in the current 3927 /// instantiation context. 3928 /// 3929 /// \param L The parameter list to instantiate 3930 /// 3931 /// \returns NULL if there was an error 3932 TemplateParameterList * 3933 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 3934 // Get errors for all the parameters before bailing out. 3935 bool Invalid = false; 3936 3937 unsigned N = L->size(); 3938 typedef SmallVector<NamedDecl *, 8> ParamVector; 3939 ParamVector Params; 3940 Params.reserve(N); 3941 for (auto &P : *L) { 3942 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P)); 3943 Params.push_back(D); 3944 Invalid = Invalid || !D || D->isInvalidDecl(); 3945 } 3946 3947 // Clean up if we had an error. 3948 if (Invalid) 3949 return nullptr; 3950 3951 // FIXME: Concepts: Substitution into requires clause should only happen when 3952 // checking satisfaction. 3953 Expr *InstRequiresClause = nullptr; 3954 if (Expr *E = L->getRequiresClause()) { 3955 EnterExpressionEvaluationContext ConstantEvaluated( 3956 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated); 3957 ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs); 3958 if (Res.isInvalid() || !Res.isUsable()) { 3959 return nullptr; 3960 } 3961 InstRequiresClause = Res.get(); 3962 } 3963 3964 TemplateParameterList *InstL 3965 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 3966 L->getLAngleLoc(), Params, 3967 L->getRAngleLoc(), InstRequiresClause); 3968 return InstL; 3969 } 3970 3971 TemplateParameterList * 3972 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 3973 const MultiLevelTemplateArgumentList &TemplateArgs) { 3974 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3975 return Instantiator.SubstTemplateParams(Params); 3976 } 3977 3978 /// Instantiate the declaration of a class template partial 3979 /// specialization. 3980 /// 3981 /// \param ClassTemplate the (instantiated) class template that is partially 3982 // specialized by the instantiation of \p PartialSpec. 3983 /// 3984 /// \param PartialSpec the (uninstantiated) class template partial 3985 /// specialization that we are instantiating. 3986 /// 3987 /// \returns The instantiated partial specialization, if successful; otherwise, 3988 /// NULL to indicate an error. 3989 ClassTemplatePartialSpecializationDecl * 3990 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 3991 ClassTemplateDecl *ClassTemplate, 3992 ClassTemplatePartialSpecializationDecl *PartialSpec) { 3993 // Create a local instantiation scope for this class template partial 3994 // specialization, which will contain the instantiations of the template 3995 // parameters. 3996 LocalInstantiationScope Scope(SemaRef); 3997 3998 // Substitute into the template parameters of the class template partial 3999 // specialization. 4000 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 4001 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 4002 if (!InstParams) 4003 return nullptr; 4004 4005 // Substitute into the template arguments of the class template partial 4006 // specialization. 4007 const ASTTemplateArgumentListInfo *TemplArgInfo 4008 = PartialSpec->getTemplateArgsAsWritten(); 4009 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 4010 TemplArgInfo->RAngleLoc); 4011 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs, 4012 InstTemplateArgs)) 4013 return nullptr; 4014 4015 // Check that the template argument list is well-formed for this 4016 // class template. 4017 SmallVector<TemplateArgument, 4> Converted; 4018 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 4019 PartialSpec->getLocation(), 4020 InstTemplateArgs, 4021 false, 4022 Converted)) 4023 return nullptr; 4024 4025 // Check these arguments are valid for a template partial specialization. 4026 if (SemaRef.CheckTemplatePartialSpecializationArgs( 4027 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(), 4028 Converted)) 4029 return nullptr; 4030 4031 // Figure out where to insert this class template partial specialization 4032 // in the member template's set of class template partial specializations. 4033 void *InsertPos = nullptr; 4034 ClassTemplateSpecializationDecl *PrevDecl 4035 = ClassTemplate->findPartialSpecialization(Converted, InstParams, 4036 InsertPos); 4037 4038 // Build the canonical type that describes the converted template 4039 // arguments of the class template partial specialization. 4040 QualType CanonType 4041 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 4042 Converted); 4043 4044 // Build the fully-sugared type for this class template 4045 // specialization as the user wrote in the specialization 4046 // itself. This means that we'll pretty-print the type retrieved 4047 // from the specialization's declaration the way that the user 4048 // actually wrote the specialization, rather than formatting the 4049 // name based on the "canonical" representation used to store the 4050 // template arguments in the specialization. 4051 TypeSourceInfo *WrittenTy 4052 = SemaRef.Context.getTemplateSpecializationTypeInfo( 4053 TemplateName(ClassTemplate), 4054 PartialSpec->getLocation(), 4055 InstTemplateArgs, 4056 CanonType); 4057 4058 if (PrevDecl) { 4059 // We've already seen a partial specialization with the same template 4060 // parameters and template arguments. This can happen, for example, when 4061 // substituting the outer template arguments ends up causing two 4062 // class template partial specializations of a member class template 4063 // to have identical forms, e.g., 4064 // 4065 // template<typename T, typename U> 4066 // struct Outer { 4067 // template<typename X, typename Y> struct Inner; 4068 // template<typename Y> struct Inner<T, Y>; 4069 // template<typename Y> struct Inner<U, Y>; 4070 // }; 4071 // 4072 // Outer<int, int> outer; // error: the partial specializations of Inner 4073 // // have the same signature. 4074 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 4075 << WrittenTy->getType(); 4076 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 4077 << SemaRef.Context.getTypeDeclType(PrevDecl); 4078 return nullptr; 4079 } 4080 4081 4082 // Create the class template partial specialization declaration. 4083 ClassTemplatePartialSpecializationDecl *InstPartialSpec = 4084 ClassTemplatePartialSpecializationDecl::Create( 4085 SemaRef.Context, PartialSpec->getTagKind(), Owner, 4086 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams, 4087 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr); 4088 // Substitute the nested name specifier, if any. 4089 if (SubstQualifier(PartialSpec, InstPartialSpec)) 4090 return nullptr; 4091 4092 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 4093 InstPartialSpec->setTypeAsWritten(WrittenTy); 4094 4095 // Check the completed partial specialization. 4096 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 4097 4098 // Add this partial specialization to the set of class template partial 4099 // specializations. 4100 ClassTemplate->AddPartialSpecialization(InstPartialSpec, 4101 /*InsertPos=*/nullptr); 4102 return InstPartialSpec; 4103 } 4104 4105 /// Instantiate the declaration of a variable template partial 4106 /// specialization. 4107 /// 4108 /// \param VarTemplate the (instantiated) variable template that is partially 4109 /// specialized by the instantiation of \p PartialSpec. 4110 /// 4111 /// \param PartialSpec the (uninstantiated) variable template partial 4112 /// specialization that we are instantiating. 4113 /// 4114 /// \returns The instantiated partial specialization, if successful; otherwise, 4115 /// NULL to indicate an error. 4116 VarTemplatePartialSpecializationDecl * 4117 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 4118 VarTemplateDecl *VarTemplate, 4119 VarTemplatePartialSpecializationDecl *PartialSpec) { 4120 // Create a local instantiation scope for this variable template partial 4121 // specialization, which will contain the instantiations of the template 4122 // parameters. 4123 LocalInstantiationScope Scope(SemaRef); 4124 4125 // Substitute into the template parameters of the variable template partial 4126 // specialization. 4127 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 4128 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 4129 if (!InstParams) 4130 return nullptr; 4131 4132 // Substitute into the template arguments of the variable template partial 4133 // specialization. 4134 const ASTTemplateArgumentListInfo *TemplArgInfo 4135 = PartialSpec->getTemplateArgsAsWritten(); 4136 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 4137 TemplArgInfo->RAngleLoc); 4138 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs, 4139 InstTemplateArgs)) 4140 return nullptr; 4141 4142 // Check that the template argument list is well-formed for this 4143 // class template. 4144 SmallVector<TemplateArgument, 4> Converted; 4145 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 4146 InstTemplateArgs, false, Converted)) 4147 return nullptr; 4148 4149 // Check these arguments are valid for a template partial specialization. 4150 if (SemaRef.CheckTemplatePartialSpecializationArgs( 4151 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(), 4152 Converted)) 4153 return nullptr; 4154 4155 // Figure out where to insert this variable template partial specialization 4156 // in the member template's set of variable template partial specializations. 4157 void *InsertPos = nullptr; 4158 VarTemplateSpecializationDecl *PrevDecl = 4159 VarTemplate->findPartialSpecialization(Converted, InstParams, InsertPos); 4160 4161 // Build the canonical type that describes the converted template 4162 // arguments of the variable template partial specialization. 4163 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 4164 TemplateName(VarTemplate), Converted); 4165 4166 // Build the fully-sugared type for this variable template 4167 // specialization as the user wrote in the specialization 4168 // itself. This means that we'll pretty-print the type retrieved 4169 // from the specialization's declaration the way that the user 4170 // actually wrote the specialization, rather than formatting the 4171 // name based on the "canonical" representation used to store the 4172 // template arguments in the specialization. 4173 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 4174 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 4175 CanonType); 4176 4177 if (PrevDecl) { 4178 // We've already seen a partial specialization with the same template 4179 // parameters and template arguments. This can happen, for example, when 4180 // substituting the outer template arguments ends up causing two 4181 // variable template partial specializations of a member variable template 4182 // to have identical forms, e.g., 4183 // 4184 // template<typename T, typename U> 4185 // struct Outer { 4186 // template<typename X, typename Y> pair<X,Y> p; 4187 // template<typename Y> pair<T, Y> p; 4188 // template<typename Y> pair<U, Y> p; 4189 // }; 4190 // 4191 // Outer<int, int> outer; // error: the partial specializations of Inner 4192 // // have the same signature. 4193 SemaRef.Diag(PartialSpec->getLocation(), 4194 diag::err_var_partial_spec_redeclared) 4195 << WrittenTy->getType(); 4196 SemaRef.Diag(PrevDecl->getLocation(), 4197 diag::note_var_prev_partial_spec_here); 4198 return nullptr; 4199 } 4200 4201 // Do substitution on the type of the declaration 4202 TypeSourceInfo *DI = SemaRef.SubstType( 4203 PartialSpec->getTypeSourceInfo(), TemplateArgs, 4204 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 4205 if (!DI) 4206 return nullptr; 4207 4208 if (DI->getType()->isFunctionType()) { 4209 SemaRef.Diag(PartialSpec->getLocation(), 4210 diag::err_variable_instantiates_to_function) 4211 << PartialSpec->isStaticDataMember() << DI->getType(); 4212 return nullptr; 4213 } 4214 4215 // Create the variable template partial specialization declaration. 4216 VarTemplatePartialSpecializationDecl *InstPartialSpec = 4217 VarTemplatePartialSpecializationDecl::Create( 4218 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 4219 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 4220 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs); 4221 4222 // Substitute the nested name specifier, if any. 4223 if (SubstQualifier(PartialSpec, InstPartialSpec)) 4224 return nullptr; 4225 4226 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 4227 InstPartialSpec->setTypeAsWritten(WrittenTy); 4228 4229 // Check the completed partial specialization. 4230 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 4231 4232 // Add this partial specialization to the set of variable template partial 4233 // specializations. The instantiation of the initializer is not necessary. 4234 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr); 4235 4236 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 4237 LateAttrs, Owner, StartingScope); 4238 4239 return InstPartialSpec; 4240 } 4241 4242 TypeSourceInfo* 4243 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 4244 SmallVectorImpl<ParmVarDecl *> &Params) { 4245 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 4246 assert(OldTInfo && "substituting function without type source info"); 4247 assert(Params.empty() && "parameter vector is non-empty at start"); 4248 4249 CXXRecordDecl *ThisContext = nullptr; 4250 Qualifiers ThisTypeQuals; 4251 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 4252 ThisContext = cast<CXXRecordDecl>(Owner); 4253 ThisTypeQuals = Method->getMethodQualifiers(); 4254 } 4255 4256 TypeSourceInfo *NewTInfo 4257 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 4258 D->getTypeSpecStartLoc(), 4259 D->getDeclName(), 4260 ThisContext, ThisTypeQuals); 4261 if (!NewTInfo) 4262 return nullptr; 4263 4264 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 4265 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 4266 if (NewTInfo != OldTInfo) { 4267 // Get parameters from the new type info. 4268 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 4269 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 4270 unsigned NewIdx = 0; 4271 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); 4272 OldIdx != NumOldParams; ++OldIdx) { 4273 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); 4274 if (!OldParam) 4275 return nullptr; 4276 4277 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 4278 4279 Optional<unsigned> NumArgumentsInExpansion; 4280 if (OldParam->isParameterPack()) 4281 NumArgumentsInExpansion = 4282 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 4283 TemplateArgs); 4284 if (!NumArgumentsInExpansion) { 4285 // Simple case: normal parameter, or a parameter pack that's 4286 // instantiated to a (still-dependent) parameter pack. 4287 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 4288 Params.push_back(NewParam); 4289 Scope->InstantiatedLocal(OldParam, NewParam); 4290 } else { 4291 // Parameter pack expansion: make the instantiation an argument pack. 4292 Scope->MakeInstantiatedLocalArgPack(OldParam); 4293 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 4294 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 4295 Params.push_back(NewParam); 4296 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 4297 } 4298 } 4299 } 4300 } else { 4301 // The function type itself was not dependent and therefore no 4302 // substitution occurred. However, we still need to instantiate 4303 // the function parameters themselves. 4304 const FunctionProtoType *OldProto = 4305 cast<FunctionProtoType>(OldProtoLoc.getType()); 4306 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; 4307 ++i) { 4308 ParmVarDecl *OldParam = OldProtoLoc.getParam(i); 4309 if (!OldParam) { 4310 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 4311 D, D->getLocation(), OldProto->getParamType(i))); 4312 continue; 4313 } 4314 4315 ParmVarDecl *Parm = 4316 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 4317 if (!Parm) 4318 return nullptr; 4319 Params.push_back(Parm); 4320 } 4321 } 4322 } else { 4323 // If the type of this function, after ignoring parentheses, is not 4324 // *directly* a function type, then we're instantiating a function that 4325 // was declared via a typedef or with attributes, e.g., 4326 // 4327 // typedef int functype(int, int); 4328 // functype func; 4329 // int __cdecl meth(int, int); 4330 // 4331 // In this case, we'll just go instantiate the ParmVarDecls that we 4332 // synthesized in the method declaration. 4333 SmallVector<QualType, 4> ParamTypes; 4334 Sema::ExtParameterInfoBuilder ExtParamInfos; 4335 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr, 4336 TemplateArgs, ParamTypes, &Params, 4337 ExtParamInfos)) 4338 return nullptr; 4339 } 4340 4341 return NewTInfo; 4342 } 4343 4344 /// Introduce the instantiated function parameters into the local 4345 /// instantiation scope, and set the parameter names to those used 4346 /// in the template. 4347 static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function, 4348 const FunctionDecl *PatternDecl, 4349 LocalInstantiationScope &Scope, 4350 const MultiLevelTemplateArgumentList &TemplateArgs) { 4351 unsigned FParamIdx = 0; 4352 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 4353 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 4354 if (!PatternParam->isParameterPack()) { 4355 // Simple case: not a parameter pack. 4356 assert(FParamIdx < Function->getNumParams()); 4357 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 4358 FunctionParam->setDeclName(PatternParam->getDeclName()); 4359 // If the parameter's type is not dependent, update it to match the type 4360 // in the pattern. They can differ in top-level cv-qualifiers, and we want 4361 // the pattern's type here. If the type is dependent, they can't differ, 4362 // per core issue 1668. Substitute into the type from the pattern, in case 4363 // it's instantiation-dependent. 4364 // FIXME: Updating the type to work around this is at best fragile. 4365 if (!PatternDecl->getType()->isDependentType()) { 4366 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs, 4367 FunctionParam->getLocation(), 4368 FunctionParam->getDeclName()); 4369 if (T.isNull()) 4370 return true; 4371 FunctionParam->setType(T); 4372 } 4373 4374 Scope.InstantiatedLocal(PatternParam, FunctionParam); 4375 ++FParamIdx; 4376 continue; 4377 } 4378 4379 // Expand the parameter pack. 4380 Scope.MakeInstantiatedLocalArgPack(PatternParam); 4381 Optional<unsigned> NumArgumentsInExpansion 4382 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 4383 if (NumArgumentsInExpansion) { 4384 QualType PatternType = 4385 PatternParam->getType()->castAs<PackExpansionType>()->getPattern(); 4386 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 4387 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 4388 FunctionParam->setDeclName(PatternParam->getDeclName()); 4389 if (!PatternDecl->getType()->isDependentType()) { 4390 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg); 4391 QualType T = S.SubstType(PatternType, TemplateArgs, 4392 FunctionParam->getLocation(), 4393 FunctionParam->getDeclName()); 4394 if (T.isNull()) 4395 return true; 4396 FunctionParam->setType(T); 4397 } 4398 4399 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 4400 ++FParamIdx; 4401 } 4402 } 4403 } 4404 4405 return false; 4406 } 4407 4408 bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, 4409 ParmVarDecl *Param) { 4410 assert(Param->hasUninstantiatedDefaultArg()); 4411 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4412 4413 EnterExpressionEvaluationContext EvalContext( 4414 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4415 4416 // Instantiate the expression. 4417 // 4418 // FIXME: Pass in a correct Pattern argument, otherwise 4419 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4420 // 4421 // template<typename T> 4422 // struct A { 4423 // static int FooImpl(); 4424 // 4425 // template<typename Tp> 4426 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4427 // // template argument list [[T], [Tp]], should be [[Tp]]. 4428 // friend A<Tp> Foo(int a); 4429 // }; 4430 // 4431 // template<typename T> 4432 // A<T> Foo(int a = A<T>::FooImpl()); 4433 MultiLevelTemplateArgumentList TemplateArgs 4434 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4435 4436 InstantiatingTemplate Inst(*this, CallLoc, Param, 4437 TemplateArgs.getInnermost()); 4438 if (Inst.isInvalid()) 4439 return true; 4440 if (Inst.isAlreadyInstantiating()) { 4441 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4442 Param->setInvalidDecl(); 4443 return true; 4444 } 4445 4446 ExprResult Result; 4447 { 4448 // C++ [dcl.fct.default]p5: 4449 // The names in the [default argument] expression are bound, and 4450 // the semantic constraints are checked, at the point where the 4451 // default argument expression appears. 4452 ContextRAII SavedContext(*this, FD); 4453 LocalInstantiationScope Local(*this); 4454 4455 FunctionDecl *Pattern = FD->getTemplateInstantiationPattern( 4456 /*ForDefinition*/ false); 4457 if (addInstantiatedParametersToScope(*this, FD, Pattern, Local, 4458 TemplateArgs)) 4459 return true; 4460 4461 runWithSufficientStackSpace(CallLoc, [&] { 4462 Result = SubstInitializer(UninstExpr, TemplateArgs, 4463 /*DirectInit*/false); 4464 }); 4465 } 4466 if (Result.isInvalid()) 4467 return true; 4468 4469 // Check the expression as an initializer for the parameter. 4470 InitializedEntity Entity 4471 = InitializedEntity::InitializeParameter(Context, Param); 4472 InitializationKind Kind = InitializationKind::CreateCopy( 4473 Param->getLocation(), 4474 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4475 Expr *ResultE = Result.getAs<Expr>(); 4476 4477 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4478 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4479 if (Result.isInvalid()) 4480 return true; 4481 4482 Result = 4483 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4484 /*DiscardedValue*/ false); 4485 if (Result.isInvalid()) 4486 return true; 4487 4488 // Remember the instantiated default argument. 4489 Param->setDefaultArg(Result.getAs<Expr>()); 4490 if (ASTMutationListener *L = getASTMutationListener()) 4491 L->DefaultArgumentInstantiated(Param); 4492 4493 return false; 4494 } 4495 4496 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 4497 FunctionDecl *Decl) { 4498 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 4499 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 4500 return; 4501 4502 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 4503 InstantiatingTemplate::ExceptionSpecification()); 4504 if (Inst.isInvalid()) { 4505 // We hit the instantiation depth limit. Clear the exception specification 4506 // so that our callers don't have to cope with EST_Uninstantiated. 4507 UpdateExceptionSpec(Decl, EST_None); 4508 return; 4509 } 4510 if (Inst.isAlreadyInstantiating()) { 4511 // This exception specification indirectly depends on itself. Reject. 4512 // FIXME: Corresponding rule in the standard? 4513 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl; 4514 UpdateExceptionSpec(Decl, EST_None); 4515 return; 4516 } 4517 4518 // Enter the scope of this instantiation. We don't use 4519 // PushDeclContext because we don't have a scope. 4520 Sema::ContextRAII savedContext(*this, Decl); 4521 LocalInstantiationScope Scope(*this); 4522 4523 MultiLevelTemplateArgumentList TemplateArgs = 4524 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true); 4525 4526 // FIXME: We can't use getTemplateInstantiationPattern(false) in general 4527 // here, because for a non-defining friend declaration in a class template, 4528 // we don't store enough information to map back to the friend declaration in 4529 // the template. 4530 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 4531 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope, 4532 TemplateArgs)) { 4533 UpdateExceptionSpec(Decl, EST_None); 4534 return; 4535 } 4536 4537 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(), 4538 TemplateArgs); 4539 } 4540 4541 bool Sema::CheckInstantiatedFunctionTemplateConstraints( 4542 SourceLocation PointOfInstantiation, FunctionDecl *Decl, 4543 ArrayRef<TemplateArgument> TemplateArgs, 4544 ConstraintSatisfaction &Satisfaction) { 4545 // In most cases we're not going to have constraints, so check for that first. 4546 FunctionTemplateDecl *Template = Decl->getPrimaryTemplate(); 4547 // Note - code synthesis context for the constraints check is created 4548 // inside CheckConstraintsSatisfaction. 4549 SmallVector<const Expr *, 3> TemplateAC; 4550 Template->getAssociatedConstraints(TemplateAC); 4551 if (TemplateAC.empty()) { 4552 Satisfaction.IsSatisfied = true; 4553 return false; 4554 } 4555 4556 // Enter the scope of this instantiation. We don't use 4557 // PushDeclContext because we don't have a scope. 4558 Sema::ContextRAII savedContext(*this, Decl); 4559 LocalInstantiationScope Scope(*this); 4560 4561 // If this is not an explicit specialization - we need to get the instantiated 4562 // version of the template arguments and add them to scope for the 4563 // substitution. 4564 if (Decl->isTemplateInstantiation()) { 4565 InstantiatingTemplate Inst(*this, Decl->getPointOfInstantiation(), 4566 InstantiatingTemplate::ConstraintsCheck{}, Decl->getPrimaryTemplate(), 4567 TemplateArgs, SourceRange()); 4568 if (Inst.isInvalid()) 4569 return true; 4570 MultiLevelTemplateArgumentList MLTAL( 4571 *Decl->getTemplateSpecializationArgs()); 4572 if (addInstantiatedParametersToScope( 4573 *this, Decl, Decl->getPrimaryTemplate()->getTemplatedDecl(), 4574 Scope, MLTAL)) 4575 return true; 4576 } 4577 Qualifiers ThisQuals; 4578 CXXRecordDecl *Record = nullptr; 4579 if (auto *Method = dyn_cast<CXXMethodDecl>(Decl)) { 4580 ThisQuals = Method->getMethodQualifiers(); 4581 Record = Method->getParent(); 4582 } 4583 CXXThisScopeRAII ThisScope(*this, Record, ThisQuals, Record != nullptr); 4584 return CheckConstraintSatisfaction(Template, TemplateAC, TemplateArgs, 4585 PointOfInstantiation, Satisfaction); 4586 } 4587 4588 /// Initializes the common fields of an instantiation function 4589 /// declaration (New) from the corresponding fields of its template (Tmpl). 4590 /// 4591 /// \returns true if there was an error 4592 bool 4593 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 4594 FunctionDecl *Tmpl) { 4595 New->setImplicit(Tmpl->isImplicit()); 4596 4597 // Forward the mangling number from the template to the instantiated decl. 4598 SemaRef.Context.setManglingNumber(New, 4599 SemaRef.Context.getManglingNumber(Tmpl)); 4600 4601 // If we are performing substituting explicitly-specified template arguments 4602 // or deduced template arguments into a function template and we reach this 4603 // point, we are now past the point where SFINAE applies and have committed 4604 // to keeping the new function template specialization. We therefore 4605 // convert the active template instantiation for the function template 4606 // into a template instantiation for this specific function template 4607 // specialization, which is not a SFINAE context, so that we diagnose any 4608 // further errors in the declaration itself. 4609 // 4610 // FIXME: This is a hack. 4611 typedef Sema::CodeSynthesisContext ActiveInstType; 4612 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back(); 4613 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 4614 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 4615 if (FunctionTemplateDecl *FunTmpl 4616 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 4617 assert(FunTmpl->getTemplatedDecl() == Tmpl && 4618 "Deduction from the wrong function template?"); 4619 (void) FunTmpl; 4620 SemaRef.InstantiatingSpecializations.erase( 4621 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind}); 4622 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 4623 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 4624 ActiveInst.Entity = New; 4625 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 4626 } 4627 } 4628 4629 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 4630 assert(Proto && "Function template without prototype?"); 4631 4632 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 4633 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 4634 4635 // DR1330: In C++11, defer instantiation of a non-trivial 4636 // exception specification. 4637 // DR1484: Local classes and their members are instantiated along with the 4638 // containing function. 4639 if (SemaRef.getLangOpts().CPlusPlus11 && 4640 EPI.ExceptionSpec.Type != EST_None && 4641 EPI.ExceptionSpec.Type != EST_DynamicNone && 4642 EPI.ExceptionSpec.Type != EST_BasicNoexcept && 4643 !Tmpl->isInLocalScopeForInstantiation()) { 4644 FunctionDecl *ExceptionSpecTemplate = Tmpl; 4645 if (EPI.ExceptionSpec.Type == EST_Uninstantiated) 4646 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; 4647 ExceptionSpecificationType NewEST = EST_Uninstantiated; 4648 if (EPI.ExceptionSpec.Type == EST_Unevaluated) 4649 NewEST = EST_Unevaluated; 4650 4651 // Mark the function has having an uninstantiated exception specification. 4652 const FunctionProtoType *NewProto 4653 = New->getType()->getAs<FunctionProtoType>(); 4654 assert(NewProto && "Template instantiation without function prototype?"); 4655 EPI = NewProto->getExtProtoInfo(); 4656 EPI.ExceptionSpec.Type = NewEST; 4657 EPI.ExceptionSpec.SourceDecl = New; 4658 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; 4659 New->setType(SemaRef.Context.getFunctionType( 4660 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 4661 } else { 4662 Sema::ContextRAII SwitchContext(SemaRef, New); 4663 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs); 4664 } 4665 } 4666 4667 // Get the definition. Leaves the variable unchanged if undefined. 4668 const FunctionDecl *Definition = Tmpl; 4669 Tmpl->isDefined(Definition); 4670 4671 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 4672 LateAttrs, StartingScope); 4673 4674 return false; 4675 } 4676 4677 /// Initializes common fields of an instantiated method 4678 /// declaration (New) from the corresponding fields of its template 4679 /// (Tmpl). 4680 /// 4681 /// \returns true if there was an error 4682 bool 4683 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 4684 CXXMethodDecl *Tmpl) { 4685 if (InitFunctionInstantiation(New, Tmpl)) 4686 return true; 4687 4688 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11) 4689 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New)); 4690 4691 New->setAccess(Tmpl->getAccess()); 4692 if (Tmpl->isVirtualAsWritten()) 4693 New->setVirtualAsWritten(true); 4694 4695 // FIXME: New needs a pointer to Tmpl 4696 return false; 4697 } 4698 4699 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New, 4700 FunctionDecl *Tmpl) { 4701 // Transfer across any unqualified lookups. 4702 if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) { 4703 SmallVector<DeclAccessPair, 32> Lookups; 4704 Lookups.reserve(DFI->getUnqualifiedLookups().size()); 4705 bool AnyChanged = false; 4706 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) { 4707 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(), 4708 DA.getDecl(), TemplateArgs); 4709 if (!D) 4710 return true; 4711 AnyChanged |= (D != DA.getDecl()); 4712 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess())); 4713 } 4714 4715 // It's unlikely that substitution will change any declarations. Don't 4716 // store an unnecessary copy in that case. 4717 New->setDefaultedFunctionInfo( 4718 AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create( 4719 SemaRef.Context, Lookups) 4720 : DFI); 4721 } 4722 4723 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation()); 4724 return false; 4725 } 4726 4727 /// Instantiate (or find existing instantiation of) a function template with a 4728 /// given set of template arguments. 4729 /// 4730 /// Usually this should not be used, and template argument deduction should be 4731 /// used in its place. 4732 FunctionDecl * 4733 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 4734 const TemplateArgumentList *Args, 4735 SourceLocation Loc) { 4736 FunctionDecl *FD = FTD->getTemplatedDecl(); 4737 4738 sema::TemplateDeductionInfo Info(Loc); 4739 InstantiatingTemplate Inst( 4740 *this, Loc, FTD, Args->asArray(), 4741 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); 4742 if (Inst.isInvalid()) 4743 return nullptr; 4744 4745 ContextRAII SavedContext(*this, FD); 4746 MultiLevelTemplateArgumentList MArgs(*Args); 4747 4748 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs)); 4749 } 4750 4751 /// Instantiate the definition of the given function from its 4752 /// template. 4753 /// 4754 /// \param PointOfInstantiation the point at which the instantiation was 4755 /// required. Note that this is not precisely a "point of instantiation" 4756 /// for the function, but it's close. 4757 /// 4758 /// \param Function the already-instantiated declaration of a 4759 /// function template specialization or member function of a class template 4760 /// specialization. 4761 /// 4762 /// \param Recursive if true, recursively instantiates any functions that 4763 /// are required by this instantiation. 4764 /// 4765 /// \param DefinitionRequired if true, then we are performing an explicit 4766 /// instantiation where the body of the function is required. Complain if 4767 /// there is no such body. 4768 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 4769 FunctionDecl *Function, 4770 bool Recursive, 4771 bool DefinitionRequired, 4772 bool AtEndOfTU) { 4773 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function)) 4774 return; 4775 4776 // Never instantiate an explicit specialization except if it is a class scope 4777 // explicit specialization. 4778 TemplateSpecializationKind TSK = 4779 Function->getTemplateSpecializationKindForInstantiation(); 4780 if (TSK == TSK_ExplicitSpecialization) 4781 return; 4782 4783 // Don't instantiate a definition if we already have one. 4784 const FunctionDecl *ExistingDefn = nullptr; 4785 if (Function->isDefined(ExistingDefn, 4786 /*CheckForPendingFriendDefinition=*/true)) { 4787 if (ExistingDefn->isThisDeclarationADefinition()) 4788 return; 4789 4790 // If we're asked to instantiate a function whose body comes from an 4791 // instantiated friend declaration, attach the instantiated body to the 4792 // corresponding declaration of the function. 4793 assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition()); 4794 Function = const_cast<FunctionDecl*>(ExistingDefn); 4795 } 4796 4797 // Find the function body that we'll be substituting. 4798 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 4799 assert(PatternDecl && "instantiating a non-template"); 4800 4801 const FunctionDecl *PatternDef = PatternDecl->getDefinition(); 4802 Stmt *Pattern = nullptr; 4803 if (PatternDef) { 4804 Pattern = PatternDef->getBody(PatternDef); 4805 PatternDecl = PatternDef; 4806 if (PatternDef->willHaveBody()) 4807 PatternDef = nullptr; 4808 } 4809 4810 // FIXME: We need to track the instantiation stack in order to know which 4811 // definitions should be visible within this instantiation. 4812 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function, 4813 Function->getInstantiatedFromMemberFunction(), 4814 PatternDecl, PatternDef, TSK, 4815 /*Complain*/DefinitionRequired)) { 4816 if (DefinitionRequired) 4817 Function->setInvalidDecl(); 4818 else if (TSK == TSK_ExplicitInstantiationDefinition) { 4819 // Try again at the end of the translation unit (at which point a 4820 // definition will be required). 4821 assert(!Recursive); 4822 Function->setInstantiationIsPending(true); 4823 PendingInstantiations.push_back( 4824 std::make_pair(Function, PointOfInstantiation)); 4825 } else if (TSK == TSK_ImplicitInstantiation) { 4826 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 4827 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 4828 Diag(PointOfInstantiation, diag::warn_func_template_missing) 4829 << Function; 4830 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 4831 if (getLangOpts().CPlusPlus11) 4832 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) 4833 << Function; 4834 } 4835 } 4836 4837 return; 4838 } 4839 4840 // Postpone late parsed template instantiations. 4841 if (PatternDecl->isLateTemplateParsed() && 4842 !LateTemplateParser) { 4843 Function->setInstantiationIsPending(true); 4844 LateParsedInstantiations.push_back( 4845 std::make_pair(Function, PointOfInstantiation)); 4846 return; 4847 } 4848 4849 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() { 4850 std::string Name; 4851 llvm::raw_string_ostream OS(Name); 4852 Function->getNameForDiagnostic(OS, getPrintingPolicy(), 4853 /*Qualified=*/true); 4854 return Name; 4855 }); 4856 4857 // If we're performing recursive template instantiation, create our own 4858 // queue of pending implicit instantiations that we will instantiate later, 4859 // while we're still within our own instantiation context. 4860 // This has to happen before LateTemplateParser below is called, so that 4861 // it marks vtables used in late parsed templates as used. 4862 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4863 /*Enabled=*/Recursive); 4864 LocalEagerInstantiationScope LocalInstantiations(*this); 4865 4866 // Call the LateTemplateParser callback if there is a need to late parse 4867 // a templated function definition. 4868 if (!Pattern && PatternDecl->isLateTemplateParsed() && 4869 LateTemplateParser) { 4870 // FIXME: Optimize to allow individual templates to be deserialized. 4871 if (PatternDecl->isFromASTFile()) 4872 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 4873 4874 auto LPTIter = LateParsedTemplateMap.find(PatternDecl); 4875 assert(LPTIter != LateParsedTemplateMap.end() && 4876 "missing LateParsedTemplate"); 4877 LateTemplateParser(OpaqueParser, *LPTIter->second); 4878 Pattern = PatternDecl->getBody(PatternDecl); 4879 } 4880 4881 // Note, we should never try to instantiate a deleted function template. 4882 assert((Pattern || PatternDecl->isDefaulted() || 4883 PatternDecl->hasSkippedBody()) && 4884 "unexpected kind of function template definition"); 4885 4886 // C++1y [temp.explicit]p10: 4887 // Except for inline functions, declarations with types deduced from their 4888 // initializer or return value, and class template specializations, other 4889 // explicit instantiation declarations have the effect of suppressing the 4890 // implicit instantiation of the entity to which they refer. 4891 if (TSK == TSK_ExplicitInstantiationDeclaration && 4892 !PatternDecl->isInlined() && 4893 !PatternDecl->getReturnType()->getContainedAutoType()) 4894 return; 4895 4896 if (PatternDecl->isInlined()) { 4897 // Function, and all later redeclarations of it (from imported modules, 4898 // for instance), are now implicitly inline. 4899 for (auto *D = Function->getMostRecentDecl(); /**/; 4900 D = D->getPreviousDecl()) { 4901 D->setImplicitlyInline(); 4902 if (D == Function) 4903 break; 4904 } 4905 } 4906 4907 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 4908 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4909 return; 4910 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(), 4911 "instantiating function definition"); 4912 4913 // The instantiation is visible here, even if it was first declared in an 4914 // unimported module. 4915 Function->setVisibleDespiteOwningModule(); 4916 4917 // Copy the inner loc start from the pattern. 4918 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 4919 4920 EnterExpressionEvaluationContext EvalContext( 4921 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 4922 4923 // Introduce a new scope where local variable instantiations will be 4924 // recorded, unless we're actually a member function within a local 4925 // class, in which case we need to merge our results with the parent 4926 // scope (of the enclosing function). The exception is instantiating 4927 // a function template specialization, since the template to be 4928 // instantiated already has references to locals properly substituted. 4929 bool MergeWithParentScope = false; 4930 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 4931 MergeWithParentScope = 4932 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization(); 4933 4934 LocalInstantiationScope Scope(*this, MergeWithParentScope); 4935 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() { 4936 // Special members might get their TypeSourceInfo set up w.r.t the 4937 // PatternDecl context, in which case parameters could still be pointing 4938 // back to the original class, make sure arguments are bound to the 4939 // instantiated record instead. 4940 assert(PatternDecl->isDefaulted() && 4941 "Special member needs to be defaulted"); 4942 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember(); 4943 if (!(PatternSM == Sema::CXXCopyConstructor || 4944 PatternSM == Sema::CXXCopyAssignment || 4945 PatternSM == Sema::CXXMoveConstructor || 4946 PatternSM == Sema::CXXMoveAssignment)) 4947 return; 4948 4949 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()); 4950 const auto *PatternRec = 4951 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext()); 4952 if (!NewRec || !PatternRec) 4953 return; 4954 if (!PatternRec->isLambda()) 4955 return; 4956 4957 struct SpecialMemberTypeInfoRebuilder 4958 : TreeTransform<SpecialMemberTypeInfoRebuilder> { 4959 using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>; 4960 const CXXRecordDecl *OldDecl; 4961 CXXRecordDecl *NewDecl; 4962 4963 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O, 4964 CXXRecordDecl *N) 4965 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {} 4966 4967 bool TransformExceptionSpec(SourceLocation Loc, 4968 FunctionProtoType::ExceptionSpecInfo &ESI, 4969 SmallVectorImpl<QualType> &Exceptions, 4970 bool &Changed) { 4971 return false; 4972 } 4973 4974 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) { 4975 const RecordType *T = TL.getTypePtr(); 4976 RecordDecl *Record = cast_or_null<RecordDecl>( 4977 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl())); 4978 if (Record != OldDecl) 4979 return Base::TransformRecordType(TLB, TL); 4980 4981 QualType Result = getDerived().RebuildRecordType(NewDecl); 4982 if (Result.isNull()) 4983 return QualType(); 4984 4985 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result); 4986 NewTL.setNameLoc(TL.getNameLoc()); 4987 return Result; 4988 } 4989 } IR{*this, PatternRec, NewRec}; 4990 4991 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo()); 4992 Function->setType(NewSI->getType()); 4993 Function->setTypeSourceInfo(NewSI); 4994 4995 ParmVarDecl *Parm = Function->getParamDecl(0); 4996 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo()); 4997 Parm->setType(NewParmSI->getType()); 4998 Parm->setTypeSourceInfo(NewParmSI); 4999 }; 5000 5001 if (PatternDecl->isDefaulted()) { 5002 RebuildTypeSourceInfoForDefaultSpecialMembers(); 5003 SetDeclDefaulted(Function, PatternDecl->getLocation()); 5004 } else { 5005 MultiLevelTemplateArgumentList TemplateArgs = 5006 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl); 5007 5008 // Substitute into the qualifier; we can get a substitution failure here 5009 // through evil use of alias templates. 5010 // FIXME: Is CurContext correct for this? Should we go to the (instantiation 5011 // of the) lexical context of the pattern? 5012 SubstQualifier(*this, PatternDecl, Function, TemplateArgs); 5013 5014 ActOnStartOfFunctionDef(nullptr, Function); 5015 5016 // Enter the scope of this instantiation. We don't use 5017 // PushDeclContext because we don't have a scope. 5018 Sema::ContextRAII savedContext(*this, Function); 5019 5020 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 5021 TemplateArgs)) 5022 return; 5023 5024 StmtResult Body; 5025 if (PatternDecl->hasSkippedBody()) { 5026 ActOnSkippedFunctionBody(Function); 5027 Body = nullptr; 5028 } else { 5029 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) { 5030 // If this is a constructor, instantiate the member initializers. 5031 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl), 5032 TemplateArgs); 5033 5034 // If this is an MS ABI dllexport default constructor, instantiate any 5035 // default arguments. 5036 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5037 Ctor->isDefaultConstructor()) { 5038 InstantiateDefaultCtorDefaultArgs(Ctor); 5039 } 5040 } 5041 5042 // Instantiate the function body. 5043 Body = SubstStmt(Pattern, TemplateArgs); 5044 5045 if (Body.isInvalid()) 5046 Function->setInvalidDecl(); 5047 } 5048 // FIXME: finishing the function body while in an expression evaluation 5049 // context seems wrong. Investigate more. 5050 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true); 5051 5052 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 5053 5054 if (auto *Listener = getASTMutationListener()) 5055 Listener->FunctionDefinitionInstantiated(Function); 5056 5057 savedContext.pop(); 5058 } 5059 5060 DeclGroupRef DG(Function); 5061 Consumer.HandleTopLevelDecl(DG); 5062 5063 // This class may have local implicit instantiations that need to be 5064 // instantiation within this scope. 5065 LocalInstantiations.perform(); 5066 Scope.Exit(); 5067 GlobalInstantiations.perform(); 5068 } 5069 5070 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 5071 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 5072 const TemplateArgumentList &TemplateArgList, 5073 const TemplateArgumentListInfo &TemplateArgsInfo, 5074 SmallVectorImpl<TemplateArgument> &Converted, 5075 SourceLocation PointOfInstantiation, 5076 LateInstantiatedAttrVec *LateAttrs, 5077 LocalInstantiationScope *StartingScope) { 5078 if (FromVar->isInvalidDecl()) 5079 return nullptr; 5080 5081 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 5082 if (Inst.isInvalid()) 5083 return nullptr; 5084 5085 MultiLevelTemplateArgumentList TemplateArgLists; 5086 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 5087 5088 // Instantiate the first declaration of the variable template: for a partial 5089 // specialization of a static data member template, the first declaration may 5090 // or may not be the declaration in the class; if it's in the class, we want 5091 // to instantiate a member in the class (a declaration), and if it's outside, 5092 // we want to instantiate a definition. 5093 // 5094 // If we're instantiating an explicitly-specialized member template or member 5095 // partial specialization, don't do this. The member specialization completely 5096 // replaces the original declaration in this case. 5097 bool IsMemberSpec = false; 5098 if (VarTemplatePartialSpecializationDecl *PartialSpec = 5099 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) 5100 IsMemberSpec = PartialSpec->isMemberSpecialization(); 5101 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate()) 5102 IsMemberSpec = FromTemplate->isMemberSpecialization(); 5103 if (!IsMemberSpec) 5104 FromVar = FromVar->getFirstDecl(); 5105 5106 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 5107 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 5108 MultiLevelList); 5109 5110 // TODO: Set LateAttrs and StartingScope ... 5111 5112 return cast_or_null<VarTemplateSpecializationDecl>( 5113 Instantiator.VisitVarTemplateSpecializationDecl( 5114 VarTemplate, FromVar, TemplateArgsInfo, Converted)); 5115 } 5116 5117 /// Instantiates a variable template specialization by completing it 5118 /// with appropriate type information and initializer. 5119 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 5120 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 5121 const MultiLevelTemplateArgumentList &TemplateArgs) { 5122 assert(PatternDecl->isThisDeclarationADefinition() && 5123 "don't have a definition to instantiate from"); 5124 5125 // Do substitution on the type of the declaration 5126 TypeSourceInfo *DI = 5127 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 5128 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 5129 if (!DI) 5130 return nullptr; 5131 5132 // Update the type of this variable template specialization. 5133 VarSpec->setType(DI->getType()); 5134 5135 // Convert the declaration into a definition now. 5136 VarSpec->setCompleteDefinition(); 5137 5138 // Instantiate the initializer. 5139 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 5140 5141 if (getLangOpts().OpenCL) 5142 deduceOpenCLAddressSpace(VarSpec); 5143 5144 return VarSpec; 5145 } 5146 5147 /// BuildVariableInstantiation - Used after a new variable has been created. 5148 /// Sets basic variable data and decides whether to postpone the 5149 /// variable instantiation. 5150 void Sema::BuildVariableInstantiation( 5151 VarDecl *NewVar, VarDecl *OldVar, 5152 const MultiLevelTemplateArgumentList &TemplateArgs, 5153 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 5154 LocalInstantiationScope *StartingScope, 5155 bool InstantiatingVarTemplate, 5156 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) { 5157 // Instantiating a partial specialization to produce a partial 5158 // specialization. 5159 bool InstantiatingVarTemplatePartialSpec = 5160 isa<VarTemplatePartialSpecializationDecl>(OldVar) && 5161 isa<VarTemplatePartialSpecializationDecl>(NewVar); 5162 // Instantiating from a variable template (or partial specialization) to 5163 // produce a variable template specialization. 5164 bool InstantiatingSpecFromTemplate = 5165 isa<VarTemplateSpecializationDecl>(NewVar) && 5166 (OldVar->getDescribedVarTemplate() || 5167 isa<VarTemplatePartialSpecializationDecl>(OldVar)); 5168 5169 // If we are instantiating a local extern declaration, the 5170 // instantiation belongs lexically to the containing function. 5171 // If we are instantiating a static data member defined 5172 // out-of-line, the instantiation will have the same lexical 5173 // context (which will be a namespace scope) as the template. 5174 if (OldVar->isLocalExternDecl()) { 5175 NewVar->setLocalExternDecl(); 5176 NewVar->setLexicalDeclContext(Owner); 5177 } else if (OldVar->isOutOfLine()) 5178 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 5179 NewVar->setTSCSpec(OldVar->getTSCSpec()); 5180 NewVar->setInitStyle(OldVar->getInitStyle()); 5181 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 5182 NewVar->setObjCForDecl(OldVar->isObjCForDecl()); 5183 NewVar->setConstexpr(OldVar->isConstexpr()); 5184 NewVar->setInitCapture(OldVar->isInitCapture()); 5185 NewVar->setPreviousDeclInSameBlockScope( 5186 OldVar->isPreviousDeclInSameBlockScope()); 5187 NewVar->setAccess(OldVar->getAccess()); 5188 5189 if (!OldVar->isStaticDataMember()) { 5190 if (OldVar->isUsed(false)) 5191 NewVar->setIsUsed(); 5192 NewVar->setReferenced(OldVar->isReferenced()); 5193 } 5194 5195 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 5196 5197 LookupResult Previous( 5198 *this, NewVar->getDeclName(), NewVar->getLocation(), 5199 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 5200 : Sema::LookupOrdinaryName, 5201 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration 5202 : forRedeclarationInCurContext()); 5203 5204 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 5205 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 5206 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 5207 // We have a previous declaration. Use that one, so we merge with the 5208 // right type. 5209 if (NamedDecl *NewPrev = FindInstantiatedDecl( 5210 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 5211 Previous.addDecl(NewPrev); 5212 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 5213 OldVar->hasLinkage()) { 5214 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 5215 } else if (PrevDeclForVarTemplateSpecialization) { 5216 Previous.addDecl(PrevDeclForVarTemplateSpecialization); 5217 } 5218 CheckVariableDeclaration(NewVar, Previous); 5219 5220 if (!InstantiatingVarTemplate) { 5221 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 5222 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 5223 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 5224 } 5225 5226 if (!OldVar->isOutOfLine()) { 5227 if (NewVar->getDeclContext()->isFunctionOrMethod()) 5228 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 5229 } 5230 5231 // Link instantiations of static data members back to the template from 5232 // which they were instantiated. 5233 // 5234 // Don't do this when instantiating a template (we link the template itself 5235 // back in that case) nor when instantiating a static data member template 5236 // (that's not a member specialization). 5237 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate && 5238 !InstantiatingSpecFromTemplate) 5239 NewVar->setInstantiationOfStaticDataMember(OldVar, 5240 TSK_ImplicitInstantiation); 5241 5242 // If the pattern is an (in-class) explicit specialization, then the result 5243 // is also an explicit specialization. 5244 if (VarTemplateSpecializationDecl *OldVTSD = 5245 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) { 5246 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization && 5247 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD)) 5248 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind( 5249 TSK_ExplicitSpecialization); 5250 } 5251 5252 // Forward the mangling number from the template to the instantiated decl. 5253 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 5254 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar)); 5255 5256 // Figure out whether to eagerly instantiate the initializer. 5257 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) { 5258 // We're producing a template. Don't instantiate the initializer yet. 5259 } else if (NewVar->getType()->isUndeducedType()) { 5260 // We need the type to complete the declaration of the variable. 5261 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 5262 } else if (InstantiatingSpecFromTemplate || 5263 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() && 5264 !NewVar->isThisDeclarationADefinition())) { 5265 // Delay instantiation of the initializer for variable template 5266 // specializations or inline static data members until a definition of the 5267 // variable is needed. 5268 } else { 5269 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 5270 } 5271 5272 // Diagnose unused local variables with dependent types, where the diagnostic 5273 // will have been deferred. 5274 if (!NewVar->isInvalidDecl() && 5275 NewVar->getDeclContext()->isFunctionOrMethod() && 5276 OldVar->getType()->isDependentType()) 5277 DiagnoseUnusedDecl(NewVar); 5278 } 5279 5280 /// Instantiate the initializer of a variable. 5281 void Sema::InstantiateVariableInitializer( 5282 VarDecl *Var, VarDecl *OldVar, 5283 const MultiLevelTemplateArgumentList &TemplateArgs) { 5284 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 5285 L->VariableDefinitionInstantiated(Var); 5286 5287 // We propagate the 'inline' flag with the initializer, because it 5288 // would otherwise imply that the variable is a definition for a 5289 // non-static data member. 5290 if (OldVar->isInlineSpecified()) 5291 Var->setInlineSpecified(); 5292 else if (OldVar->isInline()) 5293 Var->setImplicitlyInline(); 5294 5295 if (OldVar->getInit()) { 5296 EnterExpressionEvaluationContext Evaluated( 5297 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var); 5298 5299 // Instantiate the initializer. 5300 ExprResult Init; 5301 5302 { 5303 ContextRAII SwitchContext(*this, Var->getDeclContext()); 5304 Init = SubstInitializer(OldVar->getInit(), TemplateArgs, 5305 OldVar->getInitStyle() == VarDecl::CallInit); 5306 } 5307 5308 if (!Init.isInvalid()) { 5309 Expr *InitExpr = Init.get(); 5310 5311 if (Var->hasAttr<DLLImportAttr>() && 5312 (!InitExpr || 5313 !InitExpr->isConstantInitializer(getASTContext(), false))) { 5314 // Do not dynamically initialize dllimport variables. 5315 } else if (InitExpr) { 5316 bool DirectInit = OldVar->isDirectInit(); 5317 AddInitializerToDecl(Var, InitExpr, DirectInit); 5318 } else 5319 ActOnUninitializedDecl(Var); 5320 } else { 5321 // FIXME: Not too happy about invalidating the declaration 5322 // because of a bogus initializer. 5323 Var->setInvalidDecl(); 5324 } 5325 } else { 5326 // `inline` variables are a definition and declaration all in one; we won't 5327 // pick up an initializer from anywhere else. 5328 if (Var->isStaticDataMember() && !Var->isInline()) { 5329 if (!Var->isOutOfLine()) 5330 return; 5331 5332 // If the declaration inside the class had an initializer, don't add 5333 // another one to the out-of-line definition. 5334 if (OldVar->getFirstDecl()->hasInit()) 5335 return; 5336 } 5337 5338 // We'll add an initializer to a for-range declaration later. 5339 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl()) 5340 return; 5341 5342 ActOnUninitializedDecl(Var); 5343 } 5344 5345 if (getLangOpts().CUDA) 5346 checkAllowedCUDAInitializer(Var); 5347 } 5348 5349 /// Instantiate the definition of the given variable from its 5350 /// template. 5351 /// 5352 /// \param PointOfInstantiation the point at which the instantiation was 5353 /// required. Note that this is not precisely a "point of instantiation" 5354 /// for the variable, but it's close. 5355 /// 5356 /// \param Var the already-instantiated declaration of a templated variable. 5357 /// 5358 /// \param Recursive if true, recursively instantiates any functions that 5359 /// are required by this instantiation. 5360 /// 5361 /// \param DefinitionRequired if true, then we are performing an explicit 5362 /// instantiation where a definition of the variable is required. Complain 5363 /// if there is no such definition. 5364 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 5365 VarDecl *Var, bool Recursive, 5366 bool DefinitionRequired, bool AtEndOfTU) { 5367 if (Var->isInvalidDecl()) 5368 return; 5369 5370 // Never instantiate an explicitly-specialized entity. 5371 TemplateSpecializationKind TSK = 5372 Var->getTemplateSpecializationKindForInstantiation(); 5373 if (TSK == TSK_ExplicitSpecialization) 5374 return; 5375 5376 // Find the pattern and the arguments to substitute into it. 5377 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern(); 5378 assert(PatternDecl && "no pattern for templated variable"); 5379 MultiLevelTemplateArgumentList TemplateArgs = 5380 getTemplateInstantiationArgs(Var); 5381 5382 VarTemplateSpecializationDecl *VarSpec = 5383 dyn_cast<VarTemplateSpecializationDecl>(Var); 5384 if (VarSpec) { 5385 // If this is a static data member template, there might be an 5386 // uninstantiated initializer on the declaration. If so, instantiate 5387 // it now. 5388 // 5389 // FIXME: This largely duplicates what we would do below. The difference 5390 // is that along this path we may instantiate an initializer from an 5391 // in-class declaration of the template and instantiate the definition 5392 // from a separate out-of-class definition. 5393 if (PatternDecl->isStaticDataMember() && 5394 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 5395 !Var->hasInit()) { 5396 // FIXME: Factor out the duplicated instantiation context setup/tear down 5397 // code here. 5398 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 5399 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 5400 return; 5401 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 5402 "instantiating variable initializer"); 5403 5404 // The instantiation is visible here, even if it was first declared in an 5405 // unimported module. 5406 Var->setVisibleDespiteOwningModule(); 5407 5408 // If we're performing recursive template instantiation, create our own 5409 // queue of pending implicit instantiations that we will instantiate 5410 // later, while we're still within our own instantiation context. 5411 GlobalEagerInstantiationScope GlobalInstantiations(*this, 5412 /*Enabled=*/Recursive); 5413 LocalInstantiationScope Local(*this); 5414 LocalEagerInstantiationScope LocalInstantiations(*this); 5415 5416 // Enter the scope of this instantiation. We don't use 5417 // PushDeclContext because we don't have a scope. 5418 ContextRAII PreviousContext(*this, Var->getDeclContext()); 5419 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 5420 PreviousContext.pop(); 5421 5422 // This variable may have local implicit instantiations that need to be 5423 // instantiated within this scope. 5424 LocalInstantiations.perform(); 5425 Local.Exit(); 5426 GlobalInstantiations.perform(); 5427 } 5428 } else { 5429 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && 5430 "not a static data member?"); 5431 } 5432 5433 VarDecl *Def = PatternDecl->getDefinition(getASTContext()); 5434 5435 // If we don't have a definition of the variable template, we won't perform 5436 // any instantiation. Rather, we rely on the user to instantiate this 5437 // definition (or provide a specialization for it) in another translation 5438 // unit. 5439 if (!Def && !DefinitionRequired) { 5440 if (TSK == TSK_ExplicitInstantiationDefinition) { 5441 PendingInstantiations.push_back( 5442 std::make_pair(Var, PointOfInstantiation)); 5443 } else if (TSK == TSK_ImplicitInstantiation) { 5444 // Warn about missing definition at the end of translation unit. 5445 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 5446 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 5447 Diag(PointOfInstantiation, diag::warn_var_template_missing) 5448 << Var; 5449 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 5450 if (getLangOpts().CPlusPlus11) 5451 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var; 5452 } 5453 return; 5454 } 5455 } 5456 5457 // FIXME: We need to track the instantiation stack in order to know which 5458 // definitions should be visible within this instantiation. 5459 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember(). 5460 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var, 5461 /*InstantiatedFromMember*/false, 5462 PatternDecl, Def, TSK, 5463 /*Complain*/DefinitionRequired)) 5464 return; 5465 5466 // C++11 [temp.explicit]p10: 5467 // Except for inline functions, const variables of literal types, variables 5468 // of reference types, [...] explicit instantiation declarations 5469 // have the effect of suppressing the implicit instantiation of the entity 5470 // to which they refer. 5471 // 5472 // FIXME: That's not exactly the same as "might be usable in constant 5473 // expressions", which only allows constexpr variables and const integral 5474 // types, not arbitrary const literal types. 5475 if (TSK == TSK_ExplicitInstantiationDeclaration && 5476 !Var->mightBeUsableInConstantExpressions(getASTContext())) 5477 return; 5478 5479 // Make sure to pass the instantiated variable to the consumer at the end. 5480 struct PassToConsumerRAII { 5481 ASTConsumer &Consumer; 5482 VarDecl *Var; 5483 5484 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 5485 : Consumer(Consumer), Var(Var) { } 5486 5487 ~PassToConsumerRAII() { 5488 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 5489 } 5490 } PassToConsumerRAII(Consumer, Var); 5491 5492 // If we already have a definition, we're done. 5493 if (VarDecl *Def = Var->getDefinition()) { 5494 // We may be explicitly instantiating something we've already implicitly 5495 // instantiated. 5496 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 5497 PointOfInstantiation); 5498 return; 5499 } 5500 5501 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 5502 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 5503 return; 5504 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 5505 "instantiating variable definition"); 5506 5507 // If we're performing recursive template instantiation, create our own 5508 // queue of pending implicit instantiations that we will instantiate later, 5509 // while we're still within our own instantiation context. 5510 GlobalEagerInstantiationScope GlobalInstantiations(*this, 5511 /*Enabled=*/Recursive); 5512 5513 // Enter the scope of this instantiation. We don't use 5514 // PushDeclContext because we don't have a scope. 5515 ContextRAII PreviousContext(*this, Var->getDeclContext()); 5516 LocalInstantiationScope Local(*this); 5517 5518 LocalEagerInstantiationScope LocalInstantiations(*this); 5519 5520 VarDecl *OldVar = Var; 5521 if (Def->isStaticDataMember() && !Def->isOutOfLine()) { 5522 // We're instantiating an inline static data member whose definition was 5523 // provided inside the class. 5524 InstantiateVariableInitializer(Var, Def, TemplateArgs); 5525 } else if (!VarSpec) { 5526 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 5527 TemplateArgs)); 5528 } else if (Var->isStaticDataMember() && 5529 Var->getLexicalDeclContext()->isRecord()) { 5530 // We need to instantiate the definition of a static data member template, 5531 // and all we have is the in-class declaration of it. Instantiate a separate 5532 // declaration of the definition. 5533 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 5534 TemplateArgs); 5535 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 5536 VarSpec->getSpecializedTemplate(), Def, VarSpec->getTemplateArgsInfo(), 5537 VarSpec->getTemplateArgs().asArray(), VarSpec)); 5538 if (Var) { 5539 llvm::PointerUnion<VarTemplateDecl *, 5540 VarTemplatePartialSpecializationDecl *> PatternPtr = 5541 VarSpec->getSpecializedTemplateOrPartial(); 5542 if (VarTemplatePartialSpecializationDecl *Partial = 5543 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 5544 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 5545 Partial, &VarSpec->getTemplateInstantiationArgs()); 5546 5547 // Attach the initializer. 5548 InstantiateVariableInitializer(Var, Def, TemplateArgs); 5549 } 5550 } else 5551 // Complete the existing variable's definition with an appropriately 5552 // substituted type and initializer. 5553 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 5554 5555 PreviousContext.pop(); 5556 5557 if (Var) { 5558 PassToConsumerRAII.Var = Var; 5559 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 5560 OldVar->getPointOfInstantiation()); 5561 } 5562 5563 // This variable may have local implicit instantiations that need to be 5564 // instantiated within this scope. 5565 LocalInstantiations.perform(); 5566 Local.Exit(); 5567 GlobalInstantiations.perform(); 5568 } 5569 5570 void 5571 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 5572 const CXXConstructorDecl *Tmpl, 5573 const MultiLevelTemplateArgumentList &TemplateArgs) { 5574 5575 SmallVector<CXXCtorInitializer*, 4> NewInits; 5576 bool AnyErrors = Tmpl->isInvalidDecl(); 5577 5578 // Instantiate all the initializers. 5579 for (const auto *Init : Tmpl->inits()) { 5580 // Only instantiate written initializers, let Sema re-construct implicit 5581 // ones. 5582 if (!Init->isWritten()) 5583 continue; 5584 5585 SourceLocation EllipsisLoc; 5586 5587 if (Init->isPackExpansion()) { 5588 // This is a pack expansion. We should expand it now. 5589 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 5590 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 5591 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 5592 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 5593 bool ShouldExpand = false; 5594 bool RetainExpansion = false; 5595 Optional<unsigned> NumExpansions; 5596 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 5597 BaseTL.getSourceRange(), 5598 Unexpanded, 5599 TemplateArgs, ShouldExpand, 5600 RetainExpansion, 5601 NumExpansions)) { 5602 AnyErrors = true; 5603 New->setInvalidDecl(); 5604 continue; 5605 } 5606 assert(ShouldExpand && "Partial instantiation of base initializer?"); 5607 5608 // Loop over all of the arguments in the argument pack(s), 5609 for (unsigned I = 0; I != *NumExpansions; ++I) { 5610 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 5611 5612 // Instantiate the initializer. 5613 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 5614 /*CXXDirectInit=*/true); 5615 if (TempInit.isInvalid()) { 5616 AnyErrors = true; 5617 break; 5618 } 5619 5620 // Instantiate the base type. 5621 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 5622 TemplateArgs, 5623 Init->getSourceLocation(), 5624 New->getDeclName()); 5625 if (!BaseTInfo) { 5626 AnyErrors = true; 5627 break; 5628 } 5629 5630 // Build the initializer. 5631 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 5632 BaseTInfo, TempInit.get(), 5633 New->getParent(), 5634 SourceLocation()); 5635 if (NewInit.isInvalid()) { 5636 AnyErrors = true; 5637 break; 5638 } 5639 5640 NewInits.push_back(NewInit.get()); 5641 } 5642 5643 continue; 5644 } 5645 5646 // Instantiate the initializer. 5647 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 5648 /*CXXDirectInit=*/true); 5649 if (TempInit.isInvalid()) { 5650 AnyErrors = true; 5651 continue; 5652 } 5653 5654 MemInitResult NewInit; 5655 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 5656 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 5657 TemplateArgs, 5658 Init->getSourceLocation(), 5659 New->getDeclName()); 5660 if (!TInfo) { 5661 AnyErrors = true; 5662 New->setInvalidDecl(); 5663 continue; 5664 } 5665 5666 if (Init->isBaseInitializer()) 5667 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(), 5668 New->getParent(), EllipsisLoc); 5669 else 5670 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(), 5671 cast<CXXRecordDecl>(CurContext->getParent())); 5672 } else if (Init->isMemberInitializer()) { 5673 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 5674 Init->getMemberLocation(), 5675 Init->getMember(), 5676 TemplateArgs)); 5677 if (!Member) { 5678 AnyErrors = true; 5679 New->setInvalidDecl(); 5680 continue; 5681 } 5682 5683 NewInit = BuildMemberInitializer(Member, TempInit.get(), 5684 Init->getSourceLocation()); 5685 } else if (Init->isIndirectMemberInitializer()) { 5686 IndirectFieldDecl *IndirectMember = 5687 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 5688 Init->getMemberLocation(), 5689 Init->getIndirectMember(), TemplateArgs)); 5690 5691 if (!IndirectMember) { 5692 AnyErrors = true; 5693 New->setInvalidDecl(); 5694 continue; 5695 } 5696 5697 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(), 5698 Init->getSourceLocation()); 5699 } 5700 5701 if (NewInit.isInvalid()) { 5702 AnyErrors = true; 5703 New->setInvalidDecl(); 5704 } else { 5705 NewInits.push_back(NewInit.get()); 5706 } 5707 } 5708 5709 // Assign all the initializers to the new constructor. 5710 ActOnMemInitializers(New, 5711 /*FIXME: ColonLoc */ 5712 SourceLocation(), 5713 NewInits, 5714 AnyErrors); 5715 } 5716 5717 // TODO: this could be templated if the various decl types used the 5718 // same method name. 5719 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 5720 ClassTemplateDecl *Instance) { 5721 Pattern = Pattern->getCanonicalDecl(); 5722 5723 do { 5724 Instance = Instance->getCanonicalDecl(); 5725 if (Pattern == Instance) return true; 5726 Instance = Instance->getInstantiatedFromMemberTemplate(); 5727 } while (Instance); 5728 5729 return false; 5730 } 5731 5732 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 5733 FunctionTemplateDecl *Instance) { 5734 Pattern = Pattern->getCanonicalDecl(); 5735 5736 do { 5737 Instance = Instance->getCanonicalDecl(); 5738 if (Pattern == Instance) return true; 5739 Instance = Instance->getInstantiatedFromMemberTemplate(); 5740 } while (Instance); 5741 5742 return false; 5743 } 5744 5745 static bool 5746 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 5747 ClassTemplatePartialSpecializationDecl *Instance) { 5748 Pattern 5749 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 5750 do { 5751 Instance = cast<ClassTemplatePartialSpecializationDecl>( 5752 Instance->getCanonicalDecl()); 5753 if (Pattern == Instance) 5754 return true; 5755 Instance = Instance->getInstantiatedFromMember(); 5756 } while (Instance); 5757 5758 return false; 5759 } 5760 5761 static bool isInstantiationOf(CXXRecordDecl *Pattern, 5762 CXXRecordDecl *Instance) { 5763 Pattern = Pattern->getCanonicalDecl(); 5764 5765 do { 5766 Instance = Instance->getCanonicalDecl(); 5767 if (Pattern == Instance) return true; 5768 Instance = Instance->getInstantiatedFromMemberClass(); 5769 } while (Instance); 5770 5771 return false; 5772 } 5773 5774 static bool isInstantiationOf(FunctionDecl *Pattern, 5775 FunctionDecl *Instance) { 5776 Pattern = Pattern->getCanonicalDecl(); 5777 5778 do { 5779 Instance = Instance->getCanonicalDecl(); 5780 if (Pattern == Instance) return true; 5781 Instance = Instance->getInstantiatedFromMemberFunction(); 5782 } while (Instance); 5783 5784 return false; 5785 } 5786 5787 static bool isInstantiationOf(EnumDecl *Pattern, 5788 EnumDecl *Instance) { 5789 Pattern = Pattern->getCanonicalDecl(); 5790 5791 do { 5792 Instance = Instance->getCanonicalDecl(); 5793 if (Pattern == Instance) return true; 5794 Instance = Instance->getInstantiatedFromMemberEnum(); 5795 } while (Instance); 5796 5797 return false; 5798 } 5799 5800 static bool isInstantiationOf(UsingShadowDecl *Pattern, 5801 UsingShadowDecl *Instance, 5802 ASTContext &C) { 5803 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance), 5804 Pattern); 5805 } 5806 5807 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance, 5808 ASTContext &C) { 5809 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 5810 } 5811 5812 template<typename T> 5813 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, 5814 ASTContext &Ctx) { 5815 // An unresolved using declaration can instantiate to an unresolved using 5816 // declaration, or to a using declaration or a using declaration pack. 5817 // 5818 // Multiple declarations can claim to be instantiated from an unresolved 5819 // using declaration if it's a pack expansion. We want the UsingPackDecl 5820 // in that case, not the individual UsingDecls within the pack. 5821 bool OtherIsPackExpansion; 5822 NamedDecl *OtherFrom; 5823 if (auto *OtherUUD = dyn_cast<T>(Other)) { 5824 OtherIsPackExpansion = OtherUUD->isPackExpansion(); 5825 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD); 5826 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) { 5827 OtherIsPackExpansion = true; 5828 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl(); 5829 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) { 5830 OtherIsPackExpansion = false; 5831 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD); 5832 } else { 5833 return false; 5834 } 5835 return Pattern->isPackExpansion() == OtherIsPackExpansion && 5836 declaresSameEntity(OtherFrom, Pattern); 5837 } 5838 5839 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 5840 VarDecl *Instance) { 5841 assert(Instance->isStaticDataMember()); 5842 5843 Pattern = Pattern->getCanonicalDecl(); 5844 5845 do { 5846 Instance = Instance->getCanonicalDecl(); 5847 if (Pattern == Instance) return true; 5848 Instance = Instance->getInstantiatedFromStaticDataMember(); 5849 } while (Instance); 5850 5851 return false; 5852 } 5853 5854 // Other is the prospective instantiation 5855 // D is the prospective pattern 5856 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 5857 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) 5858 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5859 5860 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D)) 5861 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5862 5863 if (D->getKind() != Other->getKind()) 5864 return false; 5865 5866 if (auto *Record = dyn_cast<CXXRecordDecl>(Other)) 5867 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 5868 5869 if (auto *Function = dyn_cast<FunctionDecl>(Other)) 5870 return isInstantiationOf(cast<FunctionDecl>(D), Function); 5871 5872 if (auto *Enum = dyn_cast<EnumDecl>(Other)) 5873 return isInstantiationOf(cast<EnumDecl>(D), Enum); 5874 5875 if (auto *Var = dyn_cast<VarDecl>(Other)) 5876 if (Var->isStaticDataMember()) 5877 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 5878 5879 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other)) 5880 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 5881 5882 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 5883 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 5884 5885 if (auto *PartialSpec = 5886 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 5887 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 5888 PartialSpec); 5889 5890 if (auto *Field = dyn_cast<FieldDecl>(Other)) { 5891 if (!Field->getDeclName()) { 5892 // This is an unnamed field. 5893 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field), 5894 cast<FieldDecl>(D)); 5895 } 5896 } 5897 5898 if (auto *Using = dyn_cast<UsingDecl>(Other)) 5899 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 5900 5901 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other)) 5902 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 5903 5904 return D->getDeclName() && 5905 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 5906 } 5907 5908 template<typename ForwardIterator> 5909 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 5910 NamedDecl *D, 5911 ForwardIterator first, 5912 ForwardIterator last) { 5913 for (; first != last; ++first) 5914 if (isInstantiationOf(Ctx, D, *first)) 5915 return cast<NamedDecl>(*first); 5916 5917 return nullptr; 5918 } 5919 5920 /// Finds the instantiation of the given declaration context 5921 /// within the current instantiation. 5922 /// 5923 /// \returns NULL if there was an error 5924 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 5925 const MultiLevelTemplateArgumentList &TemplateArgs) { 5926 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 5927 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true); 5928 return cast_or_null<DeclContext>(ID); 5929 } else return DC; 5930 } 5931 5932 /// Determine whether the given context is dependent on template parameters at 5933 /// level \p Level or below. 5934 /// 5935 /// Sometimes we only substitute an inner set of template arguments and leave 5936 /// the outer templates alone. In such cases, contexts dependent only on the 5937 /// outer levels are not effectively dependent. 5938 static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) { 5939 if (!DC->isDependentContext()) 5940 return false; 5941 if (!Level) 5942 return true; 5943 return cast<Decl>(DC)->getTemplateDepth() > Level; 5944 } 5945 5946 /// Find the instantiation of the given declaration within the 5947 /// current instantiation. 5948 /// 5949 /// This routine is intended to be used when \p D is a declaration 5950 /// referenced from within a template, that needs to mapped into the 5951 /// corresponding declaration within an instantiation. For example, 5952 /// given: 5953 /// 5954 /// \code 5955 /// template<typename T> 5956 /// struct X { 5957 /// enum Kind { 5958 /// KnownValue = sizeof(T) 5959 /// }; 5960 /// 5961 /// bool getKind() const { return KnownValue; } 5962 /// }; 5963 /// 5964 /// template struct X<int>; 5965 /// \endcode 5966 /// 5967 /// In the instantiation of X<int>::getKind(), we need to map the \p 5968 /// EnumConstantDecl for \p KnownValue (which refers to 5969 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue). 5970 /// \p FindInstantiatedDecl performs this mapping from within the instantiation 5971 /// of X<int>. 5972 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 5973 const MultiLevelTemplateArgumentList &TemplateArgs, 5974 bool FindingInstantiatedContext) { 5975 DeclContext *ParentDC = D->getDeclContext(); 5976 // Determine whether our parent context depends on any of the template 5977 // arguments we're currently substituting. 5978 bool ParentDependsOnArgs = isDependentContextAtLevel( 5979 ParentDC, TemplateArgs.getNumRetainedOuterLevels()); 5980 // FIXME: Parameters of pointer to functions (y below) that are themselves 5981 // parameters (p below) can have their ParentDC set to the translation-unit 5982 // - thus we can not consistently check if the ParentDC of such a parameter 5983 // is Dependent or/and a FunctionOrMethod. 5984 // For e.g. this code, during Template argument deduction tries to 5985 // find an instantiated decl for (T y) when the ParentDC for y is 5986 // the translation unit. 5987 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 5988 // float baz(float(*)()) { return 0.0; } 5989 // Foo(baz); 5990 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 5991 // it gets here, always has a FunctionOrMethod as its ParentDC?? 5992 // For now: 5993 // - as long as we have a ParmVarDecl whose parent is non-dependent and 5994 // whose type is not instantiation dependent, do nothing to the decl 5995 // - otherwise find its instantiated decl. 5996 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs && 5997 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 5998 return D; 5999 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 6000 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 6001 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() || 6002 isa<OMPDeclareReductionDecl>(ParentDC) || 6003 isa<OMPDeclareMapperDecl>(ParentDC))) || 6004 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 6005 // D is a local of some kind. Look into the map of local 6006 // declarations to their instantiations. 6007 if (CurrentInstantiationScope) { 6008 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) { 6009 if (Decl *FD = Found->dyn_cast<Decl *>()) 6010 return cast<NamedDecl>(FD); 6011 6012 int PackIdx = ArgumentPackSubstitutionIndex; 6013 assert(PackIdx != -1 && 6014 "found declaration pack but not pack expanding"); 6015 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 6016 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 6017 } 6018 } 6019 6020 // If we're performing a partial substitution during template argument 6021 // deduction, we may not have values for template parameters yet. They 6022 // just map to themselves. 6023 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 6024 isa<TemplateTemplateParmDecl>(D)) 6025 return D; 6026 6027 if (D->isInvalidDecl()) 6028 return nullptr; 6029 6030 // Normally this function only searches for already instantiated declaration 6031 // however we have to make an exclusion for local types used before 6032 // definition as in the code: 6033 // 6034 // template<typename T> void f1() { 6035 // void g1(struct x1); 6036 // struct x1 {}; 6037 // } 6038 // 6039 // In this case instantiation of the type of 'g1' requires definition of 6040 // 'x1', which is defined later. Error recovery may produce an enum used 6041 // before definition. In these cases we need to instantiate relevant 6042 // declarations here. 6043 bool NeedInstantiate = false; 6044 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 6045 NeedInstantiate = RD->isLocalClass(); 6046 else if (isa<TypedefNameDecl>(D) && 6047 isa<CXXDeductionGuideDecl>(D->getDeclContext())) 6048 NeedInstantiate = true; 6049 else 6050 NeedInstantiate = isa<EnumDecl>(D); 6051 if (NeedInstantiate) { 6052 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 6053 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 6054 return cast<TypeDecl>(Inst); 6055 } 6056 6057 // If we didn't find the decl, then we must have a label decl that hasn't 6058 // been found yet. Lazily instantiate it and return it now. 6059 assert(isa<LabelDecl>(D)); 6060 6061 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 6062 assert(Inst && "Failed to instantiate label??"); 6063 6064 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 6065 return cast<LabelDecl>(Inst); 6066 } 6067 6068 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 6069 if (!Record->isDependentContext()) 6070 return D; 6071 6072 // Determine whether this record is the "templated" declaration describing 6073 // a class template or class template partial specialization. 6074 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 6075 if (ClassTemplate) 6076 ClassTemplate = ClassTemplate->getCanonicalDecl(); 6077 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 6078 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 6079 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 6080 6081 // Walk the current context to find either the record or an instantiation of 6082 // it. 6083 DeclContext *DC = CurContext; 6084 while (!DC->isFileContext()) { 6085 // If we're performing substitution while we're inside the template 6086 // definition, we'll find our own context. We're done. 6087 if (DC->Equals(Record)) 6088 return Record; 6089 6090 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 6091 // Check whether we're in the process of instantiating a class template 6092 // specialization of the template we're mapping. 6093 if (ClassTemplateSpecializationDecl *InstSpec 6094 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 6095 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 6096 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 6097 return InstRecord; 6098 } 6099 6100 // Check whether we're in the process of instantiating a member class. 6101 if (isInstantiationOf(Record, InstRecord)) 6102 return InstRecord; 6103 } 6104 6105 // Move to the outer template scope. 6106 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 6107 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 6108 DC = FD->getLexicalDeclContext(); 6109 continue; 6110 } 6111 // An implicit deduction guide acts as if it's within the class template 6112 // specialization described by its name and first N template params. 6113 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD); 6114 if (Guide && Guide->isImplicit()) { 6115 TemplateDecl *TD = Guide->getDeducedTemplate(); 6116 // Convert the arguments to an "as-written" list. 6117 TemplateArgumentListInfo Args(Loc, Loc); 6118 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front( 6119 TD->getTemplateParameters()->size())) { 6120 ArrayRef<TemplateArgument> Unpacked(Arg); 6121 if (Arg.getKind() == TemplateArgument::Pack) 6122 Unpacked = Arg.pack_elements(); 6123 for (TemplateArgument UnpackedArg : Unpacked) 6124 Args.addArgument( 6125 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc)); 6126 } 6127 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args); 6128 if (T.isNull()) 6129 return nullptr; 6130 auto *SubstRecord = T->getAsCXXRecordDecl(); 6131 assert(SubstRecord && "class template id not a class type?"); 6132 // Check that this template-id names the primary template and not a 6133 // partial or explicit specialization. (In the latter cases, it's 6134 // meaningless to attempt to find an instantiation of D within the 6135 // specialization.) 6136 // FIXME: The standard doesn't say what should happen here. 6137 if (FindingInstantiatedContext && 6138 usesPartialOrExplicitSpecialization( 6139 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) { 6140 Diag(Loc, diag::err_specialization_not_primary_template) 6141 << T << (SubstRecord->getTemplateSpecializationKind() == 6142 TSK_ExplicitSpecialization); 6143 return nullptr; 6144 } 6145 DC = SubstRecord; 6146 continue; 6147 } 6148 } 6149 6150 DC = DC->getParent(); 6151 } 6152 6153 // Fall through to deal with other dependent record types (e.g., 6154 // anonymous unions in class templates). 6155 } 6156 6157 if (!ParentDependsOnArgs) 6158 return D; 6159 6160 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 6161 if (!ParentDC) 6162 return nullptr; 6163 6164 if (ParentDC != D->getDeclContext()) { 6165 // We performed some kind of instantiation in the parent context, 6166 // so now we need to look into the instantiated parent context to 6167 // find the instantiation of the declaration D. 6168 6169 // If our context used to be dependent, we may need to instantiate 6170 // it before performing lookup into that context. 6171 bool IsBeingInstantiated = false; 6172 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 6173 if (!Spec->isDependentContext()) { 6174 QualType T = Context.getTypeDeclType(Spec); 6175 const RecordType *Tag = T->getAs<RecordType>(); 6176 assert(Tag && "type of non-dependent record is not a RecordType"); 6177 if (Tag->isBeingDefined()) 6178 IsBeingInstantiated = true; 6179 if (!Tag->isBeingDefined() && 6180 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 6181 return nullptr; 6182 6183 ParentDC = Tag->getDecl(); 6184 } 6185 } 6186 6187 NamedDecl *Result = nullptr; 6188 // FIXME: If the name is a dependent name, this lookup won't necessarily 6189 // find it. Does that ever matter? 6190 if (auto Name = D->getDeclName()) { 6191 DeclarationNameInfo NameInfo(Name, D->getLocation()); 6192 DeclarationNameInfo NewNameInfo = 6193 SubstDeclarationNameInfo(NameInfo, TemplateArgs); 6194 Name = NewNameInfo.getName(); 6195 if (!Name) 6196 return nullptr; 6197 DeclContext::lookup_result Found = ParentDC->lookup(Name); 6198 6199 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 6200 } else { 6201 // Since we don't have a name for the entity we're looking for, 6202 // our only option is to walk through all of the declarations to 6203 // find that name. This will occur in a few cases: 6204 // 6205 // - anonymous struct/union within a template 6206 // - unnamed class/struct/union/enum within a template 6207 // 6208 // FIXME: Find a better way to find these instantiations! 6209 Result = findInstantiationOf(Context, D, 6210 ParentDC->decls_begin(), 6211 ParentDC->decls_end()); 6212 } 6213 6214 if (!Result) { 6215 if (isa<UsingShadowDecl>(D)) { 6216 // UsingShadowDecls can instantiate to nothing because of using hiding. 6217 } else if (hasUncompilableErrorOccurred()) { 6218 // We've already complained about some ill-formed code, so most likely 6219 // this declaration failed to instantiate. There's no point in 6220 // complaining further, since this is normal in invalid code. 6221 // FIXME: Use more fine-grained 'invalid' tracking for this. 6222 } else if (IsBeingInstantiated) { 6223 // The class in which this member exists is currently being 6224 // instantiated, and we haven't gotten around to instantiating this 6225 // member yet. This can happen when the code uses forward declarations 6226 // of member classes, and introduces ordering dependencies via 6227 // template instantiation. 6228 Diag(Loc, diag::err_member_not_yet_instantiated) 6229 << D->getDeclName() 6230 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 6231 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 6232 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 6233 // This enumeration constant was found when the template was defined, 6234 // but can't be found in the instantiation. This can happen if an 6235 // unscoped enumeration member is explicitly specialized. 6236 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 6237 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 6238 TemplateArgs)); 6239 assert(Spec->getTemplateSpecializationKind() == 6240 TSK_ExplicitSpecialization); 6241 Diag(Loc, diag::err_enumerator_does_not_exist) 6242 << D->getDeclName() 6243 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 6244 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 6245 << Context.getTypeDeclType(Spec); 6246 } else { 6247 // We should have found something, but didn't. 6248 llvm_unreachable("Unable to find instantiation of declaration!"); 6249 } 6250 } 6251 6252 D = Result; 6253 } 6254 6255 return D; 6256 } 6257 6258 /// Performs template instantiation for all implicit template 6259 /// instantiations we have seen until this point. 6260 void Sema::PerformPendingInstantiations(bool LocalOnly) { 6261 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations; 6262 while (!PendingLocalImplicitInstantiations.empty() || 6263 (!LocalOnly && !PendingInstantiations.empty())) { 6264 PendingImplicitInstantiation Inst; 6265 6266 if (PendingLocalImplicitInstantiations.empty()) { 6267 Inst = PendingInstantiations.front(); 6268 PendingInstantiations.pop_front(); 6269 } else { 6270 Inst = PendingLocalImplicitInstantiations.front(); 6271 PendingLocalImplicitInstantiations.pop_front(); 6272 } 6273 6274 // Instantiate function definitions 6275 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 6276 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 6277 TSK_ExplicitInstantiationDefinition; 6278 if (Function->isMultiVersion()) { 6279 getASTContext().forEachMultiversionedFunctionVersion( 6280 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) { 6281 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true, 6282 DefinitionRequired, true); 6283 if (CurFD->isDefined()) 6284 CurFD->setInstantiationIsPending(false); 6285 }); 6286 } else { 6287 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true, 6288 DefinitionRequired, true); 6289 if (Function->isDefined()) 6290 Function->setInstantiationIsPending(false); 6291 } 6292 // Definition of a PCH-ed template declaration may be available only in the TU. 6293 if (!LocalOnly && LangOpts.PCHInstantiateTemplates && 6294 TUKind == TU_Prefix && Function->instantiationIsPending()) 6295 delayedPCHInstantiations.push_back(Inst); 6296 continue; 6297 } 6298 6299 // Instantiate variable definitions 6300 VarDecl *Var = cast<VarDecl>(Inst.first); 6301 6302 assert((Var->isStaticDataMember() || 6303 isa<VarTemplateSpecializationDecl>(Var)) && 6304 "Not a static data member, nor a variable template" 6305 " specialization?"); 6306 6307 // Don't try to instantiate declarations if the most recent redeclaration 6308 // is invalid. 6309 if (Var->getMostRecentDecl()->isInvalidDecl()) 6310 continue; 6311 6312 // Check if the most recent declaration has changed the specialization kind 6313 // and removed the need for implicit instantiation. 6314 switch (Var->getMostRecentDecl() 6315 ->getTemplateSpecializationKindForInstantiation()) { 6316 case TSK_Undeclared: 6317 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 6318 case TSK_ExplicitInstantiationDeclaration: 6319 case TSK_ExplicitSpecialization: 6320 continue; // No longer need to instantiate this type. 6321 case TSK_ExplicitInstantiationDefinition: 6322 // We only need an instantiation if the pending instantiation *is* the 6323 // explicit instantiation. 6324 if (Var != Var->getMostRecentDecl()) 6325 continue; 6326 break; 6327 case TSK_ImplicitInstantiation: 6328 break; 6329 } 6330 6331 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 6332 "instantiating variable definition"); 6333 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 6334 TSK_ExplicitInstantiationDefinition; 6335 6336 // Instantiate static data member definitions or variable template 6337 // specializations. 6338 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 6339 DefinitionRequired, true); 6340 } 6341 6342 if (!LocalOnly && LangOpts.PCHInstantiateTemplates) 6343 PendingInstantiations.swap(delayedPCHInstantiations); 6344 } 6345 6346 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 6347 const MultiLevelTemplateArgumentList &TemplateArgs) { 6348 for (auto DD : Pattern->ddiags()) { 6349 switch (DD->getKind()) { 6350 case DependentDiagnostic::Access: 6351 HandleDependentAccessCheck(*DD, TemplateArgs); 6352 break; 6353 } 6354 } 6355 } 6356