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