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 if (Inst.isAlreadyInstantiating()) { 3400 // This exception specification indirectly depends on itself. Reject. 3401 // FIXME: Corresponding rule in the standard? 3402 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl; 3403 UpdateExceptionSpec(Decl, EST_None); 3404 return; 3405 } 3406 3407 // Enter the scope of this instantiation. We don't use 3408 // PushDeclContext because we don't have a scope. 3409 Sema::ContextRAII savedContext(*this, Decl); 3410 LocalInstantiationScope Scope(*this); 3411 3412 MultiLevelTemplateArgumentList TemplateArgs = 3413 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true); 3414 3415 FunctionDecl *Template = Proto->getExceptionSpecTemplate(); 3416 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope, 3417 TemplateArgs)) { 3418 UpdateExceptionSpec(Decl, EST_None); 3419 return; 3420 } 3421 3422 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(), 3423 TemplateArgs); 3424 } 3425 3426 /// \brief Initializes the common fields of an instantiation function 3427 /// declaration (New) from the corresponding fields of its template (Tmpl). 3428 /// 3429 /// \returns true if there was an error 3430 bool 3431 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, 3432 FunctionDecl *Tmpl) { 3433 if (Tmpl->isDeleted()) 3434 New->setDeletedAsWritten(); 3435 3436 // Forward the mangling number from the template to the instantiated decl. 3437 SemaRef.Context.setManglingNumber(New, 3438 SemaRef.Context.getManglingNumber(Tmpl)); 3439 3440 // If we are performing substituting explicitly-specified template arguments 3441 // or deduced template arguments into a function template and we reach this 3442 // point, we are now past the point where SFINAE applies and have committed 3443 // to keeping the new function template specialization. We therefore 3444 // convert the active template instantiation for the function template 3445 // into a template instantiation for this specific function template 3446 // specialization, which is not a SFINAE context, so that we diagnose any 3447 // further errors in the declaration itself. 3448 typedef Sema::ActiveTemplateInstantiation ActiveInstType; 3449 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back(); 3450 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || 3451 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { 3452 if (FunctionTemplateDecl *FunTmpl 3453 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) { 3454 assert(FunTmpl->getTemplatedDecl() == Tmpl && 3455 "Deduction from the wrong function template?"); 3456 (void) FunTmpl; 3457 ActiveInst.Kind = ActiveInstType::TemplateInstantiation; 3458 ActiveInst.Entity = New; 3459 } 3460 } 3461 3462 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); 3463 assert(Proto && "Function template without prototype?"); 3464 3465 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { 3466 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 3467 3468 // DR1330: In C++11, defer instantiation of a non-trivial 3469 // exception specification. 3470 // DR1484: Local classes and their members are instantiated along with the 3471 // containing function. 3472 if (SemaRef.getLangOpts().CPlusPlus11 && 3473 EPI.ExceptionSpec.Type != EST_None && 3474 EPI.ExceptionSpec.Type != EST_DynamicNone && 3475 EPI.ExceptionSpec.Type != EST_BasicNoexcept && 3476 !Tmpl->isLexicallyWithinFunctionOrMethod()) { 3477 FunctionDecl *ExceptionSpecTemplate = Tmpl; 3478 if (EPI.ExceptionSpec.Type == EST_Uninstantiated) 3479 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; 3480 ExceptionSpecificationType NewEST = EST_Uninstantiated; 3481 if (EPI.ExceptionSpec.Type == EST_Unevaluated) 3482 NewEST = EST_Unevaluated; 3483 3484 // Mark the function has having an uninstantiated exception specification. 3485 const FunctionProtoType *NewProto 3486 = New->getType()->getAs<FunctionProtoType>(); 3487 assert(NewProto && "Template instantiation without function prototype?"); 3488 EPI = NewProto->getExtProtoInfo(); 3489 EPI.ExceptionSpec.Type = NewEST; 3490 EPI.ExceptionSpec.SourceDecl = New; 3491 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; 3492 New->setType(SemaRef.Context.getFunctionType( 3493 NewProto->getReturnType(), NewProto->getParamTypes(), EPI)); 3494 } else { 3495 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs); 3496 } 3497 } 3498 3499 // Get the definition. Leaves the variable unchanged if undefined. 3500 const FunctionDecl *Definition = Tmpl; 3501 Tmpl->isDefined(Definition); 3502 3503 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, 3504 LateAttrs, StartingScope); 3505 3506 return false; 3507 } 3508 3509 /// \brief Initializes common fields of an instantiated method 3510 /// declaration (New) from the corresponding fields of its template 3511 /// (Tmpl). 3512 /// 3513 /// \returns true if there was an error 3514 bool 3515 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, 3516 CXXMethodDecl *Tmpl) { 3517 if (InitFunctionInstantiation(New, Tmpl)) 3518 return true; 3519 3520 New->setAccess(Tmpl->getAccess()); 3521 if (Tmpl->isVirtualAsWritten()) 3522 New->setVirtualAsWritten(true); 3523 3524 // FIXME: New needs a pointer to Tmpl 3525 return false; 3526 } 3527 3528 /// \brief Instantiate the definition of the given function from its 3529 /// template. 3530 /// 3531 /// \param PointOfInstantiation the point at which the instantiation was 3532 /// required. Note that this is not precisely a "point of instantiation" 3533 /// for the function, but it's close. 3534 /// 3535 /// \param Function the already-instantiated declaration of a 3536 /// function template specialization or member function of a class template 3537 /// specialization. 3538 /// 3539 /// \param Recursive if true, recursively instantiates any functions that 3540 /// are required by this instantiation. 3541 /// 3542 /// \param DefinitionRequired if true, then we are performing an explicit 3543 /// instantiation where the body of the function is required. Complain if 3544 /// there is no such body. 3545 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 3546 FunctionDecl *Function, 3547 bool Recursive, 3548 bool DefinitionRequired, 3549 bool AtEndOfTU) { 3550 if (Function->isInvalidDecl() || Function->isDefined()) 3551 return; 3552 3553 // Never instantiate an explicit specialization except if it is a class scope 3554 // explicit specialization. 3555 TemplateSpecializationKind TSK = Function->getTemplateSpecializationKind(); 3556 if (TSK == TSK_ExplicitSpecialization && 3557 !Function->getClassScopeSpecializationPattern()) 3558 return; 3559 3560 // Find the function body that we'll be substituting. 3561 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); 3562 assert(PatternDecl && "instantiating a non-template"); 3563 3564 const FunctionDecl *PatternDef = PatternDecl->getDefinition(); 3565 Stmt *Pattern = nullptr; 3566 if (PatternDef) { 3567 Pattern = PatternDef->getBody(PatternDef); 3568 PatternDecl = PatternDef; 3569 } 3570 3571 // FIXME: We need to track the instantiation stack in order to know which 3572 // definitions should be visible within this instantiation. 3573 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function, 3574 Function->getInstantiatedFromMemberFunction(), 3575 PatternDecl, PatternDef, TSK, 3576 /*Complain*/DefinitionRequired)) { 3577 if (DefinitionRequired) 3578 Function->setInvalidDecl(); 3579 else if (TSK == TSK_ExplicitInstantiationDefinition) { 3580 // Try again at the end of the translation unit (at which point a 3581 // definition will be required). 3582 assert(!Recursive); 3583 PendingInstantiations.push_back( 3584 std::make_pair(Function, PointOfInstantiation)); 3585 } else if (TSK == TSK_ImplicitInstantiation) { 3586 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) { 3587 Diag(PointOfInstantiation, diag::warn_func_template_missing) 3588 << Function; 3589 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 3590 if (getLangOpts().CPlusPlus11) 3591 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) 3592 << Function; 3593 } 3594 } 3595 3596 return; 3597 } 3598 3599 // Postpone late parsed template instantiations. 3600 if (PatternDecl->isLateTemplateParsed() && 3601 !LateTemplateParser) { 3602 PendingInstantiations.push_back( 3603 std::make_pair(Function, PointOfInstantiation)); 3604 return; 3605 } 3606 3607 // If we're performing recursive template instantiation, create our own 3608 // queue of pending implicit instantiations that we will instantiate later, 3609 // while we're still within our own instantiation context. 3610 // This has to happen before LateTemplateParser below is called, so that 3611 // it marks vtables used in late parsed templates as used. 3612 SavePendingLocalImplicitInstantiationsRAII 3613 SavedPendingLocalImplicitInstantiations(*this); 3614 SavePendingInstantiationsAndVTableUsesRAII 3615 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive); 3616 3617 // Call the LateTemplateParser callback if there is a need to late parse 3618 // a templated function definition. 3619 if (!Pattern && PatternDecl->isLateTemplateParsed() && 3620 LateTemplateParser) { 3621 // FIXME: Optimize to allow individual templates to be deserialized. 3622 if (PatternDecl->isFromASTFile()) 3623 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap); 3624 3625 auto LPTIter = LateParsedTemplateMap.find(PatternDecl); 3626 assert(LPTIter != LateParsedTemplateMap.end() && 3627 "missing LateParsedTemplate"); 3628 LateTemplateParser(OpaqueParser, *LPTIter->second); 3629 Pattern = PatternDecl->getBody(PatternDecl); 3630 } 3631 3632 // Note, we should never try to instantiate a deleted function template. 3633 assert((Pattern || PatternDecl->isDefaulted()) && 3634 "unexpected kind of function template definition"); 3635 3636 // C++1y [temp.explicit]p10: 3637 // Except for inline functions, declarations with types deduced from their 3638 // initializer or return value, and class template specializations, other 3639 // explicit instantiation declarations have the effect of suppressing the 3640 // implicit instantiation of the entity to which they refer. 3641 if (TSK == 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() || Inst.isAlreadyInstantiating()) 3659 return; 3660 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(), 3661 "instantiating function definition"); 3662 3663 // The instantiation is visible here, even if it was first declared in an 3664 // unimported module. 3665 Function->setHidden(false); 3666 3667 // Copy the inner loc start from the pattern. 3668 Function->setInnerLocStart(PatternDecl->getInnerLocStart()); 3669 3670 EnterExpressionEvaluationContext EvalContext(*this, 3671 Sema::PotentiallyEvaluated); 3672 3673 // Introduce a new scope where local variable instantiations will be 3674 // recorded, unless we're actually a member function within a local 3675 // class, in which case we need to merge our results with the parent 3676 // scope (of the enclosing function). 3677 bool MergeWithParentScope = false; 3678 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) 3679 MergeWithParentScope = Rec->isLocalClass(); 3680 3681 LocalInstantiationScope Scope(*this, MergeWithParentScope); 3682 3683 if (PatternDecl->isDefaulted()) 3684 SetDeclDefaulted(Function, PatternDecl->getLocation()); 3685 else { 3686 MultiLevelTemplateArgumentList TemplateArgs = 3687 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl); 3688 3689 // Substitute into the qualifier; we can get a substitution failure here 3690 // through evil use of alias templates. 3691 // FIXME: Is CurContext correct for this? Should we go to the (instantiation 3692 // of the) lexical context of the pattern? 3693 SubstQualifier(*this, PatternDecl, Function, TemplateArgs); 3694 3695 ActOnStartOfFunctionDef(nullptr, Function); 3696 3697 // Enter the scope of this instantiation. We don't use 3698 // PushDeclContext because we don't have a scope. 3699 Sema::ContextRAII savedContext(*this, Function); 3700 3701 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope, 3702 TemplateArgs)) 3703 return; 3704 3705 // If this is a constructor, instantiate the member initializers. 3706 if (const CXXConstructorDecl *Ctor = 3707 dyn_cast<CXXConstructorDecl>(PatternDecl)) { 3708 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor, 3709 TemplateArgs); 3710 } 3711 3712 // Instantiate the function body. 3713 StmtResult Body = SubstStmt(Pattern, TemplateArgs); 3714 3715 if (Body.isInvalid()) 3716 Function->setInvalidDecl(); 3717 3718 ActOnFinishFunctionBody(Function, Body.get(), 3719 /*IsInstantiation=*/true); 3720 3721 PerformDependentDiagnostics(PatternDecl, TemplateArgs); 3722 3723 if (auto *Listener = getASTMutationListener()) 3724 Listener->FunctionDefinitionInstantiated(Function); 3725 3726 savedContext.pop(); 3727 } 3728 3729 DeclGroupRef DG(Function); 3730 Consumer.HandleTopLevelDecl(DG); 3731 3732 // This class may have local implicit instantiations that need to be 3733 // instantiation within this scope. 3734 PerformPendingInstantiations(/*LocalOnly=*/true); 3735 Scope.Exit(); 3736 3737 if (Recursive) { 3738 // Define any pending vtables. 3739 DefineUsedVTables(); 3740 3741 // Instantiate any pending implicit instantiations found during the 3742 // instantiation of this template. 3743 PerformPendingInstantiations(); 3744 3745 // PendingInstantiations and VTableUses are restored through 3746 // SavePendingInstantiationsAndVTableUses's destructor. 3747 } 3748 } 3749 3750 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( 3751 VarTemplateDecl *VarTemplate, VarDecl *FromVar, 3752 const TemplateArgumentList &TemplateArgList, 3753 const TemplateArgumentListInfo &TemplateArgsInfo, 3754 SmallVectorImpl<TemplateArgument> &Converted, 3755 SourceLocation PointOfInstantiation, void *InsertPos, 3756 LateInstantiatedAttrVec *LateAttrs, 3757 LocalInstantiationScope *StartingScope) { 3758 if (FromVar->isInvalidDecl()) 3759 return nullptr; 3760 3761 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); 3762 if (Inst.isInvalid()) 3763 return nullptr; 3764 3765 MultiLevelTemplateArgumentList TemplateArgLists; 3766 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList); 3767 3768 // Instantiate the first declaration of the variable template: for a partial 3769 // specialization of a static data member template, the first declaration may 3770 // or may not be the declaration in the class; if it's in the class, we want 3771 // to instantiate a member in the class (a declaration), and if it's outside, 3772 // we want to instantiate a definition. 3773 // 3774 // If we're instantiating an explicitly-specialized member template or member 3775 // partial specialization, don't do this. The member specialization completely 3776 // replaces the original declaration in this case. 3777 bool IsMemberSpec = false; 3778 if (VarTemplatePartialSpecializationDecl *PartialSpec = 3779 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) 3780 IsMemberSpec = PartialSpec->isMemberSpecialization(); 3781 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate()) 3782 IsMemberSpec = FromTemplate->isMemberSpecialization(); 3783 if (!IsMemberSpec) 3784 FromVar = FromVar->getFirstDecl(); 3785 3786 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList); 3787 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), 3788 MultiLevelList); 3789 3790 // TODO: Set LateAttrs and StartingScope ... 3791 3792 return cast_or_null<VarTemplateSpecializationDecl>( 3793 Instantiator.VisitVarTemplateSpecializationDecl( 3794 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted)); 3795 } 3796 3797 /// \brief Instantiates a variable template specialization by completing it 3798 /// with appropriate type information and initializer. 3799 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( 3800 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, 3801 const MultiLevelTemplateArgumentList &TemplateArgs) { 3802 3803 // Do substitution on the type of the declaration 3804 TypeSourceInfo *DI = 3805 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, 3806 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); 3807 if (!DI) 3808 return nullptr; 3809 3810 // Update the type of this variable template specialization. 3811 VarSpec->setType(DI->getType()); 3812 3813 // Instantiate the initializer. 3814 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); 3815 3816 return VarSpec; 3817 } 3818 3819 /// BuildVariableInstantiation - Used after a new variable has been created. 3820 /// Sets basic variable data and decides whether to postpone the 3821 /// variable instantiation. 3822 void Sema::BuildVariableInstantiation( 3823 VarDecl *NewVar, VarDecl *OldVar, 3824 const MultiLevelTemplateArgumentList &TemplateArgs, 3825 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, 3826 LocalInstantiationScope *StartingScope, 3827 bool InstantiatingVarTemplate) { 3828 3829 // If we are instantiating a local extern declaration, the 3830 // instantiation belongs lexically to the containing function. 3831 // If we are instantiating a static data member defined 3832 // out-of-line, the instantiation will have the same lexical 3833 // context (which will be a namespace scope) as the template. 3834 if (OldVar->isLocalExternDecl()) { 3835 NewVar->setLocalExternDecl(); 3836 NewVar->setLexicalDeclContext(Owner); 3837 } else if (OldVar->isOutOfLine()) 3838 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); 3839 NewVar->setTSCSpec(OldVar->getTSCSpec()); 3840 NewVar->setInitStyle(OldVar->getInitStyle()); 3841 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); 3842 NewVar->setConstexpr(OldVar->isConstexpr()); 3843 NewVar->setInitCapture(OldVar->isInitCapture()); 3844 NewVar->setPreviousDeclInSameBlockScope( 3845 OldVar->isPreviousDeclInSameBlockScope()); 3846 NewVar->setAccess(OldVar->getAccess()); 3847 3848 if (!OldVar->isStaticDataMember()) { 3849 if (OldVar->isUsed(false)) 3850 NewVar->setIsUsed(); 3851 NewVar->setReferenced(OldVar->isReferenced()); 3852 } 3853 3854 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); 3855 3856 LookupResult Previous( 3857 *this, NewVar->getDeclName(), NewVar->getLocation(), 3858 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage 3859 : Sema::LookupOrdinaryName, 3860 Sema::ForRedeclaration); 3861 3862 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && 3863 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || 3864 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { 3865 // We have a previous declaration. Use that one, so we merge with the 3866 // right type. 3867 if (NamedDecl *NewPrev = FindInstantiatedDecl( 3868 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs)) 3869 Previous.addDecl(NewPrev); 3870 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) && 3871 OldVar->hasLinkage()) 3872 LookupQualifiedName(Previous, NewVar->getDeclContext(), false); 3873 CheckVariableDeclaration(NewVar, Previous); 3874 3875 if (!InstantiatingVarTemplate) { 3876 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); 3877 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) 3878 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); 3879 } 3880 3881 if (!OldVar->isOutOfLine()) { 3882 if (NewVar->getDeclContext()->isFunctionOrMethod()) 3883 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); 3884 } 3885 3886 // Link instantiations of static data members back to the template from 3887 // which they were instantiated. 3888 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate) 3889 NewVar->setInstantiationOfStaticDataMember(OldVar, 3890 TSK_ImplicitInstantiation); 3891 3892 // Forward the mangling number from the template to the instantiated decl. 3893 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); 3894 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar)); 3895 3896 // Delay instantiation of the initializer for variable templates or inline 3897 // static data members until a definition of the variable is needed. We need 3898 // it right away if the type contains 'auto'. 3899 if ((!isa<VarTemplateSpecializationDecl>(NewVar) && 3900 !InstantiatingVarTemplate && 3901 !(OldVar->isInline() && OldVar->isThisDeclarationADefinition())) || 3902 NewVar->getType()->isUndeducedType()) 3903 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs); 3904 3905 // Diagnose unused local variables with dependent types, where the diagnostic 3906 // will have been deferred. 3907 if (!NewVar->isInvalidDecl() && 3908 NewVar->getDeclContext()->isFunctionOrMethod() && 3909 OldVar->getType()->isDependentType()) 3910 DiagnoseUnusedDecl(NewVar); 3911 } 3912 3913 /// \brief Instantiate the initializer of a variable. 3914 void Sema::InstantiateVariableInitializer( 3915 VarDecl *Var, VarDecl *OldVar, 3916 const MultiLevelTemplateArgumentList &TemplateArgs) { 3917 // We propagate the 'inline' flag with the initializer, because it 3918 // would otherwise imply that the variable is a definition for a 3919 // non-static data member. 3920 if (OldVar->isInlineSpecified()) 3921 Var->setInlineSpecified(); 3922 else if (OldVar->isInline()) 3923 Var->setImplicitlyInline(); 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 { 3961 if (Var->isStaticDataMember()) { 3962 if (!Var->isOutOfLine()) 3963 return; 3964 3965 // If the declaration inside the class had an initializer, don't add 3966 // another one to the out-of-line definition. 3967 if (OldVar->getFirstDecl()->hasInit()) 3968 return; 3969 } 3970 3971 // We'll add an initializer to a for-range declaration later. 3972 if (Var->isCXXForRangeDecl()) 3973 return; 3974 3975 ActOnUninitializedDecl(Var, false); 3976 } 3977 } 3978 3979 /// \brief Instantiate the definition of the given variable from its 3980 /// template. 3981 /// 3982 /// \param PointOfInstantiation the point at which the instantiation was 3983 /// required. Note that this is not precisely a "point of instantiation" 3984 /// for the function, but it's close. 3985 /// 3986 /// \param Var the already-instantiated declaration of a static member 3987 /// variable of a class template specialization. 3988 /// 3989 /// \param Recursive if true, recursively instantiates any functions that 3990 /// are required by this instantiation. 3991 /// 3992 /// \param DefinitionRequired if true, then we are performing an explicit 3993 /// instantiation where an out-of-line definition of the member variable 3994 /// is required. Complain if there is no such definition. 3995 void Sema::InstantiateStaticDataMemberDefinition( 3996 SourceLocation PointOfInstantiation, 3997 VarDecl *Var, 3998 bool Recursive, 3999 bool DefinitionRequired) { 4000 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive, 4001 DefinitionRequired); 4002 } 4003 4004 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, 4005 VarDecl *Var, bool Recursive, 4006 bool DefinitionRequired, bool AtEndOfTU) { 4007 if (Var->isInvalidDecl()) 4008 return; 4009 4010 VarTemplateSpecializationDecl *VarSpec = 4011 dyn_cast<VarTemplateSpecializationDecl>(Var); 4012 VarDecl *PatternDecl = nullptr, *Def = nullptr; 4013 MultiLevelTemplateArgumentList TemplateArgs = 4014 getTemplateInstantiationArgs(Var); 4015 4016 if (VarSpec) { 4017 // If this is a variable template specialization, make sure that it is 4018 // non-dependent, then find its instantiation pattern. 4019 bool InstantiationDependent = false; 4020 assert(!TemplateSpecializationType::anyDependentTemplateArguments( 4021 VarSpec->getTemplateArgsInfo(), InstantiationDependent) && 4022 "Only instantiate variable template specializations that are " 4023 "not type-dependent"); 4024 (void)InstantiationDependent; 4025 4026 // Find the variable initialization that we'll be substituting. If the 4027 // pattern was instantiated from a member template, look back further to 4028 // find the real pattern. 4029 assert(VarSpec->getSpecializedTemplate() && 4030 "Specialization without specialized template?"); 4031 llvm::PointerUnion<VarTemplateDecl *, 4032 VarTemplatePartialSpecializationDecl *> PatternPtr = 4033 VarSpec->getSpecializedTemplateOrPartial(); 4034 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) { 4035 VarTemplatePartialSpecializationDecl *Tmpl = 4036 PatternPtr.get<VarTemplatePartialSpecializationDecl *>(); 4037 while (VarTemplatePartialSpecializationDecl *From = 4038 Tmpl->getInstantiatedFromMember()) { 4039 if (Tmpl->isMemberSpecialization()) 4040 break; 4041 4042 Tmpl = From; 4043 } 4044 PatternDecl = Tmpl; 4045 } else { 4046 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>(); 4047 while (VarTemplateDecl *From = 4048 Tmpl->getInstantiatedFromMemberTemplate()) { 4049 if (Tmpl->isMemberSpecialization()) 4050 break; 4051 4052 Tmpl = From; 4053 } 4054 PatternDecl = Tmpl->getTemplatedDecl(); 4055 } 4056 4057 // If this is a static data member template, there might be an 4058 // uninstantiated initializer on the declaration. If so, instantiate 4059 // it now. 4060 if (PatternDecl->isStaticDataMember() && 4061 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && 4062 !Var->hasInit()) { 4063 // FIXME: Factor out the duplicated instantiation context setup/tear down 4064 // code here. 4065 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 4066 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4067 return; 4068 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(), 4069 "instantiating variable initializer"); 4070 4071 // The instantiation is visible here, even if it was first declared in an 4072 // unimported module. 4073 Var->setHidden(false); 4074 4075 // If we're performing recursive template instantiation, create our own 4076 // queue of pending implicit instantiations that we will instantiate 4077 // later, while we're still within our own instantiation context. 4078 SavePendingInstantiationsAndVTableUsesRAII 4079 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive); 4080 4081 LocalInstantiationScope Local(*this); 4082 4083 // Enter the scope of this instantiation. We don't use 4084 // PushDeclContext because we don't have a scope. 4085 ContextRAII PreviousContext(*this, Var->getDeclContext()); 4086 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs); 4087 PreviousContext.pop(); 4088 4089 // FIXME: Need to inform the ASTConsumer that we instantiated the 4090 // initializer? 4091 4092 // This variable may have local implicit instantiations that need to be 4093 // instantiated within this scope. 4094 PerformPendingInstantiations(/*LocalOnly=*/true); 4095 4096 Local.Exit(); 4097 4098 if (Recursive) { 4099 // Define any newly required vtables. 4100 DefineUsedVTables(); 4101 4102 // Instantiate any pending implicit instantiations found during the 4103 // instantiation of this template. 4104 PerformPendingInstantiations(); 4105 4106 // PendingInstantiations and VTableUses are restored through 4107 // SavePendingInstantiationsAndVTableUses's destructor. 4108 } 4109 } 4110 4111 // Find actual definition 4112 Def = PatternDecl->getDefinition(getASTContext()); 4113 } else { 4114 // If this is a static data member, find its out-of-line definition. 4115 assert(Var->isStaticDataMember() && "not a static data member?"); 4116 PatternDecl = Var->getInstantiatedFromStaticDataMember(); 4117 4118 assert(PatternDecl && "data member was not instantiated from a template?"); 4119 assert(PatternDecl->isStaticDataMember() && "not a static data member?"); 4120 Def = PatternDecl->getDefinition(); 4121 } 4122 4123 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind(); 4124 4125 // If we don't have a definition of the variable template, we won't perform 4126 // any instantiation. Rather, we rely on the user to instantiate this 4127 // definition (or provide a specialization for it) in another translation 4128 // unit. 4129 if (!Def && !DefinitionRequired) { 4130 if (TSK == TSK_ExplicitInstantiationDefinition) { 4131 PendingInstantiations.push_back( 4132 std::make_pair(Var, PointOfInstantiation)); 4133 } else if (TSK == TSK_ImplicitInstantiation) { 4134 // Warn about missing definition at the end of translation unit. 4135 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) { 4136 Diag(PointOfInstantiation, diag::warn_var_template_missing) 4137 << Var; 4138 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); 4139 if (getLangOpts().CPlusPlus11) 4140 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var; 4141 } 4142 return; 4143 } 4144 4145 } 4146 4147 // FIXME: We need to track the instantiation stack in order to know which 4148 // definitions should be visible within this instantiation. 4149 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember(). 4150 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var, 4151 /*InstantiatedFromMember*/false, 4152 PatternDecl, Def, TSK, 4153 /*Complain*/DefinitionRequired)) 4154 return; 4155 4156 4157 // Never instantiate an explicit specialization. 4158 if (TSK == TSK_ExplicitSpecialization) 4159 return; 4160 4161 // C++11 [temp.explicit]p10: 4162 // Except for inline functions, [...] explicit instantiation declarations 4163 // have the effect of suppressing the implicit instantiation of the entity 4164 // to which they refer. 4165 if (TSK == TSK_ExplicitInstantiationDeclaration) 4166 return; 4167 4168 // Make sure to pass the instantiated variable to the consumer at the end. 4169 struct PassToConsumerRAII { 4170 ASTConsumer &Consumer; 4171 VarDecl *Var; 4172 4173 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) 4174 : Consumer(Consumer), Var(Var) { } 4175 4176 ~PassToConsumerRAII() { 4177 Consumer.HandleCXXStaticMemberVarInstantiation(Var); 4178 } 4179 } PassToConsumerRAII(Consumer, Var); 4180 4181 // If we already have a definition, we're done. 4182 if (VarDecl *Def = Var->getDefinition()) { 4183 // We may be explicitly instantiating something we've already implicitly 4184 // instantiated. 4185 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(), 4186 PointOfInstantiation); 4187 return; 4188 } 4189 4190 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); 4191 if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) 4192 return; 4193 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(), 4194 "instantiating variable definition"); 4195 4196 // If we're performing recursive template instantiation, create our own 4197 // queue of pending implicit instantiations that we will instantiate later, 4198 // while we're still within our own instantiation context. 4199 SavePendingLocalImplicitInstantiationsRAII 4200 SavedPendingLocalImplicitInstantiations(*this); 4201 SavePendingInstantiationsAndVTableUsesRAII 4202 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive); 4203 4204 // Enter the scope of this instantiation. We don't use 4205 // PushDeclContext because we don't have a scope. 4206 ContextRAII PreviousContext(*this, Var->getDeclContext()); 4207 LocalInstantiationScope Local(*this); 4208 4209 VarDecl *OldVar = Var; 4210 if (Def->isStaticDataMember() && !Def->isOutOfLine()) { 4211 // We're instantiating an inline static data member whose definition was 4212 // provided inside the class. 4213 // FIXME: Update record? 4214 InstantiateVariableInitializer(Var, Def, TemplateArgs); 4215 } else if (!VarSpec) { 4216 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(), 4217 TemplateArgs)); 4218 } else if (Var->isStaticDataMember() && 4219 Var->getLexicalDeclContext()->isRecord()) { 4220 // We need to instantiate the definition of a static data member template, 4221 // and all we have is the in-class declaration of it. Instantiate a separate 4222 // declaration of the definition. 4223 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), 4224 TemplateArgs); 4225 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl( 4226 VarSpec->getSpecializedTemplate(), Def, nullptr, 4227 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray())); 4228 if (Var) { 4229 llvm::PointerUnion<VarTemplateDecl *, 4230 VarTemplatePartialSpecializationDecl *> PatternPtr = 4231 VarSpec->getSpecializedTemplateOrPartial(); 4232 if (VarTemplatePartialSpecializationDecl *Partial = 4233 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) 4234 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf( 4235 Partial, &VarSpec->getTemplateInstantiationArgs()); 4236 4237 // Merge the definition with the declaration. 4238 LookupResult R(*this, Var->getDeclName(), Var->getLocation(), 4239 LookupOrdinaryName, ForRedeclaration); 4240 R.addDecl(OldVar); 4241 MergeVarDecl(Var, R); 4242 4243 // Attach the initializer. 4244 InstantiateVariableInitializer(Var, Def, TemplateArgs); 4245 } 4246 } else 4247 // Complete the existing variable's definition with an appropriately 4248 // substituted type and initializer. 4249 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs); 4250 4251 PreviousContext.pop(); 4252 4253 if (Var) { 4254 PassToConsumerRAII.Var = Var; 4255 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(), 4256 OldVar->getPointOfInstantiation()); 4257 } 4258 4259 // This variable may have local implicit instantiations that need to be 4260 // instantiated within this scope. 4261 PerformPendingInstantiations(/*LocalOnly=*/true); 4262 4263 Local.Exit(); 4264 4265 if (Recursive) { 4266 // Define any newly required vtables. 4267 DefineUsedVTables(); 4268 4269 // Instantiate any pending implicit instantiations found during the 4270 // instantiation of this template. 4271 PerformPendingInstantiations(); 4272 4273 // PendingInstantiations and VTableUses are restored through 4274 // SavePendingInstantiationsAndVTableUses's destructor. 4275 } 4276 } 4277 4278 void 4279 Sema::InstantiateMemInitializers(CXXConstructorDecl *New, 4280 const CXXConstructorDecl *Tmpl, 4281 const MultiLevelTemplateArgumentList &TemplateArgs) { 4282 4283 SmallVector<CXXCtorInitializer*, 4> NewInits; 4284 bool AnyErrors = Tmpl->isInvalidDecl(); 4285 4286 // Instantiate all the initializers. 4287 for (const auto *Init : Tmpl->inits()) { 4288 // Only instantiate written initializers, let Sema re-construct implicit 4289 // ones. 4290 if (!Init->isWritten()) 4291 continue; 4292 4293 SourceLocation EllipsisLoc; 4294 4295 if (Init->isPackExpansion()) { 4296 // This is a pack expansion. We should expand it now. 4297 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); 4298 SmallVector<UnexpandedParameterPack, 4> Unexpanded; 4299 collectUnexpandedParameterPacks(BaseTL, Unexpanded); 4300 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded); 4301 bool ShouldExpand = false; 4302 bool RetainExpansion = false; 4303 Optional<unsigned> NumExpansions; 4304 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(), 4305 BaseTL.getSourceRange(), 4306 Unexpanded, 4307 TemplateArgs, ShouldExpand, 4308 RetainExpansion, 4309 NumExpansions)) { 4310 AnyErrors = true; 4311 New->setInvalidDecl(); 4312 continue; 4313 } 4314 assert(ShouldExpand && "Partial instantiation of base initializer?"); 4315 4316 // Loop over all of the arguments in the argument pack(s), 4317 for (unsigned I = 0; I != *NumExpansions; ++I) { 4318 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); 4319 4320 // Instantiate the initializer. 4321 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4322 /*CXXDirectInit=*/true); 4323 if (TempInit.isInvalid()) { 4324 AnyErrors = true; 4325 break; 4326 } 4327 4328 // Instantiate the base type. 4329 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), 4330 TemplateArgs, 4331 Init->getSourceLocation(), 4332 New->getDeclName()); 4333 if (!BaseTInfo) { 4334 AnyErrors = true; 4335 break; 4336 } 4337 4338 // Build the initializer. 4339 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(), 4340 BaseTInfo, TempInit.get(), 4341 New->getParent(), 4342 SourceLocation()); 4343 if (NewInit.isInvalid()) { 4344 AnyErrors = true; 4345 break; 4346 } 4347 4348 NewInits.push_back(NewInit.get()); 4349 } 4350 4351 continue; 4352 } 4353 4354 // Instantiate the initializer. 4355 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs, 4356 /*CXXDirectInit=*/true); 4357 if (TempInit.isInvalid()) { 4358 AnyErrors = true; 4359 continue; 4360 } 4361 4362 MemInitResult NewInit; 4363 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { 4364 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), 4365 TemplateArgs, 4366 Init->getSourceLocation(), 4367 New->getDeclName()); 4368 if (!TInfo) { 4369 AnyErrors = true; 4370 New->setInvalidDecl(); 4371 continue; 4372 } 4373 4374 if (Init->isBaseInitializer()) 4375 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(), 4376 New->getParent(), EllipsisLoc); 4377 else 4378 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(), 4379 cast<CXXRecordDecl>(CurContext->getParent())); 4380 } else if (Init->isMemberInitializer()) { 4381 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl( 4382 Init->getMemberLocation(), 4383 Init->getMember(), 4384 TemplateArgs)); 4385 if (!Member) { 4386 AnyErrors = true; 4387 New->setInvalidDecl(); 4388 continue; 4389 } 4390 4391 NewInit = BuildMemberInitializer(Member, TempInit.get(), 4392 Init->getSourceLocation()); 4393 } else if (Init->isIndirectMemberInitializer()) { 4394 IndirectFieldDecl *IndirectMember = 4395 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl( 4396 Init->getMemberLocation(), 4397 Init->getIndirectMember(), TemplateArgs)); 4398 4399 if (!IndirectMember) { 4400 AnyErrors = true; 4401 New->setInvalidDecl(); 4402 continue; 4403 } 4404 4405 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(), 4406 Init->getSourceLocation()); 4407 } 4408 4409 if (NewInit.isInvalid()) { 4410 AnyErrors = true; 4411 New->setInvalidDecl(); 4412 } else { 4413 NewInits.push_back(NewInit.get()); 4414 } 4415 } 4416 4417 // Assign all the initializers to the new constructor. 4418 ActOnMemInitializers(New, 4419 /*FIXME: ColonLoc */ 4420 SourceLocation(), 4421 NewInits, 4422 AnyErrors); 4423 } 4424 4425 // TODO: this could be templated if the various decl types used the 4426 // same method name. 4427 static bool isInstantiationOf(ClassTemplateDecl *Pattern, 4428 ClassTemplateDecl *Instance) { 4429 Pattern = Pattern->getCanonicalDecl(); 4430 4431 do { 4432 Instance = Instance->getCanonicalDecl(); 4433 if (Pattern == Instance) return true; 4434 Instance = Instance->getInstantiatedFromMemberTemplate(); 4435 } while (Instance); 4436 4437 return false; 4438 } 4439 4440 static bool isInstantiationOf(FunctionTemplateDecl *Pattern, 4441 FunctionTemplateDecl *Instance) { 4442 Pattern = Pattern->getCanonicalDecl(); 4443 4444 do { 4445 Instance = Instance->getCanonicalDecl(); 4446 if (Pattern == Instance) return true; 4447 Instance = Instance->getInstantiatedFromMemberTemplate(); 4448 } while (Instance); 4449 4450 return false; 4451 } 4452 4453 static bool 4454 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, 4455 ClassTemplatePartialSpecializationDecl *Instance) { 4456 Pattern 4457 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); 4458 do { 4459 Instance = cast<ClassTemplatePartialSpecializationDecl>( 4460 Instance->getCanonicalDecl()); 4461 if (Pattern == Instance) 4462 return true; 4463 Instance = Instance->getInstantiatedFromMember(); 4464 } while (Instance); 4465 4466 return false; 4467 } 4468 4469 static bool isInstantiationOf(CXXRecordDecl *Pattern, 4470 CXXRecordDecl *Instance) { 4471 Pattern = Pattern->getCanonicalDecl(); 4472 4473 do { 4474 Instance = Instance->getCanonicalDecl(); 4475 if (Pattern == Instance) return true; 4476 Instance = Instance->getInstantiatedFromMemberClass(); 4477 } while (Instance); 4478 4479 return false; 4480 } 4481 4482 static bool isInstantiationOf(FunctionDecl *Pattern, 4483 FunctionDecl *Instance) { 4484 Pattern = Pattern->getCanonicalDecl(); 4485 4486 do { 4487 Instance = Instance->getCanonicalDecl(); 4488 if (Pattern == Instance) return true; 4489 Instance = Instance->getInstantiatedFromMemberFunction(); 4490 } while (Instance); 4491 4492 return false; 4493 } 4494 4495 static bool isInstantiationOf(EnumDecl *Pattern, 4496 EnumDecl *Instance) { 4497 Pattern = Pattern->getCanonicalDecl(); 4498 4499 do { 4500 Instance = Instance->getCanonicalDecl(); 4501 if (Pattern == Instance) return true; 4502 Instance = Instance->getInstantiatedFromMemberEnum(); 4503 } while (Instance); 4504 4505 return false; 4506 } 4507 4508 static bool isInstantiationOf(UsingShadowDecl *Pattern, 4509 UsingShadowDecl *Instance, 4510 ASTContext &C) { 4511 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance), 4512 Pattern); 4513 } 4514 4515 static bool isInstantiationOf(UsingDecl *Pattern, 4516 UsingDecl *Instance, 4517 ASTContext &C) { 4518 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 4519 } 4520 4521 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern, 4522 UsingDecl *Instance, 4523 ASTContext &C) { 4524 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 4525 } 4526 4527 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern, 4528 UsingDecl *Instance, 4529 ASTContext &C) { 4530 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); 4531 } 4532 4533 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, 4534 VarDecl *Instance) { 4535 assert(Instance->isStaticDataMember()); 4536 4537 Pattern = Pattern->getCanonicalDecl(); 4538 4539 do { 4540 Instance = Instance->getCanonicalDecl(); 4541 if (Pattern == Instance) return true; 4542 Instance = Instance->getInstantiatedFromStaticDataMember(); 4543 } while (Instance); 4544 4545 return false; 4546 } 4547 4548 // Other is the prospective instantiation 4549 // D is the prospective pattern 4550 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { 4551 if (D->getKind() != Other->getKind()) { 4552 if (UnresolvedUsingTypenameDecl *UUD 4553 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 4554 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 4555 return isInstantiationOf(UUD, UD, Ctx); 4556 } 4557 } 4558 4559 if (UnresolvedUsingValueDecl *UUD 4560 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 4561 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) { 4562 return isInstantiationOf(UUD, UD, Ctx); 4563 } 4564 } 4565 4566 return false; 4567 } 4568 4569 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other)) 4570 return isInstantiationOf(cast<CXXRecordDecl>(D), Record); 4571 4572 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other)) 4573 return isInstantiationOf(cast<FunctionDecl>(D), Function); 4574 4575 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other)) 4576 return isInstantiationOf(cast<EnumDecl>(D), Enum); 4577 4578 if (VarDecl *Var = dyn_cast<VarDecl>(Other)) 4579 if (Var->isStaticDataMember()) 4580 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var); 4581 4582 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other)) 4583 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp); 4584 4585 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other)) 4586 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp); 4587 4588 if (ClassTemplatePartialSpecializationDecl *PartialSpec 4589 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other)) 4590 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D), 4591 PartialSpec); 4592 4593 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) { 4594 if (!Field->getDeclName()) { 4595 // This is an unnamed field. 4596 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field), 4597 cast<FieldDecl>(D)); 4598 } 4599 } 4600 4601 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other)) 4602 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx); 4603 4604 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other)) 4605 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx); 4606 4607 return D->getDeclName() && isa<NamedDecl>(Other) && 4608 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName(); 4609 } 4610 4611 template<typename ForwardIterator> 4612 static NamedDecl *findInstantiationOf(ASTContext &Ctx, 4613 NamedDecl *D, 4614 ForwardIterator first, 4615 ForwardIterator last) { 4616 for (; first != last; ++first) 4617 if (isInstantiationOf(Ctx, D, *first)) 4618 return cast<NamedDecl>(*first); 4619 4620 return nullptr; 4621 } 4622 4623 /// \brief Finds the instantiation of the given declaration context 4624 /// within the current instantiation. 4625 /// 4626 /// \returns NULL if there was an error 4627 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, 4628 const MultiLevelTemplateArgumentList &TemplateArgs) { 4629 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) { 4630 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs); 4631 return cast_or_null<DeclContext>(ID); 4632 } else return DC; 4633 } 4634 4635 /// \brief Find the instantiation of the given declaration within the 4636 /// current instantiation. 4637 /// 4638 /// This routine is intended to be used when \p D is a declaration 4639 /// referenced from within a template, that needs to mapped into the 4640 /// corresponding declaration within an instantiation. For example, 4641 /// given: 4642 /// 4643 /// \code 4644 /// template<typename T> 4645 /// struct X { 4646 /// enum Kind { 4647 /// KnownValue = sizeof(T) 4648 /// }; 4649 /// 4650 /// bool getKind() const { return KnownValue; } 4651 /// }; 4652 /// 4653 /// template struct X<int>; 4654 /// \endcode 4655 /// 4656 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the 4657 /// \p EnumConstantDecl for \p KnownValue (which refers to 4658 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation 4659 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs 4660 /// this mapping from within the instantiation of <tt>X<int></tt>. 4661 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 4662 const MultiLevelTemplateArgumentList &TemplateArgs) { 4663 DeclContext *ParentDC = D->getDeclContext(); 4664 // FIXME: Parmeters of pointer to functions (y below) that are themselves 4665 // parameters (p below) can have their ParentDC set to the translation-unit 4666 // - thus we can not consistently check if the ParentDC of such a parameter 4667 // is Dependent or/and a FunctionOrMethod. 4668 // For e.g. this code, during Template argument deduction tries to 4669 // find an instantiated decl for (T y) when the ParentDC for y is 4670 // the translation unit. 4671 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 4672 // float baz(float(*)()) { return 0.0; } 4673 // Foo(baz); 4674 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time 4675 // it gets here, always has a FunctionOrMethod as its ParentDC?? 4676 // For now: 4677 // - as long as we have a ParmVarDecl whose parent is non-dependent and 4678 // whose type is not instantiation dependent, do nothing to the decl 4679 // - otherwise find its instantiated decl. 4680 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() && 4681 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType()) 4682 return D; 4683 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) || 4684 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) || 4685 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) || 4686 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) { 4687 // D is a local of some kind. Look into the map of local 4688 // declarations to their instantiations. 4689 if (CurrentInstantiationScope) { 4690 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) { 4691 if (Decl *FD = Found->dyn_cast<Decl *>()) 4692 return cast<NamedDecl>(FD); 4693 4694 int PackIdx = ArgumentPackSubstitutionIndex; 4695 assert(PackIdx != -1 && 4696 "found declaration pack but not pack expanding"); 4697 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; 4698 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); 4699 } 4700 } 4701 4702 // If we're performing a partial substitution during template argument 4703 // deduction, we may not have values for template parameters yet. They 4704 // just map to themselves. 4705 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) || 4706 isa<TemplateTemplateParmDecl>(D)) 4707 return D; 4708 4709 if (D->isInvalidDecl()) 4710 return nullptr; 4711 4712 // Normally this function only searches for already instantiated declaration 4713 // however we have to make an exclusion for local types used before 4714 // definition as in the code: 4715 // 4716 // template<typename T> void f1() { 4717 // void g1(struct x1); 4718 // struct x1 {}; 4719 // } 4720 // 4721 // In this case instantiation of the type of 'g1' requires definition of 4722 // 'x1', which is defined later. Error recovery may produce an enum used 4723 // before definition. In these cases we need to instantiate relevant 4724 // declarations here. 4725 bool NeedInstantiate = false; 4726 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) 4727 NeedInstantiate = RD->isLocalClass(); 4728 else 4729 NeedInstantiate = isa<EnumDecl>(D); 4730 if (NeedInstantiate) { 4731 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 4732 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 4733 return cast<TypeDecl>(Inst); 4734 } 4735 4736 // If we didn't find the decl, then we must have a label decl that hasn't 4737 // been found yet. Lazily instantiate it and return it now. 4738 assert(isa<LabelDecl>(D)); 4739 4740 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); 4741 assert(Inst && "Failed to instantiate label??"); 4742 4743 CurrentInstantiationScope->InstantiatedLocal(D, Inst); 4744 return cast<LabelDecl>(Inst); 4745 } 4746 4747 // For variable template specializations, update those that are still 4748 // type-dependent. 4749 if (VarTemplateSpecializationDecl *VarSpec = 4750 dyn_cast<VarTemplateSpecializationDecl>(D)) { 4751 bool InstantiationDependent = false; 4752 const TemplateArgumentListInfo &VarTemplateArgs = 4753 VarSpec->getTemplateArgsInfo(); 4754 if (TemplateSpecializationType::anyDependentTemplateArguments( 4755 VarTemplateArgs, InstantiationDependent)) 4756 D = cast<NamedDecl>( 4757 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs)); 4758 return D; 4759 } 4760 4761 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 4762 if (!Record->isDependentContext()) 4763 return D; 4764 4765 // Determine whether this record is the "templated" declaration describing 4766 // a class template or class template partial specialization. 4767 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); 4768 if (ClassTemplate) 4769 ClassTemplate = ClassTemplate->getCanonicalDecl(); 4770 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 4771 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 4772 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl(); 4773 4774 // Walk the current context to find either the record or an instantiation of 4775 // it. 4776 DeclContext *DC = CurContext; 4777 while (!DC->isFileContext()) { 4778 // If we're performing substitution while we're inside the template 4779 // definition, we'll find our own context. We're done. 4780 if (DC->Equals(Record)) 4781 return Record; 4782 4783 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) { 4784 // Check whether we're in the process of instantiating a class template 4785 // specialization of the template we're mapping. 4786 if (ClassTemplateSpecializationDecl *InstSpec 4787 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){ 4788 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); 4789 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate)) 4790 return InstRecord; 4791 } 4792 4793 // Check whether we're in the process of instantiating a member class. 4794 if (isInstantiationOf(Record, InstRecord)) 4795 return InstRecord; 4796 } 4797 4798 // Move to the outer template scope. 4799 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) { 4800 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){ 4801 DC = FD->getLexicalDeclContext(); 4802 continue; 4803 } 4804 } 4805 4806 DC = DC->getParent(); 4807 } 4808 4809 // Fall through to deal with other dependent record types (e.g., 4810 // anonymous unions in class templates). 4811 } 4812 4813 if (!ParentDC->isDependentContext()) 4814 return D; 4815 4816 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs); 4817 if (!ParentDC) 4818 return nullptr; 4819 4820 if (ParentDC != D->getDeclContext()) { 4821 // We performed some kind of instantiation in the parent context, 4822 // so now we need to look into the instantiated parent context to 4823 // find the instantiation of the declaration D. 4824 4825 // If our context used to be dependent, we may need to instantiate 4826 // it before performing lookup into that context. 4827 bool IsBeingInstantiated = false; 4828 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) { 4829 if (!Spec->isDependentContext()) { 4830 QualType T = Context.getTypeDeclType(Spec); 4831 const RecordType *Tag = T->getAs<RecordType>(); 4832 assert(Tag && "type of non-dependent record is not a RecordType"); 4833 if (Tag->isBeingDefined()) 4834 IsBeingInstantiated = true; 4835 if (!Tag->isBeingDefined() && 4836 RequireCompleteType(Loc, T, diag::err_incomplete_type)) 4837 return nullptr; 4838 4839 ParentDC = Tag->getDecl(); 4840 } 4841 } 4842 4843 NamedDecl *Result = nullptr; 4844 if (D->getDeclName()) { 4845 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName()); 4846 Result = findInstantiationOf(Context, D, Found.begin(), Found.end()); 4847 } else { 4848 // Since we don't have a name for the entity we're looking for, 4849 // our only option is to walk through all of the declarations to 4850 // find that name. This will occur in a few cases: 4851 // 4852 // - anonymous struct/union within a template 4853 // - unnamed class/struct/union/enum within a template 4854 // 4855 // FIXME: Find a better way to find these instantiations! 4856 Result = findInstantiationOf(Context, D, 4857 ParentDC->decls_begin(), 4858 ParentDC->decls_end()); 4859 } 4860 4861 if (!Result) { 4862 if (isa<UsingShadowDecl>(D)) { 4863 // UsingShadowDecls can instantiate to nothing because of using hiding. 4864 } else if (Diags.hasErrorOccurred()) { 4865 // We've already complained about something, so most likely this 4866 // declaration failed to instantiate. There's no point in complaining 4867 // further, since this is normal in invalid code. 4868 } else if (IsBeingInstantiated) { 4869 // The class in which this member exists is currently being 4870 // instantiated, and we haven't gotten around to instantiating this 4871 // member yet. This can happen when the code uses forward declarations 4872 // of member classes, and introduces ordering dependencies via 4873 // template instantiation. 4874 Diag(Loc, diag::err_member_not_yet_instantiated) 4875 << D->getDeclName() 4876 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); 4877 Diag(D->getLocation(), diag::note_non_instantiated_member_here); 4878 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) { 4879 // This enumeration constant was found when the template was defined, 4880 // but can't be found in the instantiation. This can happen if an 4881 // unscoped enumeration member is explicitly specialized. 4882 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); 4883 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum, 4884 TemplateArgs)); 4885 assert(Spec->getTemplateSpecializationKind() == 4886 TSK_ExplicitSpecialization); 4887 Diag(Loc, diag::err_enumerator_does_not_exist) 4888 << D->getDeclName() 4889 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); 4890 Diag(Spec->getLocation(), diag::note_enum_specialized_here) 4891 << Context.getTypeDeclType(Spec); 4892 } else { 4893 // We should have found something, but didn't. 4894 llvm_unreachable("Unable to find instantiation of declaration!"); 4895 } 4896 } 4897 4898 D = Result; 4899 } 4900 4901 return D; 4902 } 4903 4904 /// \brief Performs template instantiation for all implicit template 4905 /// instantiations we have seen until this point. 4906 void Sema::PerformPendingInstantiations(bool LocalOnly) { 4907 while (!PendingLocalImplicitInstantiations.empty() || 4908 (!LocalOnly && !PendingInstantiations.empty())) { 4909 PendingImplicitInstantiation Inst; 4910 4911 if (PendingLocalImplicitInstantiations.empty()) { 4912 Inst = PendingInstantiations.front(); 4913 PendingInstantiations.pop_front(); 4914 } else { 4915 Inst = PendingLocalImplicitInstantiations.front(); 4916 PendingLocalImplicitInstantiations.pop_front(); 4917 } 4918 4919 // Instantiate function definitions 4920 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) { 4921 bool DefinitionRequired = Function->getTemplateSpecializationKind() == 4922 TSK_ExplicitInstantiationDefinition; 4923 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true, 4924 DefinitionRequired, true); 4925 continue; 4926 } 4927 4928 // Instantiate variable definitions 4929 VarDecl *Var = cast<VarDecl>(Inst.first); 4930 4931 assert((Var->isStaticDataMember() || 4932 isa<VarTemplateSpecializationDecl>(Var)) && 4933 "Not a static data member, nor a variable template" 4934 " specialization?"); 4935 4936 // Don't try to instantiate declarations if the most recent redeclaration 4937 // is invalid. 4938 if (Var->getMostRecentDecl()->isInvalidDecl()) 4939 continue; 4940 4941 // Check if the most recent declaration has changed the specialization kind 4942 // and removed the need for implicit instantiation. 4943 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) { 4944 case TSK_Undeclared: 4945 llvm_unreachable("Cannot instantitiate an undeclared specialization."); 4946 case TSK_ExplicitInstantiationDeclaration: 4947 case TSK_ExplicitSpecialization: 4948 continue; // No longer need to instantiate this type. 4949 case TSK_ExplicitInstantiationDefinition: 4950 // We only need an instantiation if the pending instantiation *is* the 4951 // explicit instantiation. 4952 if (Var != Var->getMostRecentDecl()) continue; 4953 case TSK_ImplicitInstantiation: 4954 break; 4955 } 4956 4957 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(), 4958 "instantiating variable definition"); 4959 bool DefinitionRequired = Var->getTemplateSpecializationKind() == 4960 TSK_ExplicitInstantiationDefinition; 4961 4962 // Instantiate static data member definitions or variable template 4963 // specializations. 4964 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true, 4965 DefinitionRequired, true); 4966 } 4967 } 4968 4969 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, 4970 const MultiLevelTemplateArgumentList &TemplateArgs) { 4971 for (auto DD : Pattern->ddiags()) { 4972 switch (DD->getKind()) { 4973 case DependentDiagnostic::Access: 4974 HandleDependentAccessCheck(*DD, TemplateArgs); 4975 break; 4976 } 4977 } 4978 } 4979