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