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