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