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