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 // FIXME: Concepts: Do not substitute into constraint expressions 2066 Expr *TrailingRequiresClause = D->getTrailingRequiresClause(); 2067 if (TrailingRequiresClause) { 2068 EnterExpressionEvaluationContext ConstantEvaluated( 2069 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated); 2070 ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause, 2071 TemplateArgs); 2072 if (SubstRC.isInvalid()) 2073 return nullptr; 2074 TrailingRequiresClause = SubstRC.get(); 2075 if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause)) 2076 return nullptr; 2077 } 2078 2079 // If we're instantiating a local function declaration, put the result 2080 // in the enclosing namespace; otherwise we need to find the instantiated 2081 // context. 2082 DeclContext *DC; 2083 if (D->isLocalExternDecl()) { 2084 DC = Owner; 2085 SemaRef.adjustContextForLocalExternDecl(DC); 2086 } else if (isFriend && QualifierLoc) { 2087 CXXScopeSpec SS; 2088 SS.Adopt(QualifierLoc); 2089 DC = SemaRef.computeDeclContext(SS); 2090 if (!DC) return nullptr; 2091 } else { 2092 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(), 2093 TemplateArgs); 2094 } 2095 2096 DeclarationNameInfo NameInfo 2097 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2098 2099 if (FunctionRewriteKind != RewriteKind::None) 2100 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo); 2101 2102 FunctionDecl *Function; 2103 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) { 2104 Function = CXXDeductionGuideDecl::Create( 2105 SemaRef.Context, DC, D->getInnerLocStart(), 2106 InstantiatedExplicitSpecifier, NameInfo, T, TInfo, 2107 D->getSourceRange().getEnd()); 2108 if (DGuide->isCopyDeductionCandidate()) 2109 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate(); 2110 Function->setAccess(D->getAccess()); 2111 } else { 2112 Function = FunctionDecl::Create( 2113 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo, 2114 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(), 2115 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(), 2116 TrailingRequiresClause); 2117 Function->setRangeEnd(D->getSourceRange().getEnd()); 2118 } 2119 2120 if (D->isInlined()) 2121 Function->setImplicitlyInline(); 2122 2123 if (QualifierLoc) 2124 Function->setQualifierInfo(QualifierLoc); 2125 2126 if (D->isLocalExternDecl()) 2127 Function->setLocalExternDecl(); 2128 2129 DeclContext *LexicalDC = Owner; 2130 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) { 2131 assert(D->getDeclContext()->isFileContext()); 2132 LexicalDC = D->getDeclContext(); 2133 } 2134 2135 Function->setLexicalDeclContext(LexicalDC); 2136 2137 // Attach the parameters 2138 for (unsigned P = 0; P < Params.size(); ++P) 2139 if (Params[P]) 2140 Params[P]->setOwningFunction(Function); 2141 Function->setParams(Params); 2142 2143 if (TrailingRequiresClause) 2144 Function->setTrailingRequiresClause(TrailingRequiresClause); 2145 2146 if (TemplateParams) { 2147 // Our resulting instantiation is actually a function template, since we 2148 // are substituting only the outer template parameters. For example, given 2149 // 2150 // template<typename T> 2151 // struct X { 2152 // template<typename U> friend void f(T, U); 2153 // }; 2154 // 2155 // X<int> x; 2156 // 2157 // We are instantiating the friend function template "f" within X<int>, 2158 // which means substituting int for T, but leaving "f" as a friend function 2159 // template. 2160 // Build the function template itself. 2161 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC, 2162 Function->getLocation(), 2163 Function->getDeclName(), 2164 TemplateParams, Function); 2165 Function->setDescribedFunctionTemplate(FunctionTemplate); 2166 2167 FunctionTemplate->setLexicalDeclContext(LexicalDC); 2168 2169 if (isFriend && D->isThisDeclarationADefinition()) { 2170 FunctionTemplate->setInstantiatedFromMemberTemplate( 2171 D->getDescribedFunctionTemplate()); 2172 } 2173 } else if (FunctionTemplate) { 2174 // Record this function template specialization. 2175 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 2176 Function->setFunctionTemplateSpecialization(FunctionTemplate, 2177 TemplateArgumentList::CreateCopy(SemaRef.Context, 2178 Innermost), 2179 /*InsertPos=*/nullptr); 2180 } else if (isFriend && D->isThisDeclarationADefinition()) { 2181 // Do not connect the friend to the template unless it's actually a 2182 // definition. We don't want non-template functions to be marked as being 2183 // template instantiations. 2184 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 2185 } 2186 2187 if (isFriend) { 2188 Function->setObjectOfFriendDecl(); 2189 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate()) 2190 FT->setObjectOfFriendDecl(); 2191 } 2192 2193 if (InitFunctionInstantiation(Function, D)) 2194 Function->setInvalidDecl(); 2195 2196 bool IsExplicitSpecialization = false; 2197 2198 LookupResult Previous( 2199 SemaRef, Function->getDeclName(), SourceLocation(), 2200 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 2201 : Sema::LookupOrdinaryName, 2202 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration 2203 : SemaRef.forRedeclarationInCurContext()); 2204 2205 if (DependentFunctionTemplateSpecializationInfo *Info 2206 = D->getDependentSpecializationInfo()) { 2207 assert(isFriend && "non-friend has dependent specialization info?"); 2208 2209 // Instantiate the explicit template arguments. 2210 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2211 Info->getRAngleLoc()); 2212 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs, 2213 ExplicitArgs)) 2214 return nullptr; 2215 2216 // Map the candidate templates to their instantiations. 2217 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 2218 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 2219 Info->getTemplate(I), 2220 TemplateArgs); 2221 if (!Temp) return nullptr; 2222 2223 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 2224 } 2225 2226 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 2227 &ExplicitArgs, 2228 Previous)) 2229 Function->setInvalidDecl(); 2230 2231 IsExplicitSpecialization = true; 2232 } else if (const ASTTemplateArgumentListInfo *Info = 2233 D->getTemplateSpecializationArgsAsWritten()) { 2234 // The name of this function was written as a template-id. 2235 SemaRef.LookupQualifiedName(Previous, DC); 2236 2237 // Instantiate the explicit template arguments. 2238 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2239 Info->getRAngleLoc()); 2240 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs, 2241 ExplicitArgs)) 2242 return nullptr; 2243 2244 if (SemaRef.CheckFunctionTemplateSpecialization(Function, 2245 &ExplicitArgs, 2246 Previous)) 2247 Function->setInvalidDecl(); 2248 2249 IsExplicitSpecialization = true; 2250 } else if (TemplateParams || !FunctionTemplate) { 2251 // Look only into the namespace where the friend would be declared to 2252 // find a previous declaration. This is the innermost enclosing namespace, 2253 // as described in ActOnFriendFunctionDecl. 2254 SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext()); 2255 2256 // In C++, the previous declaration we find might be a tag type 2257 // (class or enum). In this case, the new declaration will hide the 2258 // tag type. Note that this does does not apply if we're declaring a 2259 // typedef (C++ [dcl.typedef]p4). 2260 if (Previous.isSingleTagDecl()) 2261 Previous.clear(); 2262 2263 // Filter out previous declarations that don't match the scope. The only 2264 // effect this has is to remove declarations found in inline namespaces 2265 // for friend declarations with unqualified names. 2266 SemaRef.FilterLookupForScope(Previous, DC, /*Scope*/ nullptr, 2267 /*ConsiderLinkage*/ true, 2268 QualifierLoc.hasQualifier()); 2269 } 2270 2271 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous, 2272 IsExplicitSpecialization, 2273 Function->isThisDeclarationADefinition()); 2274 2275 // Check the template parameter list against the previous declaration. The 2276 // goal here is to pick up default arguments added since the friend was 2277 // declared; we know the template parameter lists match, since otherwise 2278 // we would not have picked this template as the previous declaration. 2279 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) { 2280 SemaRef.CheckTemplateParameterList( 2281 TemplateParams, 2282 FunctionTemplate->getPreviousDecl()->getTemplateParameters(), 2283 Function->isThisDeclarationADefinition() 2284 ? Sema::TPC_FriendFunctionTemplateDefinition 2285 : Sema::TPC_FriendFunctionTemplate); 2286 } 2287 2288 // If we're introducing a friend definition after the first use, trigger 2289 // instantiation. 2290 // FIXME: If this is a friend function template definition, we should check 2291 // to see if any specializations have been used. 2292 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) { 2293 if (MemberSpecializationInfo *MSInfo = 2294 Function->getMemberSpecializationInfo()) { 2295 if (MSInfo->getPointOfInstantiation().isInvalid()) { 2296 SourceLocation Loc = D->getLocation(); // FIXME 2297 MSInfo->setPointOfInstantiation(Loc); 2298 SemaRef.PendingLocalImplicitInstantiations.push_back( 2299 std::make_pair(Function, Loc)); 2300 } 2301 } 2302 } 2303 2304 if (D->isExplicitlyDefaulted()) { 2305 if (SubstDefaultedFunction(Function, D)) 2306 return nullptr; 2307 } 2308 if (D->isDeleted()) 2309 SemaRef.SetDeclDeleted(Function, D->getLocation()); 2310 2311 NamedDecl *PrincipalDecl = 2312 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function); 2313 2314 // If this declaration lives in a different context from its lexical context, 2315 // add it to the corresponding lookup table. 2316 if (isFriend || 2317 (Function->isLocalExternDecl() && !Function->getPreviousDecl())) 2318 DC->makeDeclVisibleInContext(PrincipalDecl); 2319 2320 if (Function->isOverloadedOperator() && !DC->isRecord() && 2321 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 2322 PrincipalDecl->setNonMemberOperator(); 2323 2324 return Function; 2325 } 2326 2327 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl( 2328 CXXMethodDecl *D, TemplateParameterList *TemplateParams, 2329 Optional<const ASTTemplateArgumentListInfo *> ClassScopeSpecializationArgs, 2330 RewriteKind FunctionRewriteKind) { 2331 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); 2332 if (FunctionTemplate && !TemplateParams) { 2333 // We are creating a function template specialization from a function 2334 // template. Check whether there is already a function template 2335 // specialization for this particular set of template arguments. 2336 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 2337 2338 void *InsertPos = nullptr; 2339 FunctionDecl *SpecFunc 2340 = FunctionTemplate->findSpecialization(Innermost, InsertPos); 2341 2342 // If we already have a function template specialization, return it. 2343 if (SpecFunc) 2344 return SpecFunc; 2345 } 2346 2347 bool isFriend; 2348 if (FunctionTemplate) 2349 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); 2350 else 2351 isFriend = (D->getFriendObjectKind() != Decl::FOK_None); 2352 2353 bool MergeWithParentScope = (TemplateParams != nullptr) || 2354 !(isa<Decl>(Owner) && 2355 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod()); 2356 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); 2357 2358 // Instantiate enclosing template arguments for friends. 2359 SmallVector<TemplateParameterList *, 4> TempParamLists; 2360 unsigned NumTempParamLists = 0; 2361 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { 2362 TempParamLists.resize(NumTempParamLists); 2363 for (unsigned I = 0; I != NumTempParamLists; ++I) { 2364 TemplateParameterList *TempParams = D->getTemplateParameterList(I); 2365 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 2366 if (!InstParams) 2367 return nullptr; 2368 TempParamLists[I] = InstParams; 2369 } 2370 } 2371 2372 ExplicitSpecifier InstantiatedExplicitSpecifier = 2373 instantiateExplicitSpecifier(SemaRef, TemplateArgs, 2374 ExplicitSpecifier::getFromDecl(D), D); 2375 if (InstantiatedExplicitSpecifier.isInvalid()) 2376 return nullptr; 2377 2378 // Implicit destructors/constructors created for local classes in 2379 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI. 2380 // Unfortunately there isn't enough context in those functions to 2381 // conditionally populate the TSI without breaking non-template related use 2382 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get 2383 // a proper transformation. 2384 if (cast<CXXRecordDecl>(D->getParent())->isLambda() && 2385 !D->getTypeSourceInfo() && 2386 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) { 2387 TypeSourceInfo *TSI = 2388 SemaRef.Context.getTrivialTypeSourceInfo(D->getType()); 2389 D->setTypeSourceInfo(TSI); 2390 } 2391 2392 SmallVector<ParmVarDecl *, 4> Params; 2393 TypeSourceInfo *TInfo = SubstFunctionType(D, Params); 2394 if (!TInfo) 2395 return nullptr; 2396 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); 2397 2398 if (TemplateParams && TemplateParams->size()) { 2399 auto *LastParam = 2400 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back()); 2401 if (LastParam && LastParam->isImplicit() && 2402 LastParam->hasTypeConstraint()) { 2403 // In abbreviated templates, the type-constraints of invented template 2404 // type parameters are instantiated with the function type, invalidating 2405 // the TemplateParameterList which relied on the template type parameter 2406 // not having a type constraint. Recreate the TemplateParameterList with 2407 // the updated parameter list. 2408 TemplateParams = TemplateParameterList::Create( 2409 SemaRef.Context, TemplateParams->getTemplateLoc(), 2410 TemplateParams->getLAngleLoc(), TemplateParams->asArray(), 2411 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause()); 2412 } 2413 } 2414 2415 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); 2416 if (QualifierLoc) { 2417 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 2418 TemplateArgs); 2419 if (!QualifierLoc) 2420 return nullptr; 2421 } 2422 2423 // FIXME: Concepts: Do not substitute into constraint expressions 2424 Expr *TrailingRequiresClause = D->getTrailingRequiresClause(); 2425 if (TrailingRequiresClause) { 2426 EnterExpressionEvaluationContext ConstantEvaluated( 2427 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated); 2428 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 2429 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, 2430 D->getMethodQualifiers(), ThisContext); 2431 ExprResult SubstRC = SemaRef.SubstExpr(TrailingRequiresClause, 2432 TemplateArgs); 2433 if (SubstRC.isInvalid()) 2434 return nullptr; 2435 TrailingRequiresClause = SubstRC.get(); 2436 if (!SemaRef.CheckConstraintExpression(TrailingRequiresClause)) 2437 return nullptr; 2438 } 2439 2440 DeclContext *DC = Owner; 2441 if (isFriend) { 2442 if (QualifierLoc) { 2443 CXXScopeSpec SS; 2444 SS.Adopt(QualifierLoc); 2445 DC = SemaRef.computeDeclContext(SS); 2446 2447 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) 2448 return nullptr; 2449 } else { 2450 DC = SemaRef.FindInstantiatedContext(D->getLocation(), 2451 D->getDeclContext(), 2452 TemplateArgs); 2453 } 2454 if (!DC) return nullptr; 2455 } 2456 2457 DeclarationNameInfo NameInfo 2458 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 2459 2460 if (FunctionRewriteKind != RewriteKind::None) 2461 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo); 2462 2463 // Build the instantiated method declaration. 2464 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 2465 CXXMethodDecl *Method = nullptr; 2466 2467 SourceLocation StartLoc = D->getInnerLocStart(); 2468 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 2469 Method = CXXConstructorDecl::Create( 2470 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2471 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(), 2472 Constructor->isInlineSpecified(), false, 2473 Constructor->getConstexprKind(), InheritedConstructor(), 2474 TrailingRequiresClause); 2475 Method->setRangeEnd(Constructor->getEndLoc()); 2476 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) { 2477 Method = CXXDestructorDecl::Create( 2478 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2479 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false, 2480 Destructor->getConstexprKind(), TrailingRequiresClause); 2481 Method->setRangeEnd(Destructor->getEndLoc()); 2482 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName( 2483 SemaRef.Context.getCanonicalType( 2484 SemaRef.Context.getTypeDeclType(Record)))); 2485 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) { 2486 Method = CXXConversionDecl::Create( 2487 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, 2488 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(), 2489 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(), 2490 Conversion->getEndLoc(), TrailingRequiresClause); 2491 } else { 2492 StorageClass SC = D->isStatic() ? SC_Static : SC_None; 2493 Method = CXXMethodDecl::Create( 2494 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC, 2495 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(), 2496 D->getEndLoc(), TrailingRequiresClause); 2497 } 2498 2499 if (D->isInlined()) 2500 Method->setImplicitlyInline(); 2501 2502 if (QualifierLoc) 2503 Method->setQualifierInfo(QualifierLoc); 2504 2505 if (TemplateParams) { 2506 // Our resulting instantiation is actually a function template, since we 2507 // are substituting only the outer template parameters. For example, given 2508 // 2509 // template<typename T> 2510 // struct X { 2511 // template<typename U> void f(T, U); 2512 // }; 2513 // 2514 // X<int> x; 2515 // 2516 // We are instantiating the member template "f" within X<int>, which means 2517 // substituting int for T, but leaving "f" as a member function template. 2518 // Build the function template itself. 2519 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record, 2520 Method->getLocation(), 2521 Method->getDeclName(), 2522 TemplateParams, Method); 2523 if (isFriend) { 2524 FunctionTemplate->setLexicalDeclContext(Owner); 2525 FunctionTemplate->setObjectOfFriendDecl(); 2526 } else if (D->isOutOfLine()) 2527 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); 2528 Method->setDescribedFunctionTemplate(FunctionTemplate); 2529 } else if (FunctionTemplate) { 2530 // Record this function template specialization. 2531 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); 2532 Method->setFunctionTemplateSpecialization(FunctionTemplate, 2533 TemplateArgumentList::CreateCopy(SemaRef.Context, 2534 Innermost), 2535 /*InsertPos=*/nullptr); 2536 } else if (!isFriend) { 2537 // Record that this is an instantiation of a member function. 2538 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); 2539 } 2540 2541 // If we are instantiating a member function defined 2542 // out-of-line, the instantiation will have the same lexical 2543 // context (which will be a namespace scope) as the template. 2544 if (isFriend) { 2545 if (NumTempParamLists) 2546 Method->setTemplateParameterListsInfo( 2547 SemaRef.Context, 2548 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists)); 2549 2550 Method->setLexicalDeclContext(Owner); 2551 Method->setObjectOfFriendDecl(); 2552 } else if (D->isOutOfLine()) 2553 Method->setLexicalDeclContext(D->getLexicalDeclContext()); 2554 2555 // Attach the parameters 2556 for (unsigned P = 0; P < Params.size(); ++P) 2557 Params[P]->setOwningFunction(Method); 2558 Method->setParams(Params); 2559 2560 if (InitMethodInstantiation(Method, D)) 2561 Method->setInvalidDecl(); 2562 2563 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, 2564 Sema::ForExternalRedeclaration); 2565 2566 bool IsExplicitSpecialization = false; 2567 2568 // If the name of this function was written as a template-id, instantiate 2569 // the explicit template arguments. 2570 if (DependentFunctionTemplateSpecializationInfo *Info 2571 = D->getDependentSpecializationInfo()) { 2572 assert(isFriend && "non-friend has dependent specialization info?"); 2573 2574 // Instantiate the explicit template arguments. 2575 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2576 Info->getRAngleLoc()); 2577 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs, 2578 ExplicitArgs)) 2579 return nullptr; 2580 2581 // Map the candidate templates to their instantiations. 2582 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) { 2583 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(), 2584 Info->getTemplate(I), 2585 TemplateArgs); 2586 if (!Temp) return nullptr; 2587 2588 Previous.addDecl(cast<FunctionTemplateDecl>(Temp)); 2589 } 2590 2591 if (SemaRef.CheckFunctionTemplateSpecialization(Method, 2592 &ExplicitArgs, 2593 Previous)) 2594 Method->setInvalidDecl(); 2595 2596 IsExplicitSpecialization = true; 2597 } else if (const ASTTemplateArgumentListInfo *Info = 2598 ClassScopeSpecializationArgs.getValueOr( 2599 D->getTemplateSpecializationArgsAsWritten())) { 2600 SemaRef.LookupQualifiedName(Previous, DC); 2601 2602 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(), 2603 Info->getRAngleLoc()); 2604 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs, 2605 ExplicitArgs)) 2606 return nullptr; 2607 2608 if (SemaRef.CheckFunctionTemplateSpecialization(Method, 2609 &ExplicitArgs, 2610 Previous)) 2611 Method->setInvalidDecl(); 2612 2613 IsExplicitSpecialization = true; 2614 } else if (ClassScopeSpecializationArgs) { 2615 // Class-scope explicit specialization written without explicit template 2616 // arguments. 2617 SemaRef.LookupQualifiedName(Previous, DC); 2618 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous)) 2619 Method->setInvalidDecl(); 2620 2621 IsExplicitSpecialization = true; 2622 } else if (!FunctionTemplate || TemplateParams || isFriend) { 2623 SemaRef.LookupQualifiedName(Previous, Record); 2624 2625 // In C++, the previous declaration we find might be a tag type 2626 // (class or enum). In this case, the new declaration will hide the 2627 // tag type. Note that this does does not apply if we're declaring a 2628 // typedef (C++ [dcl.typedef]p4). 2629 if (Previous.isSingleTagDecl()) 2630 Previous.clear(); 2631 } 2632 2633 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, 2634 IsExplicitSpecialization, 2635 Method->isThisDeclarationADefinition()); 2636 2637 if (D->isPure()) 2638 SemaRef.CheckPureMethod(Method, SourceRange()); 2639 2640 // Propagate access. For a non-friend declaration, the access is 2641 // whatever we're propagating from. For a friend, it should be the 2642 // previous declaration we just found. 2643 if (isFriend && Method->getPreviousDecl()) 2644 Method->setAccess(Method->getPreviousDecl()->getAccess()); 2645 else 2646 Method->setAccess(D->getAccess()); 2647 if (FunctionTemplate) 2648 FunctionTemplate->setAccess(Method->getAccess()); 2649 2650 SemaRef.CheckOverrideControl(Method); 2651 2652 // If a function is defined as defaulted or deleted, mark it as such now. 2653 if (D->isExplicitlyDefaulted()) { 2654 if (SubstDefaultedFunction(Method, D)) 2655 return nullptr; 2656 } 2657 if (D->isDeletedAsWritten()) 2658 SemaRef.SetDeclDeleted(Method, Method->getLocation()); 2659 2660 // If this is an explicit specialization, mark the implicitly-instantiated 2661 // template specialization as being an explicit specialization too. 2662 // FIXME: Is this necessary? 2663 if (IsExplicitSpecialization && !isFriend) 2664 SemaRef.CompleteMemberSpecialization(Method, Previous); 2665 2666 // If there's a function template, let our caller handle it. 2667 if (FunctionTemplate) { 2668 // do nothing 2669 2670 // Don't hide a (potentially) valid declaration with an invalid one. 2671 } else if (Method->isInvalidDecl() && !Previous.empty()) { 2672 // do nothing 2673 2674 // Otherwise, check access to friends and make them visible. 2675 } else if (isFriend) { 2676 // We only need to re-check access for methods which we didn't 2677 // manage to match during parsing. 2678 if (!D->getPreviousDecl()) 2679 SemaRef.CheckFriendAccess(Method); 2680 2681 Record->makeDeclVisibleInContext(Method); 2682 2683 // Otherwise, add the declaration. We don't need to do this for 2684 // class-scope specializations because we'll have matched them with 2685 // the appropriate template. 2686 } else { 2687 Owner->addDecl(Method); 2688 } 2689 2690 // PR17480: Honor the used attribute to instantiate member function 2691 // definitions 2692 if (Method->hasAttr<UsedAttr>()) { 2693 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) { 2694 SourceLocation Loc; 2695 if (const MemberSpecializationInfo *MSInfo = 2696 A->getMemberSpecializationInfo()) 2697 Loc = MSInfo->getPointOfInstantiation(); 2698 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A)) 2699 Loc = Spec->getPointOfInstantiation(); 2700 SemaRef.MarkFunctionReferenced(Loc, Method); 2701 } 2702 } 2703 2704 return Method; 2705 } 2706 2707 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 2708 return VisitCXXMethodDecl(D); 2709 } 2710 2711 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 2712 return VisitCXXMethodDecl(D); 2713 } 2714 2715 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { 2716 return VisitCXXMethodDecl(D); 2717 } 2718 2719 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { 2720 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None, 2721 /*ExpectParameterPack=*/ false); 2722 } 2723 2724 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( 2725 TemplateTypeParmDecl *D) { 2726 assert(D->getTypeForDecl()->isTemplateTypeParmType()); 2727 2728 Optional<unsigned> NumExpanded; 2729 2730 if (const TypeConstraint *TC = D->getTypeConstraint()) { 2731 if (D->isPackExpansion() && !D->isExpandedParameterPack()) { 2732 assert(TC->getTemplateArgsAsWritten() && 2733 "type parameter can only be an expansion when explicit arguments " 2734 "are specified"); 2735 // The template type parameter pack's type is a pack expansion of types. 2736 // Determine whether we need to expand this parameter pack into separate 2737 // types. 2738 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2739 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments()) 2740 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded); 2741 2742 // Determine whether the set of unexpanded parameter packs can and should 2743 // be expanded. 2744 bool Expand = true; 2745 bool RetainExpansion = false; 2746 if (SemaRef.CheckParameterPacksForExpansion( 2747 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint()) 2748 ->getEllipsisLoc(), 2749 SourceRange(TC->getConceptNameLoc(), 2750 TC->hasExplicitTemplateArgs() ? 2751 TC->getTemplateArgsAsWritten()->getRAngleLoc() : 2752 TC->getConceptNameInfo().getEndLoc()), 2753 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded)) 2754 return nullptr; 2755 } 2756 } 2757 2758 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create( 2759 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(), 2760 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(), 2761 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(), 2762 D->hasTypeConstraint(), NumExpanded); 2763 2764 Inst->setAccess(AS_public); 2765 Inst->setImplicit(D->isImplicit()); 2766 if (auto *TC = D->getTypeConstraint()) { 2767 if (!D->isImplicit()) { 2768 // Invented template parameter type constraints will be instantiated with 2769 // the corresponding auto-typed parameter as it might reference other 2770 // parameters. 2771 2772 // TODO: Concepts: do not instantiate the constraint (delayed constraint 2773 // substitution) 2774 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs)) 2775 return nullptr; 2776 } 2777 } 2778 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2779 TypeSourceInfo *InstantiatedDefaultArg = 2780 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, 2781 D->getDefaultArgumentLoc(), D->getDeclName()); 2782 if (InstantiatedDefaultArg) 2783 Inst->setDefaultArgument(InstantiatedDefaultArg); 2784 } 2785 2786 // Introduce this template parameter's instantiation into the instantiation 2787 // scope. 2788 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); 2789 2790 return Inst; 2791 } 2792 2793 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( 2794 NonTypeTemplateParmDecl *D) { 2795 // Substitute into the type of the non-type template parameter. 2796 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); 2797 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; 2798 SmallVector<QualType, 4> ExpandedParameterPackTypes; 2799 bool IsExpandedParameterPack = false; 2800 TypeSourceInfo *DI; 2801 QualType T; 2802 bool Invalid = false; 2803 2804 if (D->isExpandedParameterPack()) { 2805 // The non-type template parameter pack is an already-expanded pack 2806 // expansion of types. Substitute into each of the expanded types. 2807 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes()); 2808 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes()); 2809 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { 2810 TypeSourceInfo *NewDI = 2811 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs, 2812 D->getLocation(), D->getDeclName()); 2813 if (!NewDI) 2814 return nullptr; 2815 2816 QualType NewT = 2817 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2818 if (NewT.isNull()) 2819 return nullptr; 2820 2821 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2822 ExpandedParameterPackTypes.push_back(NewT); 2823 } 2824 2825 IsExpandedParameterPack = true; 2826 DI = D->getTypeSourceInfo(); 2827 T = DI->getType(); 2828 } else if (D->isPackExpansion()) { 2829 // The non-type template parameter pack's type is a pack expansion of types. 2830 // Determine whether we need to expand this parameter pack into separate 2831 // types. 2832 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); 2833 TypeLoc Pattern = Expansion.getPatternLoc(); 2834 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2835 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); 2836 2837 // Determine whether the set of unexpanded parameter packs can and should 2838 // be expanded. 2839 bool Expand = true; 2840 bool RetainExpansion = false; 2841 Optional<unsigned> OrigNumExpansions 2842 = Expansion.getTypePtr()->getNumExpansions(); 2843 Optional<unsigned> NumExpansions = OrigNumExpansions; 2844 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(), 2845 Pattern.getSourceRange(), 2846 Unexpanded, 2847 TemplateArgs, 2848 Expand, RetainExpansion, 2849 NumExpansions)) 2850 return nullptr; 2851 2852 if (Expand) { 2853 for (unsigned I = 0; I != *NumExpansions; ++I) { 2854 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 2855 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, 2856 D->getLocation(), 2857 D->getDeclName()); 2858 if (!NewDI) 2859 return nullptr; 2860 2861 QualType NewT = 2862 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); 2863 if (NewT.isNull()) 2864 return nullptr; 2865 2866 ExpandedParameterPackTypesAsWritten.push_back(NewDI); 2867 ExpandedParameterPackTypes.push_back(NewT); 2868 } 2869 2870 // Note that we have an expanded parameter pack. The "type" of this 2871 // expanded parameter pack is the original expansion type, but callers 2872 // will end up using the expanded parameter pack types for type-checking. 2873 IsExpandedParameterPack = true; 2874 DI = D->getTypeSourceInfo(); 2875 T = DI->getType(); 2876 } else { 2877 // We cannot fully expand the pack expansion now, so substitute into the 2878 // pattern and create a new pack expansion type. 2879 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 2880 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, 2881 D->getLocation(), 2882 D->getDeclName()); 2883 if (!NewPattern) 2884 return nullptr; 2885 2886 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation()); 2887 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(), 2888 NumExpansions); 2889 if (!DI) 2890 return nullptr; 2891 2892 T = DI->getType(); 2893 } 2894 } else { 2895 // Simple case: substitution into a parameter that is not a parameter pack. 2896 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 2897 D->getLocation(), D->getDeclName()); 2898 if (!DI) 2899 return nullptr; 2900 2901 // Check that this type is acceptable for a non-type template parameter. 2902 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation()); 2903 if (T.isNull()) { 2904 T = SemaRef.Context.IntTy; 2905 Invalid = true; 2906 } 2907 } 2908 2909 NonTypeTemplateParmDecl *Param; 2910 if (IsExpandedParameterPack) 2911 Param = NonTypeTemplateParmDecl::Create( 2912 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2913 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2914 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes, 2915 ExpandedParameterPackTypesAsWritten); 2916 else 2917 Param = NonTypeTemplateParmDecl::Create( 2918 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 2919 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 2920 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI); 2921 2922 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc()) 2923 if (AutoLoc.isConstrained()) 2924 if (SemaRef.AttachTypeConstraint( 2925 AutoLoc, Param, 2926 IsExpandedParameterPack 2927 ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>() 2928 .getEllipsisLoc() 2929 : SourceLocation())) 2930 Invalid = true; 2931 2932 Param->setAccess(AS_public); 2933 Param->setImplicit(D->isImplicit()); 2934 if (Invalid) 2935 Param->setInvalidDecl(); 2936 2937 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 2938 EnterExpressionEvaluationContext ConstantEvaluated( 2939 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 2940 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs); 2941 if (!Value.isInvalid()) 2942 Param->setDefaultArgument(Value.get()); 2943 } 2944 2945 // Introduce this template parameter's instantiation into the instantiation 2946 // scope. 2947 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 2948 return Param; 2949 } 2950 2951 static void collectUnexpandedParameterPacks( 2952 Sema &S, 2953 TemplateParameterList *Params, 2954 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { 2955 for (const auto &P : *Params) { 2956 if (P->isTemplateParameterPack()) 2957 continue; 2958 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) 2959 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), 2960 Unexpanded); 2961 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P)) 2962 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), 2963 Unexpanded); 2964 } 2965 } 2966 2967 Decl * 2968 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( 2969 TemplateTemplateParmDecl *D) { 2970 // Instantiate the template parameter list of the template template parameter. 2971 TemplateParameterList *TempParams = D->getTemplateParameters(); 2972 TemplateParameterList *InstParams; 2973 SmallVector<TemplateParameterList*, 8> ExpandedParams; 2974 2975 bool IsExpandedParameterPack = false; 2976 2977 if (D->isExpandedParameterPack()) { 2978 // The template template parameter pack is an already-expanded pack 2979 // expansion of template parameters. Substitute into each of the expanded 2980 // parameters. 2981 ExpandedParams.reserve(D->getNumExpansionTemplateParameters()); 2982 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); 2983 I != N; ++I) { 2984 LocalInstantiationScope Scope(SemaRef); 2985 TemplateParameterList *Expansion = 2986 SubstTemplateParams(D->getExpansionTemplateParameters(I)); 2987 if (!Expansion) 2988 return nullptr; 2989 ExpandedParams.push_back(Expansion); 2990 } 2991 2992 IsExpandedParameterPack = true; 2993 InstParams = TempParams; 2994 } else if (D->isPackExpansion()) { 2995 // The template template parameter pack expands to a pack of template 2996 // template parameters. Determine whether we need to expand this parameter 2997 // pack into separate parameters. 2998 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 2999 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), 3000 Unexpanded); 3001 3002 // Determine whether the set of unexpanded parameter packs can and should 3003 // be expanded. 3004 bool Expand = true; 3005 bool RetainExpansion = false; 3006 Optional<unsigned> NumExpansions; 3007 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(), 3008 TempParams->getSourceRange(), 3009 Unexpanded, 3010 TemplateArgs, 3011 Expand, RetainExpansion, 3012 NumExpansions)) 3013 return nullptr; 3014 3015 if (Expand) { 3016 for (unsigned I = 0; I != *NumExpansions; ++I) { 3017 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 3018 LocalInstantiationScope Scope(SemaRef); 3019 TemplateParameterList *Expansion = SubstTemplateParams(TempParams); 3020 if (!Expansion) 3021 return nullptr; 3022 ExpandedParams.push_back(Expansion); 3023 } 3024 3025 // Note that we have an expanded parameter pack. The "type" of this 3026 // expanded parameter pack is the original expansion type, but callers 3027 // will end up using the expanded parameter pack types for type-checking. 3028 IsExpandedParameterPack = true; 3029 InstParams = TempParams; 3030 } else { 3031 // We cannot fully expand the pack expansion now, so just substitute 3032 // into the pattern. 3033 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 3034 3035 LocalInstantiationScope Scope(SemaRef); 3036 InstParams = SubstTemplateParams(TempParams); 3037 if (!InstParams) 3038 return nullptr; 3039 } 3040 } else { 3041 // Perform the actual substitution of template parameters within a new, 3042 // local instantiation scope. 3043 LocalInstantiationScope Scope(SemaRef); 3044 InstParams = SubstTemplateParams(TempParams); 3045 if (!InstParams) 3046 return nullptr; 3047 } 3048 3049 // Build the template template parameter. 3050 TemplateTemplateParmDecl *Param; 3051 if (IsExpandedParameterPack) 3052 Param = TemplateTemplateParmDecl::Create( 3053 SemaRef.Context, Owner, D->getLocation(), 3054 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 3055 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams); 3056 else 3057 Param = TemplateTemplateParmDecl::Create( 3058 SemaRef.Context, Owner, D->getLocation(), 3059 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), 3060 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams); 3061 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { 3062 NestedNameSpecifierLoc QualifierLoc = 3063 D->getDefaultArgument().getTemplateQualifierLoc(); 3064 QualifierLoc = 3065 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs); 3066 TemplateName TName = SemaRef.SubstTemplateName( 3067 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(), 3068 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); 3069 if (!TName.isNull()) 3070 Param->setDefaultArgument( 3071 SemaRef.Context, 3072 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName), 3073 D->getDefaultArgument().getTemplateQualifierLoc(), 3074 D->getDefaultArgument().getTemplateNameLoc())); 3075 } 3076 Param->setAccess(AS_public); 3077 Param->setImplicit(D->isImplicit()); 3078 3079 // Introduce this template parameter's instantiation into the instantiation 3080 // scope. 3081 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); 3082 3083 return Param; 3084 } 3085 3086 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 3087 // Using directives are never dependent (and never contain any types or 3088 // expressions), so they require no explicit instantiation work. 3089 3090 UsingDirectiveDecl *Inst 3091 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(), 3092 D->getNamespaceKeyLocation(), 3093 D->getQualifierLoc(), 3094 D->getIdentLocation(), 3095 D->getNominatedNamespace(), 3096 D->getCommonAncestor()); 3097 3098 // Add the using directive to its declaration context 3099 // only if this is not a function or method. 3100 if (!Owner->isFunctionOrMethod()) 3101 Owner->addDecl(Inst); 3102 3103 return Inst; 3104 } 3105 3106 Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D, 3107 BaseUsingDecl *Inst, 3108 LookupResult *Lookup) { 3109 3110 bool isFunctionScope = Owner->isFunctionOrMethod(); 3111 3112 for (auto *Shadow : D->shadows()) { 3113 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so 3114 // reconstruct it in the case where it matters. Hm, can we extract it from 3115 // the DeclSpec when parsing and save it in the UsingDecl itself? 3116 NamedDecl *OldTarget = Shadow->getTargetDecl(); 3117 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow)) 3118 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl()) 3119 OldTarget = BaseShadow; 3120 3121 NamedDecl *InstTarget = nullptr; 3122 if (auto *EmptyD = 3123 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) { 3124 InstTarget = UnresolvedUsingIfExistsDecl::Create( 3125 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName()); 3126 } else { 3127 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( 3128 Shadow->getLocation(), OldTarget, TemplateArgs)); 3129 } 3130 if (!InstTarget) 3131 return nullptr; 3132 3133 UsingShadowDecl *PrevDecl = nullptr; 3134 if (Lookup && 3135 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl)) 3136 continue; 3137 3138 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow)) 3139 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( 3140 Shadow->getLocation(), OldPrev, TemplateArgs)); 3141 3142 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl( 3143 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl); 3144 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow); 3145 3146 if (isFunctionScope) 3147 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); 3148 } 3149 3150 return Inst; 3151 } 3152 3153 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { 3154 3155 // The nested name specifier may be dependent, for example 3156 // template <typename T> struct t { 3157 // struct s1 { T f1(); }; 3158 // struct s2 : s1 { using s1::f1; }; 3159 // }; 3160 // template struct t<int>; 3161 // Here, in using s1::f1, s1 refers to t<T>::s1; 3162 // we need to substitute for t<int>::s1. 3163 NestedNameSpecifierLoc QualifierLoc 3164 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 3165 TemplateArgs); 3166 if (!QualifierLoc) 3167 return nullptr; 3168 3169 // For an inheriting constructor declaration, the name of the using 3170 // declaration is the name of a constructor in this class, not in the 3171 // base class. 3172 DeclarationNameInfo NameInfo = D->getNameInfo(); 3173 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 3174 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext)) 3175 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName( 3176 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD)))); 3177 3178 // We only need to do redeclaration lookups if we're in a class scope (in 3179 // fact, it's not really even possible in non-class scopes). 3180 bool CheckRedeclaration = Owner->isRecord(); 3181 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, 3182 Sema::ForVisibleRedeclaration); 3183 3184 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner, 3185 D->getUsingLoc(), 3186 QualifierLoc, 3187 NameInfo, 3188 D->hasTypename()); 3189 3190 CXXScopeSpec SS; 3191 SS.Adopt(QualifierLoc); 3192 if (CheckRedeclaration) { 3193 Prev.setHideTags(false); 3194 SemaRef.LookupQualifiedName(Prev, Owner); 3195 3196 // Check for invalid redeclarations. 3197 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(), 3198 D->hasTypename(), SS, 3199 D->getLocation(), Prev)) 3200 NewUD->setInvalidDecl(); 3201 } 3202 3203 if (!NewUD->isInvalidDecl() && 3204 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS, 3205 NameInfo, D->getLocation(), nullptr, D)) 3206 NewUD->setInvalidDecl(); 3207 3208 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); 3209 NewUD->setAccess(D->getAccess()); 3210 Owner->addDecl(NewUD); 3211 3212 // Don't process the shadow decls for an invalid decl. 3213 if (NewUD->isInvalidDecl()) 3214 return NewUD; 3215 3216 // If the using scope was dependent, or we had dependent bases, we need to 3217 // recheck the inheritance 3218 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) 3219 SemaRef.CheckInheritingConstructorUsingDecl(NewUD); 3220 3221 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr); 3222 } 3223 3224 Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) { 3225 // Cannot be a dependent type, but still could be an instantiation 3226 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl( 3227 D->getLocation(), D->getEnumDecl(), TemplateArgs)); 3228 3229 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation())) 3230 return nullptr; 3231 3232 UsingEnumDecl *NewUD = 3233 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(), 3234 D->getEnumLoc(), D->getLocation(), EnumD); 3235 3236 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D); 3237 NewUD->setAccess(D->getAccess()); 3238 Owner->addDecl(NewUD); 3239 3240 // Don't process the shadow decls for an invalid decl. 3241 if (NewUD->isInvalidDecl()) 3242 return NewUD; 3243 3244 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it 3245 // cannot be dependent, and will therefore have been checked during template 3246 // definition. 3247 3248 return VisitBaseUsingDecls(D, NewUD, nullptr); 3249 } 3250 3251 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { 3252 // Ignore these; we handle them in bulk when processing the UsingDecl. 3253 return nullptr; 3254 } 3255 3256 Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl( 3257 ConstructorUsingShadowDecl *D) { 3258 // Ignore these; we handle them in bulk when processing the UsingDecl. 3259 return nullptr; 3260 } 3261 3262 template <typename T> 3263 Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl( 3264 T *D, bool InstantiatingPackElement) { 3265 // If this is a pack expansion, expand it now. 3266 if (D->isPackExpansion() && !InstantiatingPackElement) { 3267 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 3268 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded); 3269 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded); 3270 3271 // Determine whether the set of unexpanded parameter packs can and should 3272 // be expanded. 3273 bool Expand = true; 3274 bool RetainExpansion = false; 3275 Optional<unsigned> NumExpansions; 3276 if (SemaRef.CheckParameterPacksForExpansion( 3277 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs, 3278 Expand, RetainExpansion, NumExpansions)) 3279 return nullptr; 3280 3281 // This declaration cannot appear within a function template signature, 3282 // so we can't have a partial argument list for a parameter pack. 3283 assert(!RetainExpansion && 3284 "should never need to retain an expansion for UsingPackDecl"); 3285 3286 if (!Expand) { 3287 // We cannot fully expand the pack expansion now, so substitute into the 3288 // pattern and create a new pack expansion. 3289 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); 3290 return instantiateUnresolvedUsingDecl(D, true); 3291 } 3292 3293 // Within a function, we don't have any normal way to check for conflicts 3294 // between shadow declarations from different using declarations in the 3295 // same pack expansion, but this is always ill-formed because all expansions 3296 // must produce (conflicting) enumerators. 3297 // 3298 // Sadly we can't just reject this in the template definition because it 3299 // could be valid if the pack is empty or has exactly one expansion. 3300 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) { 3301 SemaRef.Diag(D->getEllipsisLoc(), 3302 diag::err_using_decl_redeclaration_expansion); 3303 return nullptr; 3304 } 3305 3306 // Instantiate the slices of this pack and build a UsingPackDecl. 3307 SmallVector<NamedDecl*, 8> Expansions; 3308 for (unsigned I = 0; I != *NumExpansions; ++I) { 3309 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); 3310 Decl *Slice = instantiateUnresolvedUsingDecl(D, true); 3311 if (!Slice) 3312 return nullptr; 3313 // Note that we can still get unresolved using declarations here, if we 3314 // had arguments for all packs but the pattern also contained other 3315 // template arguments (this only happens during partial substitution, eg 3316 // into the body of a generic lambda in a function template). 3317 Expansions.push_back(cast<NamedDecl>(Slice)); 3318 } 3319 3320 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 3321 if (isDeclWithinFunction(D)) 3322 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 3323 return NewD; 3324 } 3325 3326 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D); 3327 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation(); 3328 3329 NestedNameSpecifierLoc QualifierLoc 3330 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), 3331 TemplateArgs); 3332 if (!QualifierLoc) 3333 return nullptr; 3334 3335 CXXScopeSpec SS; 3336 SS.Adopt(QualifierLoc); 3337 3338 DeclarationNameInfo NameInfo 3339 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs); 3340 3341 // Produce a pack expansion only if we're not instantiating a particular 3342 // slice of a pack expansion. 3343 bool InstantiatingSlice = D->getEllipsisLoc().isValid() && 3344 SemaRef.ArgumentPackSubstitutionIndex != -1; 3345 SourceLocation EllipsisLoc = 3346 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc(); 3347 3348 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>(); 3349 NamedDecl *UD = SemaRef.BuildUsingDeclaration( 3350 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(), 3351 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc, 3352 ParsedAttributesView(), 3353 /*IsInstantiation*/ true, IsUsingIfExists); 3354 if (UD) { 3355 SemaRef.InstantiateAttrs(TemplateArgs, D, UD); 3356 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D); 3357 } 3358 3359 return UD; 3360 } 3361 3362 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl( 3363 UnresolvedUsingTypenameDecl *D) { 3364 return instantiateUnresolvedUsingDecl(D); 3365 } 3366 3367 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl( 3368 UnresolvedUsingValueDecl *D) { 3369 return instantiateUnresolvedUsingDecl(D); 3370 } 3371 3372 Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl( 3373 UnresolvedUsingIfExistsDecl *D) { 3374 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl"); 3375 } 3376 3377 Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) { 3378 SmallVector<NamedDecl*, 8> Expansions; 3379 for (auto *UD : D->expansions()) { 3380 if (NamedDecl *NewUD = 3381 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs)) 3382 Expansions.push_back(NewUD); 3383 else 3384 return nullptr; 3385 } 3386 3387 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); 3388 if (isDeclWithinFunction(D)) 3389 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD); 3390 return NewD; 3391 } 3392 3393 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl( 3394 ClassScopeFunctionSpecializationDecl *Decl) { 3395 CXXMethodDecl *OldFD = Decl->getSpecialization(); 3396 return cast_or_null<CXXMethodDecl>( 3397 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten())); 3398 } 3399 3400 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( 3401 OMPThreadPrivateDecl *D) { 3402 SmallVector<Expr *, 5> Vars; 3403 for (auto *I : D->varlists()) { 3404 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 3405 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr"); 3406 Vars.push_back(Var); 3407 } 3408 3409 OMPThreadPrivateDecl *TD = 3410 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars); 3411 3412 TD->setAccess(AS_public); 3413 Owner->addDecl(TD); 3414 3415 return TD; 3416 } 3417 3418 Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) { 3419 SmallVector<Expr *, 5> Vars; 3420 for (auto *I : D->varlists()) { 3421 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get(); 3422 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr"); 3423 Vars.push_back(Var); 3424 } 3425 SmallVector<OMPClause *, 4> Clauses; 3426 // Copy map clauses from the original mapper. 3427 for (OMPClause *C : D->clauselists()) { 3428 OMPClause *IC = nullptr; 3429 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) { 3430 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs); 3431 if (!NewE.isUsable()) 3432 continue; 3433 IC = SemaRef.ActOnOpenMPAllocatorClause( 3434 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc()); 3435 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) { 3436 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs); 3437 if (!NewE.isUsable()) 3438 continue; 3439 IC = SemaRef.ActOnOpenMPAlignClause(NewE.get(), AC->getBeginLoc(), 3440 AC->getLParenLoc(), AC->getEndLoc()); 3441 // If align clause value ends up being invalid, this can end up null. 3442 if (!IC) 3443 continue; 3444 } 3445 Clauses.push_back(IC); 3446 } 3447 3448 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective( 3449 D->getLocation(), Vars, Clauses, Owner); 3450 if (Res.get().isNull()) 3451 return nullptr; 3452 return Res.get().getSingleDecl(); 3453 } 3454 3455 Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) { 3456 llvm_unreachable( 3457 "Requires directive cannot be instantiated within a dependent context"); 3458 } 3459 3460 Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl( 3461 OMPDeclareReductionDecl *D) { 3462 // Instantiate type and check if it is allowed. 3463 const bool RequiresInstantiation = 3464 D->getType()->isDependentType() || 3465 D->getType()->isInstantiationDependentType() || 3466 D->getType()->containsUnexpandedParameterPack(); 3467 QualType SubstReductionType; 3468 if (RequiresInstantiation) { 3469 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType( 3470 D->getLocation(), 3471 ParsedType::make(SemaRef.SubstType( 3472 D->getType(), TemplateArgs, D->getLocation(), DeclarationName()))); 3473 } else { 3474 SubstReductionType = D->getType(); 3475 } 3476 if (SubstReductionType.isNull()) 3477 return nullptr; 3478 Expr *Combiner = D->getCombiner(); 3479 Expr *Init = D->getInitializer(); 3480 bool IsCorrect = true; 3481 // Create instantiated copy. 3482 std::pair<QualType, SourceLocation> ReductionTypes[] = { 3483 std::make_pair(SubstReductionType, D->getLocation())}; 3484 auto *PrevDeclInScope = D->getPrevDeclInScope(); 3485 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 3486 PrevDeclInScope = cast<OMPDeclareReductionDecl>( 3487 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 3488 ->get<Decl *>()); 3489 } 3490 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart( 3491 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(), 3492 PrevDeclInScope); 3493 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl()); 3494 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD); 3495 Expr *SubstCombiner = nullptr; 3496 Expr *SubstInitializer = nullptr; 3497 // Combiners instantiation sequence. 3498 if (Combiner) { 3499 SemaRef.ActOnOpenMPDeclareReductionCombinerStart( 3500 /*S=*/nullptr, NewDRD); 3501 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3502 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(), 3503 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl()); 3504 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3505 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(), 3506 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl()); 3507 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3508 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3509 ThisContext); 3510 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get(); 3511 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner); 3512 } 3513 // Initializers instantiation sequence. 3514 if (Init) { 3515 VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart( 3516 /*S=*/nullptr, NewDRD); 3517 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3518 cast<DeclRefExpr>(D->getInitOrig())->getDecl(), 3519 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl()); 3520 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3521 cast<DeclRefExpr>(D->getInitPriv())->getDecl(), 3522 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl()); 3523 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) { 3524 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get(); 3525 } else { 3526 auto *OldPrivParm = 3527 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()); 3528 IsCorrect = IsCorrect && OldPrivParm->hasInit(); 3529 if (IsCorrect) 3530 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm, 3531 TemplateArgs); 3532 } 3533 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer, 3534 OmpPrivParm); 3535 } 3536 IsCorrect = IsCorrect && SubstCombiner && 3537 (!Init || 3538 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit && 3539 SubstInitializer) || 3540 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit && 3541 !SubstInitializer)); 3542 3543 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd( 3544 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl()); 3545 3546 return NewDRD; 3547 } 3548 3549 Decl * 3550 TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) { 3551 // Instantiate type and check if it is allowed. 3552 const bool RequiresInstantiation = 3553 D->getType()->isDependentType() || 3554 D->getType()->isInstantiationDependentType() || 3555 D->getType()->containsUnexpandedParameterPack(); 3556 QualType SubstMapperTy; 3557 DeclarationName VN = D->getVarName(); 3558 if (RequiresInstantiation) { 3559 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType( 3560 D->getLocation(), 3561 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs, 3562 D->getLocation(), VN))); 3563 } else { 3564 SubstMapperTy = D->getType(); 3565 } 3566 if (SubstMapperTy.isNull()) 3567 return nullptr; 3568 // Create an instantiated copy of mapper. 3569 auto *PrevDeclInScope = D->getPrevDeclInScope(); 3570 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { 3571 PrevDeclInScope = cast<OMPDeclareMapperDecl>( 3572 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) 3573 ->get<Decl *>()); 3574 } 3575 bool IsCorrect = true; 3576 SmallVector<OMPClause *, 6> Clauses; 3577 // Instantiate the mapper variable. 3578 DeclarationNameInfo DirName; 3579 SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName, 3580 /*S=*/nullptr, 3581 (*D->clauselist_begin())->getBeginLoc()); 3582 ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl( 3583 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN); 3584 SemaRef.CurrentInstantiationScope->InstantiatedLocal( 3585 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(), 3586 cast<DeclRefExpr>(MapperVarRef.get())->getDecl()); 3587 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner); 3588 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), 3589 ThisContext); 3590 // Instantiate map clauses. 3591 for (OMPClause *C : D->clauselists()) { 3592 auto *OldC = cast<OMPMapClause>(C); 3593 SmallVector<Expr *, 4> NewVars; 3594 for (Expr *OE : OldC->varlists()) { 3595 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get(); 3596 if (!NE) { 3597 IsCorrect = false; 3598 break; 3599 } 3600 NewVars.push_back(NE); 3601 } 3602 if (!IsCorrect) 3603 break; 3604 NestedNameSpecifierLoc NewQualifierLoc = 3605 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(), 3606 TemplateArgs); 3607 CXXScopeSpec SS; 3608 SS.Adopt(NewQualifierLoc); 3609 DeclarationNameInfo NewNameInfo = 3610 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs); 3611 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(), 3612 OldC->getEndLoc()); 3613 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause( 3614 OldC->getMapTypeModifiers(), OldC->getMapTypeModifiersLoc(), SS, 3615 NewNameInfo, OldC->getMapType(), OldC->isImplicitMapType(), 3616 OldC->getMapLoc(), OldC->getColonLoc(), NewVars, Locs); 3617 Clauses.push_back(NewC); 3618 } 3619 SemaRef.EndOpenMPDSABlock(nullptr); 3620 if (!IsCorrect) 3621 return nullptr; 3622 Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective( 3623 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(), 3624 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope); 3625 Decl *NewDMD = DG.get().getSingleDecl(); 3626 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD); 3627 return NewDMD; 3628 } 3629 3630 Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl( 3631 OMPCapturedExprDecl * /*D*/) { 3632 llvm_unreachable("Should not be met in templates"); 3633 } 3634 3635 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { 3636 return VisitFunctionDecl(D, nullptr); 3637 } 3638 3639 Decl * 3640 TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { 3641 Decl *Inst = VisitFunctionDecl(D, nullptr); 3642 if (Inst && !D->getDescribedFunctionTemplate()) 3643 Owner->addDecl(Inst); 3644 return Inst; 3645 } 3646 3647 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { 3648 return VisitCXXMethodDecl(D, nullptr); 3649 } 3650 3651 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { 3652 llvm_unreachable("There are only CXXRecordDecls in C++"); 3653 } 3654 3655 Decl * 3656 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( 3657 ClassTemplateSpecializationDecl *D) { 3658 // As a MS extension, we permit class-scope explicit specialization 3659 // of member class templates. 3660 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); 3661 assert(ClassTemplate->getDeclContext()->isRecord() && 3662 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 3663 "can only instantiate an explicit specialization " 3664 "for a member class template"); 3665 3666 // Lookup the already-instantiated declaration in the instantiation 3667 // of the class template. 3668 ClassTemplateDecl *InstClassTemplate = 3669 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl( 3670 D->getLocation(), ClassTemplate, TemplateArgs)); 3671 if (!InstClassTemplate) 3672 return nullptr; 3673 3674 // Substitute into the template arguments of the class template explicit 3675 // specialization. 3676 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). 3677 castAs<TemplateSpecializationTypeLoc>(); 3678 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), 3679 Loc.getRAngleLoc()); 3680 SmallVector<TemplateArgumentLoc, 4> ArgLocs; 3681 for (unsigned I = 0; I != Loc.getNumArgs(); ++I) 3682 ArgLocs.push_back(Loc.getArgLoc(I)); 3683 if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs)) 3684 return nullptr; 3685 3686 // Check that the template argument list is well-formed for this 3687 // class template. 3688 SmallVector<TemplateArgument, 4> Converted; 3689 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, 3690 D->getLocation(), 3691 InstTemplateArgs, 3692 false, 3693 Converted, 3694 /*UpdateArgsWithConversions=*/true)) 3695 return nullptr; 3696 3697 // Figure out where to insert this class template explicit specialization 3698 // in the member template's set of class template explicit specializations. 3699 void *InsertPos = nullptr; 3700 ClassTemplateSpecializationDecl *PrevDecl = 3701 InstClassTemplate->findSpecialization(Converted, InsertPos); 3702 3703 // Check whether we've already seen a conflicting instantiation of this 3704 // declaration (for instance, if there was a prior implicit instantiation). 3705 bool Ignored; 3706 if (PrevDecl && 3707 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(), 3708 D->getSpecializationKind(), 3709 PrevDecl, 3710 PrevDecl->getSpecializationKind(), 3711 PrevDecl->getPointOfInstantiation(), 3712 Ignored)) 3713 return nullptr; 3714 3715 // If PrevDecl was a definition and D is also a definition, diagnose. 3716 // This happens in cases like: 3717 // 3718 // template<typename T, typename U> 3719 // struct Outer { 3720 // template<typename X> struct Inner; 3721 // template<> struct Inner<T> {}; 3722 // template<> struct Inner<U> {}; 3723 // }; 3724 // 3725 // Outer<int, int> outer; // error: the explicit specializations of Inner 3726 // // have the same signature. 3727 if (PrevDecl && PrevDecl->getDefinition() && 3728 D->isThisDeclarationADefinition()) { 3729 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; 3730 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), 3731 diag::note_previous_definition); 3732 return nullptr; 3733 } 3734 3735 // Create the class template partial specialization declaration. 3736 ClassTemplateSpecializationDecl *InstD = 3737 ClassTemplateSpecializationDecl::Create( 3738 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(), 3739 D->getLocation(), InstClassTemplate, Converted, PrevDecl); 3740 3741 // Add this partial specialization to the set of class template partial 3742 // specializations. 3743 if (!PrevDecl) 3744 InstClassTemplate->AddSpecialization(InstD, InsertPos); 3745 3746 // Substitute the nested name specifier, if any. 3747 if (SubstQualifier(D, InstD)) 3748 return nullptr; 3749 3750 // Build the canonical type that describes the converted template 3751 // arguments of the class template explicit specialization. 3752 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 3753 TemplateName(InstClassTemplate), Converted, 3754 SemaRef.Context.getRecordType(InstD)); 3755 3756 // Build the fully-sugared type for this class template 3757 // specialization as the user wrote in the specialization 3758 // itself. This means that we'll pretty-print the type retrieved 3759 // from the specialization's declaration the way that the user 3760 // actually wrote the specialization, rather than formatting the 3761 // name based on the "canonical" representation used to store the 3762 // template arguments in the specialization. 3763 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 3764 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs, 3765 CanonType); 3766 3767 InstD->setAccess(D->getAccess()); 3768 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); 3769 InstD->setSpecializationKind(D->getSpecializationKind()); 3770 InstD->setTypeAsWritten(WrittenTy); 3771 InstD->setExternLoc(D->getExternLoc()); 3772 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); 3773 3774 Owner->addDecl(InstD); 3775 3776 // Instantiate the members of the class-scope explicit specialization eagerly. 3777 // We don't have support for lazy instantiation of an explicit specialization 3778 // yet, and MSVC eagerly instantiates in this case. 3779 // FIXME: This is wrong in standard C++. 3780 if (D->isThisDeclarationADefinition() && 3781 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs, 3782 TSK_ImplicitInstantiation, 3783 /*Complain=*/true)) 3784 return nullptr; 3785 3786 return InstD; 3787 } 3788 3789 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3790 VarTemplateSpecializationDecl *D) { 3791 3792 TemplateArgumentListInfo VarTemplateArgsInfo; 3793 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); 3794 assert(VarTemplate && 3795 "A template specialization without specialized template?"); 3796 3797 VarTemplateDecl *InstVarTemplate = 3798 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl( 3799 D->getLocation(), VarTemplate, TemplateArgs)); 3800 if (!InstVarTemplate) 3801 return nullptr; 3802 3803 // Substitute the current template arguments. 3804 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo(); 3805 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc()); 3806 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc()); 3807 3808 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo.arguments(), TemplateArgs, 3809 VarTemplateArgsInfo)) 3810 return nullptr; 3811 3812 // Check that the template argument list is well-formed for this template. 3813 SmallVector<TemplateArgument, 4> Converted; 3814 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(), 3815 VarTemplateArgsInfo, false, Converted, 3816 /*UpdateArgsWithConversions=*/true)) 3817 return nullptr; 3818 3819 // Check whether we've already seen a declaration of this specialization. 3820 void *InsertPos = nullptr; 3821 VarTemplateSpecializationDecl *PrevDecl = 3822 InstVarTemplate->findSpecialization(Converted, InsertPos); 3823 3824 // Check whether we've already seen a conflicting instantiation of this 3825 // declaration (for instance, if there was a prior implicit instantiation). 3826 bool Ignored; 3827 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl( 3828 D->getLocation(), D->getSpecializationKind(), PrevDecl, 3829 PrevDecl->getSpecializationKind(), 3830 PrevDecl->getPointOfInstantiation(), Ignored)) 3831 return nullptr; 3832 3833 return VisitVarTemplateSpecializationDecl( 3834 InstVarTemplate, D, VarTemplateArgsInfo, Converted, PrevDecl); 3835 } 3836 3837 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( 3838 VarTemplateDecl *VarTemplate, VarDecl *D, 3839 const TemplateArgumentListInfo &TemplateArgsInfo, 3840 ArrayRef<TemplateArgument> Converted, 3841 VarTemplateSpecializationDecl *PrevDecl) { 3842 3843 // Do substitution on the type of the declaration 3844 TypeSourceInfo *DI = 3845 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, 3846 D->getTypeSpecStartLoc(), D->getDeclName()); 3847 if (!DI) 3848 return nullptr; 3849 3850 if (DI->getType()->isFunctionType()) { 3851 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) 3852 << D->isStaticDataMember() << DI->getType(); 3853 return nullptr; 3854 } 3855 3856 // Build the instantiated declaration 3857 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( 3858 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), 3859 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted); 3860 Var->setTemplateArgsInfo(TemplateArgsInfo); 3861 if (!PrevDecl) { 3862 void *InsertPos = nullptr; 3863 VarTemplate->findSpecialization(Converted, InsertPos); 3864 VarTemplate->AddSpecialization(Var, InsertPos); 3865 } 3866 3867 if (SemaRef.getLangOpts().OpenCL) 3868 SemaRef.deduceOpenCLAddressSpace(Var); 3869 3870 // Substitute the nested name specifier, if any. 3871 if (SubstQualifier(D, Var)) 3872 return nullptr; 3873 3874 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, 3875 StartingScope, false, PrevDecl); 3876 3877 return Var; 3878 } 3879 3880 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { 3881 llvm_unreachable("@defs is not supported in Objective-C++"); 3882 } 3883 3884 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { 3885 // FIXME: We need to be able to instantiate FriendTemplateDecls. 3886 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( 3887 DiagnosticsEngine::Error, 3888 "cannot instantiate %0 yet"); 3889 SemaRef.Diag(D->getLocation(), DiagID) 3890 << D->getDeclKindName(); 3891 3892 return nullptr; 3893 } 3894 3895 Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) { 3896 llvm_unreachable("Concept definitions cannot reside inside a template"); 3897 } 3898 3899 Decl * 3900 TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) { 3901 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(), 3902 D->getBeginLoc()); 3903 } 3904 3905 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { 3906 llvm_unreachable("Unexpected decl"); 3907 } 3908 3909 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, 3910 const MultiLevelTemplateArgumentList &TemplateArgs) { 3911 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 3912 if (D->isInvalidDecl()) 3913 return nullptr; 3914 3915 Decl *SubstD; 3916 runWithSufficientStackSpace(D->getLocation(), [&] { 3917 SubstD = Instantiator.Visit(D); 3918 }); 3919 return SubstD; 3920 } 3921 3922 void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK, 3923 FunctionDecl *Orig, QualType &T, 3924 TypeSourceInfo *&TInfo, 3925 DeclarationNameInfo &NameInfo) { 3926 assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual); 3927 3928 // C++2a [class.compare.default]p3: 3929 // the return type is replaced with bool 3930 auto *FPT = T->castAs<FunctionProtoType>(); 3931 T = SemaRef.Context.getFunctionType( 3932 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo()); 3933 3934 // Update the return type in the source info too. The most straightforward 3935 // way is to create new TypeSourceInfo for the new type. Use the location of 3936 // the '= default' as the location of the new type. 3937 // 3938 // FIXME: Set the correct return type when we initially transform the type, 3939 // rather than delaying it to now. 3940 TypeSourceInfo *NewTInfo = 3941 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc()); 3942 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>(); 3943 assert(OldLoc && "type of function is not a function type?"); 3944 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>(); 3945 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I) 3946 NewLoc.setParam(I, OldLoc.getParam(I)); 3947 TInfo = NewTInfo; 3948 3949 // and the declarator-id is replaced with operator== 3950 NameInfo.setName( 3951 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual)); 3952 } 3953 3954 FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, 3955 FunctionDecl *Spaceship) { 3956 if (Spaceship->isInvalidDecl()) 3957 return nullptr; 3958 3959 // C++2a [class.compare.default]p3: 3960 // an == operator function is declared implicitly [...] with the same 3961 // access and function-definition and in the same class scope as the 3962 // three-way comparison operator function 3963 MultiLevelTemplateArgumentList NoTemplateArgs; 3964 NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite); 3965 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth()); 3966 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs); 3967 Decl *R; 3968 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) { 3969 R = Instantiator.VisitCXXMethodDecl( 3970 MD, nullptr, None, 3971 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual); 3972 } else { 3973 assert(Spaceship->getFriendObjectKind() && 3974 "defaulted spaceship is neither a member nor a friend"); 3975 3976 R = Instantiator.VisitFunctionDecl( 3977 Spaceship, nullptr, 3978 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual); 3979 if (!R) 3980 return nullptr; 3981 3982 FriendDecl *FD = 3983 FriendDecl::Create(Context, RD, Spaceship->getLocation(), 3984 cast<NamedDecl>(R), Spaceship->getBeginLoc()); 3985 FD->setAccess(AS_public); 3986 RD->addDecl(FD); 3987 } 3988 return cast_or_null<FunctionDecl>(R); 3989 } 3990 3991 /// Instantiates a nested template parameter list in the current 3992 /// instantiation context. 3993 /// 3994 /// \param L The parameter list to instantiate 3995 /// 3996 /// \returns NULL if there was an error 3997 TemplateParameterList * 3998 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { 3999 // Get errors for all the parameters before bailing out. 4000 bool Invalid = false; 4001 4002 unsigned N = L->size(); 4003 typedef SmallVector<NamedDecl *, 8> ParamVector; 4004 ParamVector Params; 4005 Params.reserve(N); 4006 for (auto &P : *L) { 4007 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P)); 4008 Params.push_back(D); 4009 Invalid = Invalid || !D || D->isInvalidDecl(); 4010 } 4011 4012 // Clean up if we had an error. 4013 if (Invalid) 4014 return nullptr; 4015 4016 // FIXME: Concepts: Substitution into requires clause should only happen when 4017 // checking satisfaction. 4018 Expr *InstRequiresClause = nullptr; 4019 if (Expr *E = L->getRequiresClause()) { 4020 EnterExpressionEvaluationContext ConstantEvaluated( 4021 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated); 4022 ExprResult Res = SemaRef.SubstExpr(E, TemplateArgs); 4023 if (Res.isInvalid() || !Res.isUsable()) { 4024 return nullptr; 4025 } 4026 InstRequiresClause = Res.get(); 4027 } 4028 4029 TemplateParameterList *InstL 4030 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(), 4031 L->getLAngleLoc(), Params, 4032 L->getRAngleLoc(), InstRequiresClause); 4033 return InstL; 4034 } 4035 4036 TemplateParameterList * 4037 Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, 4038 const MultiLevelTemplateArgumentList &TemplateArgs) { 4039 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); 4040 return Instantiator.SubstTemplateParams(Params); 4041 } 4042 4043 /// Instantiate the declaration of a class template partial 4044 /// specialization. 4045 /// 4046 /// \param ClassTemplate the (instantiated) class template that is partially 4047 // specialized by the instantiation of \p PartialSpec. 4048 /// 4049 /// \param PartialSpec the (uninstantiated) class template partial 4050 /// specialization that we are instantiating. 4051 /// 4052 /// \returns The instantiated partial specialization, if successful; otherwise, 4053 /// NULL to indicate an error. 4054 ClassTemplatePartialSpecializationDecl * 4055 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( 4056 ClassTemplateDecl *ClassTemplate, 4057 ClassTemplatePartialSpecializationDecl *PartialSpec) { 4058 // Create a local instantiation scope for this class template partial 4059 // specialization, which will contain the instantiations of the template 4060 // parameters. 4061 LocalInstantiationScope Scope(SemaRef); 4062 4063 // Substitute into the template parameters of the class template partial 4064 // specialization. 4065 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 4066 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 4067 if (!InstParams) 4068 return nullptr; 4069 4070 // Substitute into the template arguments of the class template partial 4071 // specialization. 4072 const ASTTemplateArgumentListInfo *TemplArgInfo 4073 = PartialSpec->getTemplateArgsAsWritten(); 4074 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 4075 TemplArgInfo->RAngleLoc); 4076 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs, 4077 InstTemplateArgs)) 4078 return nullptr; 4079 4080 // Check that the template argument list is well-formed for this 4081 // class template. 4082 SmallVector<TemplateArgument, 4> Converted; 4083 if (SemaRef.CheckTemplateArgumentList(ClassTemplate, 4084 PartialSpec->getLocation(), 4085 InstTemplateArgs, 4086 false, 4087 Converted)) 4088 return nullptr; 4089 4090 // Check these arguments are valid for a template partial specialization. 4091 if (SemaRef.CheckTemplatePartialSpecializationArgs( 4092 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(), 4093 Converted)) 4094 return nullptr; 4095 4096 // Figure out where to insert this class template partial specialization 4097 // in the member template's set of class template partial specializations. 4098 void *InsertPos = nullptr; 4099 ClassTemplateSpecializationDecl *PrevDecl 4100 = ClassTemplate->findPartialSpecialization(Converted, InstParams, 4101 InsertPos); 4102 4103 // Build the canonical type that describes the converted template 4104 // arguments of the class template partial specialization. 4105 QualType CanonType 4106 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate), 4107 Converted); 4108 4109 // Build the fully-sugared type for this class template 4110 // specialization as the user wrote in the specialization 4111 // itself. This means that we'll pretty-print the type retrieved 4112 // from the specialization's declaration the way that the user 4113 // actually wrote the specialization, rather than formatting the 4114 // name based on the "canonical" representation used to store the 4115 // template arguments in the specialization. 4116 TypeSourceInfo *WrittenTy 4117 = SemaRef.Context.getTemplateSpecializationTypeInfo( 4118 TemplateName(ClassTemplate), 4119 PartialSpec->getLocation(), 4120 InstTemplateArgs, 4121 CanonType); 4122 4123 if (PrevDecl) { 4124 // We've already seen a partial specialization with the same template 4125 // parameters and template arguments. This can happen, for example, when 4126 // substituting the outer template arguments ends up causing two 4127 // class template partial specializations of a member class template 4128 // to have identical forms, e.g., 4129 // 4130 // template<typename T, typename U> 4131 // struct Outer { 4132 // template<typename X, typename Y> struct Inner; 4133 // template<typename Y> struct Inner<T, Y>; 4134 // template<typename Y> struct Inner<U, Y>; 4135 // }; 4136 // 4137 // Outer<int, int> outer; // error: the partial specializations of Inner 4138 // // have the same signature. 4139 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) 4140 << WrittenTy->getType(); 4141 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) 4142 << SemaRef.Context.getTypeDeclType(PrevDecl); 4143 return nullptr; 4144 } 4145 4146 4147 // Create the class template partial specialization declaration. 4148 ClassTemplatePartialSpecializationDecl *InstPartialSpec = 4149 ClassTemplatePartialSpecializationDecl::Create( 4150 SemaRef.Context, PartialSpec->getTagKind(), Owner, 4151 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams, 4152 ClassTemplate, Converted, InstTemplateArgs, CanonType, nullptr); 4153 // Substitute the nested name specifier, if any. 4154 if (SubstQualifier(PartialSpec, InstPartialSpec)) 4155 return nullptr; 4156 4157 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 4158 InstPartialSpec->setTypeAsWritten(WrittenTy); 4159 4160 // Check the completed partial specialization. 4161 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 4162 4163 // Add this partial specialization to the set of class template partial 4164 // specializations. 4165 ClassTemplate->AddPartialSpecialization(InstPartialSpec, 4166 /*InsertPos=*/nullptr); 4167 return InstPartialSpec; 4168 } 4169 4170 /// Instantiate the declaration of a variable template partial 4171 /// specialization. 4172 /// 4173 /// \param VarTemplate the (instantiated) variable template that is partially 4174 /// specialized by the instantiation of \p PartialSpec. 4175 /// 4176 /// \param PartialSpec the (uninstantiated) variable template partial 4177 /// specialization that we are instantiating. 4178 /// 4179 /// \returns The instantiated partial specialization, if successful; otherwise, 4180 /// NULL to indicate an error. 4181 VarTemplatePartialSpecializationDecl * 4182 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( 4183 VarTemplateDecl *VarTemplate, 4184 VarTemplatePartialSpecializationDecl *PartialSpec) { 4185 // Create a local instantiation scope for this variable template partial 4186 // specialization, which will contain the instantiations of the template 4187 // parameters. 4188 LocalInstantiationScope Scope(SemaRef); 4189 4190 // Substitute into the template parameters of the variable template partial 4191 // specialization. 4192 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); 4193 TemplateParameterList *InstParams = SubstTemplateParams(TempParams); 4194 if (!InstParams) 4195 return nullptr; 4196 4197 // Substitute into the template arguments of the variable template partial 4198 // specialization. 4199 const ASTTemplateArgumentListInfo *TemplArgInfo 4200 = PartialSpec->getTemplateArgsAsWritten(); 4201 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, 4202 TemplArgInfo->RAngleLoc); 4203 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs, 4204 InstTemplateArgs)) 4205 return nullptr; 4206 4207 // Check that the template argument list is well-formed for this 4208 // class template. 4209 SmallVector<TemplateArgument, 4> Converted; 4210 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(), 4211 InstTemplateArgs, false, Converted)) 4212 return nullptr; 4213 4214 // Check these arguments are valid for a template partial specialization. 4215 if (SemaRef.CheckTemplatePartialSpecializationArgs( 4216 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(), 4217 Converted)) 4218 return nullptr; 4219 4220 // Figure out where to insert this variable template partial specialization 4221 // in the member template's set of variable template partial specializations. 4222 void *InsertPos = nullptr; 4223 VarTemplateSpecializationDecl *PrevDecl = 4224 VarTemplate->findPartialSpecialization(Converted, InstParams, InsertPos); 4225 4226 // Build the canonical type that describes the converted template 4227 // arguments of the variable template partial specialization. 4228 QualType CanonType = SemaRef.Context.getTemplateSpecializationType( 4229 TemplateName(VarTemplate), Converted); 4230 4231 // Build the fully-sugared type for this variable template 4232 // specialization as the user wrote in the specialization 4233 // itself. This means that we'll pretty-print the type retrieved 4234 // from the specialization's declaration the way that the user 4235 // actually wrote the specialization, rather than formatting the 4236 // name based on the "canonical" representation used to store the 4237 // template arguments in the specialization. 4238 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( 4239 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs, 4240 CanonType); 4241 4242 if (PrevDecl) { 4243 // We've already seen a partial specialization with the same template 4244 // parameters and template arguments. This can happen, for example, when 4245 // substituting the outer template arguments ends up causing two 4246 // variable template partial specializations of a member variable template 4247 // to have identical forms, e.g., 4248 // 4249 // template<typename T, typename U> 4250 // struct Outer { 4251 // template<typename X, typename Y> pair<X,Y> p; 4252 // template<typename Y> pair<T, Y> p; 4253 // template<typename Y> pair<U, Y> p; 4254 // }; 4255 // 4256 // Outer<int, int> outer; // error: the partial specializations of Inner 4257 // // have the same signature. 4258 SemaRef.Diag(PartialSpec->getLocation(), 4259 diag::err_var_partial_spec_redeclared) 4260 << WrittenTy->getType(); 4261 SemaRef.Diag(PrevDecl->getLocation(), 4262 diag::note_var_prev_partial_spec_here); 4263 return nullptr; 4264 } 4265 4266 // Do substitution on the type of the declaration 4267 TypeSourceInfo *DI = SemaRef.SubstType( 4268 PartialSpec->getTypeSourceInfo(), TemplateArgs, 4269 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); 4270 if (!DI) 4271 return nullptr; 4272 4273 if (DI->getType()->isFunctionType()) { 4274 SemaRef.Diag(PartialSpec->getLocation(), 4275 diag::err_variable_instantiates_to_function) 4276 << PartialSpec->isStaticDataMember() << DI->getType(); 4277 return nullptr; 4278 } 4279 4280 // Create the variable template partial specialization declaration. 4281 VarTemplatePartialSpecializationDecl *InstPartialSpec = 4282 VarTemplatePartialSpecializationDecl::Create( 4283 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(), 4284 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(), 4285 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs); 4286 4287 // Substitute the nested name specifier, if any. 4288 if (SubstQualifier(PartialSpec, InstPartialSpec)) 4289 return nullptr; 4290 4291 InstPartialSpec->setInstantiatedFromMember(PartialSpec); 4292 InstPartialSpec->setTypeAsWritten(WrittenTy); 4293 4294 // Check the completed partial specialization. 4295 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec); 4296 4297 // Add this partial specialization to the set of variable template partial 4298 // specializations. The instantiation of the initializer is not necessary. 4299 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr); 4300 4301 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, 4302 LateAttrs, Owner, StartingScope); 4303 4304 return InstPartialSpec; 4305 } 4306 4307 TypeSourceInfo* 4308 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, 4309 SmallVectorImpl<ParmVarDecl *> &Params) { 4310 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); 4311 assert(OldTInfo && "substituting function without type source info"); 4312 assert(Params.empty() && "parameter vector is non-empty at start"); 4313 4314 CXXRecordDecl *ThisContext = nullptr; 4315 Qualifiers ThisTypeQuals; 4316 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 4317 ThisContext = cast<CXXRecordDecl>(Owner); 4318 ThisTypeQuals = Method->getMethodQualifiers(); 4319 } 4320 4321 TypeSourceInfo *NewTInfo 4322 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs, 4323 D->getTypeSpecStartLoc(), 4324 D->getDeclName(), 4325 ThisContext, ThisTypeQuals); 4326 if (!NewTInfo) 4327 return nullptr; 4328 4329 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); 4330 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { 4331 if (NewTInfo != OldTInfo) { 4332 // Get parameters from the new type info. 4333 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); 4334 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); 4335 unsigned NewIdx = 0; 4336 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); 4337 OldIdx != NumOldParams; ++OldIdx) { 4338 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); 4339 if (!OldParam) 4340 return nullptr; 4341 4342 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; 4343 4344 Optional<unsigned> NumArgumentsInExpansion; 4345 if (OldParam->isParameterPack()) 4346 NumArgumentsInExpansion = 4347 SemaRef.getNumArgumentsInExpansion(OldParam->getType(), 4348 TemplateArgs); 4349 if (!NumArgumentsInExpansion) { 4350 // Simple case: normal parameter, or a parameter pack that's 4351 // instantiated to a (still-dependent) parameter pack. 4352 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 4353 Params.push_back(NewParam); 4354 Scope->InstantiatedLocal(OldParam, NewParam); 4355 } else { 4356 // Parameter pack expansion: make the instantiation an argument pack. 4357 Scope->MakeInstantiatedLocalArgPack(OldParam); 4358 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { 4359 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); 4360 Params.push_back(NewParam); 4361 Scope->InstantiatedLocalPackArg(OldParam, NewParam); 4362 } 4363 } 4364 } 4365 } else { 4366 // The function type itself was not dependent and therefore no 4367 // substitution occurred. However, we still need to instantiate 4368 // the function parameters themselves. 4369 const FunctionProtoType *OldProto = 4370 cast<FunctionProtoType>(OldProtoLoc.getType()); 4371 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; 4372 ++i) { 4373 ParmVarDecl *OldParam = OldProtoLoc.getParam(i); 4374 if (!OldParam) { 4375 Params.push_back(SemaRef.BuildParmVarDeclForTypedef( 4376 D, D->getLocation(), OldProto->getParamType(i))); 4377 continue; 4378 } 4379 4380 ParmVarDecl *Parm = 4381 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); 4382 if (!Parm) 4383 return nullptr; 4384 Params.push_back(Parm); 4385 } 4386 } 4387 } else { 4388 // If the type of this function, after ignoring parentheses, is not 4389 // *directly* a function type, then we're instantiating a function that 4390 // was declared via a typedef or with attributes, e.g., 4391 // 4392 // typedef int functype(int, int); 4393 // functype func; 4394 // int __cdecl meth(int, int); 4395 // 4396 // In this case, we'll just go instantiate the ParmVarDecls that we 4397 // synthesized in the method declaration. 4398 SmallVector<QualType, 4> ParamTypes; 4399 Sema::ExtParameterInfoBuilder ExtParamInfos; 4400 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr, 4401 TemplateArgs, ParamTypes, &Params, 4402 ExtParamInfos)) 4403 return nullptr; 4404 } 4405 4406 return NewTInfo; 4407 } 4408 4409 /// Introduce the instantiated function parameters into the local 4410 /// instantiation scope, and set the parameter names to those used 4411 /// in the template. 4412 bool Sema::addInstantiatedParametersToScope( 4413 FunctionDecl *Function, const FunctionDecl *PatternDecl, 4414 LocalInstantiationScope &Scope, 4415 const MultiLevelTemplateArgumentList &TemplateArgs) { 4416 unsigned FParamIdx = 0; 4417 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { 4418 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I); 4419 if (!PatternParam->isParameterPack()) { 4420 // Simple case: not a parameter pack. 4421 assert(FParamIdx < Function->getNumParams()); 4422 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 4423 FunctionParam->setDeclName(PatternParam->getDeclName()); 4424 // If the parameter's type is not dependent, update it to match the type 4425 // in the pattern. They can differ in top-level cv-qualifiers, and we want 4426 // the pattern's type here. If the type is dependent, they can't differ, 4427 // per core issue 1668. Substitute into the type from the pattern, in case 4428 // it's instantiation-dependent. 4429 // FIXME: Updating the type to work around this is at best fragile. 4430 if (!PatternDecl->getType()->isDependentType()) { 4431 QualType T = SubstType(PatternParam->getType(), TemplateArgs, 4432 FunctionParam->getLocation(), 4433 FunctionParam->getDeclName()); 4434 if (T.isNull()) 4435 return true; 4436 FunctionParam->setType(T); 4437 } 4438 4439 Scope.InstantiatedLocal(PatternParam, FunctionParam); 4440 ++FParamIdx; 4441 continue; 4442 } 4443 4444 // Expand the parameter pack. 4445 Scope.MakeInstantiatedLocalArgPack(PatternParam); 4446 Optional<unsigned> NumArgumentsInExpansion = 4447 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs); 4448 if (NumArgumentsInExpansion) { 4449 QualType PatternType = 4450 PatternParam->getType()->castAs<PackExpansionType>()->getPattern(); 4451 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { 4452 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx); 4453 FunctionParam->setDeclName(PatternParam->getDeclName()); 4454 if (!PatternDecl->getType()->isDependentType()) { 4455 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg); 4456 QualType T = 4457 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(), 4458 FunctionParam->getDeclName()); 4459 if (T.isNull()) 4460 return true; 4461 FunctionParam->setType(T); 4462 } 4463 4464 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); 4465 ++FParamIdx; 4466 } 4467 } 4468 } 4469 4470 return false; 4471 } 4472 4473 bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, 4474 ParmVarDecl *Param) { 4475 assert(Param->hasUninstantiatedDefaultArg()); 4476 Expr *UninstExpr = Param->getUninstantiatedDefaultArg(); 4477 4478 EnterExpressionEvaluationContext EvalContext( 4479 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); 4480 4481 // Instantiate the expression. 4482 // 4483 // FIXME: Pass in a correct Pattern argument, otherwise 4484 // getTemplateInstantiationArgs uses the lexical context of FD, e.g. 4485 // 4486 // template<typename T> 4487 // struct A { 4488 // static int FooImpl(); 4489 // 4490 // template<typename Tp> 4491 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level 4492 // // template argument list [[T], [Tp]], should be [[Tp]]. 4493 // friend A<Tp> Foo(int a); 4494 // }; 4495 // 4496 // template<typename T> 4497 // A<T> Foo(int a = A<T>::FooImpl()); 4498 MultiLevelTemplateArgumentList TemplateArgs 4499 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true); 4500 4501 InstantiatingTemplate Inst(*this, CallLoc, Param, 4502 TemplateArgs.getInnermost()); 4503 if (Inst.isInvalid()) 4504 return true; 4505 if (Inst.isAlreadyInstantiating()) { 4506 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; 4507 Param->setInvalidDecl(); 4508 return true; 4509 } 4510 4511 ExprResult Result; 4512 { 4513 // C++ [dcl.fct.default]p5: 4514 // The names in the [default argument] expression are bound, and 4515 // the semantic constraints are checked, at the point where the 4516 // default argument expression appears. 4517 ContextRAII SavedContext(*this, FD); 4518 LocalInstantiationScope Local(*this); 4519 4520 FunctionDecl *Pattern = FD->getTemplateInstantiationPattern( 4521 /*ForDefinition*/ false); 4522 if (addInstantiatedParametersToScope(FD, Pattern, Local, TemplateArgs)) 4523 return true; 4524 4525 runWithSufficientStackSpace(CallLoc, [&] { 4526 Result = SubstInitializer(UninstExpr, TemplateArgs, 4527 /*DirectInit*/false); 4528 }); 4529 } 4530 if (Result.isInvalid()) 4531 return true; 4532 4533 // Check the expression as an initializer for the parameter. 4534 InitializedEntity Entity 4535 = InitializedEntity::InitializeParameter(Context, Param); 4536 InitializationKind Kind = InitializationKind::CreateCopy( 4537 Param->getLocation(), 4538 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc()); 4539 Expr *ResultE = Result.getAs<Expr>(); 4540 4541 InitializationSequence InitSeq(*this, Entity, Kind, ResultE); 4542 Result = InitSeq.Perform(*this, Entity, Kind, ResultE); 4543 if (Result.isInvalid()) 4544 return true; 4545 4546 Result = 4547 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), 4548 /*DiscardedValue*/ false); 4549 if (Result.isInvalid()) 4550 return true; 4551 4552 // Remember the instantiated default argument. 4553 Param->setDefaultArg(Result.getAs<Expr>()); 4554 if (ASTMutationListener *L = getASTMutationListener()) 4555 L->DefaultArgumentInstantiated(Param); 4556 4557 return false; 4558 } 4559 4560 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 4561 FunctionDecl *Decl) { 4562 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); 4563 if (Proto->getExceptionSpecType() != EST_Uninstantiated) 4564 return; 4565 4566 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, 4567 InstantiatingTemplate::ExceptionSpecification()); 4568 if (Inst.isInvalid()) { 4569 // We hit the instantiation depth limit. Clear the exception specification 4570 // so that our callers don't have to cope with EST_Uninstantiated. 4571 UpdateExceptionSpec(Decl, EST_None); 4572 return; 4573 } 4574 if (Inst.isAlreadyInstantiating()) { 4575 // This exception specification indirectly depends on itself. Reject. 4576 // FIXME: Corresponding rule in the standard? 4577 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl; 4578 UpdateExceptionSpec(Decl, EST_None); 4579 return; 4580 } 4581 4582 // Enter the scope of this instantiation. We don't use 4583 // PushDeclContext because we don't have a scope. 4584 Sema::ContextRAII savedContext(*this, Decl); 4585 LocalInstantiationScope Scope(*this); 4586 4587 MultiLevelTemplateArgumentList TemplateArgs = 4588 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true); 4589 4590 // FIXME: We can't use getTemplateInstantiationPattern(false) in general 4591 // here, because for a non-defining friend declaration in a class template, 4592 // we don't store enough information to map back to the friend declaration in 4593 // the template. 4594 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 4595 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) { 4596 UpdateExceptionSpec(Decl, EST_None); 4597 return; 4598 } 4599 4600 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(), 4601 TemplateArgs); 4602 } 4603 4604 /// Initializes the common fields of an instantiation function 4605 /// declaration (New) from the corresponding fields of its template (Tmpl). 4606 /// 4607 /// \returns true if there was an error 4608 bool 4609 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 4610 FunctionDecl *Tmpl) { 4611 New->setImplicit(Tmpl->isImplicit()); 4612 4613 // Forward the mangling number from the template to the instantiated decl. 4614 SemaRef.Context.setManglingNumber(New, 4615 SemaRef.Context.getManglingNumber(Tmpl)); 4616 4617 // If we are performing substituting explicitly-specified template arguments 4618 // or deduced template arguments into a function template and we reach this 4619 // point, we are now past the point where SFINAE applies and have committed 4620 // to keeping the new function template specialization. We therefore 4621 // convert the active template instantiation for the function template 4622 // into a template instantiation for this specific function template 4623 // specialization, which is not a SFINAE context, so that we diagnose any 4624 // further errors in the declaration itself. 4625 // 4626 // FIXME: This is a hack. 4627 typedef Sema::CodeSynthesisContext ActiveInstType; 4628 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back(); 4629 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 4630 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 4631 if (FunctionTemplateDecl *FunTmpl 4632 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 4633 assert(FunTmpl->getTemplatedDecl() == Tmpl && 4634 "Deduction from the wrong function template?"); 4635 (void) FunTmpl; 4636 SemaRef.InstantiatingSpecializations.erase( 4637 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind}); 4638 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 4639 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 4640 ActiveInst.Entity = New; 4641 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst); 4642 } 4643 } 4644 4645 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 4646 assert(Proto && "Function template without prototype?"); 4647 4648 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 4649 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 4650 4651 // DR1330: In C++11, defer instantiation of a non-trivial 4652 // exception specification. 4653 // DR1484: Local classes and their members are instantiated along with the 4654 // containing function. 4655 if (SemaRef.getLangOpts().CPlusPlus11 && 4656 EPI.ExceptionSpec.Type != EST_None && 4657 EPI.ExceptionSpec.Type != EST_DynamicNone && 4658 EPI.ExceptionSpec.Type != EST_BasicNoexcept && 4659 !Tmpl->isInLocalScopeForInstantiation()) { 4660 FunctionDecl *ExceptionSpecTemplate = Tmpl; 4661 if (EPI.ExceptionSpec.Type == EST_Uninstantiated) 4662 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; 4663 ExceptionSpecificationType NewEST = EST_Uninstantiated; 4664 if (EPI.ExceptionSpec.Type == EST_Unevaluated) 4665 NewEST = EST_Unevaluated; 4666 4667 // Mark the function has having an uninstantiated exception specification. 4668 const FunctionProtoType *NewProto 4669 = New->getType()->getAs<FunctionProtoType>(); 4670 assert(NewProto && "Template instantiation without function prototype?"); 4671 EPI = NewProto->getExtProtoInfo(); 4672 EPI.ExceptionSpec.Type = NewEST; 4673 EPI.ExceptionSpec.SourceDecl = New; 4674 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; 4675 New->setType(SemaRef.Context.getFunctionType( 4676 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 4677 } else { 4678 Sema::ContextRAII SwitchContext(SemaRef, New); 4679 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs); 4680 } 4681 } 4682 4683 // Get the definition. Leaves the variable unchanged if undefined. 4684 const FunctionDecl *Definition = Tmpl; 4685 Tmpl->isDefined(Definition); 4686 4687 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 4688 LateAttrs, StartingScope); 4689 4690 return false; 4691 } 4692 4693 /// Initializes common fields of an instantiated method 4694 /// declaration (New) from the corresponding fields of its template 4695 /// (Tmpl). 4696 /// 4697 /// \returns true if there was an error 4698 bool 4699 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 4700 CXXMethodDecl *Tmpl) { 4701 if (InitFunctionInstantiation(New, Tmpl)) 4702 return true; 4703 4704 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11) 4705 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New)); 4706 4707 New->setAccess(Tmpl->getAccess()); 4708 if (Tmpl->isVirtualAsWritten()) 4709 New->setVirtualAsWritten(true); 4710 4711 // FIXME: New needs a pointer to Tmpl 4712 return false; 4713 } 4714 4715 bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New, 4716 FunctionDecl *Tmpl) { 4717 // Transfer across any unqualified lookups. 4718 if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) { 4719 SmallVector<DeclAccessPair, 32> Lookups; 4720 Lookups.reserve(DFI->getUnqualifiedLookups().size()); 4721 bool AnyChanged = false; 4722 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) { 4723 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(), 4724 DA.getDecl(), TemplateArgs); 4725 if (!D) 4726 return true; 4727 AnyChanged |= (D != DA.getDecl()); 4728 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess())); 4729 } 4730 4731 // It's unlikely that substitution will change any declarations. Don't 4732 // store an unnecessary copy in that case. 4733 New->setDefaultedFunctionInfo( 4734 AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create( 4735 SemaRef.Context, Lookups) 4736 : DFI); 4737 } 4738 4739 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation()); 4740 return false; 4741 } 4742 4743 /// Instantiate (or find existing instantiation of) a function template with a 4744 /// given set of template arguments. 4745 /// 4746 /// Usually this should not be used, and template argument deduction should be 4747 /// used in its place. 4748 FunctionDecl * 4749 Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, 4750 const TemplateArgumentList *Args, 4751 SourceLocation Loc) { 4752 FunctionDecl *FD = FTD->getTemplatedDecl(); 4753 4754 sema::TemplateDeductionInfo Info(Loc); 4755 InstantiatingTemplate Inst( 4756 *this, Loc, FTD, Args->asArray(), 4757 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); 4758 if (Inst.isInvalid()) 4759 return nullptr; 4760 4761 ContextRAII SavedContext(*this, FD); 4762 MultiLevelTemplateArgumentList MArgs(*Args); 4763 4764 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs)); 4765 } 4766 4767 /// Instantiate the definition of the given function from its 4768 /// template. 4769 /// 4770 /// \param PointOfInstantiation the point at which the instantiation was 4771 /// required. Note that this is not precisely a "point of instantiation" 4772 /// for the function, but it's close. 4773 /// 4774 /// \param Function the already-instantiated declaration of a 4775 /// function template specialization or member function of a class template 4776 /// specialization. 4777 /// 4778 /// \param Recursive if true, recursively instantiates any functions that 4779 /// are required by this instantiation. 4780 /// 4781 /// \param DefinitionRequired if true, then we are performing an explicit 4782 /// instantiation where the body of the function is required. Complain if 4783 /// there is no such body. 4784 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 4785 FunctionDecl *Function, 4786 bool Recursive, 4787 bool DefinitionRequired, 4788 bool AtEndOfTU) { 4789 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function)) 4790 return; 4791 4792 // Never instantiate an explicit specialization except if it is a class scope 4793 // explicit specialization. 4794 TemplateSpecializationKind TSK = 4795 Function->getTemplateSpecializationKindForInstantiation(); 4796 if (TSK == TSK_ExplicitSpecialization) 4797 return; 4798 4799 // Never implicitly instantiate a builtin; we don't actually need a function 4800 // body. 4801 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation && 4802 !DefinitionRequired) 4803 return; 4804 4805 // Don't instantiate a definition if we already have one. 4806 const FunctionDecl *ExistingDefn = nullptr; 4807 if (Function->isDefined(ExistingDefn, 4808 /*CheckForPendingFriendDefinition=*/true)) { 4809 if (ExistingDefn->isThisDeclarationADefinition()) 4810 return; 4811 4812 // If we're asked to instantiate a function whose body comes from an 4813 // instantiated friend declaration, attach the instantiated body to the 4814 // corresponding declaration of the function. 4815 assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition()); 4816 Function = const_cast<FunctionDecl*>(ExistingDefn); 4817 } 4818 4819 // Find the function body that we'll be substituting. 4820 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 4821 assert(PatternDecl && "instantiating a non-template"); 4822 4823 const FunctionDecl *PatternDef = PatternDecl->getDefinition(); 4824 Stmt *Pattern = nullptr; 4825 if (PatternDef) { 4826 Pattern = PatternDef->getBody(PatternDef); 4827 PatternDecl = PatternDef; 4828 if (PatternDef->willHaveBody()) 4829 PatternDef = nullptr; 4830 } 4831 4832 // FIXME: We need to track the instantiation stack in order to know which 4833 // definitions should be visible within this instantiation. 4834 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function, 4835 Function->getInstantiatedFromMemberFunction(), 4836 PatternDecl, PatternDef, TSK, 4837 /*Complain*/DefinitionRequired)) { 4838 if (DefinitionRequired) 4839 Function->setInvalidDecl(); 4840 else if (TSK == TSK_ExplicitInstantiationDefinition) { 4841 // Try again at the end of the translation unit (at which point a 4842 // definition will be required). 4843 assert(!Recursive); 4844 Function->setInstantiationIsPending(true); 4845 PendingInstantiations.push_back( 4846 std::make_pair(Function, PointOfInstantiation)); 4847 } else if (TSK == TSK_ImplicitInstantiation) { 4848 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 4849 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 4850 Diag(PointOfInstantiation, diag::warn_func_template_missing) 4851 << Function; 4852 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 4853 if (getLangOpts().CPlusPlus11) 4854 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) 4855 << Function; 4856 } 4857 } 4858 4859 return; 4860 } 4861 4862 // Postpone late parsed template instantiations. 4863 if (PatternDecl->isLateTemplateParsed() && 4864 !LateTemplateParser) { 4865 Function->setInstantiationIsPending(true); 4866 LateParsedInstantiations.push_back( 4867 std::make_pair(Function, PointOfInstantiation)); 4868 return; 4869 } 4870 4871 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() { 4872 std::string Name; 4873 llvm::raw_string_ostream OS(Name); 4874 Function->getNameForDiagnostic(OS, getPrintingPolicy(), 4875 /*Qualified=*/true); 4876 return Name; 4877 }); 4878 4879 // If we're performing recursive template instantiation, create our own 4880 // queue of pending implicit instantiations that we will instantiate later, 4881 // while we're still within our own instantiation context. 4882 // This has to happen before LateTemplateParser below is called, so that 4883 // it marks vtables used in late parsed templates as used. 4884 GlobalEagerInstantiationScope GlobalInstantiations(*this, 4885 /*Enabled=*/Recursive); 4886 LocalEagerInstantiationScope LocalInstantiations(*this); 4887 4888 // Call the LateTemplateParser callback if there is a need to late parse 4889 // a templated function definition. 4890 if (!Pattern && PatternDecl->isLateTemplateParsed() && 4891 LateTemplateParser) { 4892 // FIXME: Optimize to allow individual templates to be deserialized. 4893 if (PatternDecl->isFromASTFile()) 4894 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 4895 4896 auto LPTIter = LateParsedTemplateMap.find(PatternDecl); 4897 assert(LPTIter != LateParsedTemplateMap.end() && 4898 "missing LateParsedTemplate"); 4899 LateTemplateParser(OpaqueParser, *LPTIter->second); 4900 Pattern = PatternDecl->getBody(PatternDecl); 4901 } 4902 4903 // Note, we should never try to instantiate a deleted function template. 4904 assert((Pattern || PatternDecl->isDefaulted() || 4905 PatternDecl->hasSkippedBody()) && 4906 "unexpected kind of function template definition"); 4907 4908 // C++1y [temp.explicit]p10: 4909 // Except for inline functions, declarations with types deduced from their 4910 // initializer or return value, and class template specializations, other 4911 // explicit instantiation declarations have the effect of suppressing the 4912 // implicit instantiation of the entity to which they refer. 4913 if (TSK == TSK_ExplicitInstantiationDeclaration && 4914 !PatternDecl->isInlined() && 4915 !PatternDecl->getReturnType()->getContainedAutoType()) 4916 return; 4917 4918 if (PatternDecl->isInlined()) { 4919 // Function, and all later redeclarations of it (from imported modules, 4920 // for instance), are now implicitly inline. 4921 for (auto *D = Function->getMostRecentDecl(); /**/; 4922 D = D->getPreviousDecl()) { 4923 D->setImplicitlyInline(); 4924 if (D == Function) 4925 break; 4926 } 4927 } 4928 4929 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); 4930 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4931 return; 4932 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(), 4933 "instantiating function definition"); 4934 4935 // The instantiation is visible here, even if it was first declared in an 4936 // unimported module. 4937 Function->setVisibleDespiteOwningModule(); 4938 4939 // Copy the inner loc start from the pattern. 4940 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 4941 4942 EnterExpressionEvaluationContext EvalContext( 4943 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 4944 4945 // Introduce a new scope where local variable instantiations will be 4946 // recorded, unless we're actually a member function within a local 4947 // class, in which case we need to merge our results with the parent 4948 // scope (of the enclosing function). The exception is instantiating 4949 // a function template specialization, since the template to be 4950 // instantiated already has references to locals properly substituted. 4951 bool MergeWithParentScope = false; 4952 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 4953 MergeWithParentScope = 4954 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization(); 4955 4956 LocalInstantiationScope Scope(*this, MergeWithParentScope); 4957 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() { 4958 // Special members might get their TypeSourceInfo set up w.r.t the 4959 // PatternDecl context, in which case parameters could still be pointing 4960 // back to the original class, make sure arguments are bound to the 4961 // instantiated record instead. 4962 assert(PatternDecl->isDefaulted() && 4963 "Special member needs to be defaulted"); 4964 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember(); 4965 if (!(PatternSM == Sema::CXXCopyConstructor || 4966 PatternSM == Sema::CXXCopyAssignment || 4967 PatternSM == Sema::CXXMoveConstructor || 4968 PatternSM == Sema::CXXMoveAssignment)) 4969 return; 4970 4971 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()); 4972 const auto *PatternRec = 4973 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext()); 4974 if (!NewRec || !PatternRec) 4975 return; 4976 if (!PatternRec->isLambda()) 4977 return; 4978 4979 struct SpecialMemberTypeInfoRebuilder 4980 : TreeTransform<SpecialMemberTypeInfoRebuilder> { 4981 using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>; 4982 const CXXRecordDecl *OldDecl; 4983 CXXRecordDecl *NewDecl; 4984 4985 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O, 4986 CXXRecordDecl *N) 4987 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {} 4988 4989 bool TransformExceptionSpec(SourceLocation Loc, 4990 FunctionProtoType::ExceptionSpecInfo &ESI, 4991 SmallVectorImpl<QualType> &Exceptions, 4992 bool &Changed) { 4993 return false; 4994 } 4995 4996 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) { 4997 const RecordType *T = TL.getTypePtr(); 4998 RecordDecl *Record = cast_or_null<RecordDecl>( 4999 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl())); 5000 if (Record != OldDecl) 5001 return Base::TransformRecordType(TLB, TL); 5002 5003 QualType Result = getDerived().RebuildRecordType(NewDecl); 5004 if (Result.isNull()) 5005 return QualType(); 5006 5007 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result); 5008 NewTL.setNameLoc(TL.getNameLoc()); 5009 return Result; 5010 } 5011 } IR{*this, PatternRec, NewRec}; 5012 5013 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo()); 5014 Function->setType(NewSI->getType()); 5015 Function->setTypeSourceInfo(NewSI); 5016 5017 ParmVarDecl *Parm = Function->getParamDecl(0); 5018 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo()); 5019 Parm->setType(NewParmSI->getType()); 5020 Parm->setTypeSourceInfo(NewParmSI); 5021 }; 5022 5023 if (PatternDecl->isDefaulted()) { 5024 RebuildTypeSourceInfoForDefaultSpecialMembers(); 5025 SetDeclDefaulted(Function, PatternDecl->getLocation()); 5026 } else { 5027 MultiLevelTemplateArgumentList TemplateArgs = 5028 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl); 5029 5030 // Substitute into the qualifier; we can get a substitution failure here 5031 // through evil use of alias templates. 5032 // FIXME: Is CurContext correct for this? Should we go to the (instantiation 5033 // of the) lexical context of the pattern? 5034 SubstQualifier(*this, PatternDecl, Function, TemplateArgs); 5035 5036 ActOnStartOfFunctionDef(nullptr, Function); 5037 5038 // Enter the scope of this instantiation. We don't use 5039 // PushDeclContext because we don't have a scope. 5040 Sema::ContextRAII savedContext(*this, Function); 5041 5042 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope, 5043 TemplateArgs)) 5044 return; 5045 5046 StmtResult Body; 5047 if (PatternDecl->hasSkippedBody()) { 5048 ActOnSkippedFunctionBody(Function); 5049 Body = nullptr; 5050 } else { 5051 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) { 5052 // If this is a constructor, instantiate the member initializers. 5053 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl), 5054 TemplateArgs); 5055 5056 // If this is an MS ABI dllexport default constructor, instantiate any 5057 // default arguments. 5058 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5059 Ctor->isDefaultConstructor()) { 5060 InstantiateDefaultCtorDefaultArgs(Ctor); 5061 } 5062 } 5063 5064 // Instantiate the function body. 5065 Body = SubstStmt(Pattern, TemplateArgs); 5066 5067 if (Body.isInvalid()) 5068 Function->setInvalidDecl(); 5069 } 5070 // FIXME: finishing the function body while in an expression evaluation 5071 // context seems wrong. Investigate more. 5072 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true); 5073 5074 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 5075 5076 if (auto *Listener = getASTMutationListener()) 5077 Listener->FunctionDefinitionInstantiated(Function); 5078 5079 savedContext.pop(); 5080 } 5081 5082 DeclGroupRef DG(Function); 5083 Consumer.HandleTopLevelDecl(DG); 5084 5085 // This class may have local implicit instantiations that need to be 5086 // instantiation within this scope. 5087 LocalInstantiations.perform(); 5088 Scope.Exit(); 5089 GlobalInstantiations.perform(); 5090 } 5091 5092 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 5093 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 5094 const TemplateArgumentList &TemplateArgList, 5095 const TemplateArgumentListInfo &TemplateArgsInfo, 5096 SmallVectorImpl<TemplateArgument> &Converted, 5097 SourceLocation PointOfInstantiation, 5098 LateInstantiatedAttrVec *LateAttrs, 5099 LocalInstantiationScope *StartingScope) { 5100 if (FromVar->isInvalidDecl()) 5101 return nullptr; 5102 5103 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 5104 if (Inst.isInvalid()) 5105 return nullptr; 5106 5107 MultiLevelTemplateArgumentList TemplateArgLists; 5108 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 5109 5110 // Instantiate the first declaration of the variable template: for a partial 5111 // specialization of a static data member template, the first declaration may 5112 // or may not be the declaration in the class; if it's in the class, we want 5113 // to instantiate a member in the class (a declaration), and if it's outside, 5114 // we want to instantiate a definition. 5115 // 5116 // If we're instantiating an explicitly-specialized member template or member 5117 // partial specialization, don't do this. The member specialization completely 5118 // replaces the original declaration in this case. 5119 bool IsMemberSpec = false; 5120 if (VarTemplatePartialSpecializationDecl *PartialSpec = 5121 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) 5122 IsMemberSpec = PartialSpec->isMemberSpecialization(); 5123 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate()) 5124 IsMemberSpec = FromTemplate->isMemberSpecialization(); 5125 if (!IsMemberSpec) 5126 FromVar = FromVar->getFirstDecl(); 5127 5128 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 5129 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 5130 MultiLevelList); 5131 5132 // TODO: Set LateAttrs and StartingScope ... 5133 5134 return cast_or_null<VarTemplateSpecializationDecl>( 5135 Instantiator.VisitVarTemplateSpecializationDecl( 5136 VarTemplate, FromVar, TemplateArgsInfo, Converted)); 5137 } 5138 5139 /// Instantiates a variable template specialization by completing it 5140 /// with appropriate type information and initializer. 5141 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 5142 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 5143 const MultiLevelTemplateArgumentList &TemplateArgs) { 5144 assert(PatternDecl->isThisDeclarationADefinition() && 5145 "don't have a definition to instantiate from"); 5146 5147 // Do substitution on the type of the declaration 5148 TypeSourceInfo *DI = 5149 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 5150 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 5151 if (!DI) 5152 return nullptr; 5153 5154 // Update the type of this variable template specialization. 5155 VarSpec->setType(DI->getType()); 5156 5157 // Convert the declaration into a definition now. 5158 VarSpec->setCompleteDefinition(); 5159 5160 // Instantiate the initializer. 5161 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 5162 5163 if (getLangOpts().OpenCL) 5164 deduceOpenCLAddressSpace(VarSpec); 5165 5166 return VarSpec; 5167 } 5168 5169 /// BuildVariableInstantiation - Used after a new variable has been created. 5170 /// Sets basic variable data and decides whether to postpone the 5171 /// variable instantiation. 5172 void Sema::BuildVariableInstantiation( 5173 VarDecl *NewVar, VarDecl *OldVar, 5174 const MultiLevelTemplateArgumentList &TemplateArgs, 5175 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 5176 LocalInstantiationScope *StartingScope, 5177 bool InstantiatingVarTemplate, 5178 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) { 5179 // Instantiating a partial specialization to produce a partial 5180 // specialization. 5181 bool InstantiatingVarTemplatePartialSpec = 5182 isa<VarTemplatePartialSpecializationDecl>(OldVar) && 5183 isa<VarTemplatePartialSpecializationDecl>(NewVar); 5184 // Instantiating from a variable template (or partial specialization) to 5185 // produce a variable template specialization. 5186 bool InstantiatingSpecFromTemplate = 5187 isa<VarTemplateSpecializationDecl>(NewVar) && 5188 (OldVar->getDescribedVarTemplate() || 5189 isa<VarTemplatePartialSpecializationDecl>(OldVar)); 5190 5191 // If we are instantiating a local extern declaration, the 5192 // instantiation belongs lexically to the containing function. 5193 // If we are instantiating a static data member defined 5194 // out-of-line, the instantiation will have the same lexical 5195 // context (which will be a namespace scope) as the template. 5196 if (OldVar->isLocalExternDecl()) { 5197 NewVar->setLocalExternDecl(); 5198 NewVar->setLexicalDeclContext(Owner); 5199 } else if (OldVar->isOutOfLine()) 5200 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 5201 NewVar->setTSCSpec(OldVar->getTSCSpec()); 5202 NewVar->setInitStyle(OldVar->getInitStyle()); 5203 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 5204 NewVar->setObjCForDecl(OldVar->isObjCForDecl()); 5205 NewVar->setConstexpr(OldVar->isConstexpr()); 5206 NewVar->setInitCapture(OldVar->isInitCapture()); 5207 NewVar->setPreviousDeclInSameBlockScope( 5208 OldVar->isPreviousDeclInSameBlockScope()); 5209 NewVar->setAccess(OldVar->getAccess()); 5210 5211 if (!OldVar->isStaticDataMember()) { 5212 if (OldVar->isUsed(false)) 5213 NewVar->setIsUsed(); 5214 NewVar->setReferenced(OldVar->isReferenced()); 5215 } 5216 5217 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 5218 5219 LookupResult Previous( 5220 *this, NewVar->getDeclName(), NewVar->getLocation(), 5221 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 5222 : Sema::LookupOrdinaryName, 5223 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration 5224 : forRedeclarationInCurContext()); 5225 5226 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 5227 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 5228 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 5229 // We have a previous declaration. Use that one, so we merge with the 5230 // right type. 5231 if (NamedDecl *NewPrev = FindInstantiatedDecl( 5232 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 5233 Previous.addDecl(NewPrev); 5234 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 5235 OldVar->hasLinkage()) { 5236 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 5237 } else if (PrevDeclForVarTemplateSpecialization) { 5238 Previous.addDecl(PrevDeclForVarTemplateSpecialization); 5239 } 5240 CheckVariableDeclaration(NewVar, Previous); 5241 5242 if (!InstantiatingVarTemplate) { 5243 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 5244 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 5245 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 5246 } 5247 5248 if (!OldVar->isOutOfLine()) { 5249 if (NewVar->getDeclContext()->isFunctionOrMethod()) 5250 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 5251 } 5252 5253 // Link instantiations of static data members back to the template from 5254 // which they were instantiated. 5255 // 5256 // Don't do this when instantiating a template (we link the template itself 5257 // back in that case) nor when instantiating a static data member template 5258 // (that's not a member specialization). 5259 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate && 5260 !InstantiatingSpecFromTemplate) 5261 NewVar->setInstantiationOfStaticDataMember(OldVar, 5262 TSK_ImplicitInstantiation); 5263 5264 // If the pattern is an (in-class) explicit specialization, then the result 5265 // is also an explicit specialization. 5266 if (VarTemplateSpecializationDecl *OldVTSD = 5267 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) { 5268 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization && 5269 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD)) 5270 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind( 5271 TSK_ExplicitSpecialization); 5272 } 5273 5274 // Forward the mangling number from the template to the instantiated decl. 5275 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 5276 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar)); 5277 5278 // Figure out whether to eagerly instantiate the initializer. 5279 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) { 5280 // We're producing a template. Don't instantiate the initializer yet. 5281 } else if (NewVar->getType()->isUndeducedType()) { 5282 // We need the type to complete the declaration of the variable. 5283 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 5284 } else if (InstantiatingSpecFromTemplate || 5285 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() && 5286 !NewVar->isThisDeclarationADefinition())) { 5287 // Delay instantiation of the initializer for variable template 5288 // specializations or inline static data members until a definition of the 5289 // variable is needed. 5290 } else { 5291 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 5292 } 5293 5294 // Diagnose unused local variables with dependent types, where the diagnostic 5295 // will have been deferred. 5296 if (!NewVar->isInvalidDecl() && 5297 NewVar->getDeclContext()->isFunctionOrMethod() && 5298 OldVar->getType()->isDependentType()) 5299 DiagnoseUnusedDecl(NewVar); 5300 } 5301 5302 /// Instantiate the initializer of a variable. 5303 void Sema::InstantiateVariableInitializer( 5304 VarDecl *Var, VarDecl *OldVar, 5305 const MultiLevelTemplateArgumentList &TemplateArgs) { 5306 if (ASTMutationListener *L = getASTContext().getASTMutationListener()) 5307 L->VariableDefinitionInstantiated(Var); 5308 5309 // We propagate the 'inline' flag with the initializer, because it 5310 // would otherwise imply that the variable is a definition for a 5311 // non-static data member. 5312 if (OldVar->isInlineSpecified()) 5313 Var->setInlineSpecified(); 5314 else if (OldVar->isInline()) 5315 Var->setImplicitlyInline(); 5316 5317 if (OldVar->getInit()) { 5318 EnterExpressionEvaluationContext Evaluated( 5319 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var); 5320 5321 // Instantiate the initializer. 5322 ExprResult Init; 5323 5324 { 5325 ContextRAII SwitchContext(*this, Var->getDeclContext()); 5326 Init = SubstInitializer(OldVar->getInit(), TemplateArgs, 5327 OldVar->getInitStyle() == VarDecl::CallInit); 5328 } 5329 5330 if (!Init.isInvalid()) { 5331 Expr *InitExpr = Init.get(); 5332 5333 if (Var->hasAttr<DLLImportAttr>() && 5334 (!InitExpr || 5335 !InitExpr->isConstantInitializer(getASTContext(), false))) { 5336 // Do not dynamically initialize dllimport variables. 5337 } else if (InitExpr) { 5338 bool DirectInit = OldVar->isDirectInit(); 5339 AddInitializerToDecl(Var, InitExpr, DirectInit); 5340 } else 5341 ActOnUninitializedDecl(Var); 5342 } else { 5343 // FIXME: Not too happy about invalidating the declaration 5344 // because of a bogus initializer. 5345 Var->setInvalidDecl(); 5346 } 5347 } else { 5348 // `inline` variables are a definition and declaration all in one; we won't 5349 // pick up an initializer from anywhere else. 5350 if (Var->isStaticDataMember() && !Var->isInline()) { 5351 if (!Var->isOutOfLine()) 5352 return; 5353 5354 // If the declaration inside the class had an initializer, don't add 5355 // another one to the out-of-line definition. 5356 if (OldVar->getFirstDecl()->hasInit()) 5357 return; 5358 } 5359 5360 // We'll add an initializer to a for-range declaration later. 5361 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl()) 5362 return; 5363 5364 ActOnUninitializedDecl(Var); 5365 } 5366 5367 if (getLangOpts().CUDA) 5368 checkAllowedCUDAInitializer(Var); 5369 } 5370 5371 /// Instantiate the definition of the given variable from its 5372 /// template. 5373 /// 5374 /// \param PointOfInstantiation the point at which the instantiation was 5375 /// required. Note that this is not precisely a "point of instantiation" 5376 /// for the variable, but it's close. 5377 /// 5378 /// \param Var the already-instantiated declaration of a templated variable. 5379 /// 5380 /// \param Recursive if true, recursively instantiates any functions that 5381 /// are required by this instantiation. 5382 /// 5383 /// \param DefinitionRequired if true, then we are performing an explicit 5384 /// instantiation where a definition of the variable is required. Complain 5385 /// if there is no such definition. 5386 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 5387 VarDecl *Var, bool Recursive, 5388 bool DefinitionRequired, bool AtEndOfTU) { 5389 if (Var->isInvalidDecl()) 5390 return; 5391 5392 // Never instantiate an explicitly-specialized entity. 5393 TemplateSpecializationKind TSK = 5394 Var->getTemplateSpecializationKindForInstantiation(); 5395 if (TSK == TSK_ExplicitSpecialization) 5396 return; 5397 5398 // Find the pattern and the arguments to substitute into it. 5399 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern(); 5400 assert(PatternDecl && "no pattern for templated variable"); 5401 MultiLevelTemplateArgumentList TemplateArgs = 5402 getTemplateInstantiationArgs(Var); 5403 5404 VarTemplateSpecializationDecl *VarSpec = 5405 dyn_cast<VarTemplateSpecializationDecl>(Var); 5406 if (VarSpec) { 5407 // If this is a static data member template, there might be an 5408 // uninstantiated initializer on the declaration. If so, instantiate 5409 // it now. 5410 // 5411 // FIXME: This largely duplicates what we would do below. The difference 5412 // is that along this path we may instantiate an initializer from an 5413 // in-class declaration of the template and instantiate the definition 5414 // from a separate out-of-class definition. 5415 if (PatternDecl->isStaticDataMember() && 5416 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 5417 !Var->hasInit()) { 5418 // FIXME: Factor out the duplicated instantiation context setup/tear down 5419 // code here. 5420 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 5421 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 5422 return; 5423 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 5424 "instantiating variable initializer"); 5425 5426 // The instantiation is visible here, even if it was first declared in an 5427 // unimported module. 5428 Var->setVisibleDespiteOwningModule(); 5429 5430 // If we're performing recursive template instantiation, create our own 5431 // queue of pending implicit instantiations that we will instantiate 5432 // later, while we're still within our own instantiation context. 5433 GlobalEagerInstantiationScope GlobalInstantiations(*this, 5434 /*Enabled=*/Recursive); 5435 LocalInstantiationScope Local(*this); 5436 LocalEagerInstantiationScope LocalInstantiations(*this); 5437 5438 // Enter the scope of this instantiation. We don't use 5439 // PushDeclContext because we don't have a scope. 5440 ContextRAII PreviousContext(*this, Var->getDeclContext()); 5441 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 5442 PreviousContext.pop(); 5443 5444 // This variable may have local implicit instantiations that need to be 5445 // instantiated within this scope. 5446 LocalInstantiations.perform(); 5447 Local.Exit(); 5448 GlobalInstantiations.perform(); 5449 } 5450 } else { 5451 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && 5452 "not a static data member?"); 5453 } 5454 5455 VarDecl *Def = PatternDecl->getDefinition(getASTContext()); 5456 5457 // If we don't have a definition of the variable template, we won't perform 5458 // any instantiation. Rather, we rely on the user to instantiate this 5459 // definition (or provide a specialization for it) in another translation 5460 // unit. 5461 if (!Def && !DefinitionRequired) { 5462 if (TSK == TSK_ExplicitInstantiationDefinition) { 5463 PendingInstantiations.push_back( 5464 std::make_pair(Var, PointOfInstantiation)); 5465 } else if (TSK == TSK_ImplicitInstantiation) { 5466 // Warn about missing definition at the end of translation unit. 5467 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && 5468 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) { 5469 Diag(PointOfInstantiation, diag::warn_var_template_missing) 5470 << Var; 5471 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 5472 if (getLangOpts().CPlusPlus11) 5473 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var; 5474 } 5475 return; 5476 } 5477 } 5478 5479 // FIXME: We need to track the instantiation stack in order to know which 5480 // definitions should be visible within this instantiation. 5481 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember(). 5482 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var, 5483 /*InstantiatedFromMember*/false, 5484 PatternDecl, Def, TSK, 5485 /*Complain*/DefinitionRequired)) 5486 return; 5487 5488 // C++11 [temp.explicit]p10: 5489 // Except for inline functions, const variables of literal types, variables 5490 // of reference types, [...] explicit instantiation declarations 5491 // have the effect of suppressing the implicit instantiation of the entity 5492 // to which they refer. 5493 // 5494 // FIXME: That's not exactly the same as "might be usable in constant 5495 // expressions", which only allows constexpr variables and const integral 5496 // types, not arbitrary const literal types. 5497 if (TSK == TSK_ExplicitInstantiationDeclaration && 5498 !Var->mightBeUsableInConstantExpressions(getASTContext())) 5499 return; 5500 5501 // Make sure to pass the instantiated variable to the consumer at the end. 5502 struct PassToConsumerRAII { 5503 ASTConsumer &Consumer; 5504 VarDecl *Var; 5505 5506 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 5507 : Consumer(Consumer), Var(Var) { } 5508 5509 ~PassToConsumerRAII() { 5510 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 5511 } 5512 } PassToConsumerRAII(Consumer, Var); 5513 5514 // If we already have a definition, we're done. 5515 if (VarDecl *Def = Var->getDefinition()) { 5516 // We may be explicitly instantiating something we've already implicitly 5517 // instantiated. 5518 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 5519 PointOfInstantiation); 5520 return; 5521 } 5522 5523 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 5524 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 5525 return; 5526 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 5527 "instantiating variable definition"); 5528 5529 // If we're performing recursive template instantiation, create our own 5530 // queue of pending implicit instantiations that we will instantiate later, 5531 // while we're still within our own instantiation context. 5532 GlobalEagerInstantiationScope GlobalInstantiations(*this, 5533 /*Enabled=*/Recursive); 5534 5535 // Enter the scope of this instantiation. We don't use 5536 // PushDeclContext because we don't have a scope. 5537 ContextRAII PreviousContext(*this, Var->getDeclContext()); 5538 LocalInstantiationScope Local(*this); 5539 5540 LocalEagerInstantiationScope LocalInstantiations(*this); 5541 5542 VarDecl *OldVar = Var; 5543 if (Def->isStaticDataMember() && !Def->isOutOfLine()) { 5544 // We're instantiating an inline static data member whose definition was 5545 // provided inside the class. 5546 InstantiateVariableInitializer(Var, Def, TemplateArgs); 5547 } else if (!VarSpec) { 5548 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 5549 TemplateArgs)); 5550 } else if (Var->isStaticDataMember() && 5551 Var->getLexicalDeclContext()->isRecord()) { 5552 // We need to instantiate the definition of a static data member template, 5553 // and all we have is the in-class declaration of it. Instantiate a separate 5554 // declaration of the definition. 5555 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 5556 TemplateArgs); 5557 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 5558 VarSpec->getSpecializedTemplate(), Def, VarSpec->getTemplateArgsInfo(), 5559 VarSpec->getTemplateArgs().asArray(), VarSpec)); 5560 if (Var) { 5561 llvm::PointerUnion<VarTemplateDecl *, 5562 VarTemplatePartialSpecializationDecl *> PatternPtr = 5563 VarSpec->getSpecializedTemplateOrPartial(); 5564 if (VarTemplatePartialSpecializationDecl *Partial = 5565 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 5566 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 5567 Partial, &VarSpec->getTemplateInstantiationArgs()); 5568 5569 // Attach the initializer. 5570 InstantiateVariableInitializer(Var, Def, TemplateArgs); 5571 } 5572 } else 5573 // Complete the existing variable's definition with an appropriately 5574 // substituted type and initializer. 5575 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 5576 5577 PreviousContext.pop(); 5578 5579 if (Var) { 5580 PassToConsumerRAII.Var = Var; 5581 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 5582 OldVar->getPointOfInstantiation()); 5583 } 5584 5585 // This variable may have local implicit instantiations that need to be 5586 // instantiated within this scope. 5587 LocalInstantiations.perform(); 5588 Local.Exit(); 5589 GlobalInstantiations.perform(); 5590 } 5591 5592 void 5593 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 5594 const CXXConstructorDecl *Tmpl, 5595 const MultiLevelTemplateArgumentList &TemplateArgs) { 5596 5597 SmallVector<CXXCtorInitializer*, 4> NewInits; 5598 bool AnyErrors = Tmpl->isInvalidDecl(); 5599 5600 // Instantiate all the initializers. 5601 for (const auto *Init : Tmpl->inits()) { 5602 // Only instantiate written initializers, let Sema re-construct implicit 5603 // ones. 5604 if (!Init->isWritten()) 5605 continue; 5606 5607 SourceLocation EllipsisLoc; 5608 5609 if (Init->isPackExpansion()) { 5610 // This is a pack expansion. We should expand it now. 5611 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 5612 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 5613 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 5614 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 5615 bool ShouldExpand = false; 5616 bool RetainExpansion = false; 5617 Optional<unsigned> NumExpansions; 5618 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 5619 BaseTL.getSourceRange(), 5620 Unexpanded, 5621 TemplateArgs, ShouldExpand, 5622 RetainExpansion, 5623 NumExpansions)) { 5624 AnyErrors = true; 5625 New->setInvalidDecl(); 5626 continue; 5627 } 5628 assert(ShouldExpand && "Partial instantiation of base initializer?"); 5629 5630 // Loop over all of the arguments in the argument pack(s), 5631 for (unsigned I = 0; I != *NumExpansions; ++I) { 5632 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 5633 5634 // Instantiate the initializer. 5635 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 5636 /*CXXDirectInit=*/true); 5637 if (TempInit.isInvalid()) { 5638 AnyErrors = true; 5639 break; 5640 } 5641 5642 // Instantiate the base type. 5643 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 5644 TemplateArgs, 5645 Init->getSourceLocation(), 5646 New->getDeclName()); 5647 if (!BaseTInfo) { 5648 AnyErrors = true; 5649 break; 5650 } 5651 5652 // Build the initializer. 5653 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 5654 BaseTInfo, TempInit.get(), 5655 New->getParent(), 5656 SourceLocation()); 5657 if (NewInit.isInvalid()) { 5658 AnyErrors = true; 5659 break; 5660 } 5661 5662 NewInits.push_back(NewInit.get()); 5663 } 5664 5665 continue; 5666 } 5667 5668 // Instantiate the initializer. 5669 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 5670 /*CXXDirectInit=*/true); 5671 if (TempInit.isInvalid()) { 5672 AnyErrors = true; 5673 continue; 5674 } 5675 5676 MemInitResult NewInit; 5677 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 5678 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 5679 TemplateArgs, 5680 Init->getSourceLocation(), 5681 New->getDeclName()); 5682 if (!TInfo) { 5683 AnyErrors = true; 5684 New->setInvalidDecl(); 5685 continue; 5686 } 5687 5688 if (Init->isBaseInitializer()) 5689 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(), 5690 New->getParent(), EllipsisLoc); 5691 else 5692 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(), 5693 cast<CXXRecordDecl>(CurContext->getParent())); 5694 } else if (Init->isMemberInitializer()) { 5695 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 5696 Init->getMemberLocation(), 5697 Init->getMember(), 5698 TemplateArgs)); 5699 if (!Member) { 5700 AnyErrors = true; 5701 New->setInvalidDecl(); 5702 continue; 5703 } 5704 5705 NewInit = BuildMemberInitializer(Member, TempInit.get(), 5706 Init->getSourceLocation()); 5707 } else if (Init->isIndirectMemberInitializer()) { 5708 IndirectFieldDecl *IndirectMember = 5709 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 5710 Init->getMemberLocation(), 5711 Init->getIndirectMember(), TemplateArgs)); 5712 5713 if (!IndirectMember) { 5714 AnyErrors = true; 5715 New->setInvalidDecl(); 5716 continue; 5717 } 5718 5719 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(), 5720 Init->getSourceLocation()); 5721 } 5722 5723 if (NewInit.isInvalid()) { 5724 AnyErrors = true; 5725 New->setInvalidDecl(); 5726 } else { 5727 NewInits.push_back(NewInit.get()); 5728 } 5729 } 5730 5731 // Assign all the initializers to the new constructor. 5732 ActOnMemInitializers(New, 5733 /*FIXME: ColonLoc */ 5734 SourceLocation(), 5735 NewInits, 5736 AnyErrors); 5737 } 5738 5739 // TODO: this could be templated if the various decl types used the 5740 // same method name. 5741 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 5742 ClassTemplateDecl *Instance) { 5743 Pattern = Pattern->getCanonicalDecl(); 5744 5745 do { 5746 Instance = Instance->getCanonicalDecl(); 5747 if (Pattern == Instance) return true; 5748 Instance = Instance->getInstantiatedFromMemberTemplate(); 5749 } while (Instance); 5750 5751 return false; 5752 } 5753 5754 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 5755 FunctionTemplateDecl *Instance) { 5756 Pattern = Pattern->getCanonicalDecl(); 5757 5758 do { 5759 Instance = Instance->getCanonicalDecl(); 5760 if (Pattern == Instance) return true; 5761 Instance = Instance->getInstantiatedFromMemberTemplate(); 5762 } while (Instance); 5763 5764 return false; 5765 } 5766 5767 static bool 5768 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 5769 ClassTemplatePartialSpecializationDecl *Instance) { 5770 Pattern 5771 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 5772 do { 5773 Instance = cast<ClassTemplatePartialSpecializationDecl>( 5774 Instance->getCanonicalDecl()); 5775 if (Pattern == Instance) 5776 return true; 5777 Instance = Instance->getInstantiatedFromMember(); 5778 } while (Instance); 5779 5780 return false; 5781 } 5782 5783 static bool isInstantiationOf(CXXRecordDecl *Pattern, 5784 CXXRecordDecl *Instance) { 5785 Pattern = Pattern->getCanonicalDecl(); 5786 5787 do { 5788 Instance = Instance->getCanonicalDecl(); 5789 if (Pattern == Instance) return true; 5790 Instance = Instance->getInstantiatedFromMemberClass(); 5791 } while (Instance); 5792 5793 return false; 5794 } 5795 5796 static bool isInstantiationOf(FunctionDecl *Pattern, 5797 FunctionDecl *Instance) { 5798 Pattern = Pattern->getCanonicalDecl(); 5799 5800 do { 5801 Instance = Instance->getCanonicalDecl(); 5802 if (Pattern == Instance) return true; 5803 Instance = Instance->getInstantiatedFromMemberFunction(); 5804 } while (Instance); 5805 5806 return false; 5807 } 5808 5809 static bool isInstantiationOf(EnumDecl *Pattern, 5810 EnumDecl *Instance) { 5811 Pattern = Pattern->getCanonicalDecl(); 5812 5813 do { 5814 Instance = Instance->getCanonicalDecl(); 5815 if (Pattern == Instance) return true; 5816 Instance = Instance->getInstantiatedFromMemberEnum(); 5817 } while (Instance); 5818 5819 return false; 5820 } 5821 5822 static bool isInstantiationOf(UsingShadowDecl *Pattern, 5823 UsingShadowDecl *Instance, 5824 ASTContext &C) { 5825 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance), 5826 Pattern); 5827 } 5828 5829 static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance, 5830 ASTContext &C) { 5831 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 5832 } 5833 5834 template<typename T> 5835 static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, 5836 ASTContext &Ctx) { 5837 // An unresolved using declaration can instantiate to an unresolved using 5838 // declaration, or to a using declaration or a using declaration pack. 5839 // 5840 // Multiple declarations can claim to be instantiated from an unresolved 5841 // using declaration if it's a pack expansion. We want the UsingPackDecl 5842 // in that case, not the individual UsingDecls within the pack. 5843 bool OtherIsPackExpansion; 5844 NamedDecl *OtherFrom; 5845 if (auto *OtherUUD = dyn_cast<T>(Other)) { 5846 OtherIsPackExpansion = OtherUUD->isPackExpansion(); 5847 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD); 5848 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) { 5849 OtherIsPackExpansion = true; 5850 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl(); 5851 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) { 5852 OtherIsPackExpansion = false; 5853 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD); 5854 } else { 5855 return false; 5856 } 5857 return Pattern->isPackExpansion() == OtherIsPackExpansion && 5858 declaresSameEntity(OtherFrom, Pattern); 5859 } 5860 5861 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 5862 VarDecl *Instance) { 5863 assert(Instance->isStaticDataMember()); 5864 5865 Pattern = Pattern->getCanonicalDecl(); 5866 5867 do { 5868 Instance = Instance->getCanonicalDecl(); 5869 if (Pattern == Instance) return true; 5870 Instance = Instance->getInstantiatedFromStaticDataMember(); 5871 } while (Instance); 5872 5873 return false; 5874 } 5875 5876 // Other is the prospective instantiation 5877 // D is the prospective pattern 5878 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 5879 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D)) 5880 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5881 5882 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D)) 5883 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx); 5884 5885 if (D->getKind() != Other->getKind()) 5886 return false; 5887 5888 if (auto *Record = dyn_cast<CXXRecordDecl>(Other)) 5889 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 5890 5891 if (auto *Function = dyn_cast<FunctionDecl>(Other)) 5892 return isInstantiationOf(cast<FunctionDecl>(D), Function); 5893 5894 if (auto *Enum = dyn_cast<EnumDecl>(Other)) 5895 return isInstantiationOf(cast<EnumDecl>(D), Enum); 5896 5897 if (auto *Var = dyn_cast<VarDecl>(Other)) 5898 if (Var->isStaticDataMember()) 5899 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 5900 5901 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other)) 5902 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 5903 5904 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 5905 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 5906 5907 if (auto *PartialSpec = 5908 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 5909 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 5910 PartialSpec); 5911 5912 if (auto *Field = dyn_cast<FieldDecl>(Other)) { 5913 if (!Field->getDeclName()) { 5914 // This is an unnamed field. 5915 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field), 5916 cast<FieldDecl>(D)); 5917 } 5918 } 5919 5920 if (auto *Using = dyn_cast<UsingDecl>(Other)) 5921 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 5922 5923 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other)) 5924 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 5925 5926 return D->getDeclName() && 5927 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 5928 } 5929 5930 template<typename ForwardIterator> 5931 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 5932 NamedDecl *D, 5933 ForwardIterator first, 5934 ForwardIterator last) { 5935 for (; first != last; ++first) 5936 if (isInstantiationOf(Ctx, D, *first)) 5937 return cast<NamedDecl>(*first); 5938 5939 return nullptr; 5940 } 5941 5942 /// Finds the instantiation of the given declaration context 5943 /// within the current instantiation. 5944 /// 5945 /// \returns NULL if there was an error 5946 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 5947 const MultiLevelTemplateArgumentList &TemplateArgs) { 5948 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 5949 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true); 5950 return cast_or_null<DeclContext>(ID); 5951 } else return DC; 5952 } 5953 5954 /// Determine whether the given context is dependent on template parameters at 5955 /// level \p Level or below. 5956 /// 5957 /// Sometimes we only substitute an inner set of template arguments and leave 5958 /// the outer templates alone. In such cases, contexts dependent only on the 5959 /// outer levels are not effectively dependent. 5960 static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) { 5961 if (!DC->isDependentContext()) 5962 return false; 5963 if (!Level) 5964 return true; 5965 return cast<Decl>(DC)->getTemplateDepth() > Level; 5966 } 5967 5968 /// Find the instantiation of the given declaration within the 5969 /// current instantiation. 5970 /// 5971 /// This routine is intended to be used when \p D is a declaration 5972 /// referenced from within a template, that needs to mapped into the 5973 /// corresponding declaration within an instantiation. For example, 5974 /// given: 5975 /// 5976 /// \code 5977 /// template<typename T> 5978 /// struct X { 5979 /// enum Kind { 5980 /// KnownValue = sizeof(T) 5981 /// }; 5982 /// 5983 /// bool getKind() const { return KnownValue; } 5984 /// }; 5985 /// 5986 /// template struct X<int>; 5987 /// \endcode 5988 /// 5989 /// In the instantiation of X<int>::getKind(), we need to map the \p 5990 /// EnumConstantDecl for \p KnownValue (which refers to 5991 /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue). 5992 /// \p FindInstantiatedDecl performs this mapping from within the instantiation 5993 /// of X<int>. 5994 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 5995 const MultiLevelTemplateArgumentList &TemplateArgs, 5996 bool FindingInstantiatedContext) { 5997 DeclContext *ParentDC = D->getDeclContext(); 5998 // Determine whether our parent context depends on any of the template 5999 // arguments we're currently substituting. 6000 bool ParentDependsOnArgs = isDependentContextAtLevel( 6001 ParentDC, TemplateArgs.getNumRetainedOuterLevels()); 6002 // FIXME: Parameters of pointer to functions (y below) that are themselves 6003 // parameters (p below) can have their ParentDC set to the translation-unit 6004 // - thus we can not consistently check if the ParentDC of such a parameter 6005 // is Dependent or/and a FunctionOrMethod. 6006 // For e.g. this code, during Template argument deduction tries to 6007 // find an instantiated decl for (T y) when the ParentDC for y is 6008 // the translation unit. 6009 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 6010 // float baz(float(*)()) { return 0.0; } 6011 // Foo(baz); 6012 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 6013 // it gets here, always has a FunctionOrMethod as its ParentDC?? 6014 // For now: 6015 // - as long as we have a ParmVarDecl whose parent is non-dependent and 6016 // whose type is not instantiation dependent, do nothing to the decl 6017 // - otherwise find its instantiated decl. 6018 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs && 6019 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 6020 return D; 6021 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 6022 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 6023 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() || 6024 isa<OMPDeclareReductionDecl>(ParentDC) || 6025 isa<OMPDeclareMapperDecl>(ParentDC))) || 6026 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() && 6027 cast<CXXRecordDecl>(D)->getTemplateDepth() > 6028 TemplateArgs.getNumRetainedOuterLevels())) { 6029 // D is a local of some kind. Look into the map of local 6030 // declarations to their instantiations. 6031 if (CurrentInstantiationScope) { 6032 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) { 6033 if (Decl *FD = Found->dyn_cast<Decl *>()) 6034 return cast<NamedDecl>(FD); 6035 6036 int PackIdx = ArgumentPackSubstitutionIndex; 6037 assert(PackIdx != -1 && 6038 "found declaration pack but not pack expanding"); 6039 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 6040 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 6041 } 6042 } 6043 6044 // If we're performing a partial substitution during template argument 6045 // deduction, we may not have values for template parameters yet. They 6046 // just map to themselves. 6047 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 6048 isa<TemplateTemplateParmDecl>(D)) 6049 return D; 6050 6051 if (D->isInvalidDecl()) 6052 return nullptr; 6053 6054 // Normally this function only searches for already instantiated declaration 6055 // however we have to make an exclusion for local types used before 6056 // definition as in the code: 6057 // 6058 // template<typename T> void f1() { 6059 // void g1(struct x1); 6060 // struct x1 {}; 6061 // } 6062 // 6063 // In this case instantiation of the type of 'g1' requires definition of 6064 // 'x1', which is defined later. Error recovery may produce an enum used 6065 // before definition. In these cases we need to instantiate relevant 6066 // declarations here. 6067 bool NeedInstantiate = false; 6068 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 6069 NeedInstantiate = RD->isLocalClass(); 6070 else if (isa<TypedefNameDecl>(D) && 6071 isa<CXXDeductionGuideDecl>(D->getDeclContext())) 6072 NeedInstantiate = true; 6073 else 6074 NeedInstantiate = isa<EnumDecl>(D); 6075 if (NeedInstantiate) { 6076 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 6077 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 6078 return cast<TypeDecl>(Inst); 6079 } 6080 6081 // If we didn't find the decl, then we must have a label decl that hasn't 6082 // been found yet. Lazily instantiate it and return it now. 6083 assert(isa<LabelDecl>(D)); 6084 6085 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 6086 assert(Inst && "Failed to instantiate label??"); 6087 6088 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 6089 return cast<LabelDecl>(Inst); 6090 } 6091 6092 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 6093 if (!Record->isDependentContext()) 6094 return D; 6095 6096 // Determine whether this record is the "templated" declaration describing 6097 // a class template or class template partial specialization. 6098 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 6099 if (ClassTemplate) 6100 ClassTemplate = ClassTemplate->getCanonicalDecl(); 6101 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 6102 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 6103 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 6104 6105 // Walk the current context to find either the record or an instantiation of 6106 // it. 6107 DeclContext *DC = CurContext; 6108 while (!DC->isFileContext()) { 6109 // If we're performing substitution while we're inside the template 6110 // definition, we'll find our own context. We're done. 6111 if (DC->Equals(Record)) 6112 return Record; 6113 6114 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 6115 // Check whether we're in the process of instantiating a class template 6116 // specialization of the template we're mapping. 6117 if (ClassTemplateSpecializationDecl *InstSpec 6118 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 6119 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 6120 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 6121 return InstRecord; 6122 } 6123 6124 // Check whether we're in the process of instantiating a member class. 6125 if (isInstantiationOf(Record, InstRecord)) 6126 return InstRecord; 6127 } 6128 6129 // Move to the outer template scope. 6130 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 6131 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 6132 DC = FD->getLexicalDeclContext(); 6133 continue; 6134 } 6135 // An implicit deduction guide acts as if it's within the class template 6136 // specialization described by its name and first N template params. 6137 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD); 6138 if (Guide && Guide->isImplicit()) { 6139 TemplateDecl *TD = Guide->getDeducedTemplate(); 6140 // Convert the arguments to an "as-written" list. 6141 TemplateArgumentListInfo Args(Loc, Loc); 6142 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front( 6143 TD->getTemplateParameters()->size())) { 6144 ArrayRef<TemplateArgument> Unpacked(Arg); 6145 if (Arg.getKind() == TemplateArgument::Pack) 6146 Unpacked = Arg.pack_elements(); 6147 for (TemplateArgument UnpackedArg : Unpacked) 6148 Args.addArgument( 6149 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc)); 6150 } 6151 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args); 6152 if (T.isNull()) 6153 return nullptr; 6154 auto *SubstRecord = T->getAsCXXRecordDecl(); 6155 assert(SubstRecord && "class template id not a class type?"); 6156 // Check that this template-id names the primary template and not a 6157 // partial or explicit specialization. (In the latter cases, it's 6158 // meaningless to attempt to find an instantiation of D within the 6159 // specialization.) 6160 // FIXME: The standard doesn't say what should happen here. 6161 if (FindingInstantiatedContext && 6162 usesPartialOrExplicitSpecialization( 6163 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) { 6164 Diag(Loc, diag::err_specialization_not_primary_template) 6165 << T << (SubstRecord->getTemplateSpecializationKind() == 6166 TSK_ExplicitSpecialization); 6167 return nullptr; 6168 } 6169 DC = SubstRecord; 6170 continue; 6171 } 6172 } 6173 6174 DC = DC->getParent(); 6175 } 6176 6177 // Fall through to deal with other dependent record types (e.g., 6178 // anonymous unions in class templates). 6179 } 6180 6181 if (!ParentDependsOnArgs) 6182 return D; 6183 6184 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 6185 if (!ParentDC) 6186 return nullptr; 6187 6188 if (ParentDC != D->getDeclContext()) { 6189 // We performed some kind of instantiation in the parent context, 6190 // so now we need to look into the instantiated parent context to 6191 // find the instantiation of the declaration D. 6192 6193 // If our context used to be dependent, we may need to instantiate 6194 // it before performing lookup into that context. 6195 bool IsBeingInstantiated = false; 6196 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 6197 if (!Spec->isDependentContext()) { 6198 QualType T = Context.getTypeDeclType(Spec); 6199 const RecordType *Tag = T->getAs<RecordType>(); 6200 assert(Tag && "type of non-dependent record is not a RecordType"); 6201 if (Tag->isBeingDefined()) 6202 IsBeingInstantiated = true; 6203 if (!Tag->isBeingDefined() && 6204 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 6205 return nullptr; 6206 6207 ParentDC = Tag->getDecl(); 6208 } 6209 } 6210 6211 NamedDecl *Result = nullptr; 6212 // FIXME: If the name is a dependent name, this lookup won't necessarily 6213 // find it. Does that ever matter? 6214 if (auto Name = D->getDeclName()) { 6215 DeclarationNameInfo NameInfo(Name, D->getLocation()); 6216 DeclarationNameInfo NewNameInfo = 6217 SubstDeclarationNameInfo(NameInfo, TemplateArgs); 6218 Name = NewNameInfo.getName(); 6219 if (!Name) 6220 return nullptr; 6221 DeclContext::lookup_result Found = ParentDC->lookup(Name); 6222 6223 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 6224 } else { 6225 // Since we don't have a name for the entity we're looking for, 6226 // our only option is to walk through all of the declarations to 6227 // find that name. This will occur in a few cases: 6228 // 6229 // - anonymous struct/union within a template 6230 // - unnamed class/struct/union/enum within a template 6231 // 6232 // FIXME: Find a better way to find these instantiations! 6233 Result = findInstantiationOf(Context, D, 6234 ParentDC->decls_begin(), 6235 ParentDC->decls_end()); 6236 } 6237 6238 if (!Result) { 6239 if (isa<UsingShadowDecl>(D)) { 6240 // UsingShadowDecls can instantiate to nothing because of using hiding. 6241 } else if (hasUncompilableErrorOccurred()) { 6242 // We've already complained about some ill-formed code, so most likely 6243 // this declaration failed to instantiate. There's no point in 6244 // complaining further, since this is normal in invalid code. 6245 // FIXME: Use more fine-grained 'invalid' tracking for this. 6246 } else if (IsBeingInstantiated) { 6247 // The class in which this member exists is currently being 6248 // instantiated, and we haven't gotten around to instantiating this 6249 // member yet. This can happen when the code uses forward declarations 6250 // of member classes, and introduces ordering dependencies via 6251 // template instantiation. 6252 Diag(Loc, diag::err_member_not_yet_instantiated) 6253 << D->getDeclName() 6254 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 6255 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 6256 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 6257 // This enumeration constant was found when the template was defined, 6258 // but can't be found in the instantiation. This can happen if an 6259 // unscoped enumeration member is explicitly specialized. 6260 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 6261 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 6262 TemplateArgs)); 6263 assert(Spec->getTemplateSpecializationKind() == 6264 TSK_ExplicitSpecialization); 6265 Diag(Loc, diag::err_enumerator_does_not_exist) 6266 << D->getDeclName() 6267 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 6268 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 6269 << Context.getTypeDeclType(Spec); 6270 } else { 6271 // We should have found something, but didn't. 6272 llvm_unreachable("Unable to find instantiation of declaration!"); 6273 } 6274 } 6275 6276 D = Result; 6277 } 6278 6279 return D; 6280 } 6281 6282 /// Performs template instantiation for all implicit template 6283 /// instantiations we have seen until this point. 6284 void Sema::PerformPendingInstantiations(bool LocalOnly) { 6285 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations; 6286 while (!PendingLocalImplicitInstantiations.empty() || 6287 (!LocalOnly && !PendingInstantiations.empty())) { 6288 PendingImplicitInstantiation Inst; 6289 6290 if (PendingLocalImplicitInstantiations.empty()) { 6291 Inst = PendingInstantiations.front(); 6292 PendingInstantiations.pop_front(); 6293 } else { 6294 Inst = PendingLocalImplicitInstantiations.front(); 6295 PendingLocalImplicitInstantiations.pop_front(); 6296 } 6297 6298 // Instantiate function definitions 6299 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 6300 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 6301 TSK_ExplicitInstantiationDefinition; 6302 if (Function->isMultiVersion()) { 6303 getASTContext().forEachMultiversionedFunctionVersion( 6304 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) { 6305 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true, 6306 DefinitionRequired, true); 6307 if (CurFD->isDefined()) 6308 CurFD->setInstantiationIsPending(false); 6309 }); 6310 } else { 6311 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true, 6312 DefinitionRequired, true); 6313 if (Function->isDefined()) 6314 Function->setInstantiationIsPending(false); 6315 } 6316 // Definition of a PCH-ed template declaration may be available only in the TU. 6317 if (!LocalOnly && LangOpts.PCHInstantiateTemplates && 6318 TUKind == TU_Prefix && Function->instantiationIsPending()) 6319 delayedPCHInstantiations.push_back(Inst); 6320 continue; 6321 } 6322 6323 // Instantiate variable definitions 6324 VarDecl *Var = cast<VarDecl>(Inst.first); 6325 6326 assert((Var->isStaticDataMember() || 6327 isa<VarTemplateSpecializationDecl>(Var)) && 6328 "Not a static data member, nor a variable template" 6329 " specialization?"); 6330 6331 // Don't try to instantiate declarations if the most recent redeclaration 6332 // is invalid. 6333 if (Var->getMostRecentDecl()->isInvalidDecl()) 6334 continue; 6335 6336 // Check if the most recent declaration has changed the specialization kind 6337 // and removed the need for implicit instantiation. 6338 switch (Var->getMostRecentDecl() 6339 ->getTemplateSpecializationKindForInstantiation()) { 6340 case TSK_Undeclared: 6341 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 6342 case TSK_ExplicitInstantiationDeclaration: 6343 case TSK_ExplicitSpecialization: 6344 continue; // No longer need to instantiate this type. 6345 case TSK_ExplicitInstantiationDefinition: 6346 // We only need an instantiation if the pending instantiation *is* the 6347 // explicit instantiation. 6348 if (Var != Var->getMostRecentDecl()) 6349 continue; 6350 break; 6351 case TSK_ImplicitInstantiation: 6352 break; 6353 } 6354 6355 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), 6356 "instantiating variable definition"); 6357 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 6358 TSK_ExplicitInstantiationDefinition; 6359 6360 // Instantiate static data member definitions or variable template 6361 // specializations. 6362 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 6363 DefinitionRequired, true); 6364 } 6365 6366 if (!LocalOnly && LangOpts.PCHInstantiateTemplates) 6367 PendingInstantiations.swap(delayedPCHInstantiations); 6368 } 6369 6370 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 6371 const MultiLevelTemplateArgumentList &TemplateArgs) { 6372 for (auto DD : Pattern->ddiags()) { 6373 switch (DD->getKind()) { 6374 case DependentDiagnostic::Access: 6375 HandleDependentAccessCheck(*DD, TemplateArgs); 6376 break; 6377 } 6378 } 6379 } 6380