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