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