1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 //===----------------------------------------------------------------------===// 7 // 8 // This file implements semantic analysis for C++ templates. 9 //===----------------------------------------------------------------------===// 10 11 #include "TreeTransform.h" 12 #include "clang/AST/ASTConsumer.h" 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/DeclFriend.h" 15 #include "clang/AST/DeclTemplate.h" 16 #include "clang/AST/Expr.h" 17 #include "clang/AST/ExprCXX.h" 18 #include "clang/AST/RecursiveASTVisitor.h" 19 #include "clang/AST/TypeVisitor.h" 20 #include "clang/Basic/Builtins.h" 21 #include "clang/Basic/LangOptions.h" 22 #include "clang/Basic/PartialDiagnostic.h" 23 #include "clang/Basic/TargetInfo.h" 24 #include "clang/Sema/DeclSpec.h" 25 #include "clang/Sema/Lookup.h" 26 #include "clang/Sema/ParsedTemplate.h" 27 #include "clang/Sema/Scope.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/SmallBitVector.h" 32 #include "llvm/ADT/SmallString.h" 33 #include "llvm/ADT/StringExtras.h" 34 35 #include <iterator> 36 using namespace clang; 37 using namespace sema; 38 39 // Exported for use by Parser. 40 SourceRange 41 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, 42 unsigned N) { 43 if (!N) return SourceRange(); 44 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); 45 } 46 47 namespace clang { 48 /// [temp.constr.decl]p2: A template's associated constraints are 49 /// defined as a single constraint-expression derived from the introduced 50 /// constraint-expressions [ ... ]. 51 /// 52 /// \param Params The template parameter list and optional requires-clause. 53 /// 54 /// \param FD The underlying templated function declaration for a function 55 /// template. 56 static Expr *formAssociatedConstraints(TemplateParameterList *Params, 57 FunctionDecl *FD); 58 } 59 60 static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params, 61 FunctionDecl *FD) { 62 // FIXME: Concepts: collect additional introduced constraint-expressions 63 assert(!FD && "Cannot collect constraints from function declaration yet."); 64 return Params->getRequiresClause(); 65 } 66 67 /// Determine whether the declaration found is acceptable as the name 68 /// of a template and, if so, return that template declaration. Otherwise, 69 /// returns null. 70 /// 71 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent 72 /// is true. In all other cases it will return a TemplateDecl (or null). 73 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D, 74 bool AllowFunctionTemplates, 75 bool AllowDependent) { 76 D = D->getUnderlyingDecl(); 77 78 if (isa<TemplateDecl>(D)) { 79 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D)) 80 return nullptr; 81 82 return D; 83 } 84 85 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 86 // C++ [temp.local]p1: 87 // Like normal (non-template) classes, class templates have an 88 // injected-class-name (Clause 9). The injected-class-name 89 // can be used with or without a template-argument-list. When 90 // it is used without a template-argument-list, it is 91 // equivalent to the injected-class-name followed by the 92 // template-parameters of the class template enclosed in 93 // <>. When it is used with a template-argument-list, it 94 // refers to the specified class template specialization, 95 // which could be the current specialization or another 96 // specialization. 97 if (Record->isInjectedClassName()) { 98 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 99 if (Record->getDescribedClassTemplate()) 100 return Record->getDescribedClassTemplate(); 101 102 if (ClassTemplateSpecializationDecl *Spec 103 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 104 return Spec->getSpecializedTemplate(); 105 } 106 107 return nullptr; 108 } 109 110 // 'using Dependent::foo;' can resolve to a template name. 111 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an 112 // injected-class-name). 113 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D)) 114 return D; 115 116 return nullptr; 117 } 118 119 void Sema::FilterAcceptableTemplateNames(LookupResult &R, 120 bool AllowFunctionTemplates, 121 bool AllowDependent) { 122 LookupResult::Filter filter = R.makeFilter(); 123 while (filter.hasNext()) { 124 NamedDecl *Orig = filter.next(); 125 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent)) 126 filter.erase(); 127 } 128 filter.done(); 129 } 130 131 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R, 132 bool AllowFunctionTemplates, 133 bool AllowDependent) { 134 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) 135 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent)) 136 return true; 137 138 return false; 139 } 140 141 TemplateNameKind Sema::isTemplateName(Scope *S, 142 CXXScopeSpec &SS, 143 bool hasTemplateKeyword, 144 const UnqualifiedId &Name, 145 ParsedType ObjectTypePtr, 146 bool EnteringContext, 147 TemplateTy &TemplateResult, 148 bool &MemberOfUnknownSpecialization) { 149 assert(getLangOpts().CPlusPlus && "No template names in C!"); 150 151 DeclarationName TName; 152 MemberOfUnknownSpecialization = false; 153 154 switch (Name.getKind()) { 155 case UnqualifiedIdKind::IK_Identifier: 156 TName = DeclarationName(Name.Identifier); 157 break; 158 159 case UnqualifiedIdKind::IK_OperatorFunctionId: 160 TName = Context.DeclarationNames.getCXXOperatorName( 161 Name.OperatorFunctionId.Operator); 162 break; 163 164 case UnqualifiedIdKind::IK_LiteralOperatorId: 165 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); 166 break; 167 168 default: 169 return TNK_Non_template; 170 } 171 172 QualType ObjectType = ObjectTypePtr.get(); 173 174 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName); 175 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext, 176 MemberOfUnknownSpecialization)) 177 return TNK_Non_template; 178 if (R.empty()) return TNK_Non_template; 179 180 NamedDecl *D = nullptr; 181 if (R.isAmbiguous()) { 182 // If we got an ambiguity involving a non-function template, treat this 183 // as a template name, and pick an arbitrary template for error recovery. 184 bool AnyFunctionTemplates = false; 185 for (NamedDecl *FoundD : R) { 186 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) { 187 if (isa<FunctionTemplateDecl>(FoundTemplate)) 188 AnyFunctionTemplates = true; 189 else { 190 D = FoundTemplate; 191 break; 192 } 193 } 194 } 195 196 // If we didn't find any templates at all, this isn't a template name. 197 // Leave the ambiguity for a later lookup to diagnose. 198 if (!D && !AnyFunctionTemplates) { 199 R.suppressDiagnostics(); 200 return TNK_Non_template; 201 } 202 203 // If the only templates were function templates, filter out the rest. 204 // We'll diagnose the ambiguity later. 205 if (!D) 206 FilterAcceptableTemplateNames(R); 207 } 208 209 // At this point, we have either picked a single template name declaration D 210 // or we have a non-empty set of results R containing either one template name 211 // declaration or a set of function templates. 212 213 TemplateName Template; 214 TemplateNameKind TemplateKind; 215 216 unsigned ResultCount = R.end() - R.begin(); 217 if (!D && ResultCount > 1) { 218 // We assume that we'll preserve the qualifier from a function 219 // template name in other ways. 220 Template = Context.getOverloadedTemplateName(R.begin(), R.end()); 221 TemplateKind = TNK_Function_template; 222 223 // We'll do this lookup again later. 224 R.suppressDiagnostics(); 225 } else { 226 if (!D) { 227 D = getAsTemplateNameDecl(*R.begin()); 228 assert(D && "unambiguous result is not a template name"); 229 } 230 231 if (isa<UnresolvedUsingValueDecl>(D)) { 232 // We don't yet know whether this is a template-name or not. 233 MemberOfUnknownSpecialization = true; 234 return TNK_Non_template; 235 } 236 237 TemplateDecl *TD = cast<TemplateDecl>(D); 238 239 if (SS.isSet() && !SS.isInvalid()) { 240 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 241 Template = Context.getQualifiedTemplateName(Qualifier, 242 hasTemplateKeyword, TD); 243 } else { 244 Template = TemplateName(TD); 245 } 246 247 if (isa<FunctionTemplateDecl>(TD)) { 248 TemplateKind = TNK_Function_template; 249 250 // We'll do this lookup again later. 251 R.suppressDiagnostics(); 252 } else { 253 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || 254 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || 255 isa<BuiltinTemplateDecl>(TD)); 256 TemplateKind = 257 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template; 258 } 259 } 260 261 TemplateResult = TemplateTy::make(Template); 262 return TemplateKind; 263 } 264 265 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name, 266 SourceLocation NameLoc, 267 ParsedTemplateTy *Template) { 268 CXXScopeSpec SS; 269 bool MemberOfUnknownSpecialization = false; 270 271 // We could use redeclaration lookup here, but we don't need to: the 272 // syntactic form of a deduction guide is enough to identify it even 273 // if we can't look up the template name at all. 274 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName); 275 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(), 276 /*EnteringContext*/ false, 277 MemberOfUnknownSpecialization)) 278 return false; 279 280 if (R.empty()) return false; 281 if (R.isAmbiguous()) { 282 // FIXME: Diagnose an ambiguity if we find at least one template. 283 R.suppressDiagnostics(); 284 return false; 285 } 286 287 // We only treat template-names that name type templates as valid deduction 288 // guide names. 289 TemplateDecl *TD = R.getAsSingle<TemplateDecl>(); 290 if (!TD || !getAsTypeTemplateDecl(TD)) 291 return false; 292 293 if (Template) 294 *Template = TemplateTy::make(TemplateName(TD)); 295 return true; 296 } 297 298 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, 299 SourceLocation IILoc, 300 Scope *S, 301 const CXXScopeSpec *SS, 302 TemplateTy &SuggestedTemplate, 303 TemplateNameKind &SuggestedKind) { 304 // We can't recover unless there's a dependent scope specifier preceding the 305 // template name. 306 // FIXME: Typo correction? 307 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || 308 computeDeclContext(*SS)) 309 return false; 310 311 // The code is missing a 'template' keyword prior to the dependent template 312 // name. 313 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); 314 Diag(IILoc, diag::err_template_kw_missing) 315 << Qualifier << II.getName() 316 << FixItHint::CreateInsertion(IILoc, "template "); 317 SuggestedTemplate 318 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); 319 SuggestedKind = TNK_Dependent_template_name; 320 return true; 321 } 322 323 bool Sema::LookupTemplateName(LookupResult &Found, 324 Scope *S, CXXScopeSpec &SS, 325 QualType ObjectType, 326 bool EnteringContext, 327 bool &MemberOfUnknownSpecialization, 328 SourceLocation TemplateKWLoc) { 329 Found.setTemplateNameLookup(true); 330 331 // Determine where to perform name lookup 332 MemberOfUnknownSpecialization = false; 333 DeclContext *LookupCtx = nullptr; 334 bool IsDependent = false; 335 if (!ObjectType.isNull()) { 336 // This nested-name-specifier occurs in a member access expression, e.g., 337 // x->B::f, and we are looking into the type of the object. 338 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 339 LookupCtx = computeDeclContext(ObjectType); 340 IsDependent = !LookupCtx; 341 assert((IsDependent || !ObjectType->isIncompleteType() || 342 ObjectType->castAs<TagType>()->isBeingDefined()) && 343 "Caller should have completed object type"); 344 345 // Template names cannot appear inside an Objective-C class or object type. 346 if (ObjectType->isObjCObjectOrInterfaceType()) { 347 Found.clear(); 348 return false; 349 } 350 } else if (SS.isSet()) { 351 // This nested-name-specifier occurs after another nested-name-specifier, 352 // so long into the context associated with the prior nested-name-specifier. 353 LookupCtx = computeDeclContext(SS, EnteringContext); 354 IsDependent = !LookupCtx; 355 356 // The declaration context must be complete. 357 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) 358 return true; 359 } 360 361 bool ObjectTypeSearchedInScope = false; 362 bool AllowFunctionTemplatesInLookup = true; 363 if (LookupCtx) { 364 // Perform "qualified" name lookup into the declaration context we 365 // computed, which is either the type of the base of a member access 366 // expression or the declaration context associated with a prior 367 // nested-name-specifier. 368 LookupQualifiedName(Found, LookupCtx); 369 370 // FIXME: The C++ standard does not clearly specify what happens in the 371 // case where the object type is dependent, and implementations vary. In 372 // Clang, we treat a name after a . or -> as a template-name if lookup 373 // finds a non-dependent member or member of the current instantiation that 374 // is a type template, or finds no such members and lookup in the context 375 // of the postfix-expression finds a type template. In the latter case, the 376 // name is nonetheless dependent, and we may resolve it to a member of an 377 // unknown specialization when we come to instantiate the template. 378 IsDependent |= Found.wasNotFoundInCurrentInstantiation(); 379 } 380 381 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) { 382 // C++ [basic.lookup.classref]p1: 383 // In a class member access expression (5.2.5), if the . or -> token is 384 // immediately followed by an identifier followed by a <, the 385 // identifier must be looked up to determine whether the < is the 386 // beginning of a template argument list (14.2) or a less-than operator. 387 // The identifier is first looked up in the class of the object 388 // expression. If the identifier is not found, it is then looked up in 389 // the context of the entire postfix-expression and shall name a class 390 // template. 391 if (S) 392 LookupName(Found, S); 393 394 if (!ObjectType.isNull()) { 395 // FIXME: We should filter out all non-type templates here, particularly 396 // variable templates and concepts. But the exclusion of alias templates 397 // and template template parameters is a wording defect. 398 AllowFunctionTemplatesInLookup = false; 399 ObjectTypeSearchedInScope = true; 400 } 401 402 IsDependent |= Found.wasNotFoundInCurrentInstantiation(); 403 } 404 405 if (Found.isAmbiguous()) 406 return false; 407 408 if (Found.empty() && !IsDependent) { 409 // If we did not find any names, attempt to correct any typos. 410 DeclarationName Name = Found.getLookupName(); 411 Found.clear(); 412 // Simple filter callback that, for keywords, only accepts the C++ *_cast 413 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>(); 414 FilterCCC->WantTypeSpecifiers = false; 415 FilterCCC->WantExpressionKeywords = false; 416 FilterCCC->WantRemainingKeywords = false; 417 FilterCCC->WantCXXNamedCasts = true; 418 if (TypoCorrection Corrected = CorrectTypo( 419 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, 420 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) { 421 Found.setLookupName(Corrected.getCorrection()); 422 if (auto *ND = Corrected.getFoundDecl()) 423 Found.addDecl(ND); 424 FilterAcceptableTemplateNames(Found); 425 if (Found.isAmbiguous()) { 426 Found.clear(); 427 } else if (!Found.empty()) { 428 if (LookupCtx) { 429 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 430 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 431 Name.getAsString() == CorrectedStr; 432 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest) 433 << Name << LookupCtx << DroppedSpecifier 434 << SS.getRange()); 435 } else { 436 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name); 437 } 438 } 439 } else { 440 Found.setLookupName(Name); 441 } 442 } 443 444 NamedDecl *ExampleLookupResult = 445 Found.empty() ? nullptr : Found.getRepresentativeDecl(); 446 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup); 447 if (Found.empty()) { 448 if (IsDependent) { 449 MemberOfUnknownSpecialization = true; 450 return false; 451 } 452 453 // If a 'template' keyword was used, a lookup that finds only non-template 454 // names is an error. 455 if (ExampleLookupResult && TemplateKWLoc.isValid()) { 456 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template) 457 << Found.getLookupName() << SS.getRange(); 458 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(), 459 diag::note_template_kw_refers_to_non_template) 460 << Found.getLookupName(); 461 return true; 462 } 463 464 return false; 465 } 466 467 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope && 468 !getLangOpts().CPlusPlus11) { 469 // C++03 [basic.lookup.classref]p1: 470 // [...] If the lookup in the class of the object expression finds a 471 // template, the name is also looked up in the context of the entire 472 // postfix-expression and [...] 473 // 474 // Note: C++11 does not perform this second lookup. 475 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 476 LookupOrdinaryName); 477 FoundOuter.setTemplateNameLookup(true); 478 LookupName(FoundOuter, S); 479 // FIXME: We silently accept an ambiguous lookup here, in violation of 480 // [basic.lookup]/1. 481 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false); 482 483 NamedDecl *OuterTemplate; 484 if (FoundOuter.empty()) { 485 // - if the name is not found, the name found in the class of the 486 // object expression is used, otherwise 487 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() || 488 !(OuterTemplate = 489 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) { 490 // - if the name is found in the context of the entire 491 // postfix-expression and does not name a class template, the name 492 // found in the class of the object expression is used, otherwise 493 FoundOuter.clear(); 494 } else if (!Found.isSuppressingDiagnostics()) { 495 // - if the name found is a class template, it must refer to the same 496 // entity as the one found in the class of the object expression, 497 // otherwise the program is ill-formed. 498 if (!Found.isSingleResult() || 499 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() != 500 OuterTemplate->getCanonicalDecl()) { 501 Diag(Found.getNameLoc(), 502 diag::ext_nested_name_member_ref_lookup_ambiguous) 503 << Found.getLookupName() 504 << ObjectType; 505 Diag(Found.getRepresentativeDecl()->getLocation(), 506 diag::note_ambig_member_ref_object_type) 507 << ObjectType; 508 Diag(FoundOuter.getFoundDecl()->getLocation(), 509 diag::note_ambig_member_ref_scope); 510 511 // Recover by taking the template that we found in the object 512 // expression's type. 513 } 514 } 515 } 516 517 return false; 518 } 519 520 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, 521 SourceLocation Less, 522 SourceLocation Greater) { 523 if (TemplateName.isInvalid()) 524 return; 525 526 DeclarationNameInfo NameInfo; 527 CXXScopeSpec SS; 528 LookupNameKind LookupKind; 529 530 DeclContext *LookupCtx = nullptr; 531 NamedDecl *Found = nullptr; 532 bool MissingTemplateKeyword = false; 533 534 // Figure out what name we looked up. 535 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) { 536 NameInfo = DRE->getNameInfo(); 537 SS.Adopt(DRE->getQualifierLoc()); 538 LookupKind = LookupOrdinaryName; 539 Found = DRE->getFoundDecl(); 540 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) { 541 NameInfo = ME->getMemberNameInfo(); 542 SS.Adopt(ME->getQualifierLoc()); 543 LookupKind = LookupMemberName; 544 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl(); 545 Found = ME->getMemberDecl(); 546 } else if (auto *DSDRE = 547 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) { 548 NameInfo = DSDRE->getNameInfo(); 549 SS.Adopt(DSDRE->getQualifierLoc()); 550 MissingTemplateKeyword = true; 551 } else if (auto *DSME = 552 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) { 553 NameInfo = DSME->getMemberNameInfo(); 554 SS.Adopt(DSME->getQualifierLoc()); 555 MissingTemplateKeyword = true; 556 } else { 557 llvm_unreachable("unexpected kind of potential template name"); 558 } 559 560 // If this is a dependent-scope lookup, diagnose that the 'template' keyword 561 // was missing. 562 if (MissingTemplateKeyword) { 563 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing) 564 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater); 565 return; 566 } 567 568 // Try to correct the name by looking for templates and C++ named casts. 569 struct TemplateCandidateFilter : CorrectionCandidateCallback { 570 Sema &S; 571 TemplateCandidateFilter(Sema &S) : S(S) { 572 WantTypeSpecifiers = false; 573 WantExpressionKeywords = false; 574 WantRemainingKeywords = false; 575 WantCXXNamedCasts = true; 576 }; 577 bool ValidateCandidate(const TypoCorrection &Candidate) override { 578 if (auto *ND = Candidate.getCorrectionDecl()) 579 return S.getAsTemplateNameDecl(ND); 580 return Candidate.isKeyword(); 581 } 582 }; 583 584 DeclarationName Name = NameInfo.getName(); 585 if (TypoCorrection Corrected = 586 CorrectTypo(NameInfo, LookupKind, S, &SS, 587 llvm::make_unique<TemplateCandidateFilter>(*this), 588 CTK_ErrorRecovery, LookupCtx)) { 589 auto *ND = Corrected.getFoundDecl(); 590 if (ND) 591 ND = getAsTemplateNameDecl(ND); 592 if (ND || Corrected.isKeyword()) { 593 if (LookupCtx) { 594 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 595 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 596 Name.getAsString() == CorrectedStr; 597 diagnoseTypo(Corrected, 598 PDiag(diag::err_non_template_in_member_template_id_suggest) 599 << Name << LookupCtx << DroppedSpecifier 600 << SS.getRange(), false); 601 } else { 602 diagnoseTypo(Corrected, 603 PDiag(diag::err_non_template_in_template_id_suggest) 604 << Name, false); 605 } 606 if (Found) 607 Diag(Found->getLocation(), 608 diag::note_non_template_in_template_id_found); 609 return; 610 } 611 } 612 613 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id) 614 << Name << SourceRange(Less, Greater); 615 if (Found) 616 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found); 617 } 618 619 /// ActOnDependentIdExpression - Handle a dependent id-expression that 620 /// was just parsed. This is only possible with an explicit scope 621 /// specifier naming a dependent type. 622 ExprResult 623 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 624 SourceLocation TemplateKWLoc, 625 const DeclarationNameInfo &NameInfo, 626 bool isAddressOfOperand, 627 const TemplateArgumentListInfo *TemplateArgs) { 628 DeclContext *DC = getFunctionLevelDeclContext(); 629 630 // C++11 [expr.prim.general]p12: 631 // An id-expression that denotes a non-static data member or non-static 632 // member function of a class can only be used: 633 // (...) 634 // - if that id-expression denotes a non-static data member and it 635 // appears in an unevaluated operand. 636 // 637 // If this might be the case, form a DependentScopeDeclRefExpr instead of a 638 // CXXDependentScopeMemberExpr. The former can instantiate to either 639 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is 640 // always a MemberExpr. 641 bool MightBeCxx11UnevalField = 642 getLangOpts().CPlusPlus11 && isUnevaluatedContext(); 643 644 // Check if the nested name specifier is an enum type. 645 bool IsEnum = false; 646 if (NestedNameSpecifier *NNS = SS.getScopeRep()) 647 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType()); 648 649 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum && 650 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) { 651 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(); 652 653 // Since the 'this' expression is synthesized, we don't need to 654 // perform the double-lookup check. 655 NamedDecl *FirstQualifierInScope = nullptr; 656 657 return CXXDependentScopeMemberExpr::Create( 658 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true, 659 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc, 660 FirstQualifierInScope, NameInfo, TemplateArgs); 661 } 662 663 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); 664 } 665 666 ExprResult 667 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 668 SourceLocation TemplateKWLoc, 669 const DeclarationNameInfo &NameInfo, 670 const TemplateArgumentListInfo *TemplateArgs) { 671 return DependentScopeDeclRefExpr::Create( 672 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 673 TemplateArgs); 674 } 675 676 677 /// Determine whether we would be unable to instantiate this template (because 678 /// it either has no definition, or is in the process of being instantiated). 679 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, 680 NamedDecl *Instantiation, 681 bool InstantiatedFromMember, 682 const NamedDecl *Pattern, 683 const NamedDecl *PatternDef, 684 TemplateSpecializationKind TSK, 685 bool Complain /*= true*/) { 686 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || 687 isa<VarDecl>(Instantiation)); 688 689 bool IsEntityBeingDefined = false; 690 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef)) 691 IsEntityBeingDefined = TD->isBeingDefined(); 692 693 if (PatternDef && !IsEntityBeingDefined) { 694 NamedDecl *SuggestedDef = nullptr; 695 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef, 696 /*OnlyNeedComplete*/false)) { 697 // If we're allowed to diagnose this and recover, do so. 698 bool Recover = Complain && !isSFINAEContext(); 699 if (Complain) 700 diagnoseMissingImport(PointOfInstantiation, SuggestedDef, 701 Sema::MissingImportKind::Definition, Recover); 702 return !Recover; 703 } 704 return false; 705 } 706 707 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) 708 return true; 709 710 llvm::Optional<unsigned> Note; 711 QualType InstantiationTy; 712 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation)) 713 InstantiationTy = Context.getTypeDeclType(TD); 714 if (PatternDef) { 715 Diag(PointOfInstantiation, 716 diag::err_template_instantiate_within_definition) 717 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation) 718 << InstantiationTy; 719 // Not much point in noting the template declaration here, since 720 // we're lexically inside it. 721 Instantiation->setInvalidDecl(); 722 } else if (InstantiatedFromMember) { 723 if (isa<FunctionDecl>(Instantiation)) { 724 Diag(PointOfInstantiation, 725 diag::err_explicit_instantiation_undefined_member) 726 << /*member function*/ 1 << Instantiation->getDeclName() 727 << Instantiation->getDeclContext(); 728 Note = diag::note_explicit_instantiation_here; 729 } else { 730 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!"); 731 Diag(PointOfInstantiation, 732 diag::err_implicit_instantiate_member_undefined) 733 << InstantiationTy; 734 Note = diag::note_member_declared_at; 735 } 736 } else { 737 if (isa<FunctionDecl>(Instantiation)) { 738 Diag(PointOfInstantiation, 739 diag::err_explicit_instantiation_undefined_func_template) 740 << Pattern; 741 Note = diag::note_explicit_instantiation_here; 742 } else if (isa<TagDecl>(Instantiation)) { 743 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 744 << (TSK != TSK_ImplicitInstantiation) 745 << InstantiationTy; 746 Note = diag::note_template_decl_here; 747 } else { 748 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!"); 749 if (isa<VarTemplateSpecializationDecl>(Instantiation)) { 750 Diag(PointOfInstantiation, 751 diag::err_explicit_instantiation_undefined_var_template) 752 << Instantiation; 753 Instantiation->setInvalidDecl(); 754 } else 755 Diag(PointOfInstantiation, 756 diag::err_explicit_instantiation_undefined_member) 757 << /*static data member*/ 2 << Instantiation->getDeclName() 758 << Instantiation->getDeclContext(); 759 Note = diag::note_explicit_instantiation_here; 760 } 761 } 762 if (Note) // Diagnostics were emitted. 763 Diag(Pattern->getLocation(), Note.getValue()); 764 765 // In general, Instantiation isn't marked invalid to get more than one 766 // error for multiple undefined instantiations. But the code that does 767 // explicit declaration -> explicit definition conversion can't handle 768 // invalid declarations, so mark as invalid in that case. 769 if (TSK == TSK_ExplicitInstantiationDeclaration) 770 Instantiation->setInvalidDecl(); 771 return true; 772 } 773 774 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 775 /// that the template parameter 'PrevDecl' is being shadowed by a new 776 /// declaration at location Loc. Returns true to indicate that this is 777 /// an error, and false otherwise. 778 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 779 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 780 781 // Microsoft Visual C++ permits template parameters to be shadowed. 782 if (getLangOpts().MicrosoftExt) 783 return; 784 785 // C++ [temp.local]p4: 786 // A template-parameter shall not be redeclared within its 787 // scope (including nested scopes). 788 Diag(Loc, diag::err_template_param_shadow) 789 << cast<NamedDecl>(PrevDecl)->getDeclName(); 790 Diag(PrevDecl->getLocation(), diag::note_template_param_here); 791 } 792 793 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 794 /// the parameter D to reference the templated declaration and return a pointer 795 /// to the template declaration. Otherwise, do nothing to D and return null. 796 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { 797 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { 798 D = Temp->getTemplatedDecl(); 799 return Temp; 800 } 801 return nullptr; 802 } 803 804 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( 805 SourceLocation EllipsisLoc) const { 806 assert(Kind == Template && 807 "Only template template arguments can be pack expansions here"); 808 assert(getAsTemplate().get().containsUnexpandedParameterPack() && 809 "Template template argument pack expansion without packs"); 810 ParsedTemplateArgument Result(*this); 811 Result.EllipsisLoc = EllipsisLoc; 812 return Result; 813 } 814 815 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 816 const ParsedTemplateArgument &Arg) { 817 818 switch (Arg.getKind()) { 819 case ParsedTemplateArgument::Type: { 820 TypeSourceInfo *DI; 821 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 822 if (!DI) 823 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); 824 return TemplateArgumentLoc(TemplateArgument(T), DI); 825 } 826 827 case ParsedTemplateArgument::NonType: { 828 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 829 return TemplateArgumentLoc(TemplateArgument(E), E); 830 } 831 832 case ParsedTemplateArgument::Template: { 833 TemplateName Template = Arg.getAsTemplate().get(); 834 TemplateArgument TArg; 835 if (Arg.getEllipsisLoc().isValid()) 836 TArg = TemplateArgument(Template, Optional<unsigned int>()); 837 else 838 TArg = Template; 839 return TemplateArgumentLoc(TArg, 840 Arg.getScopeSpec().getWithLocInContext( 841 SemaRef.Context), 842 Arg.getLocation(), 843 Arg.getEllipsisLoc()); 844 } 845 } 846 847 llvm_unreachable("Unhandled parsed template argument"); 848 } 849 850 /// Translates template arguments as provided by the parser 851 /// into template arguments used by semantic analysis. 852 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 853 TemplateArgumentListInfo &TemplateArgs) { 854 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 855 TemplateArgs.addArgument(translateTemplateArgument(*this, 856 TemplateArgsIn[I])); 857 } 858 859 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, 860 SourceLocation Loc, 861 IdentifierInfo *Name) { 862 NamedDecl *PrevDecl = SemaRef.LookupSingleName( 863 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 864 if (PrevDecl && PrevDecl->isTemplateParameter()) 865 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl); 866 } 867 868 /// Convert a parsed type into a parsed template argument. This is mostly 869 /// trivial, except that we may have parsed a C++17 deduced class template 870 /// specialization type, in which case we should form a template template 871 /// argument instead of a type template argument. 872 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) { 873 TypeSourceInfo *TInfo; 874 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo); 875 if (T.isNull()) 876 return ParsedTemplateArgument(); 877 assert(TInfo && "template argument with no location"); 878 879 // If we might have formed a deduced template specialization type, convert 880 // it to a template template argument. 881 if (getLangOpts().CPlusPlus17) { 882 TypeLoc TL = TInfo->getTypeLoc(); 883 SourceLocation EllipsisLoc; 884 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) { 885 EllipsisLoc = PET.getEllipsisLoc(); 886 TL = PET.getPatternLoc(); 887 } 888 889 CXXScopeSpec SS; 890 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) { 891 SS.Adopt(ET.getQualifierLoc()); 892 TL = ET.getNamedTypeLoc(); 893 } 894 895 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) { 896 TemplateName Name = DTST.getTypePtr()->getTemplateName(); 897 if (SS.isSet()) 898 Name = Context.getQualifiedTemplateName(SS.getScopeRep(), 899 /*HasTemplateKeyword*/ false, 900 Name.getAsTemplateDecl()); 901 ParsedTemplateArgument Result(SS, TemplateTy::make(Name), 902 DTST.getTemplateNameLoc()); 903 if (EllipsisLoc.isValid()) 904 Result = Result.getTemplatePackExpansion(EllipsisLoc); 905 return Result; 906 } 907 } 908 909 // This is a normal type template argument. Note, if the type template 910 // argument is an injected-class-name for a template, it has a dual nature 911 // and can be used as either a type or a template. We handle that in 912 // convertTypeTemplateArgumentToTemplate. 913 return ParsedTemplateArgument(ParsedTemplateArgument::Type, 914 ParsedType.get().getAsOpaquePtr(), 915 TInfo->getTypeLoc().getBeginLoc()); 916 } 917 918 /// ActOnTypeParameter - Called when a C++ template type parameter 919 /// (e.g., "typename T") has been parsed. Typename specifies whether 920 /// the keyword "typename" was used to declare the type parameter 921 /// (otherwise, "class" was used), and KeyLoc is the location of the 922 /// "class" or "typename" keyword. ParamName is the name of the 923 /// parameter (NULL indicates an unnamed template parameter) and 924 /// ParamNameLoc is the location of the parameter name (if any). 925 /// If the type parameter has a default argument, it will be added 926 /// later via ActOnTypeParameterDefault. 927 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename, 928 SourceLocation EllipsisLoc, 929 SourceLocation KeyLoc, 930 IdentifierInfo *ParamName, 931 SourceLocation ParamNameLoc, 932 unsigned Depth, unsigned Position, 933 SourceLocation EqualLoc, 934 ParsedType DefaultArg) { 935 assert(S->isTemplateParamScope() && 936 "Template type parameter not in template parameter scope!"); 937 938 SourceLocation Loc = ParamNameLoc; 939 if (!ParamName) 940 Loc = KeyLoc; 941 942 bool IsParameterPack = EllipsisLoc.isValid(); 943 TemplateTypeParmDecl *Param 944 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), 945 KeyLoc, Loc, Depth, Position, ParamName, 946 Typename, IsParameterPack); 947 Param->setAccess(AS_public); 948 949 if (ParamName) { 950 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName); 951 952 // Add the template parameter into the current scope. 953 S->AddDecl(Param); 954 IdResolver.AddDecl(Param); 955 } 956 957 // C++0x [temp.param]p9: 958 // A default template-argument may be specified for any kind of 959 // template-parameter that is not a template parameter pack. 960 if (DefaultArg && IsParameterPack) { 961 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 962 DefaultArg = nullptr; 963 } 964 965 // Handle the default argument, if provided. 966 if (DefaultArg) { 967 TypeSourceInfo *DefaultTInfo; 968 GetTypeFromParser(DefaultArg, &DefaultTInfo); 969 970 assert(DefaultTInfo && "expected source information for type"); 971 972 // Check for unexpanded parameter packs. 973 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo, 974 UPPC_DefaultArgument)) 975 return Param; 976 977 // Check the template argument itself. 978 if (CheckTemplateArgument(Param, DefaultTInfo)) { 979 Param->setInvalidDecl(); 980 return Param; 981 } 982 983 Param->setDefaultArgument(DefaultTInfo); 984 } 985 986 return Param; 987 } 988 989 /// Check that the type of a non-type template parameter is 990 /// well-formed. 991 /// 992 /// \returns the (possibly-promoted) parameter type if valid; 993 /// otherwise, produces a diagnostic and returns a NULL type. 994 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, 995 SourceLocation Loc) { 996 if (TSI->getType()->isUndeducedType()) { 997 // C++17 [temp.dep.expr]p3: 998 // An id-expression is type-dependent if it contains 999 // - an identifier associated by name lookup with a non-type 1000 // template-parameter declared with a type that contains a 1001 // placeholder type (7.1.7.4), 1002 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy); 1003 } 1004 1005 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc); 1006 } 1007 1008 QualType Sema::CheckNonTypeTemplateParameterType(QualType T, 1009 SourceLocation Loc) { 1010 // We don't allow variably-modified types as the type of non-type template 1011 // parameters. 1012 if (T->isVariablyModifiedType()) { 1013 Diag(Loc, diag::err_variably_modified_nontype_template_param) 1014 << T; 1015 return QualType(); 1016 } 1017 1018 // C++ [temp.param]p4: 1019 // 1020 // A non-type template-parameter shall have one of the following 1021 // (optionally cv-qualified) types: 1022 // 1023 // -- integral or enumeration type, 1024 if (T->isIntegralOrEnumerationType() || 1025 // -- pointer to object or pointer to function, 1026 T->isPointerType() || 1027 // -- reference to object or reference to function, 1028 T->isReferenceType() || 1029 // -- pointer to member, 1030 T->isMemberPointerType() || 1031 // -- std::nullptr_t. 1032 T->isNullPtrType() || 1033 // If T is a dependent type, we can't do the check now, so we 1034 // assume that it is well-formed. 1035 T->isDependentType() || 1036 // Allow use of auto in template parameter declarations. 1037 T->isUndeducedType()) { 1038 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter 1039 // are ignored when determining its type. 1040 return T.getUnqualifiedType(); 1041 } 1042 1043 // C++ [temp.param]p8: 1044 // 1045 // A non-type template-parameter of type "array of T" or 1046 // "function returning T" is adjusted to be of type "pointer to 1047 // T" or "pointer to function returning T", respectively. 1048 else if (T->isArrayType() || T->isFunctionType()) 1049 return Context.getDecayedType(T); 1050 1051 Diag(Loc, diag::err_template_nontype_parm_bad_type) 1052 << T; 1053 1054 return QualType(); 1055 } 1056 1057 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 1058 unsigned Depth, 1059 unsigned Position, 1060 SourceLocation EqualLoc, 1061 Expr *Default) { 1062 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 1063 1064 // Check that we have valid decl-specifiers specified. 1065 auto CheckValidDeclSpecifiers = [this, &D] { 1066 // C++ [temp.param] 1067 // p1 1068 // template-parameter: 1069 // ... 1070 // parameter-declaration 1071 // p2 1072 // ... A storage class shall not be specified in a template-parameter 1073 // declaration. 1074 // [dcl.typedef]p1: 1075 // The typedef specifier [...] shall not be used in the decl-specifier-seq 1076 // of a parameter-declaration 1077 const DeclSpec &DS = D.getDeclSpec(); 1078 auto EmitDiag = [this](SourceLocation Loc) { 1079 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm) 1080 << FixItHint::CreateRemoval(Loc); 1081 }; 1082 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) 1083 EmitDiag(DS.getStorageClassSpecLoc()); 1084 1085 if (DS.getThreadStorageClassSpec() != TSCS_unspecified) 1086 EmitDiag(DS.getThreadStorageClassSpecLoc()); 1087 1088 // [dcl.inline]p1: 1089 // The inline specifier can be applied only to the declaration or 1090 // definition of a variable or function. 1091 1092 if (DS.isInlineSpecified()) 1093 EmitDiag(DS.getInlineSpecLoc()); 1094 1095 // [dcl.constexpr]p1: 1096 // The constexpr specifier shall be applied only to the definition of a 1097 // variable or variable template or the declaration of a function or 1098 // function template. 1099 1100 if (DS.isConstexprSpecified()) 1101 EmitDiag(DS.getConstexprSpecLoc()); 1102 1103 // [dcl.fct.spec]p1: 1104 // Function-specifiers can be used only in function declarations. 1105 1106 if (DS.isVirtualSpecified()) 1107 EmitDiag(DS.getVirtualSpecLoc()); 1108 1109 if (DS.isExplicitSpecified()) 1110 EmitDiag(DS.getExplicitSpecLoc()); 1111 1112 if (DS.isNoreturnSpecified()) 1113 EmitDiag(DS.getNoreturnSpecLoc()); 1114 }; 1115 1116 CheckValidDeclSpecifiers(); 1117 1118 if (TInfo->getType()->isUndeducedType()) { 1119 Diag(D.getIdentifierLoc(), 1120 diag::warn_cxx14_compat_template_nontype_parm_auto_type) 1121 << QualType(TInfo->getType()->getContainedAutoType(), 0); 1122 } 1123 1124 assert(S->isTemplateParamScope() && 1125 "Non-type template parameter not in template parameter scope!"); 1126 bool Invalid = false; 1127 1128 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc()); 1129 if (T.isNull()) { 1130 T = Context.IntTy; // Recover with an 'int' type. 1131 Invalid = true; 1132 } 1133 1134 IdentifierInfo *ParamName = D.getIdentifier(); 1135 bool IsParameterPack = D.hasEllipsis(); 1136 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create( 1137 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(), 1138 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack, 1139 TInfo); 1140 Param->setAccess(AS_public); 1141 1142 if (Invalid) 1143 Param->setInvalidDecl(); 1144 1145 if (ParamName) { 1146 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(), 1147 ParamName); 1148 1149 // Add the template parameter into the current scope. 1150 S->AddDecl(Param); 1151 IdResolver.AddDecl(Param); 1152 } 1153 1154 // C++0x [temp.param]p9: 1155 // A default template-argument may be specified for any kind of 1156 // template-parameter that is not a template parameter pack. 1157 if (Default && IsParameterPack) { 1158 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 1159 Default = nullptr; 1160 } 1161 1162 // Check the well-formedness of the default template argument, if provided. 1163 if (Default) { 1164 // Check for unexpanded parameter packs. 1165 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) 1166 return Param; 1167 1168 TemplateArgument Converted; 1169 ExprResult DefaultRes = 1170 CheckTemplateArgument(Param, Param->getType(), Default, Converted); 1171 if (DefaultRes.isInvalid()) { 1172 Param->setInvalidDecl(); 1173 return Param; 1174 } 1175 Default = DefaultRes.get(); 1176 1177 Param->setDefaultArgument(Default); 1178 } 1179 1180 return Param; 1181 } 1182 1183 /// ActOnTemplateTemplateParameter - Called when a C++ template template 1184 /// parameter (e.g. T in template <template \<typename> class T> class array) 1185 /// has been parsed. S is the current scope. 1186 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S, 1187 SourceLocation TmpLoc, 1188 TemplateParameterList *Params, 1189 SourceLocation EllipsisLoc, 1190 IdentifierInfo *Name, 1191 SourceLocation NameLoc, 1192 unsigned Depth, 1193 unsigned Position, 1194 SourceLocation EqualLoc, 1195 ParsedTemplateArgument Default) { 1196 assert(S->isTemplateParamScope() && 1197 "Template template parameter not in template parameter scope!"); 1198 1199 // Construct the parameter object. 1200 bool IsParameterPack = EllipsisLoc.isValid(); 1201 TemplateTemplateParmDecl *Param = 1202 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 1203 NameLoc.isInvalid()? TmpLoc : NameLoc, 1204 Depth, Position, IsParameterPack, 1205 Name, Params); 1206 Param->setAccess(AS_public); 1207 1208 // If the template template parameter has a name, then link the identifier 1209 // into the scope and lookup mechanisms. 1210 if (Name) { 1211 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name); 1212 1213 S->AddDecl(Param); 1214 IdResolver.AddDecl(Param); 1215 } 1216 1217 if (Params->size() == 0) { 1218 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) 1219 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); 1220 Param->setInvalidDecl(); 1221 } 1222 1223 // C++0x [temp.param]p9: 1224 // A default template-argument may be specified for any kind of 1225 // template-parameter that is not a template parameter pack. 1226 if (IsParameterPack && !Default.isInvalid()) { 1227 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 1228 Default = ParsedTemplateArgument(); 1229 } 1230 1231 if (!Default.isInvalid()) { 1232 // Check only that we have a template template argument. We don't want to 1233 // try to check well-formedness now, because our template template parameter 1234 // might have dependent types in its template parameters, which we wouldn't 1235 // be able to match now. 1236 // 1237 // If none of the template template parameter's template arguments mention 1238 // other template parameters, we could actually perform more checking here. 1239 // However, it isn't worth doing. 1240 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 1241 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 1242 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template) 1243 << DefaultArg.getSourceRange(); 1244 return Param; 1245 } 1246 1247 // Check for unexpanded parameter packs. 1248 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), 1249 DefaultArg.getArgument().getAsTemplate(), 1250 UPPC_DefaultArgument)) 1251 return Param; 1252 1253 Param->setDefaultArgument(Context, DefaultArg); 1254 } 1255 1256 return Param; 1257 } 1258 1259 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally 1260 /// constrained by RequiresClause, that contains the template parameters in 1261 /// Params. 1262 TemplateParameterList * 1263 Sema::ActOnTemplateParameterList(unsigned Depth, 1264 SourceLocation ExportLoc, 1265 SourceLocation TemplateLoc, 1266 SourceLocation LAngleLoc, 1267 ArrayRef<NamedDecl *> Params, 1268 SourceLocation RAngleLoc, 1269 Expr *RequiresClause) { 1270 if (ExportLoc.isValid()) 1271 Diag(ExportLoc, diag::warn_template_export_unsupported); 1272 1273 return TemplateParameterList::Create( 1274 Context, TemplateLoc, LAngleLoc, 1275 llvm::makeArrayRef(Params.data(), Params.size()), 1276 RAngleLoc, RequiresClause); 1277 } 1278 1279 static void SetNestedNameSpecifier(Sema &S, TagDecl *T, 1280 const CXXScopeSpec &SS) { 1281 if (SS.isSet()) 1282 T->setQualifierInfo(SS.getWithLocInContext(S.Context)); 1283 } 1284 1285 DeclResult Sema::CheckClassTemplate( 1286 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 1287 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 1288 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, 1289 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 1290 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, 1291 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) { 1292 assert(TemplateParams && TemplateParams->size() > 0 && 1293 "No template parameters"); 1294 assert(TUK != TUK_Reference && "Can only declare or define class templates"); 1295 bool Invalid = false; 1296 1297 // Check that we can declare a template here. 1298 if (CheckTemplateDeclScope(S, TemplateParams)) 1299 return true; 1300 1301 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 1302 assert(Kind != TTK_Enum && "can't build template of enumerated type"); 1303 1304 // There is no such thing as an unnamed class template. 1305 if (!Name) { 1306 Diag(KWLoc, diag::err_template_unnamed_class); 1307 return true; 1308 } 1309 1310 // Find any previous declaration with this name. For a friend with no 1311 // scope explicitly specified, we only look for tag declarations (per 1312 // C++11 [basic.lookup.elab]p2). 1313 DeclContext *SemanticContext; 1314 LookupResult Previous(*this, Name, NameLoc, 1315 (SS.isEmpty() && TUK == TUK_Friend) 1316 ? LookupTagName : LookupOrdinaryName, 1317 forRedeclarationInCurContext()); 1318 if (SS.isNotEmpty() && !SS.isInvalid()) { 1319 SemanticContext = computeDeclContext(SS, true); 1320 if (!SemanticContext) { 1321 // FIXME: Horrible, horrible hack! We can't currently represent this 1322 // in the AST, and historically we have just ignored such friend 1323 // class templates, so don't complain here. 1324 Diag(NameLoc, TUK == TUK_Friend 1325 ? diag::warn_template_qualified_friend_ignored 1326 : diag::err_template_qualified_declarator_no_match) 1327 << SS.getScopeRep() << SS.getRange(); 1328 return TUK != TUK_Friend; 1329 } 1330 1331 if (RequireCompleteDeclContext(SS, SemanticContext)) 1332 return true; 1333 1334 // If we're adding a template to a dependent context, we may need to 1335 // rebuilding some of the types used within the template parameter list, 1336 // now that we know what the current instantiation is. 1337 if (SemanticContext->isDependentContext()) { 1338 ContextRAII SavedContext(*this, SemanticContext); 1339 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 1340 Invalid = true; 1341 } else if (TUK != TUK_Friend && TUK != TUK_Reference) 1342 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false); 1343 1344 LookupQualifiedName(Previous, SemanticContext); 1345 } else { 1346 SemanticContext = CurContext; 1347 1348 // C++14 [class.mem]p14: 1349 // If T is the name of a class, then each of the following shall have a 1350 // name different from T: 1351 // -- every member template of class T 1352 if (TUK != TUK_Friend && 1353 DiagnoseClassNameShadow(SemanticContext, 1354 DeclarationNameInfo(Name, NameLoc))) 1355 return true; 1356 1357 LookupName(Previous, S); 1358 } 1359 1360 if (Previous.isAmbiguous()) 1361 return true; 1362 1363 NamedDecl *PrevDecl = nullptr; 1364 if (Previous.begin() != Previous.end()) 1365 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 1366 1367 if (PrevDecl && PrevDecl->isTemplateParameter()) { 1368 // Maybe we will complain about the shadowed template parameter. 1369 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 1370 // Just pretend that we didn't see the previous declaration. 1371 PrevDecl = nullptr; 1372 } 1373 1374 // If there is a previous declaration with the same name, check 1375 // whether this is a valid redeclaration. 1376 ClassTemplateDecl *PrevClassTemplate = 1377 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 1378 1379 // We may have found the injected-class-name of a class template, 1380 // class template partial specialization, or class template specialization. 1381 // In these cases, grab the template that is being defined or specialized. 1382 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 1383 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { 1384 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); 1385 PrevClassTemplate 1386 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); 1387 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { 1388 PrevClassTemplate 1389 = cast<ClassTemplateSpecializationDecl>(PrevDecl) 1390 ->getSpecializedTemplate(); 1391 } 1392 } 1393 1394 if (TUK == TUK_Friend) { 1395 // C++ [namespace.memdef]p3: 1396 // [...] When looking for a prior declaration of a class or a function 1397 // declared as a friend, and when the name of the friend class or 1398 // function is neither a qualified name nor a template-id, scopes outside 1399 // the innermost enclosing namespace scope are not considered. 1400 if (!SS.isSet()) { 1401 DeclContext *OutermostContext = CurContext; 1402 while (!OutermostContext->isFileContext()) 1403 OutermostContext = OutermostContext->getLookupParent(); 1404 1405 if (PrevDecl && 1406 (OutermostContext->Equals(PrevDecl->getDeclContext()) || 1407 OutermostContext->Encloses(PrevDecl->getDeclContext()))) { 1408 SemanticContext = PrevDecl->getDeclContext(); 1409 } else { 1410 // Declarations in outer scopes don't matter. However, the outermost 1411 // context we computed is the semantic context for our new 1412 // declaration. 1413 PrevDecl = PrevClassTemplate = nullptr; 1414 SemanticContext = OutermostContext; 1415 1416 // Check that the chosen semantic context doesn't already contain a 1417 // declaration of this name as a non-tag type. 1418 Previous.clear(LookupOrdinaryName); 1419 DeclContext *LookupContext = SemanticContext; 1420 while (LookupContext->isTransparentContext()) 1421 LookupContext = LookupContext->getLookupParent(); 1422 LookupQualifiedName(Previous, LookupContext); 1423 1424 if (Previous.isAmbiguous()) 1425 return true; 1426 1427 if (Previous.begin() != Previous.end()) 1428 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 1429 } 1430 } 1431 } else if (PrevDecl && 1432 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext, 1433 S, SS.isValid())) 1434 PrevDecl = PrevClassTemplate = nullptr; 1435 1436 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>( 1437 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) { 1438 if (SS.isEmpty() && 1439 !(PrevClassTemplate && 1440 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals( 1441 SemanticContext->getRedeclContext()))) { 1442 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 1443 Diag(Shadow->getTargetDecl()->getLocation(), 1444 diag::note_using_decl_target); 1445 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 1446 // Recover by ignoring the old declaration. 1447 PrevDecl = PrevClassTemplate = nullptr; 1448 } 1449 } 1450 1451 // TODO Memory management; associated constraints are not always stored. 1452 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr); 1453 1454 if (PrevClassTemplate) { 1455 // Ensure that the template parameter lists are compatible. Skip this check 1456 // for a friend in a dependent context: the template parameter list itself 1457 // could be dependent. 1458 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && 1459 !TemplateParameterListsAreEqual(TemplateParams, 1460 PrevClassTemplate->getTemplateParameters(), 1461 /*Complain=*/true, 1462 TPL_TemplateMatch)) 1463 return true; 1464 1465 // Check for matching associated constraints on redeclarations. 1466 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints(); 1467 const bool RedeclACMismatch = [&] { 1468 if (!(CurAC || PrevAC)) 1469 return false; // Nothing to check; no mismatch. 1470 if (CurAC && PrevAC) { 1471 llvm::FoldingSetNodeID CurACInfo, PrevACInfo; 1472 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true); 1473 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true); 1474 if (CurACInfo == PrevACInfo) 1475 return false; // All good; no mismatch. 1476 } 1477 return true; 1478 }(); 1479 1480 if (RedeclACMismatch) { 1481 Diag(CurAC ? CurAC->getBeginLoc() : NameLoc, 1482 diag::err_template_different_associated_constraints); 1483 Diag(PrevAC ? PrevAC->getBeginLoc() : PrevClassTemplate->getLocation(), 1484 diag::note_template_prev_declaration) 1485 << /*declaration*/ 0; 1486 return true; 1487 } 1488 1489 // C++ [temp.class]p4: 1490 // In a redeclaration, partial specialization, explicit 1491 // specialization or explicit instantiation of a class template, 1492 // the class-key shall agree in kind with the original class 1493 // template declaration (7.1.5.3). 1494 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 1495 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, 1496 TUK == TUK_Definition, KWLoc, Name)) { 1497 Diag(KWLoc, diag::err_use_with_wrong_tag) 1498 << Name 1499 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); 1500 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 1501 Kind = PrevRecordDecl->getTagKind(); 1502 } 1503 1504 // Check for redefinition of this class template. 1505 if (TUK == TUK_Definition) { 1506 if (TagDecl *Def = PrevRecordDecl->getDefinition()) { 1507 // If we have a prior definition that is not visible, treat this as 1508 // simply making that previous definition visible. 1509 NamedDecl *Hidden = nullptr; 1510 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 1511 SkipBody->ShouldSkip = true; 1512 SkipBody->Previous = Def; 1513 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate(); 1514 assert(Tmpl && "original definition of a class template is not a " 1515 "class template?"); 1516 makeMergedDefinitionVisible(Hidden); 1517 makeMergedDefinitionVisible(Tmpl); 1518 } else { 1519 Diag(NameLoc, diag::err_redefinition) << Name; 1520 Diag(Def->getLocation(), diag::note_previous_definition); 1521 // FIXME: Would it make sense to try to "forget" the previous 1522 // definition, as part of error recovery? 1523 return true; 1524 } 1525 } 1526 } 1527 } else if (PrevDecl) { 1528 // C++ [temp]p5: 1529 // A class template shall not have the same name as any other 1530 // template, class, function, object, enumeration, enumerator, 1531 // namespace, or type in the same scope (3.3), except as specified 1532 // in (14.5.4). 1533 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 1534 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1535 return true; 1536 } 1537 1538 // Check the template parameter list of this declaration, possibly 1539 // merging in the template parameter list from the previous class 1540 // template declaration. Skip this check for a friend in a dependent 1541 // context, because the template parameter list might be dependent. 1542 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && 1543 CheckTemplateParameterList( 1544 TemplateParams, 1545 PrevClassTemplate 1546 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters() 1547 : nullptr, 1548 (SS.isSet() && SemanticContext && SemanticContext->isRecord() && 1549 SemanticContext->isDependentContext()) 1550 ? TPC_ClassTemplateMember 1551 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate, 1552 SkipBody)) 1553 Invalid = true; 1554 1555 if (SS.isSet()) { 1556 // If the name of the template was qualified, we must be defining the 1557 // template out-of-line. 1558 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) { 1559 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match 1560 : diag::err_member_decl_does_not_match) 1561 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange(); 1562 Invalid = true; 1563 } 1564 } 1565 1566 // If this is a templated friend in a dependent context we should not put it 1567 // on the redecl chain. In some cases, the templated friend can be the most 1568 // recent declaration tricking the template instantiator to make substitutions 1569 // there. 1570 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious 1571 bool ShouldAddRedecl 1572 = !(TUK == TUK_Friend && CurContext->isDependentContext()); 1573 1574 CXXRecordDecl *NewClass = 1575 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name, 1576 PrevClassTemplate && ShouldAddRedecl ? 1577 PrevClassTemplate->getTemplatedDecl() : nullptr, 1578 /*DelayTypeCreation=*/true); 1579 SetNestedNameSpecifier(*this, NewClass, SS); 1580 if (NumOuterTemplateParamLists > 0) 1581 NewClass->setTemplateParameterListsInfo( 1582 Context, llvm::makeArrayRef(OuterTemplateParamLists, 1583 NumOuterTemplateParamLists)); 1584 1585 // Add alignment attributes if necessary; these attributes are checked when 1586 // the ASTContext lays out the structure. 1587 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 1588 AddAlignmentAttributesForRecord(NewClass); 1589 AddMsStructLayoutForRecord(NewClass); 1590 } 1591 1592 // Attach the associated constraints when the declaration will not be part of 1593 // a decl chain. 1594 Expr *const ACtoAttach = 1595 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC; 1596 1597 ClassTemplateDecl *NewTemplate 1598 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 1599 DeclarationName(Name), TemplateParams, 1600 NewClass, ACtoAttach); 1601 1602 if (ShouldAddRedecl) 1603 NewTemplate->setPreviousDecl(PrevClassTemplate); 1604 1605 NewClass->setDescribedClassTemplate(NewTemplate); 1606 1607 if (ModulePrivateLoc.isValid()) 1608 NewTemplate->setModulePrivate(); 1609 1610 // Build the type for the class template declaration now. 1611 QualType T = NewTemplate->getInjectedClassNameSpecialization(); 1612 T = Context.getInjectedClassNameType(NewClass, T); 1613 assert(T->isDependentType() && "Class template type is not dependent?"); 1614 (void)T; 1615 1616 // If we are providing an explicit specialization of a member that is a 1617 // class template, make a note of that. 1618 if (PrevClassTemplate && 1619 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 1620 PrevClassTemplate->setMemberSpecialization(); 1621 1622 // Set the access specifier. 1623 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord()) 1624 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 1625 1626 // Set the lexical context of these templates 1627 NewClass->setLexicalDeclContext(CurContext); 1628 NewTemplate->setLexicalDeclContext(CurContext); 1629 1630 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 1631 NewClass->startDefinition(); 1632 1633 ProcessDeclAttributeList(S, NewClass, Attr); 1634 1635 if (PrevClassTemplate) 1636 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl()); 1637 1638 AddPushedVisibilityAttribute(NewClass); 1639 1640 if (TUK != TUK_Friend) { 1641 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes. 1642 Scope *Outer = S; 1643 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0) 1644 Outer = Outer->getParent(); 1645 PushOnScopeChains(NewTemplate, Outer); 1646 } else { 1647 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 1648 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 1649 NewClass->setAccess(PrevClassTemplate->getAccess()); 1650 } 1651 1652 NewTemplate->setObjectOfFriendDecl(); 1653 1654 // Friend templates are visible in fairly strange ways. 1655 if (!CurContext->isDependentContext()) { 1656 DeclContext *DC = SemanticContext->getRedeclContext(); 1657 DC->makeDeclVisibleInContext(NewTemplate); 1658 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 1659 PushOnScopeChains(NewTemplate, EnclosingScope, 1660 /* AddToContext = */ false); 1661 } 1662 1663 FriendDecl *Friend = FriendDecl::Create( 1664 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc); 1665 Friend->setAccess(AS_public); 1666 CurContext->addDecl(Friend); 1667 } 1668 1669 if (PrevClassTemplate) 1670 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate); 1671 1672 if (Invalid) { 1673 NewTemplate->setInvalidDecl(); 1674 NewClass->setInvalidDecl(); 1675 } 1676 1677 ActOnDocumentableDecl(NewTemplate); 1678 1679 if (SkipBody && SkipBody->ShouldSkip) 1680 return SkipBody->Previous; 1681 1682 return NewTemplate; 1683 } 1684 1685 namespace { 1686 /// Tree transform to "extract" a transformed type from a class template's 1687 /// constructor to a deduction guide. 1688 class ExtractTypeForDeductionGuide 1689 : public TreeTransform<ExtractTypeForDeductionGuide> { 1690 public: 1691 typedef TreeTransform<ExtractTypeForDeductionGuide> Base; 1692 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {} 1693 1694 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } 1695 1696 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { 1697 return TransformType( 1698 TLB, 1699 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc()); 1700 } 1701 }; 1702 1703 /// Transform to convert portions of a constructor declaration into the 1704 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1. 1705 struct ConvertConstructorToDeductionGuideTransform { 1706 ConvertConstructorToDeductionGuideTransform(Sema &S, 1707 ClassTemplateDecl *Template) 1708 : SemaRef(S), Template(Template) {} 1709 1710 Sema &SemaRef; 1711 ClassTemplateDecl *Template; 1712 1713 DeclContext *DC = Template->getDeclContext(); 1714 CXXRecordDecl *Primary = Template->getTemplatedDecl(); 1715 DeclarationName DeductionGuideName = 1716 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template); 1717 1718 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary); 1719 1720 // Index adjustment to apply to convert depth-1 template parameters into 1721 // depth-0 template parameters. 1722 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size(); 1723 1724 /// Transform a constructor declaration into a deduction guide. 1725 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD, 1726 CXXConstructorDecl *CD) { 1727 SmallVector<TemplateArgument, 16> SubstArgs; 1728 1729 LocalInstantiationScope Scope(SemaRef); 1730 1731 // C++ [over.match.class.deduct]p1: 1732 // -- For each constructor of the class template designated by the 1733 // template-name, a function template with the following properties: 1734 1735 // -- The template parameters are the template parameters of the class 1736 // template followed by the template parameters (including default 1737 // template arguments) of the constructor, if any. 1738 TemplateParameterList *TemplateParams = Template->getTemplateParameters(); 1739 if (FTD) { 1740 TemplateParameterList *InnerParams = FTD->getTemplateParameters(); 1741 SmallVector<NamedDecl *, 16> AllParams; 1742 AllParams.reserve(TemplateParams->size() + InnerParams->size()); 1743 AllParams.insert(AllParams.begin(), 1744 TemplateParams->begin(), TemplateParams->end()); 1745 SubstArgs.reserve(InnerParams->size()); 1746 1747 // Later template parameters could refer to earlier ones, so build up 1748 // a list of substituted template arguments as we go. 1749 for (NamedDecl *Param : *InnerParams) { 1750 MultiLevelTemplateArgumentList Args; 1751 Args.addOuterTemplateArguments(SubstArgs); 1752 Args.addOuterRetainedLevel(); 1753 NamedDecl *NewParam = transformTemplateParameter(Param, Args); 1754 if (!NewParam) 1755 return nullptr; 1756 AllParams.push_back(NewParam); 1757 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument( 1758 SemaRef.Context.getInjectedTemplateArg(NewParam))); 1759 } 1760 TemplateParams = TemplateParameterList::Create( 1761 SemaRef.Context, InnerParams->getTemplateLoc(), 1762 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(), 1763 /*FIXME: RequiresClause*/ nullptr); 1764 } 1765 1766 // If we built a new template-parameter-list, track that we need to 1767 // substitute references to the old parameters into references to the 1768 // new ones. 1769 MultiLevelTemplateArgumentList Args; 1770 if (FTD) { 1771 Args.addOuterTemplateArguments(SubstArgs); 1772 Args.addOuterRetainedLevel(); 1773 } 1774 1775 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc() 1776 .getAsAdjusted<FunctionProtoTypeLoc>(); 1777 assert(FPTL && "no prototype for constructor declaration"); 1778 1779 // Transform the type of the function, adjusting the return type and 1780 // replacing references to the old parameters with references to the 1781 // new ones. 1782 TypeLocBuilder TLB; 1783 SmallVector<ParmVarDecl*, 8> Params; 1784 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args); 1785 if (NewType.isNull()) 1786 return nullptr; 1787 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType); 1788 1789 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo, 1790 CD->getBeginLoc(), CD->getLocation(), 1791 CD->getEndLoc()); 1792 } 1793 1794 /// Build a deduction guide with the specified parameter types. 1795 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) { 1796 SourceLocation Loc = Template->getLocation(); 1797 1798 // Build the requested type. 1799 FunctionProtoType::ExtProtoInfo EPI; 1800 EPI.HasTrailingReturn = true; 1801 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc, 1802 DeductionGuideName, EPI); 1803 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc); 1804 1805 FunctionProtoTypeLoc FPTL = 1806 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>(); 1807 1808 // Build the parameters, needed during deduction / substitution. 1809 SmallVector<ParmVarDecl*, 4> Params; 1810 for (auto T : ParamTypes) { 1811 ParmVarDecl *NewParam = ParmVarDecl::Create( 1812 SemaRef.Context, DC, Loc, Loc, nullptr, T, 1813 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr); 1814 NewParam->setScopeInfo(0, Params.size()); 1815 FPTL.setParam(Params.size(), NewParam); 1816 Params.push_back(NewParam); 1817 } 1818 1819 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI, 1820 Loc, Loc, Loc); 1821 } 1822 1823 private: 1824 /// Transform a constructor template parameter into a deduction guide template 1825 /// parameter, rebuilding any internal references to earlier parameters and 1826 /// renumbering as we go. 1827 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam, 1828 MultiLevelTemplateArgumentList &Args) { 1829 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) { 1830 // TemplateTypeParmDecl's index cannot be changed after creation, so 1831 // substitute it directly. 1832 auto *NewTTP = TemplateTypeParmDecl::Create( 1833 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), 1834 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(), 1835 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(), 1836 TTP->isParameterPack()); 1837 if (TTP->hasDefaultArgument()) { 1838 TypeSourceInfo *InstantiatedDefaultArg = 1839 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args, 1840 TTP->getDefaultArgumentLoc(), TTP->getDeclName()); 1841 if (InstantiatedDefaultArg) 1842 NewTTP->setDefaultArgument(InstantiatedDefaultArg); 1843 } 1844 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam, 1845 NewTTP); 1846 return NewTTP; 1847 } 1848 1849 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam)) 1850 return transformTemplateParameterImpl(TTP, Args); 1851 1852 return transformTemplateParameterImpl( 1853 cast<NonTypeTemplateParmDecl>(TemplateParam), Args); 1854 } 1855 template<typename TemplateParmDecl> 1856 TemplateParmDecl * 1857 transformTemplateParameterImpl(TemplateParmDecl *OldParam, 1858 MultiLevelTemplateArgumentList &Args) { 1859 // Ask the template instantiator to do the heavy lifting for us, then adjust 1860 // the index of the parameter once it's done. 1861 auto *NewParam = 1862 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args)); 1863 assert(NewParam->getDepth() == 0 && "unexpected template param depth"); 1864 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment); 1865 return NewParam; 1866 } 1867 1868 QualType transformFunctionProtoType(TypeLocBuilder &TLB, 1869 FunctionProtoTypeLoc TL, 1870 SmallVectorImpl<ParmVarDecl*> &Params, 1871 MultiLevelTemplateArgumentList &Args) { 1872 SmallVector<QualType, 4> ParamTypes; 1873 const FunctionProtoType *T = TL.getTypePtr(); 1874 1875 // -- The types of the function parameters are those of the constructor. 1876 for (auto *OldParam : TL.getParams()) { 1877 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args); 1878 if (!NewParam) 1879 return QualType(); 1880 ParamTypes.push_back(NewParam->getType()); 1881 Params.push_back(NewParam); 1882 } 1883 1884 // -- The return type is the class template specialization designated by 1885 // the template-name and template arguments corresponding to the 1886 // template parameters obtained from the class template. 1887 // 1888 // We use the injected-class-name type of the primary template instead. 1889 // This has the convenient property that it is different from any type that 1890 // the user can write in a deduction-guide (because they cannot enter the 1891 // context of the template), so implicit deduction guides can never collide 1892 // with explicit ones. 1893 QualType ReturnType = DeducedType; 1894 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation()); 1895 1896 // Resolving a wording defect, we also inherit the variadicness of the 1897 // constructor. 1898 FunctionProtoType::ExtProtoInfo EPI; 1899 EPI.Variadic = T->isVariadic(); 1900 EPI.HasTrailingReturn = true; 1901 1902 QualType Result = SemaRef.BuildFunctionType( 1903 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI); 1904 if (Result.isNull()) 1905 return QualType(); 1906 1907 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result); 1908 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin()); 1909 NewTL.setLParenLoc(TL.getLParenLoc()); 1910 NewTL.setRParenLoc(TL.getRParenLoc()); 1911 NewTL.setExceptionSpecRange(SourceRange()); 1912 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd()); 1913 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I) 1914 NewTL.setParam(I, Params[I]); 1915 1916 return Result; 1917 } 1918 1919 ParmVarDecl * 1920 transformFunctionTypeParam(ParmVarDecl *OldParam, 1921 MultiLevelTemplateArgumentList &Args) { 1922 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo(); 1923 TypeSourceInfo *NewDI; 1924 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { 1925 // Expand out the one and only element in each inner pack. 1926 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0); 1927 NewDI = 1928 SemaRef.SubstType(PackTL.getPatternLoc(), Args, 1929 OldParam->getLocation(), OldParam->getDeclName()); 1930 if (!NewDI) return nullptr; 1931 NewDI = 1932 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(), 1933 PackTL.getTypePtr()->getNumExpansions()); 1934 } else 1935 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(), 1936 OldParam->getDeclName()); 1937 if (!NewDI) 1938 return nullptr; 1939 1940 // Extract the type. This (for instance) replaces references to typedef 1941 // members of the current instantiations with the definitions of those 1942 // typedefs, avoiding triggering instantiation of the deduced type during 1943 // deduction. 1944 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI); 1945 1946 // Resolving a wording defect, we also inherit default arguments from the 1947 // constructor. 1948 ExprResult NewDefArg; 1949 if (OldParam->hasDefaultArg()) { 1950 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args); 1951 if (NewDefArg.isInvalid()) 1952 return nullptr; 1953 } 1954 1955 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC, 1956 OldParam->getInnerLocStart(), 1957 OldParam->getLocation(), 1958 OldParam->getIdentifier(), 1959 NewDI->getType(), 1960 NewDI, 1961 OldParam->getStorageClass(), 1962 NewDefArg.get()); 1963 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(), 1964 OldParam->getFunctionScopeIndex()); 1965 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam); 1966 return NewParam; 1967 } 1968 1969 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams, 1970 bool Explicit, TypeSourceInfo *TInfo, 1971 SourceLocation LocStart, SourceLocation Loc, 1972 SourceLocation LocEnd) { 1973 DeclarationNameInfo Name(DeductionGuideName, Loc); 1974 ArrayRef<ParmVarDecl *> Params = 1975 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(); 1976 1977 // Build the implicit deduction guide template. 1978 auto *Guide = 1979 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit, 1980 Name, TInfo->getType(), TInfo, LocEnd); 1981 Guide->setImplicit(); 1982 Guide->setParams(Params); 1983 1984 for (auto *Param : Params) 1985 Param->setDeclContext(Guide); 1986 1987 auto *GuideTemplate = FunctionTemplateDecl::Create( 1988 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide); 1989 GuideTemplate->setImplicit(); 1990 Guide->setDescribedFunctionTemplate(GuideTemplate); 1991 1992 if (isa<CXXRecordDecl>(DC)) { 1993 Guide->setAccess(AS_public); 1994 GuideTemplate->setAccess(AS_public); 1995 } 1996 1997 DC->addDecl(GuideTemplate); 1998 return GuideTemplate; 1999 } 2000 }; 2001 } 2002 2003 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template, 2004 SourceLocation Loc) { 2005 DeclContext *DC = Template->getDeclContext(); 2006 if (DC->isDependentContext()) 2007 return; 2008 2009 ConvertConstructorToDeductionGuideTransform Transform( 2010 *this, cast<ClassTemplateDecl>(Template)); 2011 if (!isCompleteType(Loc, Transform.DeducedType)) 2012 return; 2013 2014 // Check whether we've already declared deduction guides for this template. 2015 // FIXME: Consider storing a flag on the template to indicate this. 2016 auto Existing = DC->lookup(Transform.DeductionGuideName); 2017 for (auto *D : Existing) 2018 if (D->isImplicit()) 2019 return; 2020 2021 // In case we were expanding a pack when we attempted to declare deduction 2022 // guides, turn off pack expansion for everything we're about to do. 2023 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); 2024 // Create a template instantiation record to track the "instantiation" of 2025 // constructors into deduction guides. 2026 // FIXME: Add a kind for this to give more meaningful diagnostics. But can 2027 // this substitution process actually fail? 2028 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template); 2029 if (BuildingDeductionGuides.isInvalid()) 2030 return; 2031 2032 // Convert declared constructors into deduction guide templates. 2033 // FIXME: Skip constructors for which deduction must necessarily fail (those 2034 // for which some class template parameter without a default argument never 2035 // appears in a deduced context). 2036 bool AddedAny = false; 2037 for (NamedDecl *D : LookupConstructors(Transform.Primary)) { 2038 D = D->getUnderlyingDecl(); 2039 if (D->isInvalidDecl() || D->isImplicit()) 2040 continue; 2041 D = cast<NamedDecl>(D->getCanonicalDecl()); 2042 2043 auto *FTD = dyn_cast<FunctionTemplateDecl>(D); 2044 auto *CD = 2045 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D); 2046 // Class-scope explicit specializations (MS extension) do not result in 2047 // deduction guides. 2048 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization())) 2049 continue; 2050 2051 Transform.transformConstructor(FTD, CD); 2052 AddedAny = true; 2053 } 2054 2055 // C++17 [over.match.class.deduct] 2056 // -- If C is not defined or does not declare any constructors, an 2057 // additional function template derived as above from a hypothetical 2058 // constructor C(). 2059 if (!AddedAny) 2060 Transform.buildSimpleDeductionGuide(None); 2061 2062 // -- An additional function template derived as above from a hypothetical 2063 // constructor C(C), called the copy deduction candidate. 2064 cast<CXXDeductionGuideDecl>( 2065 cast<FunctionTemplateDecl>( 2066 Transform.buildSimpleDeductionGuide(Transform.DeducedType)) 2067 ->getTemplatedDecl()) 2068 ->setIsCopyDeductionCandidate(); 2069 } 2070 2071 /// Diagnose the presence of a default template argument on a 2072 /// template parameter, which is ill-formed in certain contexts. 2073 /// 2074 /// \returns true if the default template argument should be dropped. 2075 static bool DiagnoseDefaultTemplateArgument(Sema &S, 2076 Sema::TemplateParamListContext TPC, 2077 SourceLocation ParamLoc, 2078 SourceRange DefArgRange) { 2079 switch (TPC) { 2080 case Sema::TPC_ClassTemplate: 2081 case Sema::TPC_VarTemplate: 2082 case Sema::TPC_TypeAliasTemplate: 2083 return false; 2084 2085 case Sema::TPC_FunctionTemplate: 2086 case Sema::TPC_FriendFunctionTemplateDefinition: 2087 // C++ [temp.param]p9: 2088 // A default template-argument shall not be specified in a 2089 // function template declaration or a function template 2090 // definition [...] 2091 // If a friend function template declaration specifies a default 2092 // template-argument, that declaration shall be a definition and shall be 2093 // the only declaration of the function template in the translation unit. 2094 // (C++98/03 doesn't have this wording; see DR226). 2095 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ? 2096 diag::warn_cxx98_compat_template_parameter_default_in_function_template 2097 : diag::ext_template_parameter_default_in_function_template) 2098 << DefArgRange; 2099 return false; 2100 2101 case Sema::TPC_ClassTemplateMember: 2102 // C++0x [temp.param]p9: 2103 // A default template-argument shall not be specified in the 2104 // template-parameter-lists of the definition of a member of a 2105 // class template that appears outside of the member's class. 2106 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) 2107 << DefArgRange; 2108 return true; 2109 2110 case Sema::TPC_FriendClassTemplate: 2111 case Sema::TPC_FriendFunctionTemplate: 2112 // C++ [temp.param]p9: 2113 // A default template-argument shall not be specified in a 2114 // friend template declaration. 2115 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) 2116 << DefArgRange; 2117 return true; 2118 2119 // FIXME: C++0x [temp.param]p9 allows default template-arguments 2120 // for friend function templates if there is only a single 2121 // declaration (and it is a definition). Strange! 2122 } 2123 2124 llvm_unreachable("Invalid TemplateParamListContext!"); 2125 } 2126 2127 /// Check for unexpanded parameter packs within the template parameters 2128 /// of a template template parameter, recursively. 2129 static bool DiagnoseUnexpandedParameterPacks(Sema &S, 2130 TemplateTemplateParmDecl *TTP) { 2131 // A template template parameter which is a parameter pack is also a pack 2132 // expansion. 2133 if (TTP->isParameterPack()) 2134 return false; 2135 2136 TemplateParameterList *Params = TTP->getTemplateParameters(); 2137 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 2138 NamedDecl *P = Params->getParam(I); 2139 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 2140 if (!NTTP->isParameterPack() && 2141 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), 2142 NTTP->getTypeSourceInfo(), 2143 Sema::UPPC_NonTypeTemplateParameterType)) 2144 return true; 2145 2146 continue; 2147 } 2148 2149 if (TemplateTemplateParmDecl *InnerTTP 2150 = dyn_cast<TemplateTemplateParmDecl>(P)) 2151 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) 2152 return true; 2153 } 2154 2155 return false; 2156 } 2157 2158 /// Checks the validity of a template parameter list, possibly 2159 /// considering the template parameter list from a previous 2160 /// declaration. 2161 /// 2162 /// If an "old" template parameter list is provided, it must be 2163 /// equivalent (per TemplateParameterListsAreEqual) to the "new" 2164 /// template parameter list. 2165 /// 2166 /// \param NewParams Template parameter list for a new template 2167 /// declaration. This template parameter list will be updated with any 2168 /// default arguments that are carried through from the previous 2169 /// template parameter list. 2170 /// 2171 /// \param OldParams If provided, template parameter list from a 2172 /// previous declaration of the same template. Default template 2173 /// arguments will be merged from the old template parameter list to 2174 /// the new template parameter list. 2175 /// 2176 /// \param TPC Describes the context in which we are checking the given 2177 /// template parameter list. 2178 /// 2179 /// \param SkipBody If we might have already made a prior merged definition 2180 /// of this template visible, the corresponding body-skipping information. 2181 /// Default argument redefinition is not an error when skipping such a body, 2182 /// because (under the ODR) we can assume the default arguments are the same 2183 /// as the prior merged definition. 2184 /// 2185 /// \returns true if an error occurred, false otherwise. 2186 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 2187 TemplateParameterList *OldParams, 2188 TemplateParamListContext TPC, 2189 SkipBodyInfo *SkipBody) { 2190 bool Invalid = false; 2191 2192 // C++ [temp.param]p10: 2193 // The set of default template-arguments available for use with a 2194 // template declaration or definition is obtained by merging the 2195 // default arguments from the definition (if in scope) and all 2196 // declarations in scope in the same way default function 2197 // arguments are (8.3.6). 2198 bool SawDefaultArgument = false; 2199 SourceLocation PreviousDefaultArgLoc; 2200 2201 // Dummy initialization to avoid warnings. 2202 TemplateParameterList::iterator OldParam = NewParams->end(); 2203 if (OldParams) 2204 OldParam = OldParams->begin(); 2205 2206 bool RemoveDefaultArguments = false; 2207 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 2208 NewParamEnd = NewParams->end(); 2209 NewParam != NewParamEnd; ++NewParam) { 2210 // Variables used to diagnose redundant default arguments 2211 bool RedundantDefaultArg = false; 2212 SourceLocation OldDefaultLoc; 2213 SourceLocation NewDefaultLoc; 2214 2215 // Variable used to diagnose missing default arguments 2216 bool MissingDefaultArg = false; 2217 2218 // Variable used to diagnose non-final parameter packs 2219 bool SawParameterPack = false; 2220 2221 if (TemplateTypeParmDecl *NewTypeParm 2222 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 2223 // Check the presence of a default argument here. 2224 if (NewTypeParm->hasDefaultArgument() && 2225 DiagnoseDefaultTemplateArgument(*this, TPC, 2226 NewTypeParm->getLocation(), 2227 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() 2228 .getSourceRange())) 2229 NewTypeParm->removeDefaultArgument(); 2230 2231 // Merge default arguments for template type parameters. 2232 TemplateTypeParmDecl *OldTypeParm 2233 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr; 2234 if (NewTypeParm->isParameterPack()) { 2235 assert(!NewTypeParm->hasDefaultArgument() && 2236 "Parameter packs can't have a default argument!"); 2237 SawParameterPack = true; 2238 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) && 2239 NewTypeParm->hasDefaultArgument() && 2240 (!SkipBody || !SkipBody->ShouldSkip)) { 2241 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 2242 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 2243 SawDefaultArgument = true; 2244 RedundantDefaultArg = true; 2245 PreviousDefaultArgLoc = NewDefaultLoc; 2246 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 2247 // Merge the default argument from the old declaration to the 2248 // new declaration. 2249 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm); 2250 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 2251 } else if (NewTypeParm->hasDefaultArgument()) { 2252 SawDefaultArgument = true; 2253 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 2254 } else if (SawDefaultArgument) 2255 MissingDefaultArg = true; 2256 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 2257 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 2258 // Check for unexpanded parameter packs. 2259 if (!NewNonTypeParm->isParameterPack() && 2260 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), 2261 NewNonTypeParm->getTypeSourceInfo(), 2262 UPPC_NonTypeTemplateParameterType)) { 2263 Invalid = true; 2264 continue; 2265 } 2266 2267 // Check the presence of a default argument here. 2268 if (NewNonTypeParm->hasDefaultArgument() && 2269 DiagnoseDefaultTemplateArgument(*this, TPC, 2270 NewNonTypeParm->getLocation(), 2271 NewNonTypeParm->getDefaultArgument()->getSourceRange())) { 2272 NewNonTypeParm->removeDefaultArgument(); 2273 } 2274 2275 // Merge default arguments for non-type template parameters 2276 NonTypeTemplateParmDecl *OldNonTypeParm 2277 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr; 2278 if (NewNonTypeParm->isParameterPack()) { 2279 assert(!NewNonTypeParm->hasDefaultArgument() && 2280 "Parameter packs can't have a default argument!"); 2281 if (!NewNonTypeParm->isPackExpansion()) 2282 SawParameterPack = true; 2283 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) && 2284 NewNonTypeParm->hasDefaultArgument() && 2285 (!SkipBody || !SkipBody->ShouldSkip)) { 2286 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 2287 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 2288 SawDefaultArgument = true; 2289 RedundantDefaultArg = true; 2290 PreviousDefaultArgLoc = NewDefaultLoc; 2291 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 2292 // Merge the default argument from the old declaration to the 2293 // new declaration. 2294 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm); 2295 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 2296 } else if (NewNonTypeParm->hasDefaultArgument()) { 2297 SawDefaultArgument = true; 2298 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 2299 } else if (SawDefaultArgument) 2300 MissingDefaultArg = true; 2301 } else { 2302 TemplateTemplateParmDecl *NewTemplateParm 2303 = cast<TemplateTemplateParmDecl>(*NewParam); 2304 2305 // Check for unexpanded parameter packs, recursively. 2306 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { 2307 Invalid = true; 2308 continue; 2309 } 2310 2311 // Check the presence of a default argument here. 2312 if (NewTemplateParm->hasDefaultArgument() && 2313 DiagnoseDefaultTemplateArgument(*this, TPC, 2314 NewTemplateParm->getLocation(), 2315 NewTemplateParm->getDefaultArgument().getSourceRange())) 2316 NewTemplateParm->removeDefaultArgument(); 2317 2318 // Merge default arguments for template template parameters 2319 TemplateTemplateParmDecl *OldTemplateParm 2320 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr; 2321 if (NewTemplateParm->isParameterPack()) { 2322 assert(!NewTemplateParm->hasDefaultArgument() && 2323 "Parameter packs can't have a default argument!"); 2324 if (!NewTemplateParm->isPackExpansion()) 2325 SawParameterPack = true; 2326 } else if (OldTemplateParm && 2327 hasVisibleDefaultArgument(OldTemplateParm) && 2328 NewTemplateParm->hasDefaultArgument() && 2329 (!SkipBody || !SkipBody->ShouldSkip)) { 2330 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 2331 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 2332 SawDefaultArgument = true; 2333 RedundantDefaultArg = true; 2334 PreviousDefaultArgLoc = NewDefaultLoc; 2335 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 2336 // Merge the default argument from the old declaration to the 2337 // new declaration. 2338 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm); 2339 PreviousDefaultArgLoc 2340 = OldTemplateParm->getDefaultArgument().getLocation(); 2341 } else if (NewTemplateParm->hasDefaultArgument()) { 2342 SawDefaultArgument = true; 2343 PreviousDefaultArgLoc 2344 = NewTemplateParm->getDefaultArgument().getLocation(); 2345 } else if (SawDefaultArgument) 2346 MissingDefaultArg = true; 2347 } 2348 2349 // C++11 [temp.param]p11: 2350 // If a template parameter of a primary class template or alias template 2351 // is a template parameter pack, it shall be the last template parameter. 2352 if (SawParameterPack && (NewParam + 1) != NewParamEnd && 2353 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate || 2354 TPC == TPC_TypeAliasTemplate)) { 2355 Diag((*NewParam)->getLocation(), 2356 diag::err_template_param_pack_must_be_last_template_parameter); 2357 Invalid = true; 2358 } 2359 2360 if (RedundantDefaultArg) { 2361 // C++ [temp.param]p12: 2362 // A template-parameter shall not be given default arguments 2363 // by two different declarations in the same scope. 2364 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 2365 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 2366 Invalid = true; 2367 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { 2368 // C++ [temp.param]p11: 2369 // If a template-parameter of a class template has a default 2370 // template-argument, each subsequent template-parameter shall either 2371 // have a default template-argument supplied or be a template parameter 2372 // pack. 2373 Diag((*NewParam)->getLocation(), 2374 diag::err_template_param_default_arg_missing); 2375 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 2376 Invalid = true; 2377 RemoveDefaultArguments = true; 2378 } 2379 2380 // If we have an old template parameter list that we're merging 2381 // in, move on to the next parameter. 2382 if (OldParams) 2383 ++OldParam; 2384 } 2385 2386 // We were missing some default arguments at the end of the list, so remove 2387 // all of the default arguments. 2388 if (RemoveDefaultArguments) { 2389 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 2390 NewParamEnd = NewParams->end(); 2391 NewParam != NewParamEnd; ++NewParam) { 2392 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) 2393 TTP->removeDefaultArgument(); 2394 else if (NonTypeTemplateParmDecl *NTTP 2395 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) 2396 NTTP->removeDefaultArgument(); 2397 else 2398 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); 2399 } 2400 } 2401 2402 return Invalid; 2403 } 2404 2405 namespace { 2406 2407 /// A class which looks for a use of a certain level of template 2408 /// parameter. 2409 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { 2410 typedef RecursiveASTVisitor<DependencyChecker> super; 2411 2412 unsigned Depth; 2413 2414 // Whether we're looking for a use of a template parameter that makes the 2415 // overall construct type-dependent / a dependent type. This is strictly 2416 // best-effort for now; we may fail to match at all for a dependent type 2417 // in some cases if this is set. 2418 bool IgnoreNonTypeDependent; 2419 2420 bool Match; 2421 SourceLocation MatchLoc; 2422 2423 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent) 2424 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent), 2425 Match(false) {} 2426 2427 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent) 2428 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) { 2429 NamedDecl *ND = Params->getParam(0); 2430 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { 2431 Depth = PD->getDepth(); 2432 } else if (NonTypeTemplateParmDecl *PD = 2433 dyn_cast<NonTypeTemplateParmDecl>(ND)) { 2434 Depth = PD->getDepth(); 2435 } else { 2436 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); 2437 } 2438 } 2439 2440 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) { 2441 if (ParmDepth >= Depth) { 2442 Match = true; 2443 MatchLoc = Loc; 2444 return true; 2445 } 2446 return false; 2447 } 2448 2449 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) { 2450 // Prune out non-type-dependent expressions if requested. This can 2451 // sometimes result in us failing to find a template parameter reference 2452 // (if a value-dependent expression creates a dependent type), but this 2453 // mode is best-effort only. 2454 if (auto *E = dyn_cast_or_null<Expr>(S)) 2455 if (IgnoreNonTypeDependent && !E->isTypeDependent()) 2456 return true; 2457 return super::TraverseStmt(S, Q); 2458 } 2459 2460 bool TraverseTypeLoc(TypeLoc TL) { 2461 if (IgnoreNonTypeDependent && !TL.isNull() && 2462 !TL.getType()->isDependentType()) 2463 return true; 2464 return super::TraverseTypeLoc(TL); 2465 } 2466 2467 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 2468 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc()); 2469 } 2470 2471 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 2472 // For a best-effort search, keep looking until we find a location. 2473 return IgnoreNonTypeDependent || !Matches(T->getDepth()); 2474 } 2475 2476 bool TraverseTemplateName(TemplateName N) { 2477 if (TemplateTemplateParmDecl *PD = 2478 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) 2479 if (Matches(PD->getDepth())) 2480 return false; 2481 return super::TraverseTemplateName(N); 2482 } 2483 2484 bool VisitDeclRefExpr(DeclRefExpr *E) { 2485 if (NonTypeTemplateParmDecl *PD = 2486 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) 2487 if (Matches(PD->getDepth(), E->getExprLoc())) 2488 return false; 2489 return super::VisitDeclRefExpr(E); 2490 } 2491 2492 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { 2493 return TraverseType(T->getReplacementType()); 2494 } 2495 2496 bool 2497 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { 2498 return TraverseTemplateArgument(T->getArgumentPack()); 2499 } 2500 2501 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) { 2502 return TraverseType(T->getInjectedSpecializationType()); 2503 } 2504 }; 2505 } // end anonymous namespace 2506 2507 /// Determines whether a given type depends on the given parameter 2508 /// list. 2509 static bool 2510 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) { 2511 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false); 2512 Checker.TraverseType(T); 2513 return Checker.Match; 2514 } 2515 2516 // Find the source range corresponding to the named type in the given 2517 // nested-name-specifier, if any. 2518 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, 2519 QualType T, 2520 const CXXScopeSpec &SS) { 2521 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data()); 2522 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) { 2523 if (const Type *CurType = NNS->getAsType()) { 2524 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0))) 2525 return NNSLoc.getTypeLoc().getSourceRange(); 2526 } else 2527 break; 2528 2529 NNSLoc = NNSLoc.getPrefix(); 2530 } 2531 2532 return SourceRange(); 2533 } 2534 2535 /// Match the given template parameter lists to the given scope 2536 /// specifier, returning the template parameter list that applies to the 2537 /// name. 2538 /// 2539 /// \param DeclStartLoc the start of the declaration that has a scope 2540 /// specifier or a template parameter list. 2541 /// 2542 /// \param DeclLoc The location of the declaration itself. 2543 /// 2544 /// \param SS the scope specifier that will be matched to the given template 2545 /// parameter lists. This scope specifier precedes a qualified name that is 2546 /// being declared. 2547 /// 2548 /// \param TemplateId The template-id following the scope specifier, if there 2549 /// is one. Used to check for a missing 'template<>'. 2550 /// 2551 /// \param ParamLists the template parameter lists, from the outermost to the 2552 /// innermost template parameter lists. 2553 /// 2554 /// \param IsFriend Whether to apply the slightly different rules for 2555 /// matching template parameters to scope specifiers in friend 2556 /// declarations. 2557 /// 2558 /// \param IsMemberSpecialization will be set true if the scope specifier 2559 /// denotes a fully-specialized type, and therefore this is a declaration of 2560 /// a member specialization. 2561 /// 2562 /// \returns the template parameter list, if any, that corresponds to the 2563 /// name that is preceded by the scope specifier @p SS. This template 2564 /// parameter list may have template parameters (if we're declaring a 2565 /// template) or may have no template parameters (if we're declaring a 2566 /// template specialization), or may be NULL (if what we're declaring isn't 2567 /// itself a template). 2568 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier( 2569 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, 2570 TemplateIdAnnotation *TemplateId, 2571 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, 2572 bool &IsMemberSpecialization, bool &Invalid) { 2573 IsMemberSpecialization = false; 2574 Invalid = false; 2575 2576 // The sequence of nested types to which we will match up the template 2577 // parameter lists. We first build this list by starting with the type named 2578 // by the nested-name-specifier and walking out until we run out of types. 2579 SmallVector<QualType, 4> NestedTypes; 2580 QualType T; 2581 if (SS.getScopeRep()) { 2582 if (CXXRecordDecl *Record 2583 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true))) 2584 T = Context.getTypeDeclType(Record); 2585 else 2586 T = QualType(SS.getScopeRep()->getAsType(), 0); 2587 } 2588 2589 // If we found an explicit specialization that prevents us from needing 2590 // 'template<>' headers, this will be set to the location of that 2591 // explicit specialization. 2592 SourceLocation ExplicitSpecLoc; 2593 2594 while (!T.isNull()) { 2595 NestedTypes.push_back(T); 2596 2597 // Retrieve the parent of a record type. 2598 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 2599 // If this type is an explicit specialization, we're done. 2600 if (ClassTemplateSpecializationDecl *Spec 2601 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 2602 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && 2603 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) { 2604 ExplicitSpecLoc = Spec->getLocation(); 2605 break; 2606 } 2607 } else if (Record->getTemplateSpecializationKind() 2608 == TSK_ExplicitSpecialization) { 2609 ExplicitSpecLoc = Record->getLocation(); 2610 break; 2611 } 2612 2613 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent())) 2614 T = Context.getTypeDeclType(Parent); 2615 else 2616 T = QualType(); 2617 continue; 2618 } 2619 2620 if (const TemplateSpecializationType *TST 2621 = T->getAs<TemplateSpecializationType>()) { 2622 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 2623 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext())) 2624 T = Context.getTypeDeclType(Parent); 2625 else 2626 T = QualType(); 2627 continue; 2628 } 2629 } 2630 2631 // Look one step prior in a dependent template specialization type. 2632 if (const DependentTemplateSpecializationType *DependentTST 2633 = T->getAs<DependentTemplateSpecializationType>()) { 2634 if (NestedNameSpecifier *NNS = DependentTST->getQualifier()) 2635 T = QualType(NNS->getAsType(), 0); 2636 else 2637 T = QualType(); 2638 continue; 2639 } 2640 2641 // Look one step prior in a dependent name type. 2642 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){ 2643 if (NestedNameSpecifier *NNS = DependentName->getQualifier()) 2644 T = QualType(NNS->getAsType(), 0); 2645 else 2646 T = QualType(); 2647 continue; 2648 } 2649 2650 // Retrieve the parent of an enumeration type. 2651 if (const EnumType *EnumT = T->getAs<EnumType>()) { 2652 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization 2653 // check here. 2654 EnumDecl *Enum = EnumT->getDecl(); 2655 2656 // Get to the parent type. 2657 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent())) 2658 T = Context.getTypeDeclType(Parent); 2659 else 2660 T = QualType(); 2661 continue; 2662 } 2663 2664 T = QualType(); 2665 } 2666 // Reverse the nested types list, since we want to traverse from the outermost 2667 // to the innermost while checking template-parameter-lists. 2668 std::reverse(NestedTypes.begin(), NestedTypes.end()); 2669 2670 // C++0x [temp.expl.spec]p17: 2671 // A member or a member template may be nested within many 2672 // enclosing class templates. In an explicit specialization for 2673 // such a member, the member declaration shall be preceded by a 2674 // template<> for each enclosing class template that is 2675 // explicitly specialized. 2676 bool SawNonEmptyTemplateParameterList = false; 2677 2678 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) { 2679 if (SawNonEmptyTemplateParameterList) { 2680 Diag(DeclLoc, diag::err_specialize_member_of_template) 2681 << !Recovery << Range; 2682 Invalid = true; 2683 IsMemberSpecialization = false; 2684 return true; 2685 } 2686 2687 return false; 2688 }; 2689 2690 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) { 2691 // Check that we can have an explicit specialization here. 2692 if (CheckExplicitSpecialization(Range, true)) 2693 return true; 2694 2695 // We don't have a template header, but we should. 2696 SourceLocation ExpectedTemplateLoc; 2697 if (!ParamLists.empty()) 2698 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc(); 2699 else 2700 ExpectedTemplateLoc = DeclStartLoc; 2701 2702 Diag(DeclLoc, diag::err_template_spec_needs_header) 2703 << Range 2704 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> "); 2705 return false; 2706 }; 2707 2708 unsigned ParamIdx = 0; 2709 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes; 2710 ++TypeIdx) { 2711 T = NestedTypes[TypeIdx]; 2712 2713 // Whether we expect a 'template<>' header. 2714 bool NeedEmptyTemplateHeader = false; 2715 2716 // Whether we expect a template header with parameters. 2717 bool NeedNonemptyTemplateHeader = false; 2718 2719 // For a dependent type, the set of template parameters that we 2720 // expect to see. 2721 TemplateParameterList *ExpectedTemplateParams = nullptr; 2722 2723 // C++0x [temp.expl.spec]p15: 2724 // A member or a member template may be nested within many enclosing 2725 // class templates. In an explicit specialization for such a member, the 2726 // member declaration shall be preceded by a template<> for each 2727 // enclosing class template that is explicitly specialized. 2728 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 2729 if (ClassTemplatePartialSpecializationDecl *Partial 2730 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 2731 ExpectedTemplateParams = Partial->getTemplateParameters(); 2732 NeedNonemptyTemplateHeader = true; 2733 } else if (Record->isDependentType()) { 2734 if (Record->getDescribedClassTemplate()) { 2735 ExpectedTemplateParams = Record->getDescribedClassTemplate() 2736 ->getTemplateParameters(); 2737 NeedNonemptyTemplateHeader = true; 2738 } 2739 } else if (ClassTemplateSpecializationDecl *Spec 2740 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 2741 // C++0x [temp.expl.spec]p4: 2742 // Members of an explicitly specialized class template are defined 2743 // in the same manner as members of normal classes, and not using 2744 // the template<> syntax. 2745 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization) 2746 NeedEmptyTemplateHeader = true; 2747 else 2748 continue; 2749 } else if (Record->getTemplateSpecializationKind()) { 2750 if (Record->getTemplateSpecializationKind() 2751 != TSK_ExplicitSpecialization && 2752 TypeIdx == NumTypes - 1) 2753 IsMemberSpecialization = true; 2754 2755 continue; 2756 } 2757 } else if (const TemplateSpecializationType *TST 2758 = T->getAs<TemplateSpecializationType>()) { 2759 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 2760 ExpectedTemplateParams = Template->getTemplateParameters(); 2761 NeedNonemptyTemplateHeader = true; 2762 } 2763 } else if (T->getAs<DependentTemplateSpecializationType>()) { 2764 // FIXME: We actually could/should check the template arguments here 2765 // against the corresponding template parameter list. 2766 NeedNonemptyTemplateHeader = false; 2767 } 2768 2769 // C++ [temp.expl.spec]p16: 2770 // In an explicit specialization declaration for a member of a class 2771 // template or a member template that ap- pears in namespace scope, the 2772 // member template and some of its enclosing class templates may remain 2773 // unspecialized, except that the declaration shall not explicitly 2774 // specialize a class member template if its en- closing class templates 2775 // are not explicitly specialized as well. 2776 if (ParamIdx < ParamLists.size()) { 2777 if (ParamLists[ParamIdx]->size() == 0) { 2778 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), 2779 false)) 2780 return nullptr; 2781 } else 2782 SawNonEmptyTemplateParameterList = true; 2783 } 2784 2785 if (NeedEmptyTemplateHeader) { 2786 // If we're on the last of the types, and we need a 'template<>' header 2787 // here, then it's a member specialization. 2788 if (TypeIdx == NumTypes - 1) 2789 IsMemberSpecialization = true; 2790 2791 if (ParamIdx < ParamLists.size()) { 2792 if (ParamLists[ParamIdx]->size() > 0) { 2793 // The header has template parameters when it shouldn't. Complain. 2794 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 2795 diag::err_template_param_list_matches_nontemplate) 2796 << T 2797 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(), 2798 ParamLists[ParamIdx]->getRAngleLoc()) 2799 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 2800 Invalid = true; 2801 return nullptr; 2802 } 2803 2804 // Consume this template header. 2805 ++ParamIdx; 2806 continue; 2807 } 2808 2809 if (!IsFriend) 2810 if (DiagnoseMissingExplicitSpecialization( 2811 getRangeOfTypeInNestedNameSpecifier(Context, T, SS))) 2812 return nullptr; 2813 2814 continue; 2815 } 2816 2817 if (NeedNonemptyTemplateHeader) { 2818 // In friend declarations we can have template-ids which don't 2819 // depend on the corresponding template parameter lists. But 2820 // assume that empty parameter lists are supposed to match this 2821 // template-id. 2822 if (IsFriend && T->isDependentType()) { 2823 if (ParamIdx < ParamLists.size() && 2824 DependsOnTemplateParameters(T, ParamLists[ParamIdx])) 2825 ExpectedTemplateParams = nullptr; 2826 else 2827 continue; 2828 } 2829 2830 if (ParamIdx < ParamLists.size()) { 2831 // Check the template parameter list, if we can. 2832 if (ExpectedTemplateParams && 2833 !TemplateParameterListsAreEqual(ParamLists[ParamIdx], 2834 ExpectedTemplateParams, 2835 true, TPL_TemplateMatch)) 2836 Invalid = true; 2837 2838 if (!Invalid && 2839 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr, 2840 TPC_ClassTemplateMember)) 2841 Invalid = true; 2842 2843 ++ParamIdx; 2844 continue; 2845 } 2846 2847 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters) 2848 << T 2849 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 2850 Invalid = true; 2851 continue; 2852 } 2853 } 2854 2855 // If there were at least as many template-ids as there were template 2856 // parameter lists, then there are no template parameter lists remaining for 2857 // the declaration itself. 2858 if (ParamIdx >= ParamLists.size()) { 2859 if (TemplateId && !IsFriend) { 2860 // We don't have a template header for the declaration itself, but we 2861 // should. 2862 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc, 2863 TemplateId->RAngleLoc)); 2864 2865 // Fabricate an empty template parameter list for the invented header. 2866 return TemplateParameterList::Create(Context, SourceLocation(), 2867 SourceLocation(), None, 2868 SourceLocation(), nullptr); 2869 } 2870 2871 return nullptr; 2872 } 2873 2874 // If there were too many template parameter lists, complain about that now. 2875 if (ParamIdx < ParamLists.size() - 1) { 2876 bool HasAnyExplicitSpecHeader = false; 2877 bool AllExplicitSpecHeaders = true; 2878 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) { 2879 if (ParamLists[I]->size() == 0) 2880 HasAnyExplicitSpecHeader = true; 2881 else 2882 AllExplicitSpecHeaders = false; 2883 } 2884 2885 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 2886 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers 2887 : diag::err_template_spec_extra_headers) 2888 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), 2889 ParamLists[ParamLists.size() - 2]->getRAngleLoc()); 2890 2891 // If there was a specialization somewhere, such that 'template<>' is 2892 // not required, and there were any 'template<>' headers, note where the 2893 // specialization occurred. 2894 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader) 2895 Diag(ExplicitSpecLoc, 2896 diag::note_explicit_template_spec_does_not_need_header) 2897 << NestedTypes.back(); 2898 2899 // We have a template parameter list with no corresponding scope, which 2900 // means that the resulting template declaration can't be instantiated 2901 // properly (we'll end up with dependent nodes when we shouldn't). 2902 if (!AllExplicitSpecHeaders) 2903 Invalid = true; 2904 } 2905 2906 // C++ [temp.expl.spec]p16: 2907 // In an explicit specialization declaration for a member of a class 2908 // template or a member template that ap- pears in namespace scope, the 2909 // member template and some of its enclosing class templates may remain 2910 // unspecialized, except that the declaration shall not explicitly 2911 // specialize a class member template if its en- closing class templates 2912 // are not explicitly specialized as well. 2913 if (ParamLists.back()->size() == 0 && 2914 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), 2915 false)) 2916 return nullptr; 2917 2918 // Return the last template parameter list, which corresponds to the 2919 // entity being declared. 2920 return ParamLists.back(); 2921 } 2922 2923 void Sema::NoteAllFoundTemplates(TemplateName Name) { 2924 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 2925 Diag(Template->getLocation(), diag::note_template_declared_here) 2926 << (isa<FunctionTemplateDecl>(Template) 2927 ? 0 2928 : isa<ClassTemplateDecl>(Template) 2929 ? 1 2930 : isa<VarTemplateDecl>(Template) 2931 ? 2 2932 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4) 2933 << Template->getDeclName(); 2934 return; 2935 } 2936 2937 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { 2938 for (OverloadedTemplateStorage::iterator I = OST->begin(), 2939 IEnd = OST->end(); 2940 I != IEnd; ++I) 2941 Diag((*I)->getLocation(), diag::note_template_declared_here) 2942 << 0 << (*I)->getDeclName(); 2943 2944 return; 2945 } 2946 } 2947 2948 static QualType 2949 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, 2950 const SmallVectorImpl<TemplateArgument> &Converted, 2951 SourceLocation TemplateLoc, 2952 TemplateArgumentListInfo &TemplateArgs) { 2953 ASTContext &Context = SemaRef.getASTContext(); 2954 switch (BTD->getBuiltinTemplateKind()) { 2955 case BTK__make_integer_seq: { 2956 // Specializations of __make_integer_seq<S, T, N> are treated like 2957 // S<T, 0, ..., N-1>. 2958 2959 // C++14 [inteseq.intseq]p1: 2960 // T shall be an integer type. 2961 if (!Converted[1].getAsType()->isIntegralType(Context)) { 2962 SemaRef.Diag(TemplateArgs[1].getLocation(), 2963 diag::err_integer_sequence_integral_element_type); 2964 return QualType(); 2965 } 2966 2967 // C++14 [inteseq.make]p1: 2968 // If N is negative the program is ill-formed. 2969 TemplateArgument NumArgsArg = Converted[2]; 2970 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); 2971 if (NumArgs < 0) { 2972 SemaRef.Diag(TemplateArgs[2].getLocation(), 2973 diag::err_integer_sequence_negative_length); 2974 return QualType(); 2975 } 2976 2977 QualType ArgTy = NumArgsArg.getIntegralType(); 2978 TemplateArgumentListInfo SyntheticTemplateArgs; 2979 // The type argument gets reused as the first template argument in the 2980 // synthetic template argument list. 2981 SyntheticTemplateArgs.addArgument(TemplateArgs[1]); 2982 // Expand N into 0 ... N-1. 2983 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned()); 2984 I < NumArgs; ++I) { 2985 TemplateArgument TA(Context, I, ArgTy); 2986 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc( 2987 TA, ArgTy, TemplateArgs[2].getLocation())); 2988 } 2989 // The first template argument will be reused as the template decl that 2990 // our synthetic template arguments will be applied to. 2991 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(), 2992 TemplateLoc, SyntheticTemplateArgs); 2993 } 2994 2995 case BTK__type_pack_element: 2996 // Specializations of 2997 // __type_pack_element<Index, T_1, ..., T_N> 2998 // are treated like T_Index. 2999 assert(Converted.size() == 2 && 3000 "__type_pack_element should be given an index and a parameter pack"); 3001 3002 // If the Index is out of bounds, the program is ill-formed. 3003 TemplateArgument IndexArg = Converted[0], Ts = Converted[1]; 3004 llvm::APSInt Index = IndexArg.getAsIntegral(); 3005 assert(Index >= 0 && "the index used with __type_pack_element should be of " 3006 "type std::size_t, and hence be non-negative"); 3007 if (Index >= Ts.pack_size()) { 3008 SemaRef.Diag(TemplateArgs[0].getLocation(), 3009 diag::err_type_pack_element_out_of_bounds); 3010 return QualType(); 3011 } 3012 3013 // We simply return the type at index `Index`. 3014 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue()); 3015 return Nth->getAsType(); 3016 } 3017 llvm_unreachable("unexpected BuiltinTemplateDecl!"); 3018 } 3019 3020 /// Determine whether this alias template is "enable_if_t". 3021 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) { 3022 return AliasTemplate->getName().equals("enable_if_t"); 3023 } 3024 3025 /// Collect all of the separable terms in the given condition, which 3026 /// might be a conjunction. 3027 /// 3028 /// FIXME: The right answer is to convert the logical expression into 3029 /// disjunctive normal form, so we can find the first failed term 3030 /// within each possible clause. 3031 static void collectConjunctionTerms(Expr *Clause, 3032 SmallVectorImpl<Expr *> &Terms) { 3033 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) { 3034 if (BinOp->getOpcode() == BO_LAnd) { 3035 collectConjunctionTerms(BinOp->getLHS(), Terms); 3036 collectConjunctionTerms(BinOp->getRHS(), Terms); 3037 } 3038 3039 return; 3040 } 3041 3042 Terms.push_back(Clause); 3043 } 3044 3045 // The ranges-v3 library uses an odd pattern of a top-level "||" with 3046 // a left-hand side that is value-dependent but never true. Identify 3047 // the idiom and ignore that term. 3048 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) { 3049 // Top-level '||'. 3050 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts()); 3051 if (!BinOp) return Cond; 3052 3053 if (BinOp->getOpcode() != BO_LOr) return Cond; 3054 3055 // With an inner '==' that has a literal on the right-hand side. 3056 Expr *LHS = BinOp->getLHS(); 3057 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts()); 3058 if (!InnerBinOp) return Cond; 3059 3060 if (InnerBinOp->getOpcode() != BO_EQ || 3061 !isa<IntegerLiteral>(InnerBinOp->getRHS())) 3062 return Cond; 3063 3064 // If the inner binary operation came from a macro expansion named 3065 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side 3066 // of the '||', which is the real, user-provided condition. 3067 SourceLocation Loc = InnerBinOp->getExprLoc(); 3068 if (!Loc.isMacroID()) return Cond; 3069 3070 StringRef MacroName = PP.getImmediateMacroName(Loc); 3071 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_") 3072 return BinOp->getRHS(); 3073 3074 return Cond; 3075 } 3076 3077 namespace { 3078 3079 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions 3080 // within failing boolean expression, such as substituting template parameters 3081 // for actual types. 3082 class FailedBooleanConditionPrinterHelper : public PrinterHelper { 3083 public: 3084 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P) 3085 : Policy(P) {} 3086 3087 bool handledStmt(Stmt *E, raw_ostream &OS) override { 3088 const auto *DR = dyn_cast<DeclRefExpr>(E); 3089 if (DR && DR->getQualifier()) { 3090 // If this is a qualified name, expand the template arguments in nested 3091 // qualifiers. 3092 DR->getQualifier()->print(OS, Policy, true); 3093 // Then print the decl itself. 3094 const ValueDecl *VD = DR->getDecl(); 3095 OS << VD->getName(); 3096 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) { 3097 // This is a template variable, print the expanded template arguments. 3098 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy); 3099 } 3100 return true; 3101 } 3102 return false; 3103 } 3104 3105 private: 3106 const PrintingPolicy Policy; 3107 }; 3108 3109 } // end anonymous namespace 3110 3111 std::pair<Expr *, std::string> 3112 Sema::findFailedBooleanCondition(Expr *Cond) { 3113 Cond = lookThroughRangesV3Condition(PP, Cond); 3114 3115 // Separate out all of the terms in a conjunction. 3116 SmallVector<Expr *, 4> Terms; 3117 collectConjunctionTerms(Cond, Terms); 3118 3119 // Determine which term failed. 3120 Expr *FailedCond = nullptr; 3121 for (Expr *Term : Terms) { 3122 Expr *TermAsWritten = Term->IgnoreParenImpCasts(); 3123 3124 // Literals are uninteresting. 3125 if (isa<CXXBoolLiteralExpr>(TermAsWritten) || 3126 isa<IntegerLiteral>(TermAsWritten)) 3127 continue; 3128 3129 // The initialization of the parameter from the argument is 3130 // a constant-evaluated context. 3131 EnterExpressionEvaluationContext ConstantEvaluated( 3132 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); 3133 3134 bool Succeeded; 3135 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) && 3136 !Succeeded) { 3137 FailedCond = TermAsWritten; 3138 break; 3139 } 3140 } 3141 if (!FailedCond) 3142 FailedCond = Cond->IgnoreParenImpCasts(); 3143 3144 std::string Description; 3145 { 3146 llvm::raw_string_ostream Out(Description); 3147 PrintingPolicy Policy = getPrintingPolicy(); 3148 Policy.PrintCanonicalTypes = true; 3149 FailedBooleanConditionPrinterHelper Helper(Policy); 3150 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr); 3151 } 3152 return { FailedCond, Description }; 3153 } 3154 3155 QualType Sema::CheckTemplateIdType(TemplateName Name, 3156 SourceLocation TemplateLoc, 3157 TemplateArgumentListInfo &TemplateArgs) { 3158 DependentTemplateName *DTN 3159 = Name.getUnderlying().getAsDependentTemplateName(); 3160 if (DTN && DTN->isIdentifier()) 3161 // When building a template-id where the template-name is dependent, 3162 // assume the template is a type template. Either our assumption is 3163 // correct, or the code is ill-formed and will be diagnosed when the 3164 // dependent name is substituted. 3165 return Context.getDependentTemplateSpecializationType(ETK_None, 3166 DTN->getQualifier(), 3167 DTN->getIdentifier(), 3168 TemplateArgs); 3169 3170 TemplateDecl *Template = Name.getAsTemplateDecl(); 3171 if (!Template || isa<FunctionTemplateDecl>(Template) || 3172 isa<VarTemplateDecl>(Template)) { 3173 // We might have a substituted template template parameter pack. If so, 3174 // build a template specialization type for it. 3175 if (Name.getAsSubstTemplateTemplateParmPack()) 3176 return Context.getTemplateSpecializationType(Name, TemplateArgs); 3177 3178 Diag(TemplateLoc, diag::err_template_id_not_a_type) 3179 << Name; 3180 NoteAllFoundTemplates(Name); 3181 return QualType(); 3182 } 3183 3184 // Check that the template argument list is well-formed for this 3185 // template. 3186 SmallVector<TemplateArgument, 4> Converted; 3187 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, 3188 false, Converted)) 3189 return QualType(); 3190 3191 QualType CanonType; 3192 3193 bool InstantiationDependent = false; 3194 if (TypeAliasTemplateDecl *AliasTemplate = 3195 dyn_cast<TypeAliasTemplateDecl>(Template)) { 3196 // Find the canonical type for this type alias template specialization. 3197 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl(); 3198 if (Pattern->isInvalidDecl()) 3199 return QualType(); 3200 3201 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack, 3202 Converted); 3203 3204 // Only substitute for the innermost template argument list. 3205 MultiLevelTemplateArgumentList TemplateArgLists; 3206 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs); 3207 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth(); 3208 for (unsigned I = 0; I < Depth; ++I) 3209 TemplateArgLists.addOuterTemplateArguments(None); 3210 3211 LocalInstantiationScope Scope(*this); 3212 InstantiatingTemplate Inst(*this, TemplateLoc, Template); 3213 if (Inst.isInvalid()) 3214 return QualType(); 3215 3216 CanonType = SubstType(Pattern->getUnderlyingType(), 3217 TemplateArgLists, AliasTemplate->getLocation(), 3218 AliasTemplate->getDeclName()); 3219 if (CanonType.isNull()) { 3220 // If this was enable_if and we failed to find the nested type 3221 // within enable_if in a SFINAE context, dig out the specific 3222 // enable_if condition that failed and present that instead. 3223 if (isEnableIfAliasTemplate(AliasTemplate)) { 3224 if (auto DeductionInfo = isSFINAEContext()) { 3225 if (*DeductionInfo && 3226 (*DeductionInfo)->hasSFINAEDiagnostic() && 3227 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() == 3228 diag::err_typename_nested_not_found_enable_if && 3229 TemplateArgs[0].getArgument().getKind() 3230 == TemplateArgument::Expression) { 3231 Expr *FailedCond; 3232 std::string FailedDescription; 3233 std::tie(FailedCond, FailedDescription) = 3234 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression()); 3235 3236 // Remove the old SFINAE diagnostic. 3237 PartialDiagnosticAt OldDiag = 3238 {SourceLocation(), PartialDiagnostic::NullDiagnostic()}; 3239 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag); 3240 3241 // Add a new SFINAE diagnostic specifying which condition 3242 // failed. 3243 (*DeductionInfo)->addSFINAEDiagnostic( 3244 OldDiag.first, 3245 PDiag(diag::err_typename_nested_not_found_requirement) 3246 << FailedDescription 3247 << FailedCond->getSourceRange()); 3248 } 3249 } 3250 } 3251 3252 return QualType(); 3253 } 3254 } else if (Name.isDependent() || 3255 TemplateSpecializationType::anyDependentTemplateArguments( 3256 TemplateArgs, InstantiationDependent)) { 3257 // This class template specialization is a dependent 3258 // type. Therefore, its canonical type is another class template 3259 // specialization type that contains all of the converted 3260 // arguments in canonical form. This ensures that, e.g., A<T> and 3261 // A<T, T> have identical types when A is declared as: 3262 // 3263 // template<typename T, typename U = T> struct A; 3264 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted); 3265 3266 // This might work out to be a current instantiation, in which 3267 // case the canonical type needs to be the InjectedClassNameType. 3268 // 3269 // TODO: in theory this could be a simple hashtable lookup; most 3270 // changes to CurContext don't change the set of current 3271 // instantiations. 3272 if (isa<ClassTemplateDecl>(Template)) { 3273 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { 3274 // If we get out to a namespace, we're done. 3275 if (Ctx->isFileContext()) break; 3276 3277 // If this isn't a record, keep looking. 3278 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); 3279 if (!Record) continue; 3280 3281 // Look for one of the two cases with InjectedClassNameTypes 3282 // and check whether it's the same template. 3283 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && 3284 !Record->getDescribedClassTemplate()) 3285 continue; 3286 3287 // Fetch the injected class name type and check whether its 3288 // injected type is equal to the type we just built. 3289 QualType ICNT = Context.getTypeDeclType(Record); 3290 QualType Injected = cast<InjectedClassNameType>(ICNT) 3291 ->getInjectedSpecializationType(); 3292 3293 if (CanonType != Injected->getCanonicalTypeInternal()) 3294 continue; 3295 3296 // If so, the canonical type of this TST is the injected 3297 // class name type of the record we just found. 3298 assert(ICNT.isCanonical()); 3299 CanonType = ICNT; 3300 break; 3301 } 3302 } 3303 } else if (ClassTemplateDecl *ClassTemplate 3304 = dyn_cast<ClassTemplateDecl>(Template)) { 3305 // Find the class template specialization declaration that 3306 // corresponds to these arguments. 3307 void *InsertPos = nullptr; 3308 ClassTemplateSpecializationDecl *Decl 3309 = ClassTemplate->findSpecialization(Converted, InsertPos); 3310 if (!Decl) { 3311 // This is the first time we have referenced this class template 3312 // specialization. Create the canonical declaration and add it to 3313 // the set of specializations. 3314 Decl = ClassTemplateSpecializationDecl::Create( 3315 Context, ClassTemplate->getTemplatedDecl()->getTagKind(), 3316 ClassTemplate->getDeclContext(), 3317 ClassTemplate->getTemplatedDecl()->getBeginLoc(), 3318 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr); 3319 ClassTemplate->AddSpecialization(Decl, InsertPos); 3320 if (ClassTemplate->isOutOfLine()) 3321 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext()); 3322 } 3323 3324 if (Decl->getSpecializationKind() == TSK_Undeclared) { 3325 MultiLevelTemplateArgumentList TemplateArgLists; 3326 TemplateArgLists.addOuterTemplateArguments(Converted); 3327 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(), 3328 Decl); 3329 } 3330 3331 // Diagnose uses of this specialization. 3332 (void)DiagnoseUseOfDecl(Decl, TemplateLoc); 3333 3334 CanonType = Context.getTypeDeclType(Decl); 3335 assert(isa<RecordType>(CanonType) && 3336 "type of non-dependent specialization is not a RecordType"); 3337 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) { 3338 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc, 3339 TemplateArgs); 3340 } 3341 3342 // Build the fully-sugared type for this class template 3343 // specialization, which refers back to the class template 3344 // specialization we created or found. 3345 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 3346 } 3347 3348 TypeResult 3349 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 3350 TemplateTy TemplateD, IdentifierInfo *TemplateII, 3351 SourceLocation TemplateIILoc, 3352 SourceLocation LAngleLoc, 3353 ASTTemplateArgsPtr TemplateArgsIn, 3354 SourceLocation RAngleLoc, 3355 bool IsCtorOrDtorName, bool IsClassName) { 3356 if (SS.isInvalid()) 3357 return true; 3358 3359 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) { 3360 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false); 3361 3362 // C++ [temp.res]p3: 3363 // A qualified-id that refers to a type and in which the 3364 // nested-name-specifier depends on a template-parameter (14.6.2) 3365 // shall be prefixed by the keyword typename to indicate that the 3366 // qualified-id denotes a type, forming an 3367 // elaborated-type-specifier (7.1.5.3). 3368 if (!LookupCtx && isDependentScopeSpecifier(SS)) { 3369 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) 3370 << SS.getScopeRep() << TemplateII->getName(); 3371 // Recover as if 'typename' were specified. 3372 // FIXME: This is not quite correct recovery as we don't transform SS 3373 // into the corresponding dependent form (and we don't diagnose missing 3374 // 'template' keywords within SS as a result). 3375 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc, 3376 TemplateD, TemplateII, TemplateIILoc, LAngleLoc, 3377 TemplateArgsIn, RAngleLoc); 3378 } 3379 3380 // Per C++ [class.qual]p2, if the template-id was an injected-class-name, 3381 // it's not actually allowed to be used as a type in most cases. Because 3382 // we annotate it before we know whether it's valid, we have to check for 3383 // this case here. 3384 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 3385 if (LookupRD && LookupRD->getIdentifier() == TemplateII) { 3386 Diag(TemplateIILoc, 3387 TemplateKWLoc.isInvalid() 3388 ? diag::err_out_of_line_qualified_id_type_names_constructor 3389 : diag::ext_out_of_line_qualified_id_type_names_constructor) 3390 << TemplateII << 0 /*injected-class-name used as template name*/ 3391 << 1 /*if any keyword was present, it was 'template'*/; 3392 } 3393 } 3394 3395 TemplateName Template = TemplateD.get(); 3396 3397 // Translate the parser's template argument list in our AST format. 3398 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 3399 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 3400 3401 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 3402 QualType T 3403 = Context.getDependentTemplateSpecializationType(ETK_None, 3404 DTN->getQualifier(), 3405 DTN->getIdentifier(), 3406 TemplateArgs); 3407 // Build type-source information. 3408 TypeLocBuilder TLB; 3409 DependentTemplateSpecializationTypeLoc SpecTL 3410 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 3411 SpecTL.setElaboratedKeywordLoc(SourceLocation()); 3412 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 3413 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 3414 SpecTL.setTemplateNameLoc(TemplateIILoc); 3415 SpecTL.setLAngleLoc(LAngleLoc); 3416 SpecTL.setRAngleLoc(RAngleLoc); 3417 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 3418 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 3419 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 3420 } 3421 3422 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); 3423 if (Result.isNull()) 3424 return true; 3425 3426 // Build type-source information. 3427 TypeLocBuilder TLB; 3428 TemplateSpecializationTypeLoc SpecTL 3429 = TLB.push<TemplateSpecializationTypeLoc>(Result); 3430 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 3431 SpecTL.setTemplateNameLoc(TemplateIILoc); 3432 SpecTL.setLAngleLoc(LAngleLoc); 3433 SpecTL.setRAngleLoc(RAngleLoc); 3434 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 3435 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 3436 3437 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a 3438 // constructor or destructor name (in such a case, the scope specifier 3439 // will be attached to the enclosing Decl or Expr node). 3440 if (SS.isNotEmpty() && !IsCtorOrDtorName) { 3441 // Create an elaborated-type-specifier containing the nested-name-specifier. 3442 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result); 3443 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 3444 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 3445 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 3446 } 3447 3448 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 3449 } 3450 3451 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, 3452 TypeSpecifierType TagSpec, 3453 SourceLocation TagLoc, 3454 CXXScopeSpec &SS, 3455 SourceLocation TemplateKWLoc, 3456 TemplateTy TemplateD, 3457 SourceLocation TemplateLoc, 3458 SourceLocation LAngleLoc, 3459 ASTTemplateArgsPtr TemplateArgsIn, 3460 SourceLocation RAngleLoc) { 3461 TemplateName Template = TemplateD.get(); 3462 3463 // Translate the parser's template argument list in our AST format. 3464 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 3465 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 3466 3467 // Determine the tag kind 3468 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 3469 ElaboratedTypeKeyword Keyword 3470 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); 3471 3472 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 3473 QualType T = Context.getDependentTemplateSpecializationType(Keyword, 3474 DTN->getQualifier(), 3475 DTN->getIdentifier(), 3476 TemplateArgs); 3477 3478 // Build type-source information. 3479 TypeLocBuilder TLB; 3480 DependentTemplateSpecializationTypeLoc SpecTL 3481 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 3482 SpecTL.setElaboratedKeywordLoc(TagLoc); 3483 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 3484 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 3485 SpecTL.setTemplateNameLoc(TemplateLoc); 3486 SpecTL.setLAngleLoc(LAngleLoc); 3487 SpecTL.setRAngleLoc(RAngleLoc); 3488 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 3489 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 3490 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 3491 } 3492 3493 if (TypeAliasTemplateDecl *TAT = 3494 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) { 3495 // C++0x [dcl.type.elab]p2: 3496 // If the identifier resolves to a typedef-name or the simple-template-id 3497 // resolves to an alias template specialization, the 3498 // elaborated-type-specifier is ill-formed. 3499 Diag(TemplateLoc, diag::err_tag_reference_non_tag) 3500 << TAT << NTK_TypeAliasTemplate << TagKind; 3501 Diag(TAT->getLocation(), diag::note_declared_at); 3502 } 3503 3504 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 3505 if (Result.isNull()) 3506 return TypeResult(true); 3507 3508 // Check the tag kind 3509 if (const RecordType *RT = Result->getAs<RecordType>()) { 3510 RecordDecl *D = RT->getDecl(); 3511 3512 IdentifierInfo *Id = D->getIdentifier(); 3513 assert(Id && "templated class must have an identifier"); 3514 3515 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, 3516 TagLoc, Id)) { 3517 Diag(TagLoc, diag::err_use_with_wrong_tag) 3518 << Result 3519 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); 3520 Diag(D->getLocation(), diag::note_previous_use); 3521 } 3522 } 3523 3524 // Provide source-location information for the template specialization. 3525 TypeLocBuilder TLB; 3526 TemplateSpecializationTypeLoc SpecTL 3527 = TLB.push<TemplateSpecializationTypeLoc>(Result); 3528 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 3529 SpecTL.setTemplateNameLoc(TemplateLoc); 3530 SpecTL.setLAngleLoc(LAngleLoc); 3531 SpecTL.setRAngleLoc(RAngleLoc); 3532 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 3533 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 3534 3535 // Construct an elaborated type containing the nested-name-specifier (if any) 3536 // and tag keyword. 3537 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); 3538 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 3539 ElabTL.setElaboratedKeywordLoc(TagLoc); 3540 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 3541 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 3542 } 3543 3544 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, 3545 NamedDecl *PrevDecl, 3546 SourceLocation Loc, 3547 bool IsPartialSpecialization); 3548 3549 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D); 3550 3551 static bool isTemplateArgumentTemplateParameter( 3552 const TemplateArgument &Arg, unsigned Depth, unsigned Index) { 3553 switch (Arg.getKind()) { 3554 case TemplateArgument::Null: 3555 case TemplateArgument::NullPtr: 3556 case TemplateArgument::Integral: 3557 case TemplateArgument::Declaration: 3558 case TemplateArgument::Pack: 3559 case TemplateArgument::TemplateExpansion: 3560 return false; 3561 3562 case TemplateArgument::Type: { 3563 QualType Type = Arg.getAsType(); 3564 const TemplateTypeParmType *TPT = 3565 Arg.getAsType()->getAs<TemplateTypeParmType>(); 3566 return TPT && !Type.hasQualifiers() && 3567 TPT->getDepth() == Depth && TPT->getIndex() == Index; 3568 } 3569 3570 case TemplateArgument::Expression: { 3571 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr()); 3572 if (!DRE || !DRE->getDecl()) 3573 return false; 3574 const NonTypeTemplateParmDecl *NTTP = 3575 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 3576 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index; 3577 } 3578 3579 case TemplateArgument::Template: 3580 const TemplateTemplateParmDecl *TTP = 3581 dyn_cast_or_null<TemplateTemplateParmDecl>( 3582 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()); 3583 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index; 3584 } 3585 llvm_unreachable("unexpected kind of template argument"); 3586 } 3587 3588 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, 3589 ArrayRef<TemplateArgument> Args) { 3590 if (Params->size() != Args.size()) 3591 return false; 3592 3593 unsigned Depth = Params->getDepth(); 3594 3595 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 3596 TemplateArgument Arg = Args[I]; 3597 3598 // If the parameter is a pack expansion, the argument must be a pack 3599 // whose only element is a pack expansion. 3600 if (Params->getParam(I)->isParameterPack()) { 3601 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 || 3602 !Arg.pack_begin()->isPackExpansion()) 3603 return false; 3604 Arg = Arg.pack_begin()->getPackExpansionPattern(); 3605 } 3606 3607 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I)) 3608 return false; 3609 } 3610 3611 return true; 3612 } 3613 3614 /// Convert the parser's template argument list representation into our form. 3615 static TemplateArgumentListInfo 3616 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) { 3617 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc, 3618 TemplateId.RAngleLoc); 3619 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(), 3620 TemplateId.NumArgs); 3621 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 3622 return TemplateArgs; 3623 } 3624 3625 template<typename PartialSpecDecl> 3626 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) { 3627 if (Partial->getDeclContext()->isDependentContext()) 3628 return; 3629 3630 // FIXME: Get the TDK from deduction in order to provide better diagnostics 3631 // for non-substitution-failure issues? 3632 TemplateDeductionInfo Info(Partial->getLocation()); 3633 if (S.isMoreSpecializedThanPrimary(Partial, Info)) 3634 return; 3635 3636 auto *Template = Partial->getSpecializedTemplate(); 3637 S.Diag(Partial->getLocation(), 3638 diag::ext_partial_spec_not_more_specialized_than_primary) 3639 << isa<VarTemplateDecl>(Template); 3640 3641 if (Info.hasSFINAEDiagnostic()) { 3642 PartialDiagnosticAt Diag = {SourceLocation(), 3643 PartialDiagnostic::NullDiagnostic()}; 3644 Info.takeSFINAEDiagnostic(Diag); 3645 SmallString<128> SFINAEArgString; 3646 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString); 3647 S.Diag(Diag.first, 3648 diag::note_partial_spec_not_more_specialized_than_primary) 3649 << SFINAEArgString; 3650 } 3651 3652 S.Diag(Template->getLocation(), diag::note_template_decl_here); 3653 } 3654 3655 static void 3656 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, 3657 const llvm::SmallBitVector &DeducibleParams) { 3658 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 3659 if (!DeducibleParams[I]) { 3660 NamedDecl *Param = TemplateParams->getParam(I); 3661 if (Param->getDeclName()) 3662 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) 3663 << Param->getDeclName(); 3664 else 3665 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) 3666 << "(anonymous)"; 3667 } 3668 } 3669 } 3670 3671 3672 template<typename PartialSpecDecl> 3673 static void checkTemplatePartialSpecialization(Sema &S, 3674 PartialSpecDecl *Partial) { 3675 // C++1z [temp.class.spec]p8: (DR1495) 3676 // - The specialization shall be more specialized than the primary 3677 // template (14.5.5.2). 3678 checkMoreSpecializedThanPrimary(S, Partial); 3679 3680 // C++ [temp.class.spec]p8: (DR1315) 3681 // - Each template-parameter shall appear at least once in the 3682 // template-id outside a non-deduced context. 3683 // C++1z [temp.class.spec.match]p3 (P0127R2) 3684 // If the template arguments of a partial specialization cannot be 3685 // deduced because of the structure of its template-parameter-list 3686 // and the template-id, the program is ill-formed. 3687 auto *TemplateParams = Partial->getTemplateParameters(); 3688 llvm::SmallBitVector DeducibleParams(TemplateParams->size()); 3689 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 3690 TemplateParams->getDepth(), DeducibleParams); 3691 3692 if (!DeducibleParams.all()) { 3693 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); 3694 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible) 3695 << isa<VarTemplatePartialSpecializationDecl>(Partial) 3696 << (NumNonDeducible > 1) 3697 << SourceRange(Partial->getLocation(), 3698 Partial->getTemplateArgsAsWritten()->RAngleLoc); 3699 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams); 3700 } 3701 } 3702 3703 void Sema::CheckTemplatePartialSpecialization( 3704 ClassTemplatePartialSpecializationDecl *Partial) { 3705 checkTemplatePartialSpecialization(*this, Partial); 3706 } 3707 3708 void Sema::CheckTemplatePartialSpecialization( 3709 VarTemplatePartialSpecializationDecl *Partial) { 3710 checkTemplatePartialSpecialization(*this, Partial); 3711 } 3712 3713 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) { 3714 // C++1z [temp.param]p11: 3715 // A template parameter of a deduction guide template that does not have a 3716 // default-argument shall be deducible from the parameter-type-list of the 3717 // deduction guide template. 3718 auto *TemplateParams = TD->getTemplateParameters(); 3719 llvm::SmallBitVector DeducibleParams(TemplateParams->size()); 3720 MarkDeducedTemplateParameters(TD, DeducibleParams); 3721 for (unsigned I = 0; I != TemplateParams->size(); ++I) { 3722 // A parameter pack is deducible (to an empty pack). 3723 auto *Param = TemplateParams->getParam(I); 3724 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param)) 3725 DeducibleParams[I] = true; 3726 } 3727 3728 if (!DeducibleParams.all()) { 3729 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); 3730 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible) 3731 << (NumNonDeducible > 1); 3732 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams); 3733 } 3734 } 3735 3736 DeclResult Sema::ActOnVarTemplateSpecialization( 3737 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, 3738 TemplateParameterList *TemplateParams, StorageClass SC, 3739 bool IsPartialSpecialization) { 3740 // D must be variable template id. 3741 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && 3742 "Variable template specialization is declared with a template it."); 3743 3744 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 3745 TemplateArgumentListInfo TemplateArgs = 3746 makeTemplateArgumentListInfo(*this, *TemplateId); 3747 SourceLocation TemplateNameLoc = D.getIdentifierLoc(); 3748 SourceLocation LAngleLoc = TemplateId->LAngleLoc; 3749 SourceLocation RAngleLoc = TemplateId->RAngleLoc; 3750 3751 TemplateName Name = TemplateId->Template.get(); 3752 3753 // The template-id must name a variable template. 3754 VarTemplateDecl *VarTemplate = 3755 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl()); 3756 if (!VarTemplate) { 3757 NamedDecl *FnTemplate; 3758 if (auto *OTS = Name.getAsOverloadedTemplate()) 3759 FnTemplate = *OTS->begin(); 3760 else 3761 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl()); 3762 if (FnTemplate) 3763 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method) 3764 << FnTemplate->getDeclName(); 3765 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) 3766 << IsPartialSpecialization; 3767 } 3768 3769 // Check for unexpanded parameter packs in any of the template arguments. 3770 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 3771 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 3772 UPPC_PartialSpecialization)) 3773 return true; 3774 3775 // Check that the template argument list is well-formed for this 3776 // template. 3777 SmallVector<TemplateArgument, 4> Converted; 3778 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs, 3779 false, Converted)) 3780 return true; 3781 3782 // Find the variable template (partial) specialization declaration that 3783 // corresponds to these arguments. 3784 if (IsPartialSpecialization) { 3785 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate, 3786 TemplateArgs.size(), Converted)) 3787 return true; 3788 3789 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we 3790 // also do them during instantiation. 3791 bool InstantiationDependent; 3792 if (!Name.isDependent() && 3793 !TemplateSpecializationType::anyDependentTemplateArguments( 3794 TemplateArgs.arguments(), 3795 InstantiationDependent)) { 3796 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 3797 << VarTemplate->getDeclName(); 3798 IsPartialSpecialization = false; 3799 } 3800 3801 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(), 3802 Converted)) { 3803 // C++ [temp.class.spec]p9b3: 3804 // 3805 // -- The argument list of the specialization shall not be identical 3806 // to the implicit argument list of the primary template. 3807 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 3808 << /*variable template*/ 1 3809 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord()) 3810 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 3811 // FIXME: Recover from this by treating the declaration as a redeclaration 3812 // of the primary template. 3813 return true; 3814 } 3815 } 3816 3817 void *InsertPos = nullptr; 3818 VarTemplateSpecializationDecl *PrevDecl = nullptr; 3819 3820 if (IsPartialSpecialization) 3821 // FIXME: Template parameter list matters too 3822 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos); 3823 else 3824 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos); 3825 3826 VarTemplateSpecializationDecl *Specialization = nullptr; 3827 3828 // Check whether we can declare a variable template specialization in 3829 // the current scope. 3830 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl, 3831 TemplateNameLoc, 3832 IsPartialSpecialization)) 3833 return true; 3834 3835 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { 3836 // Since the only prior variable template specialization with these 3837 // arguments was referenced but not declared, reuse that 3838 // declaration node as our own, updating its source location and 3839 // the list of outer template parameters to reflect our new declaration. 3840 Specialization = PrevDecl; 3841 Specialization->setLocation(TemplateNameLoc); 3842 PrevDecl = nullptr; 3843 } else if (IsPartialSpecialization) { 3844 // Create a new class template partial specialization declaration node. 3845 VarTemplatePartialSpecializationDecl *PrevPartial = 3846 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl); 3847 VarTemplatePartialSpecializationDecl *Partial = 3848 VarTemplatePartialSpecializationDecl::Create( 3849 Context, VarTemplate->getDeclContext(), TemplateKWLoc, 3850 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC, 3851 Converted, TemplateArgs); 3852 3853 if (!PrevPartial) 3854 VarTemplate->AddPartialSpecialization(Partial, InsertPos); 3855 Specialization = Partial; 3856 3857 // If we are providing an explicit specialization of a member variable 3858 // template specialization, make a note of that. 3859 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 3860 PrevPartial->setMemberSpecialization(); 3861 3862 CheckTemplatePartialSpecialization(Partial); 3863 } else { 3864 // Create a new class template specialization declaration node for 3865 // this explicit specialization or friend declaration. 3866 Specialization = VarTemplateSpecializationDecl::Create( 3867 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc, 3868 VarTemplate, DI->getType(), DI, SC, Converted); 3869 Specialization->setTemplateArgsInfo(TemplateArgs); 3870 3871 if (!PrevDecl) 3872 VarTemplate->AddSpecialization(Specialization, InsertPos); 3873 } 3874 3875 // C++ [temp.expl.spec]p6: 3876 // If a template, a member template or the member of a class template is 3877 // explicitly specialized then that specialization shall be declared 3878 // before the first use of that specialization that would cause an implicit 3879 // instantiation to take place, in every translation unit in which such a 3880 // use occurs; no diagnostic is required. 3881 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 3882 bool Okay = false; 3883 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 3884 // Is there any previous explicit specialization declaration? 3885 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 3886 Okay = true; 3887 break; 3888 } 3889 } 3890 3891 if (!Okay) { 3892 SourceRange Range(TemplateNameLoc, RAngleLoc); 3893 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 3894 << Name << Range; 3895 3896 Diag(PrevDecl->getPointOfInstantiation(), 3897 diag::note_instantiation_required_here) 3898 << (PrevDecl->getTemplateSpecializationKind() != 3899 TSK_ImplicitInstantiation); 3900 return true; 3901 } 3902 } 3903 3904 Specialization->setTemplateKeywordLoc(TemplateKWLoc); 3905 Specialization->setLexicalDeclContext(CurContext); 3906 3907 // Add the specialization into its lexical context, so that it can 3908 // be seen when iterating through the list of declarations in that 3909 // context. However, specializations are not found by name lookup. 3910 CurContext->addDecl(Specialization); 3911 3912 // Note that this is an explicit specialization. 3913 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 3914 3915 if (PrevDecl) { 3916 // Check that this isn't a redefinition of this specialization, 3917 // merging with previous declarations. 3918 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName, 3919 forRedeclarationInCurContext()); 3920 PrevSpec.addDecl(PrevDecl); 3921 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec)); 3922 } else if (Specialization->isStaticDataMember() && 3923 Specialization->isOutOfLine()) { 3924 Specialization->setAccess(VarTemplate->getAccess()); 3925 } 3926 3927 // Link instantiations of static data members back to the template from 3928 // which they were instantiated. 3929 if (Specialization->isStaticDataMember()) 3930 Specialization->setInstantiationOfStaticDataMember( 3931 VarTemplate->getTemplatedDecl(), 3932 Specialization->getSpecializationKind()); 3933 3934 return Specialization; 3935 } 3936 3937 namespace { 3938 /// A partial specialization whose template arguments have matched 3939 /// a given template-id. 3940 struct PartialSpecMatchResult { 3941 VarTemplatePartialSpecializationDecl *Partial; 3942 TemplateArgumentList *Args; 3943 }; 3944 } // end anonymous namespace 3945 3946 DeclResult 3947 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, 3948 SourceLocation TemplateNameLoc, 3949 const TemplateArgumentListInfo &TemplateArgs) { 3950 assert(Template && "A variable template id without template?"); 3951 3952 // Check that the template argument list is well-formed for this template. 3953 SmallVector<TemplateArgument, 4> Converted; 3954 if (CheckTemplateArgumentList( 3955 Template, TemplateNameLoc, 3956 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false, 3957 Converted)) 3958 return true; 3959 3960 // Find the variable template specialization declaration that 3961 // corresponds to these arguments. 3962 void *InsertPos = nullptr; 3963 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization( 3964 Converted, InsertPos)) { 3965 checkSpecializationVisibility(TemplateNameLoc, Spec); 3966 // If we already have a variable template specialization, return it. 3967 return Spec; 3968 } 3969 3970 // This is the first time we have referenced this variable template 3971 // specialization. Create the canonical declaration and add it to 3972 // the set of specializations, based on the closest partial specialization 3973 // that it represents. That is, 3974 VarDecl *InstantiationPattern = Template->getTemplatedDecl(); 3975 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack, 3976 Converted); 3977 TemplateArgumentList *InstantiationArgs = &TemplateArgList; 3978 bool AmbiguousPartialSpec = false; 3979 typedef PartialSpecMatchResult MatchResult; 3980 SmallVector<MatchResult, 4> Matched; 3981 SourceLocation PointOfInstantiation = TemplateNameLoc; 3982 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation, 3983 /*ForTakingAddress=*/false); 3984 3985 // 1. Attempt to find the closest partial specialization that this 3986 // specializes, if any. 3987 // If any of the template arguments is dependent, then this is probably 3988 // a placeholder for an incomplete declarative context; which must be 3989 // complete by instantiation time. Thus, do not search through the partial 3990 // specializations yet. 3991 // TODO: Unify with InstantiateClassTemplateSpecialization()? 3992 // Perhaps better after unification of DeduceTemplateArguments() and 3993 // getMoreSpecializedPartialSpecialization(). 3994 bool InstantiationDependent = false; 3995 if (!TemplateSpecializationType::anyDependentTemplateArguments( 3996 TemplateArgs, InstantiationDependent)) { 3997 3998 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 3999 Template->getPartialSpecializations(PartialSpecs); 4000 4001 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 4002 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; 4003 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 4004 4005 if (TemplateDeductionResult Result = 4006 DeduceTemplateArguments(Partial, TemplateArgList, Info)) { 4007 // Store the failed-deduction information for use in diagnostics, later. 4008 // TODO: Actually use the failed-deduction info? 4009 FailedCandidates.addCandidate().set( 4010 DeclAccessPair::make(Template, AS_public), Partial, 4011 MakeDeductionFailureInfo(Context, Result, Info)); 4012 (void)Result; 4013 } else { 4014 Matched.push_back(PartialSpecMatchResult()); 4015 Matched.back().Partial = Partial; 4016 Matched.back().Args = Info.take(); 4017 } 4018 } 4019 4020 if (Matched.size() >= 1) { 4021 SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); 4022 if (Matched.size() == 1) { 4023 // -- If exactly one matching specialization is found, the 4024 // instantiation is generated from that specialization. 4025 // We don't need to do anything for this. 4026 } else { 4027 // -- If more than one matching specialization is found, the 4028 // partial order rules (14.5.4.2) are used to determine 4029 // whether one of the specializations is more specialized 4030 // than the others. If none of the specializations is more 4031 // specialized than all of the other matching 4032 // specializations, then the use of the variable template is 4033 // ambiguous and the program is ill-formed. 4034 for (SmallVector<MatchResult, 4>::iterator P = Best + 1, 4035 PEnd = Matched.end(); 4036 P != PEnd; ++P) { 4037 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, 4038 PointOfInstantiation) == 4039 P->Partial) 4040 Best = P; 4041 } 4042 4043 // Determine if the best partial specialization is more specialized than 4044 // the others. 4045 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 4046 PEnd = Matched.end(); 4047 P != PEnd; ++P) { 4048 if (P != Best && getMoreSpecializedPartialSpecialization( 4049 P->Partial, Best->Partial, 4050 PointOfInstantiation) != Best->Partial) { 4051 AmbiguousPartialSpec = true; 4052 break; 4053 } 4054 } 4055 } 4056 4057 // Instantiate using the best variable template partial specialization. 4058 InstantiationPattern = Best->Partial; 4059 InstantiationArgs = Best->Args; 4060 } else { 4061 // -- If no match is found, the instantiation is generated 4062 // from the primary template. 4063 // InstantiationPattern = Template->getTemplatedDecl(); 4064 } 4065 } 4066 4067 // 2. Create the canonical declaration. 4068 // Note that we do not instantiate a definition until we see an odr-use 4069 // in DoMarkVarDeclReferenced(). 4070 // FIXME: LateAttrs et al.? 4071 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation( 4072 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs, 4073 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/); 4074 if (!Decl) 4075 return true; 4076 4077 if (AmbiguousPartialSpec) { 4078 // Partial ordering did not produce a clear winner. Complain. 4079 Decl->setInvalidDecl(); 4080 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) 4081 << Decl; 4082 4083 // Print the matching partial specializations. 4084 for (MatchResult P : Matched) 4085 Diag(P.Partial->getLocation(), diag::note_partial_spec_match) 4086 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(), 4087 *P.Args); 4088 return true; 4089 } 4090 4091 if (VarTemplatePartialSpecializationDecl *D = 4092 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern)) 4093 Decl->setInstantiationOf(D, InstantiationArgs); 4094 4095 checkSpecializationVisibility(TemplateNameLoc, Decl); 4096 4097 assert(Decl && "No variable template specialization?"); 4098 return Decl; 4099 } 4100 4101 ExprResult 4102 Sema::CheckVarTemplateId(const CXXScopeSpec &SS, 4103 const DeclarationNameInfo &NameInfo, 4104 VarTemplateDecl *Template, SourceLocation TemplateLoc, 4105 const TemplateArgumentListInfo *TemplateArgs) { 4106 4107 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(), 4108 *TemplateArgs); 4109 if (Decl.isInvalid()) 4110 return ExprError(); 4111 4112 VarDecl *Var = cast<VarDecl>(Decl.get()); 4113 if (!Var->getTemplateSpecializationKind()) 4114 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, 4115 NameInfo.getLoc()); 4116 4117 // Build an ordinary singleton decl ref. 4118 return BuildDeclarationNameExpr(SS, NameInfo, Var, 4119 /*FoundD=*/nullptr, TemplateArgs); 4120 } 4121 4122 void Sema::diagnoseMissingTemplateArguments(TemplateName Name, 4123 SourceLocation Loc) { 4124 Diag(Loc, diag::err_template_missing_args) 4125 << (int)getTemplateNameKindForDiagnostics(Name) << Name; 4126 if (TemplateDecl *TD = Name.getAsTemplateDecl()) { 4127 Diag(TD->getLocation(), diag::note_template_decl_here) 4128 << TD->getTemplateParameters()->getSourceRange(); 4129 } 4130 } 4131 4132 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 4133 SourceLocation TemplateKWLoc, 4134 LookupResult &R, 4135 bool RequiresADL, 4136 const TemplateArgumentListInfo *TemplateArgs) { 4137 // FIXME: Can we do any checking at this point? I guess we could check the 4138 // template arguments that we have against the template name, if the template 4139 // name refers to a single template. That's not a terribly common case, 4140 // though. 4141 // foo<int> could identify a single function unambiguously 4142 // This approach does NOT work, since f<int>(1); 4143 // gets resolved prior to resorting to overload resolution 4144 // i.e., template<class T> void f(double); 4145 // vs template<class T, class U> void f(U); 4146 4147 // These should be filtered out by our callers. 4148 assert(!R.empty() && "empty lookup results when building templateid"); 4149 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 4150 4151 // Non-function templates require a template argument list. 4152 if (auto *TD = R.getAsSingle<TemplateDecl>()) { 4153 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) { 4154 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc()); 4155 return ExprError(); 4156 } 4157 } 4158 4159 auto AnyDependentArguments = [&]() -> bool { 4160 bool InstantiationDependent; 4161 return TemplateArgs && 4162 TemplateSpecializationType::anyDependentTemplateArguments( 4163 *TemplateArgs, InstantiationDependent); 4164 }; 4165 4166 // In C++1y, check variable template ids. 4167 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) { 4168 return CheckVarTemplateId(SS, R.getLookupNameInfo(), 4169 R.getAsSingle<VarTemplateDecl>(), 4170 TemplateKWLoc, TemplateArgs); 4171 } 4172 4173 // We don't want lookup warnings at this point. 4174 R.suppressDiagnostics(); 4175 4176 UnresolvedLookupExpr *ULE 4177 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 4178 SS.getWithLocInContext(Context), 4179 TemplateKWLoc, 4180 R.getLookupNameInfo(), 4181 RequiresADL, TemplateArgs, 4182 R.begin(), R.end()); 4183 4184 return ULE; 4185 } 4186 4187 // We actually only call this from template instantiation. 4188 ExprResult 4189 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 4190 SourceLocation TemplateKWLoc, 4191 const DeclarationNameInfo &NameInfo, 4192 const TemplateArgumentListInfo *TemplateArgs) { 4193 4194 assert(TemplateArgs || TemplateKWLoc.isValid()); 4195 DeclContext *DC; 4196 if (!(DC = computeDeclContext(SS, false)) || 4197 DC->isDependentContext() || 4198 RequireCompleteDeclContext(SS, DC)) 4199 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); 4200 4201 bool MemberOfUnknownSpecialization; 4202 LookupResult R(*this, NameInfo, LookupOrdinaryName); 4203 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(), 4204 /*Entering*/false, MemberOfUnknownSpecialization, 4205 TemplateKWLoc)) 4206 return ExprError(); 4207 4208 if (R.isAmbiguous()) 4209 return ExprError(); 4210 4211 if (R.empty()) { 4212 Diag(NameInfo.getLoc(), diag::err_no_member) 4213 << NameInfo.getName() << DC << SS.getRange(); 4214 return ExprError(); 4215 } 4216 4217 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { 4218 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template) 4219 << SS.getScopeRep() 4220 << NameInfo.getName().getAsString() << SS.getRange(); 4221 Diag(Temp->getLocation(), diag::note_referenced_class_template); 4222 return ExprError(); 4223 } 4224 4225 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs); 4226 } 4227 4228 /// Form a dependent template name. 4229 /// 4230 /// This action forms a dependent template name given the template 4231 /// name and its (presumably dependent) scope specifier. For 4232 /// example, given "MetaFun::template apply", the scope specifier \p 4233 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location 4234 /// of the "template" keyword, and "apply" is the \p Name. 4235 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S, 4236 CXXScopeSpec &SS, 4237 SourceLocation TemplateKWLoc, 4238 const UnqualifiedId &Name, 4239 ParsedType ObjectType, 4240 bool EnteringContext, 4241 TemplateTy &Result, 4242 bool AllowInjectedClassName) { 4243 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent()) 4244 Diag(TemplateKWLoc, 4245 getLangOpts().CPlusPlus11 ? 4246 diag::warn_cxx98_compat_template_outside_of_template : 4247 diag::ext_template_outside_of_template) 4248 << FixItHint::CreateRemoval(TemplateKWLoc); 4249 4250 DeclContext *LookupCtx = nullptr; 4251 if (SS.isSet()) 4252 LookupCtx = computeDeclContext(SS, EnteringContext); 4253 if (!LookupCtx && ObjectType) 4254 LookupCtx = computeDeclContext(ObjectType.get()); 4255 if (LookupCtx) { 4256 // C++0x [temp.names]p5: 4257 // If a name prefixed by the keyword template is not the name of 4258 // a template, the program is ill-formed. [Note: the keyword 4259 // template may not be applied to non-template members of class 4260 // templates. -end note ] [ Note: as is the case with the 4261 // typename prefix, the template prefix is allowed in cases 4262 // where it is not strictly necessary; i.e., when the 4263 // nested-name-specifier or the expression on the left of the -> 4264 // or . is not dependent on a template-parameter, or the use 4265 // does not appear in the scope of a template. -end note] 4266 // 4267 // Note: C++03 was more strict here, because it banned the use of 4268 // the "template" keyword prior to a template-name that was not a 4269 // dependent name. C++ DR468 relaxed this requirement (the 4270 // "template" keyword is now permitted). We follow the C++0x 4271 // rules, even in C++03 mode with a warning, retroactively applying the DR. 4272 bool MemberOfUnknownSpecialization; 4273 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name, 4274 ObjectType, EnteringContext, Result, 4275 MemberOfUnknownSpecialization); 4276 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) { 4277 // This is a dependent template. Handle it below. 4278 } else if (TNK == TNK_Non_template) { 4279 // Do the lookup again to determine if this is a "nothing found" case or 4280 // a "not a template" case. FIXME: Refactor isTemplateName so we don't 4281 // need to do this. 4282 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name); 4283 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(), 4284 LookupOrdinaryName); 4285 bool MOUS; 4286 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, 4287 MOUS, TemplateKWLoc) && !R.isAmbiguous()) 4288 Diag(Name.getBeginLoc(), diag::err_no_member) 4289 << DNI.getName() << LookupCtx << SS.getRange(); 4290 return TNK_Non_template; 4291 } else { 4292 // We found something; return it. 4293 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx); 4294 if (!AllowInjectedClassName && SS.isSet() && LookupRD && 4295 Name.getKind() == UnqualifiedIdKind::IK_Identifier && 4296 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) { 4297 // C++14 [class.qual]p2: 4298 // In a lookup in which function names are not ignored and the 4299 // nested-name-specifier nominates a class C, if the name specified 4300 // [...] is the injected-class-name of C, [...] the name is instead 4301 // considered to name the constructor 4302 // 4303 // We don't get here if naming the constructor would be valid, so we 4304 // just reject immediately and recover by treating the 4305 // injected-class-name as naming the template. 4306 Diag(Name.getBeginLoc(), 4307 diag::ext_out_of_line_qualified_id_type_names_constructor) 4308 << Name.Identifier 4309 << 0 /*injected-class-name used as template name*/ 4310 << 1 /*'template' keyword was used*/; 4311 } 4312 return TNK; 4313 } 4314 } 4315 4316 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 4317 4318 switch (Name.getKind()) { 4319 case UnqualifiedIdKind::IK_Identifier: 4320 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 4321 Name.Identifier)); 4322 return TNK_Dependent_template_name; 4323 4324 case UnqualifiedIdKind::IK_OperatorFunctionId: 4325 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 4326 Name.OperatorFunctionId.Operator)); 4327 return TNK_Function_template; 4328 4329 case UnqualifiedIdKind::IK_LiteralOperatorId: 4330 llvm_unreachable("literal operator id cannot have a dependent scope"); 4331 4332 default: 4333 break; 4334 } 4335 4336 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template) 4337 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange() 4338 << TemplateKWLoc; 4339 return TNK_Non_template; 4340 } 4341 4342 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 4343 TemplateArgumentLoc &AL, 4344 SmallVectorImpl<TemplateArgument> &Converted) { 4345 const TemplateArgument &Arg = AL.getArgument(); 4346 QualType ArgType; 4347 TypeSourceInfo *TSI = nullptr; 4348 4349 // Check template type parameter. 4350 switch(Arg.getKind()) { 4351 case TemplateArgument::Type: 4352 // C++ [temp.arg.type]p1: 4353 // A template-argument for a template-parameter which is a 4354 // type shall be a type-id. 4355 ArgType = Arg.getAsType(); 4356 TSI = AL.getTypeSourceInfo(); 4357 break; 4358 case TemplateArgument::Template: 4359 case TemplateArgument::TemplateExpansion: { 4360 // We have a template type parameter but the template argument 4361 // is a template without any arguments. 4362 SourceRange SR = AL.getSourceRange(); 4363 TemplateName Name = Arg.getAsTemplateOrTemplatePattern(); 4364 diagnoseMissingTemplateArguments(Name, SR.getEnd()); 4365 return true; 4366 } 4367 case TemplateArgument::Expression: { 4368 // We have a template type parameter but the template argument is an 4369 // expression; see if maybe it is missing the "typename" keyword. 4370 CXXScopeSpec SS; 4371 DeclarationNameInfo NameInfo; 4372 4373 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) { 4374 SS.Adopt(ArgExpr->getQualifierLoc()); 4375 NameInfo = ArgExpr->getNameInfo(); 4376 } else if (DependentScopeDeclRefExpr *ArgExpr = 4377 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) { 4378 SS.Adopt(ArgExpr->getQualifierLoc()); 4379 NameInfo = ArgExpr->getNameInfo(); 4380 } else if (CXXDependentScopeMemberExpr *ArgExpr = 4381 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) { 4382 if (ArgExpr->isImplicitAccess()) { 4383 SS.Adopt(ArgExpr->getQualifierLoc()); 4384 NameInfo = ArgExpr->getMemberNameInfo(); 4385 } 4386 } 4387 4388 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) { 4389 LookupResult Result(*this, NameInfo, LookupOrdinaryName); 4390 LookupParsedName(Result, CurScope, &SS); 4391 4392 if (Result.getAsSingle<TypeDecl>() || 4393 Result.getResultKind() == 4394 LookupResult::NotFoundInCurrentInstantiation) { 4395 // Suggest that the user add 'typename' before the NNS. 4396 SourceLocation Loc = AL.getSourceRange().getBegin(); 4397 Diag(Loc, getLangOpts().MSVCCompat 4398 ? diag::ext_ms_template_type_arg_missing_typename 4399 : diag::err_template_arg_must_be_type_suggest) 4400 << FixItHint::CreateInsertion(Loc, "typename "); 4401 Diag(Param->getLocation(), diag::note_template_param_here); 4402 4403 // Recover by synthesizing a type using the location information that we 4404 // already have. 4405 ArgType = 4406 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II); 4407 TypeLocBuilder TLB; 4408 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType); 4409 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/)); 4410 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4411 TL.setNameLoc(NameInfo.getLoc()); 4412 TSI = TLB.getTypeSourceInfo(Context, ArgType); 4413 4414 // Overwrite our input TemplateArgumentLoc so that we can recover 4415 // properly. 4416 AL = TemplateArgumentLoc(TemplateArgument(ArgType), 4417 TemplateArgumentLocInfo(TSI)); 4418 4419 break; 4420 } 4421 } 4422 // fallthrough 4423 LLVM_FALLTHROUGH; 4424 } 4425 default: { 4426 // We have a template type parameter but the template argument 4427 // is not a type. 4428 SourceRange SR = AL.getSourceRange(); 4429 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 4430 Diag(Param->getLocation(), diag::note_template_param_here); 4431 4432 return true; 4433 } 4434 } 4435 4436 if (CheckTemplateArgument(Param, TSI)) 4437 return true; 4438 4439 // Add the converted template type argument. 4440 ArgType = Context.getCanonicalType(ArgType); 4441 4442 // Objective-C ARC: 4443 // If an explicitly-specified template argument type is a lifetime type 4444 // with no lifetime qualifier, the __strong lifetime qualifier is inferred. 4445 if (getLangOpts().ObjCAutoRefCount && 4446 ArgType->isObjCLifetimeType() && 4447 !ArgType.getObjCLifetime()) { 4448 Qualifiers Qs; 4449 Qs.setObjCLifetime(Qualifiers::OCL_Strong); 4450 ArgType = Context.getQualifiedType(ArgType, Qs); 4451 } 4452 4453 Converted.push_back(TemplateArgument(ArgType)); 4454 return false; 4455 } 4456 4457 /// Substitute template arguments into the default template argument for 4458 /// the given template type parameter. 4459 /// 4460 /// \param SemaRef the semantic analysis object for which we are performing 4461 /// the substitution. 4462 /// 4463 /// \param Template the template that we are synthesizing template arguments 4464 /// for. 4465 /// 4466 /// \param TemplateLoc the location of the template name that started the 4467 /// template-id we are checking. 4468 /// 4469 /// \param RAngleLoc the location of the right angle bracket ('>') that 4470 /// terminates the template-id. 4471 /// 4472 /// \param Param the template template parameter whose default we are 4473 /// substituting into. 4474 /// 4475 /// \param Converted the list of template arguments provided for template 4476 /// parameters that precede \p Param in the template parameter list. 4477 /// \returns the substituted template argument, or NULL if an error occurred. 4478 static TypeSourceInfo * 4479 SubstDefaultTemplateArgument(Sema &SemaRef, 4480 TemplateDecl *Template, 4481 SourceLocation TemplateLoc, 4482 SourceLocation RAngleLoc, 4483 TemplateTypeParmDecl *Param, 4484 SmallVectorImpl<TemplateArgument> &Converted) { 4485 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); 4486 4487 // If the argument type is dependent, instantiate it now based 4488 // on the previously-computed template arguments. 4489 if (ArgType->getType()->isInstantiationDependentType()) { 4490 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 4491 Param, Template, Converted, 4492 SourceRange(TemplateLoc, RAngleLoc)); 4493 if (Inst.isInvalid()) 4494 return nullptr; 4495 4496 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted); 4497 4498 // Only substitute for the innermost template argument list. 4499 MultiLevelTemplateArgumentList TemplateArgLists; 4500 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); 4501 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 4502 TemplateArgLists.addOuterTemplateArguments(None); 4503 4504 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); 4505 ArgType = 4506 SemaRef.SubstType(ArgType, TemplateArgLists, 4507 Param->getDefaultArgumentLoc(), Param->getDeclName()); 4508 } 4509 4510 return ArgType; 4511 } 4512 4513 /// Substitute template arguments into the default template argument for 4514 /// the given non-type template parameter. 4515 /// 4516 /// \param SemaRef the semantic analysis object for which we are performing 4517 /// the substitution. 4518 /// 4519 /// \param Template the template that we are synthesizing template arguments 4520 /// for. 4521 /// 4522 /// \param TemplateLoc the location of the template name that started the 4523 /// template-id we are checking. 4524 /// 4525 /// \param RAngleLoc the location of the right angle bracket ('>') that 4526 /// terminates the template-id. 4527 /// 4528 /// \param Param the non-type template parameter whose default we are 4529 /// substituting into. 4530 /// 4531 /// \param Converted the list of template arguments provided for template 4532 /// parameters that precede \p Param in the template parameter list. 4533 /// 4534 /// \returns the substituted template argument, or NULL if an error occurred. 4535 static ExprResult 4536 SubstDefaultTemplateArgument(Sema &SemaRef, 4537 TemplateDecl *Template, 4538 SourceLocation TemplateLoc, 4539 SourceLocation RAngleLoc, 4540 NonTypeTemplateParmDecl *Param, 4541 SmallVectorImpl<TemplateArgument> &Converted) { 4542 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 4543 Param, Template, Converted, 4544 SourceRange(TemplateLoc, RAngleLoc)); 4545 if (Inst.isInvalid()) 4546 return ExprError(); 4547 4548 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted); 4549 4550 // Only substitute for the innermost template argument list. 4551 MultiLevelTemplateArgumentList TemplateArgLists; 4552 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); 4553 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 4554 TemplateArgLists.addOuterTemplateArguments(None); 4555 4556 EnterExpressionEvaluationContext ConstantEvaluated( 4557 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 4558 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists); 4559 } 4560 4561 /// Substitute template arguments into the default template argument for 4562 /// the given template template parameter. 4563 /// 4564 /// \param SemaRef the semantic analysis object for which we are performing 4565 /// the substitution. 4566 /// 4567 /// \param Template the template that we are synthesizing template arguments 4568 /// for. 4569 /// 4570 /// \param TemplateLoc the location of the template name that started the 4571 /// template-id we are checking. 4572 /// 4573 /// \param RAngleLoc the location of the right angle bracket ('>') that 4574 /// terminates the template-id. 4575 /// 4576 /// \param Param the template template parameter whose default we are 4577 /// substituting into. 4578 /// 4579 /// \param Converted the list of template arguments provided for template 4580 /// parameters that precede \p Param in the template parameter list. 4581 /// 4582 /// \param QualifierLoc Will be set to the nested-name-specifier (with 4583 /// source-location information) that precedes the template name. 4584 /// 4585 /// \returns the substituted template argument, or NULL if an error occurred. 4586 static TemplateName 4587 SubstDefaultTemplateArgument(Sema &SemaRef, 4588 TemplateDecl *Template, 4589 SourceLocation TemplateLoc, 4590 SourceLocation RAngleLoc, 4591 TemplateTemplateParmDecl *Param, 4592 SmallVectorImpl<TemplateArgument> &Converted, 4593 NestedNameSpecifierLoc &QualifierLoc) { 4594 Sema::InstantiatingTemplate Inst( 4595 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted, 4596 SourceRange(TemplateLoc, RAngleLoc)); 4597 if (Inst.isInvalid()) 4598 return TemplateName(); 4599 4600 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted); 4601 4602 // Only substitute for the innermost template argument list. 4603 MultiLevelTemplateArgumentList TemplateArgLists; 4604 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); 4605 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 4606 TemplateArgLists.addOuterTemplateArguments(None); 4607 4608 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); 4609 // Substitute into the nested-name-specifier first, 4610 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc(); 4611 if (QualifierLoc) { 4612 QualifierLoc = 4613 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists); 4614 if (!QualifierLoc) 4615 return TemplateName(); 4616 } 4617 4618 return SemaRef.SubstTemplateName( 4619 QualifierLoc, 4620 Param->getDefaultArgument().getArgument().getAsTemplate(), 4621 Param->getDefaultArgument().getTemplateNameLoc(), 4622 TemplateArgLists); 4623 } 4624 4625 /// If the given template parameter has a default template 4626 /// argument, substitute into that default template argument and 4627 /// return the corresponding template argument. 4628 TemplateArgumentLoc 4629 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 4630 SourceLocation TemplateLoc, 4631 SourceLocation RAngleLoc, 4632 Decl *Param, 4633 SmallVectorImpl<TemplateArgument> 4634 &Converted, 4635 bool &HasDefaultArg) { 4636 HasDefaultArg = false; 4637 4638 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { 4639 if (!hasVisibleDefaultArgument(TypeParm)) 4640 return TemplateArgumentLoc(); 4641 4642 HasDefaultArg = true; 4643 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template, 4644 TemplateLoc, 4645 RAngleLoc, 4646 TypeParm, 4647 Converted); 4648 if (DI) 4649 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); 4650 4651 return TemplateArgumentLoc(); 4652 } 4653 4654 if (NonTypeTemplateParmDecl *NonTypeParm 4655 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4656 if (!hasVisibleDefaultArgument(NonTypeParm)) 4657 return TemplateArgumentLoc(); 4658 4659 HasDefaultArg = true; 4660 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template, 4661 TemplateLoc, 4662 RAngleLoc, 4663 NonTypeParm, 4664 Converted); 4665 if (Arg.isInvalid()) 4666 return TemplateArgumentLoc(); 4667 4668 Expr *ArgE = Arg.getAs<Expr>(); 4669 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); 4670 } 4671 4672 TemplateTemplateParmDecl *TempTempParm 4673 = cast<TemplateTemplateParmDecl>(Param); 4674 if (!hasVisibleDefaultArgument(TempTempParm)) 4675 return TemplateArgumentLoc(); 4676 4677 HasDefaultArg = true; 4678 NestedNameSpecifierLoc QualifierLoc; 4679 TemplateName TName = SubstDefaultTemplateArgument(*this, Template, 4680 TemplateLoc, 4681 RAngleLoc, 4682 TempTempParm, 4683 Converted, 4684 QualifierLoc); 4685 if (TName.isNull()) 4686 return TemplateArgumentLoc(); 4687 4688 return TemplateArgumentLoc(TemplateArgument(TName), 4689 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(), 4690 TempTempParm->getDefaultArgument().getTemplateNameLoc()); 4691 } 4692 4693 /// Convert a template-argument that we parsed as a type into a template, if 4694 /// possible. C++ permits injected-class-names to perform dual service as 4695 /// template template arguments and as template type arguments. 4696 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) { 4697 // Extract and step over any surrounding nested-name-specifier. 4698 NestedNameSpecifierLoc QualLoc; 4699 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) { 4700 if (ETLoc.getTypePtr()->getKeyword() != ETK_None) 4701 return TemplateArgumentLoc(); 4702 4703 QualLoc = ETLoc.getQualifierLoc(); 4704 TLoc = ETLoc.getNamedTypeLoc(); 4705 } 4706 4707 // If this type was written as an injected-class-name, it can be used as a 4708 // template template argument. 4709 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>()) 4710 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(), 4711 QualLoc, InjLoc.getNameLoc()); 4712 4713 // If this type was written as an injected-class-name, it may have been 4714 // converted to a RecordType during instantiation. If the RecordType is 4715 // *not* wrapped in a TemplateSpecializationType and denotes a class 4716 // template specialization, it must have come from an injected-class-name. 4717 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>()) 4718 if (auto *CTSD = 4719 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl())) 4720 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()), 4721 QualLoc, RecLoc.getNameLoc()); 4722 4723 return TemplateArgumentLoc(); 4724 } 4725 4726 /// Check that the given template argument corresponds to the given 4727 /// template parameter. 4728 /// 4729 /// \param Param The template parameter against which the argument will be 4730 /// checked. 4731 /// 4732 /// \param Arg The template argument, which may be updated due to conversions. 4733 /// 4734 /// \param Template The template in which the template argument resides. 4735 /// 4736 /// \param TemplateLoc The location of the template name for the template 4737 /// whose argument list we're matching. 4738 /// 4739 /// \param RAngleLoc The location of the right angle bracket ('>') that closes 4740 /// the template argument list. 4741 /// 4742 /// \param ArgumentPackIndex The index into the argument pack where this 4743 /// argument will be placed. Only valid if the parameter is a parameter pack. 4744 /// 4745 /// \param Converted The checked, converted argument will be added to the 4746 /// end of this small vector. 4747 /// 4748 /// \param CTAK Describes how we arrived at this particular template argument: 4749 /// explicitly written, deduced, etc. 4750 /// 4751 /// \returns true on error, false otherwise. 4752 bool Sema::CheckTemplateArgument(NamedDecl *Param, 4753 TemplateArgumentLoc &Arg, 4754 NamedDecl *Template, 4755 SourceLocation TemplateLoc, 4756 SourceLocation RAngleLoc, 4757 unsigned ArgumentPackIndex, 4758 SmallVectorImpl<TemplateArgument> &Converted, 4759 CheckTemplateArgumentKind CTAK) { 4760 // Check template type parameters. 4761 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 4762 return CheckTemplateTypeArgument(TTP, Arg, Converted); 4763 4764 // Check non-type template parameters. 4765 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4766 // Do substitution on the type of the non-type template parameter 4767 // with the template arguments we've seen thus far. But if the 4768 // template has a dependent context then we cannot substitute yet. 4769 QualType NTTPType = NTTP->getType(); 4770 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) 4771 NTTPType = NTTP->getExpansionType(ArgumentPackIndex); 4772 4773 // FIXME: Do we need to substitute into parameters here if they're 4774 // instantiation-dependent but not dependent? 4775 if (NTTPType->isDependentType() && 4776 !isa<TemplateTemplateParmDecl>(Template) && 4777 !Template->getDeclContext()->isDependentContext()) { 4778 // Do substitution on the type of the non-type template parameter. 4779 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 4780 NTTP, Converted, 4781 SourceRange(TemplateLoc, RAngleLoc)); 4782 if (Inst.isInvalid()) 4783 return true; 4784 4785 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 4786 Converted); 4787 NTTPType = SubstType(NTTPType, 4788 MultiLevelTemplateArgumentList(TemplateArgs), 4789 NTTP->getLocation(), 4790 NTTP->getDeclName()); 4791 // If that worked, check the non-type template parameter type 4792 // for validity. 4793 if (!NTTPType.isNull()) 4794 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 4795 NTTP->getLocation()); 4796 if (NTTPType.isNull()) 4797 return true; 4798 } 4799 4800 switch (Arg.getArgument().getKind()) { 4801 case TemplateArgument::Null: 4802 llvm_unreachable("Should never see a NULL template argument here"); 4803 4804 case TemplateArgument::Expression: { 4805 TemplateArgument Result; 4806 unsigned CurSFINAEErrors = NumSFINAEErrors; 4807 ExprResult Res = 4808 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(), 4809 Result, CTAK); 4810 if (Res.isInvalid()) 4811 return true; 4812 // If the current template argument causes an error, give up now. 4813 if (CurSFINAEErrors < NumSFINAEErrors) 4814 return true; 4815 4816 // If the resulting expression is new, then use it in place of the 4817 // old expression in the template argument. 4818 if (Res.get() != Arg.getArgument().getAsExpr()) { 4819 TemplateArgument TA(Res.get()); 4820 Arg = TemplateArgumentLoc(TA, Res.get()); 4821 } 4822 4823 Converted.push_back(Result); 4824 break; 4825 } 4826 4827 case TemplateArgument::Declaration: 4828 case TemplateArgument::Integral: 4829 case TemplateArgument::NullPtr: 4830 // We've already checked this template argument, so just copy 4831 // it to the list of converted arguments. 4832 Converted.push_back(Arg.getArgument()); 4833 break; 4834 4835 case TemplateArgument::Template: 4836 case TemplateArgument::TemplateExpansion: 4837 // We were given a template template argument. It may not be ill-formed; 4838 // see below. 4839 if (DependentTemplateName *DTN 4840 = Arg.getArgument().getAsTemplateOrTemplatePattern() 4841 .getAsDependentTemplateName()) { 4842 // We have a template argument such as \c T::template X, which we 4843 // parsed as a template template argument. However, since we now 4844 // know that we need a non-type template argument, convert this 4845 // template name into an expression. 4846 4847 DeclarationNameInfo NameInfo(DTN->getIdentifier(), 4848 Arg.getTemplateNameLoc()); 4849 4850 CXXScopeSpec SS; 4851 SS.Adopt(Arg.getTemplateQualifierLoc()); 4852 // FIXME: the template-template arg was a DependentTemplateName, 4853 // so it was provided with a template keyword. However, its source 4854 // location is not stored in the template argument structure. 4855 SourceLocation TemplateKWLoc; 4856 ExprResult E = DependentScopeDeclRefExpr::Create( 4857 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 4858 nullptr); 4859 4860 // If we parsed the template argument as a pack expansion, create a 4861 // pack expansion expression. 4862 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ 4863 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc()); 4864 if (E.isInvalid()) 4865 return true; 4866 } 4867 4868 TemplateArgument Result; 4869 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result); 4870 if (E.isInvalid()) 4871 return true; 4872 4873 Converted.push_back(Result); 4874 break; 4875 } 4876 4877 // We have a template argument that actually does refer to a class 4878 // template, alias template, or template template parameter, and 4879 // therefore cannot be a non-type template argument. 4880 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 4881 << Arg.getSourceRange(); 4882 4883 Diag(Param->getLocation(), diag::note_template_param_here); 4884 return true; 4885 4886 case TemplateArgument::Type: { 4887 // We have a non-type template parameter but the template 4888 // argument is a type. 4889 4890 // C++ [temp.arg]p2: 4891 // In a template-argument, an ambiguity between a type-id and 4892 // an expression is resolved to a type-id, regardless of the 4893 // form of the corresponding template-parameter. 4894 // 4895 // We warn specifically about this case, since it can be rather 4896 // confusing for users. 4897 QualType T = Arg.getArgument().getAsType(); 4898 SourceRange SR = Arg.getSourceRange(); 4899 if (T->isFunctionType()) 4900 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 4901 else 4902 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 4903 Diag(Param->getLocation(), diag::note_template_param_here); 4904 return true; 4905 } 4906 4907 case TemplateArgument::Pack: 4908 llvm_unreachable("Caller must expand template argument packs"); 4909 } 4910 4911 return false; 4912 } 4913 4914 4915 // Check template template parameters. 4916 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 4917 4918 TemplateParameterList *Params = TempParm->getTemplateParameters(); 4919 if (TempParm->isExpandedParameterPack()) 4920 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex); 4921 4922 // Substitute into the template parameter list of the template 4923 // template parameter, since previously-supplied template arguments 4924 // may appear within the template template parameter. 4925 // 4926 // FIXME: Skip this if the parameters aren't instantiation-dependent. 4927 { 4928 // Set up a template instantiation context. 4929 LocalInstantiationScope Scope(*this); 4930 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 4931 TempParm, Converted, 4932 SourceRange(TemplateLoc, RAngleLoc)); 4933 if (Inst.isInvalid()) 4934 return true; 4935 4936 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted); 4937 Params = SubstTemplateParams(Params, CurContext, 4938 MultiLevelTemplateArgumentList(TemplateArgs)); 4939 if (!Params) 4940 return true; 4941 } 4942 4943 // C++1z [temp.local]p1: (DR1004) 4944 // When [the injected-class-name] is used [...] as a template-argument for 4945 // a template template-parameter [...] it refers to the class template 4946 // itself. 4947 if (Arg.getArgument().getKind() == TemplateArgument::Type) { 4948 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate( 4949 Arg.getTypeSourceInfo()->getTypeLoc()); 4950 if (!ConvertedArg.getArgument().isNull()) 4951 Arg = ConvertedArg; 4952 } 4953 4954 switch (Arg.getArgument().getKind()) { 4955 case TemplateArgument::Null: 4956 llvm_unreachable("Should never see a NULL template argument here"); 4957 4958 case TemplateArgument::Template: 4959 case TemplateArgument::TemplateExpansion: 4960 if (CheckTemplateTemplateArgument(Params, Arg)) 4961 return true; 4962 4963 Converted.push_back(Arg.getArgument()); 4964 break; 4965 4966 case TemplateArgument::Expression: 4967 case TemplateArgument::Type: 4968 // We have a template template parameter but the template 4969 // argument does not refer to a template. 4970 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template) 4971 << getLangOpts().CPlusPlus11; 4972 return true; 4973 4974 case TemplateArgument::Declaration: 4975 llvm_unreachable("Declaration argument with template template parameter"); 4976 case TemplateArgument::Integral: 4977 llvm_unreachable("Integral argument with template template parameter"); 4978 case TemplateArgument::NullPtr: 4979 llvm_unreachable("Null pointer argument with template template parameter"); 4980 4981 case TemplateArgument::Pack: 4982 llvm_unreachable("Caller must expand template argument packs"); 4983 } 4984 4985 return false; 4986 } 4987 4988 /// Check whether the template parameter is a pack expansion, and if so, 4989 /// determine the number of parameters produced by that expansion. For instance: 4990 /// 4991 /// \code 4992 /// template<typename ...Ts> struct A { 4993 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B; 4994 /// }; 4995 /// \endcode 4996 /// 4997 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us 4998 /// is not a pack expansion, so returns an empty Optional. 4999 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) { 5000 if (NonTypeTemplateParmDecl *NTTP 5001 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5002 if (NTTP->isExpandedParameterPack()) 5003 return NTTP->getNumExpansionTypes(); 5004 } 5005 5006 if (TemplateTemplateParmDecl *TTP 5007 = dyn_cast<TemplateTemplateParmDecl>(Param)) { 5008 if (TTP->isExpandedParameterPack()) 5009 return TTP->getNumExpansionTemplateParameters(); 5010 } 5011 5012 return None; 5013 } 5014 5015 /// Diagnose a missing template argument. 5016 template<typename TemplateParmDecl> 5017 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, 5018 TemplateDecl *TD, 5019 const TemplateParmDecl *D, 5020 TemplateArgumentListInfo &Args) { 5021 // Dig out the most recent declaration of the template parameter; there may be 5022 // declarations of the template that are more recent than TD. 5023 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl()) 5024 ->getTemplateParameters() 5025 ->getParam(D->getIndex())); 5026 5027 // If there's a default argument that's not visible, diagnose that we're 5028 // missing a module import. 5029 llvm::SmallVector<Module*, 8> Modules; 5030 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) { 5031 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD), 5032 D->getDefaultArgumentLoc(), Modules, 5033 Sema::MissingImportKind::DefaultArgument, 5034 /*Recover*/true); 5035 return true; 5036 } 5037 5038 // FIXME: If there's a more recent default argument that *is* visible, 5039 // diagnose that it was declared too late. 5040 5041 TemplateParameterList *Params = TD->getTemplateParameters(); 5042 5043 S.Diag(Loc, diag::err_template_arg_list_different_arity) 5044 << /*not enough args*/0 5045 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD)) 5046 << TD; 5047 S.Diag(TD->getLocation(), diag::note_template_decl_here) 5048 << Params->getSourceRange(); 5049 return true; 5050 } 5051 5052 /// Check that the given template argument list is well-formed 5053 /// for specializing the given template. 5054 bool Sema::CheckTemplateArgumentList( 5055 TemplateDecl *Template, SourceLocation TemplateLoc, 5056 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, 5057 SmallVectorImpl<TemplateArgument> &Converted, 5058 bool UpdateArgsWithConversions) { 5059 // Make a copy of the template arguments for processing. Only make the 5060 // changes at the end when successful in matching the arguments to the 5061 // template. 5062 TemplateArgumentListInfo NewArgs = TemplateArgs; 5063 5064 // Make sure we get the template parameter list from the most 5065 // recentdeclaration, since that is the only one that has is guaranteed to 5066 // have all the default template argument information. 5067 TemplateParameterList *Params = 5068 cast<TemplateDecl>(Template->getMostRecentDecl()) 5069 ->getTemplateParameters(); 5070 5071 SourceLocation RAngleLoc = NewArgs.getRAngleLoc(); 5072 5073 // C++ [temp.arg]p1: 5074 // [...] The type and form of each template-argument specified in 5075 // a template-id shall match the type and form specified for the 5076 // corresponding parameter declared by the template in its 5077 // template-parameter-list. 5078 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template); 5079 SmallVector<TemplateArgument, 2> ArgumentPack; 5080 unsigned ArgIdx = 0, NumArgs = NewArgs.size(); 5081 LocalInstantiationScope InstScope(*this, true); 5082 for (TemplateParameterList::iterator Param = Params->begin(), 5083 ParamEnd = Params->end(); 5084 Param != ParamEnd; /* increment in loop */) { 5085 // If we have an expanded parameter pack, make sure we don't have too 5086 // many arguments. 5087 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) { 5088 if (*Expansions == ArgumentPack.size()) { 5089 // We're done with this parameter pack. Pack up its arguments and add 5090 // them to the list. 5091 Converted.push_back( 5092 TemplateArgument::CreatePackCopy(Context, ArgumentPack)); 5093 ArgumentPack.clear(); 5094 5095 // This argument is assigned to the next parameter. 5096 ++Param; 5097 continue; 5098 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) { 5099 // Not enough arguments for this parameter pack. 5100 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 5101 << /*not enough args*/0 5102 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) 5103 << Template; 5104 Diag(Template->getLocation(), diag::note_template_decl_here) 5105 << Params->getSourceRange(); 5106 return true; 5107 } 5108 } 5109 5110 if (ArgIdx < NumArgs) { 5111 // Check the template argument we were given. 5112 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, 5113 TemplateLoc, RAngleLoc, 5114 ArgumentPack.size(), Converted)) 5115 return true; 5116 5117 bool PackExpansionIntoNonPack = 5118 NewArgs[ArgIdx].getArgument().isPackExpansion() && 5119 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param)); 5120 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) { 5121 // Core issue 1430: we have a pack expansion as an argument to an 5122 // alias template, and it's not part of a parameter pack. This 5123 // can't be canonicalized, so reject it now. 5124 Diag(NewArgs[ArgIdx].getLocation(), 5125 diag::err_alias_template_expansion_into_fixed_list) 5126 << NewArgs[ArgIdx].getSourceRange(); 5127 Diag((*Param)->getLocation(), diag::note_template_param_here); 5128 return true; 5129 } 5130 5131 // We're now done with this argument. 5132 ++ArgIdx; 5133 5134 if ((*Param)->isTemplateParameterPack()) { 5135 // The template parameter was a template parameter pack, so take the 5136 // deduced argument and place it on the argument pack. Note that we 5137 // stay on the same template parameter so that we can deduce more 5138 // arguments. 5139 ArgumentPack.push_back(Converted.pop_back_val()); 5140 } else { 5141 // Move to the next template parameter. 5142 ++Param; 5143 } 5144 5145 // If we just saw a pack expansion into a non-pack, then directly convert 5146 // the remaining arguments, because we don't know what parameters they'll 5147 // match up with. 5148 if (PackExpansionIntoNonPack) { 5149 if (!ArgumentPack.empty()) { 5150 // If we were part way through filling in an expanded parameter pack, 5151 // fall back to just producing individual arguments. 5152 Converted.insert(Converted.end(), 5153 ArgumentPack.begin(), ArgumentPack.end()); 5154 ArgumentPack.clear(); 5155 } 5156 5157 while (ArgIdx < NumArgs) { 5158 Converted.push_back(NewArgs[ArgIdx].getArgument()); 5159 ++ArgIdx; 5160 } 5161 5162 return false; 5163 } 5164 5165 continue; 5166 } 5167 5168 // If we're checking a partial template argument list, we're done. 5169 if (PartialTemplateArgs) { 5170 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty()) 5171 Converted.push_back( 5172 TemplateArgument::CreatePackCopy(Context, ArgumentPack)); 5173 5174 return false; 5175 } 5176 5177 // If we have a template parameter pack with no more corresponding 5178 // arguments, just break out now and we'll fill in the argument pack below. 5179 if ((*Param)->isTemplateParameterPack()) { 5180 assert(!getExpandedPackSize(*Param) && 5181 "Should have dealt with this already"); 5182 5183 // A non-expanded parameter pack before the end of the parameter list 5184 // only occurs for an ill-formed template parameter list, unless we've 5185 // got a partial argument list for a function template, so just bail out. 5186 if (Param + 1 != ParamEnd) 5187 return true; 5188 5189 Converted.push_back( 5190 TemplateArgument::CreatePackCopy(Context, ArgumentPack)); 5191 ArgumentPack.clear(); 5192 5193 ++Param; 5194 continue; 5195 } 5196 5197 // Check whether we have a default argument. 5198 TemplateArgumentLoc Arg; 5199 5200 // Retrieve the default template argument from the template 5201 // parameter. For each kind of template parameter, we substitute the 5202 // template arguments provided thus far and any "outer" template arguments 5203 // (when the template parameter was part of a nested template) into 5204 // the default argument. 5205 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 5206 if (!hasVisibleDefaultArgument(TTP)) 5207 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP, 5208 NewArgs); 5209 5210 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this, 5211 Template, 5212 TemplateLoc, 5213 RAngleLoc, 5214 TTP, 5215 Converted); 5216 if (!ArgType) 5217 return true; 5218 5219 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 5220 ArgType); 5221 } else if (NonTypeTemplateParmDecl *NTTP 5222 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 5223 if (!hasVisibleDefaultArgument(NTTP)) 5224 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP, 5225 NewArgs); 5226 5227 ExprResult E = SubstDefaultTemplateArgument(*this, Template, 5228 TemplateLoc, 5229 RAngleLoc, 5230 NTTP, 5231 Converted); 5232 if (E.isInvalid()) 5233 return true; 5234 5235 Expr *Ex = E.getAs<Expr>(); 5236 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 5237 } else { 5238 TemplateTemplateParmDecl *TempParm 5239 = cast<TemplateTemplateParmDecl>(*Param); 5240 5241 if (!hasVisibleDefaultArgument(TempParm)) 5242 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm, 5243 NewArgs); 5244 5245 NestedNameSpecifierLoc QualifierLoc; 5246 TemplateName Name = SubstDefaultTemplateArgument(*this, Template, 5247 TemplateLoc, 5248 RAngleLoc, 5249 TempParm, 5250 Converted, 5251 QualifierLoc); 5252 if (Name.isNull()) 5253 return true; 5254 5255 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc, 5256 TempParm->getDefaultArgument().getTemplateNameLoc()); 5257 } 5258 5259 // Introduce an instantiation record that describes where we are using 5260 // the default template argument. We're not actually instantiating a 5261 // template here, we just create this object to put a note into the 5262 // context stack. 5263 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted, 5264 SourceRange(TemplateLoc, RAngleLoc)); 5265 if (Inst.isInvalid()) 5266 return true; 5267 5268 // Check the default template argument. 5269 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, 5270 RAngleLoc, 0, Converted)) 5271 return true; 5272 5273 // Core issue 150 (assumed resolution): if this is a template template 5274 // parameter, keep track of the default template arguments from the 5275 // template definition. 5276 if (isTemplateTemplateParameter) 5277 NewArgs.addArgument(Arg); 5278 5279 // Move to the next template parameter and argument. 5280 ++Param; 5281 ++ArgIdx; 5282 } 5283 5284 // If we're performing a partial argument substitution, allow any trailing 5285 // pack expansions; they might be empty. This can happen even if 5286 // PartialTemplateArgs is false (the list of arguments is complete but 5287 // still dependent). 5288 if (ArgIdx < NumArgs && CurrentInstantiationScope && 5289 CurrentInstantiationScope->getPartiallySubstitutedPack()) { 5290 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion()) 5291 Converted.push_back(NewArgs[ArgIdx++].getArgument()); 5292 } 5293 5294 // If we have any leftover arguments, then there were too many arguments. 5295 // Complain and fail. 5296 if (ArgIdx < NumArgs) { 5297 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 5298 << /*too many args*/1 5299 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) 5300 << Template 5301 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc()); 5302 Diag(Template->getLocation(), diag::note_template_decl_here) 5303 << Params->getSourceRange(); 5304 return true; 5305 } 5306 5307 // No problems found with the new argument list, propagate changes back 5308 // to caller. 5309 if (UpdateArgsWithConversions) 5310 TemplateArgs = std::move(NewArgs); 5311 5312 return false; 5313 } 5314 5315 namespace { 5316 class UnnamedLocalNoLinkageFinder 5317 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool> 5318 { 5319 Sema &S; 5320 SourceRange SR; 5321 5322 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited; 5323 5324 public: 5325 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { } 5326 5327 bool Visit(QualType T) { 5328 return T.isNull() ? false : inherited::Visit(T.getTypePtr()); 5329 } 5330 5331 #define TYPE(Class, Parent) \ 5332 bool Visit##Class##Type(const Class##Type *); 5333 #define ABSTRACT_TYPE(Class, Parent) \ 5334 bool Visit##Class##Type(const Class##Type *) { return false; } 5335 #define NON_CANONICAL_TYPE(Class, Parent) \ 5336 bool Visit##Class##Type(const Class##Type *) { return false; } 5337 #include "clang/AST/TypeNodes.def" 5338 5339 bool VisitTagDecl(const TagDecl *Tag); 5340 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS); 5341 }; 5342 } // end anonymous namespace 5343 5344 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) { 5345 return false; 5346 } 5347 5348 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) { 5349 return Visit(T->getElementType()); 5350 } 5351 5352 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) { 5353 return Visit(T->getPointeeType()); 5354 } 5355 5356 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType( 5357 const BlockPointerType* T) { 5358 return Visit(T->getPointeeType()); 5359 } 5360 5361 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType( 5362 const LValueReferenceType* T) { 5363 return Visit(T->getPointeeType()); 5364 } 5365 5366 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType( 5367 const RValueReferenceType* T) { 5368 return Visit(T->getPointeeType()); 5369 } 5370 5371 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType( 5372 const MemberPointerType* T) { 5373 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0)); 5374 } 5375 5376 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType( 5377 const ConstantArrayType* T) { 5378 return Visit(T->getElementType()); 5379 } 5380 5381 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType( 5382 const IncompleteArrayType* T) { 5383 return Visit(T->getElementType()); 5384 } 5385 5386 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType( 5387 const VariableArrayType* T) { 5388 return Visit(T->getElementType()); 5389 } 5390 5391 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType( 5392 const DependentSizedArrayType* T) { 5393 return Visit(T->getElementType()); 5394 } 5395 5396 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType( 5397 const DependentSizedExtVectorType* T) { 5398 return Visit(T->getElementType()); 5399 } 5400 5401 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType( 5402 const DependentAddressSpaceType *T) { 5403 return Visit(T->getPointeeType()); 5404 } 5405 5406 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) { 5407 return Visit(T->getElementType()); 5408 } 5409 5410 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType( 5411 const DependentVectorType *T) { 5412 return Visit(T->getElementType()); 5413 } 5414 5415 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) { 5416 return Visit(T->getElementType()); 5417 } 5418 5419 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType( 5420 const FunctionProtoType* T) { 5421 for (const auto &A : T->param_types()) { 5422 if (Visit(A)) 5423 return true; 5424 } 5425 5426 return Visit(T->getReturnType()); 5427 } 5428 5429 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType( 5430 const FunctionNoProtoType* T) { 5431 return Visit(T->getReturnType()); 5432 } 5433 5434 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType( 5435 const UnresolvedUsingType*) { 5436 return false; 5437 } 5438 5439 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) { 5440 return false; 5441 } 5442 5443 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) { 5444 return Visit(T->getUnderlyingType()); 5445 } 5446 5447 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { 5448 return false; 5449 } 5450 5451 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType( 5452 const UnaryTransformType*) { 5453 return false; 5454 } 5455 5456 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) { 5457 return Visit(T->getDeducedType()); 5458 } 5459 5460 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType( 5461 const DeducedTemplateSpecializationType *T) { 5462 return Visit(T->getDeducedType()); 5463 } 5464 5465 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) { 5466 return VisitTagDecl(T->getDecl()); 5467 } 5468 5469 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) { 5470 return VisitTagDecl(T->getDecl()); 5471 } 5472 5473 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType( 5474 const TemplateTypeParmType*) { 5475 return false; 5476 } 5477 5478 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType( 5479 const SubstTemplateTypeParmPackType *) { 5480 return false; 5481 } 5482 5483 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType( 5484 const TemplateSpecializationType*) { 5485 return false; 5486 } 5487 5488 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType( 5489 const InjectedClassNameType* T) { 5490 return VisitTagDecl(T->getDecl()); 5491 } 5492 5493 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType( 5494 const DependentNameType* T) { 5495 return VisitNestedNameSpecifier(T->getQualifier()); 5496 } 5497 5498 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType( 5499 const DependentTemplateSpecializationType* T) { 5500 return VisitNestedNameSpecifier(T->getQualifier()); 5501 } 5502 5503 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType( 5504 const PackExpansionType* T) { 5505 return Visit(T->getPattern()); 5506 } 5507 5508 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) { 5509 return false; 5510 } 5511 5512 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType( 5513 const ObjCInterfaceType *) { 5514 return false; 5515 } 5516 5517 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType( 5518 const ObjCObjectPointerType *) { 5519 return false; 5520 } 5521 5522 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) { 5523 return Visit(T->getValueType()); 5524 } 5525 5526 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) { 5527 return false; 5528 } 5529 5530 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) { 5531 if (Tag->getDeclContext()->isFunctionOrMethod()) { 5532 S.Diag(SR.getBegin(), 5533 S.getLangOpts().CPlusPlus11 ? 5534 diag::warn_cxx98_compat_template_arg_local_type : 5535 diag::ext_template_arg_local_type) 5536 << S.Context.getTypeDeclType(Tag) << SR; 5537 return true; 5538 } 5539 5540 if (!Tag->hasNameForLinkage()) { 5541 S.Diag(SR.getBegin(), 5542 S.getLangOpts().CPlusPlus11 ? 5543 diag::warn_cxx98_compat_template_arg_unnamed_type : 5544 diag::ext_template_arg_unnamed_type) << SR; 5545 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here); 5546 return true; 5547 } 5548 5549 return false; 5550 } 5551 5552 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier( 5553 NestedNameSpecifier *NNS) { 5554 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix())) 5555 return true; 5556 5557 switch (NNS->getKind()) { 5558 case NestedNameSpecifier::Identifier: 5559 case NestedNameSpecifier::Namespace: 5560 case NestedNameSpecifier::NamespaceAlias: 5561 case NestedNameSpecifier::Global: 5562 case NestedNameSpecifier::Super: 5563 return false; 5564 5565 case NestedNameSpecifier::TypeSpec: 5566 case NestedNameSpecifier::TypeSpecWithTemplate: 5567 return Visit(QualType(NNS->getAsType(), 0)); 5568 } 5569 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 5570 } 5571 5572 /// Check a template argument against its corresponding 5573 /// template type parameter. 5574 /// 5575 /// This routine implements the semantics of C++ [temp.arg.type]. It 5576 /// returns true if an error occurred, and false otherwise. 5577 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 5578 TypeSourceInfo *ArgInfo) { 5579 assert(ArgInfo && "invalid TypeSourceInfo"); 5580 QualType Arg = ArgInfo->getType(); 5581 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange(); 5582 5583 if (Arg->isVariablyModifiedType()) { 5584 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg; 5585 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) { 5586 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; 5587 } 5588 5589 // C++03 [temp.arg.type]p2: 5590 // A local type, a type with no linkage, an unnamed type or a type 5591 // compounded from any of these types shall not be used as a 5592 // template-argument for a template type-parameter. 5593 // 5594 // C++11 allows these, and even in C++03 we allow them as an extension with 5595 // a warning. 5596 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) { 5597 UnnamedLocalNoLinkageFinder Finder(*this, SR); 5598 (void)Finder.Visit(Context.getCanonicalType(Arg)); 5599 } 5600 5601 return false; 5602 } 5603 5604 enum NullPointerValueKind { 5605 NPV_NotNullPointer, 5606 NPV_NullPointer, 5607 NPV_Error 5608 }; 5609 5610 /// Determine whether the given template argument is a null pointer 5611 /// value of the appropriate type. 5612 static NullPointerValueKind 5613 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, 5614 QualType ParamType, Expr *Arg, 5615 Decl *Entity = nullptr) { 5616 if (Arg->isValueDependent() || Arg->isTypeDependent()) 5617 return NPV_NotNullPointer; 5618 5619 // dllimport'd entities aren't constant but are available inside of template 5620 // arguments. 5621 if (Entity && Entity->hasAttr<DLLImportAttr>()) 5622 return NPV_NotNullPointer; 5623 5624 if (!S.isCompleteType(Arg->getExprLoc(), ParamType)) 5625 llvm_unreachable( 5626 "Incomplete parameter type in isNullPointerValueTemplateArgument!"); 5627 5628 if (!S.getLangOpts().CPlusPlus11) 5629 return NPV_NotNullPointer; 5630 5631 // Determine whether we have a constant expression. 5632 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg); 5633 if (ArgRV.isInvalid()) 5634 return NPV_Error; 5635 Arg = ArgRV.get(); 5636 5637 Expr::EvalResult EvalResult; 5638 SmallVector<PartialDiagnosticAt, 8> Notes; 5639 EvalResult.Diag = &Notes; 5640 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) || 5641 EvalResult.HasSideEffects) { 5642 SourceLocation DiagLoc = Arg->getExprLoc(); 5643 5644 // If our only note is the usual "invalid subexpression" note, just point 5645 // the caret at its location rather than producing an essentially 5646 // redundant note. 5647 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 5648 diag::note_invalid_subexpr_in_const_expr) { 5649 DiagLoc = Notes[0].first; 5650 Notes.clear(); 5651 } 5652 5653 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant) 5654 << Arg->getType() << Arg->getSourceRange(); 5655 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 5656 S.Diag(Notes[I].first, Notes[I].second); 5657 5658 S.Diag(Param->getLocation(), diag::note_template_param_here); 5659 return NPV_Error; 5660 } 5661 5662 // C++11 [temp.arg.nontype]p1: 5663 // - an address constant expression of type std::nullptr_t 5664 if (Arg->getType()->isNullPtrType()) 5665 return NPV_NullPointer; 5666 5667 // - a constant expression that evaluates to a null pointer value (4.10); or 5668 // - a constant expression that evaluates to a null member pointer value 5669 // (4.11); or 5670 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) || 5671 (EvalResult.Val.isMemberPointer() && 5672 !EvalResult.Val.getMemberPointerDecl())) { 5673 // If our expression has an appropriate type, we've succeeded. 5674 bool ObjCLifetimeConversion; 5675 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) || 5676 S.IsQualificationConversion(Arg->getType(), ParamType, false, 5677 ObjCLifetimeConversion)) 5678 return NPV_NullPointer; 5679 5680 // The types didn't match, but we know we got a null pointer; complain, 5681 // then recover as if the types were correct. 5682 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant) 5683 << Arg->getType() << ParamType << Arg->getSourceRange(); 5684 S.Diag(Param->getLocation(), diag::note_template_param_here); 5685 return NPV_NullPointer; 5686 } 5687 5688 // If we don't have a null pointer value, but we do have a NULL pointer 5689 // constant, suggest a cast to the appropriate type. 5690 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) { 5691 std::string Code = "static_cast<" + ParamType.getAsString() + ">("; 5692 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant) 5693 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code) 5694 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()), 5695 ")"); 5696 S.Diag(Param->getLocation(), diag::note_template_param_here); 5697 return NPV_NullPointer; 5698 } 5699 5700 // FIXME: If we ever want to support general, address-constant expressions 5701 // as non-type template arguments, we should return the ExprResult here to 5702 // be interpreted by the caller. 5703 return NPV_NotNullPointer; 5704 } 5705 5706 /// Checks whether the given template argument is compatible with its 5707 /// template parameter. 5708 static bool CheckTemplateArgumentIsCompatibleWithParameter( 5709 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, 5710 Expr *Arg, QualType ArgType) { 5711 bool ObjCLifetimeConversion; 5712 if (ParamType->isPointerType() && 5713 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() && 5714 S.IsQualificationConversion(ArgType, ParamType, false, 5715 ObjCLifetimeConversion)) { 5716 // For pointer-to-object types, qualification conversions are 5717 // permitted. 5718 } else { 5719 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) { 5720 if (!ParamRef->getPointeeType()->isFunctionType()) { 5721 // C++ [temp.arg.nontype]p5b3: 5722 // For a non-type template-parameter of type reference to 5723 // object, no conversions apply. The type referred to by the 5724 // reference may be more cv-qualified than the (otherwise 5725 // identical) type of the template- argument. The 5726 // template-parameter is bound directly to the 5727 // template-argument, which shall be an lvalue. 5728 5729 // FIXME: Other qualifiers? 5730 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers(); 5731 unsigned ArgQuals = ArgType.getCVRQualifiers(); 5732 5733 if ((ParamQuals | ArgQuals) != ParamQuals) { 5734 S.Diag(Arg->getBeginLoc(), 5735 diag::err_template_arg_ref_bind_ignores_quals) 5736 << ParamType << Arg->getType() << Arg->getSourceRange(); 5737 S.Diag(Param->getLocation(), diag::note_template_param_here); 5738 return true; 5739 } 5740 } 5741 } 5742 5743 // At this point, the template argument refers to an object or 5744 // function with external linkage. We now need to check whether the 5745 // argument and parameter types are compatible. 5746 if (!S.Context.hasSameUnqualifiedType(ArgType, 5747 ParamType.getNonReferenceType())) { 5748 // We can't perform this conversion or binding. 5749 if (ParamType->isReferenceType()) 5750 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind) 5751 << ParamType << ArgIn->getType() << Arg->getSourceRange(); 5752 else 5753 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) 5754 << ArgIn->getType() << ParamType << Arg->getSourceRange(); 5755 S.Diag(Param->getLocation(), diag::note_template_param_here); 5756 return true; 5757 } 5758 } 5759 5760 return false; 5761 } 5762 5763 /// Checks whether the given template argument is the address 5764 /// of an object or function according to C++ [temp.arg.nontype]p1. 5765 static bool 5766 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, 5767 NonTypeTemplateParmDecl *Param, 5768 QualType ParamType, 5769 Expr *ArgIn, 5770 TemplateArgument &Converted) { 5771 bool Invalid = false; 5772 Expr *Arg = ArgIn; 5773 QualType ArgType = Arg->getType(); 5774 5775 bool AddressTaken = false; 5776 SourceLocation AddrOpLoc; 5777 if (S.getLangOpts().MicrosoftExt) { 5778 // Microsoft Visual C++ strips all casts, allows an arbitrary number of 5779 // dereference and address-of operators. 5780 Arg = Arg->IgnoreParenCasts(); 5781 5782 bool ExtWarnMSTemplateArg = false; 5783 UnaryOperatorKind FirstOpKind; 5784 SourceLocation FirstOpLoc; 5785 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 5786 UnaryOperatorKind UnOpKind = UnOp->getOpcode(); 5787 if (UnOpKind == UO_Deref) 5788 ExtWarnMSTemplateArg = true; 5789 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) { 5790 Arg = UnOp->getSubExpr()->IgnoreParenCasts(); 5791 if (!AddrOpLoc.isValid()) { 5792 FirstOpKind = UnOpKind; 5793 FirstOpLoc = UnOp->getOperatorLoc(); 5794 } 5795 } else 5796 break; 5797 } 5798 if (FirstOpLoc.isValid()) { 5799 if (ExtWarnMSTemplateArg) 5800 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument) 5801 << ArgIn->getSourceRange(); 5802 5803 if (FirstOpKind == UO_AddrOf) 5804 AddressTaken = true; 5805 else if (Arg->getType()->isPointerType()) { 5806 // We cannot let pointers get dereferenced here, that is obviously not a 5807 // constant expression. 5808 assert(FirstOpKind == UO_Deref); 5809 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) 5810 << Arg->getSourceRange(); 5811 } 5812 } 5813 } else { 5814 // See through any implicit casts we added to fix the type. 5815 Arg = Arg->IgnoreImpCasts(); 5816 5817 // C++ [temp.arg.nontype]p1: 5818 // 5819 // A template-argument for a non-type, non-template 5820 // template-parameter shall be one of: [...] 5821 // 5822 // -- the address of an object or function with external 5823 // linkage, including function templates and function 5824 // template-ids but excluding non-static class members, 5825 // expressed as & id-expression where the & is optional if 5826 // the name refers to a function or array, or if the 5827 // corresponding template-parameter is a reference; or 5828 5829 // In C++98/03 mode, give an extension warning on any extra parentheses. 5830 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 5831 bool ExtraParens = false; 5832 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 5833 if (!Invalid && !ExtraParens) { 5834 S.Diag(Arg->getBeginLoc(), 5835 S.getLangOpts().CPlusPlus11 5836 ? diag::warn_cxx98_compat_template_arg_extra_parens 5837 : diag::ext_template_arg_extra_parens) 5838 << Arg->getSourceRange(); 5839 ExtraParens = true; 5840 } 5841 5842 Arg = Parens->getSubExpr(); 5843 } 5844 5845 while (SubstNonTypeTemplateParmExpr *subst = 5846 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 5847 Arg = subst->getReplacement()->IgnoreImpCasts(); 5848 5849 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 5850 if (UnOp->getOpcode() == UO_AddrOf) { 5851 Arg = UnOp->getSubExpr(); 5852 AddressTaken = true; 5853 AddrOpLoc = UnOp->getOperatorLoc(); 5854 } 5855 } 5856 5857 while (SubstNonTypeTemplateParmExpr *subst = 5858 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 5859 Arg = subst->getReplacement()->IgnoreImpCasts(); 5860 } 5861 5862 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg); 5863 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr; 5864 5865 // If our parameter has pointer type, check for a null template value. 5866 if (ParamType->isPointerType() || ParamType->isNullPtrType()) { 5867 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn, 5868 Entity)) { 5869 case NPV_NullPointer: 5870 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 5871 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType), 5872 /*isNullPtr=*/true); 5873 return false; 5874 5875 case NPV_Error: 5876 return true; 5877 5878 case NPV_NotNullPointer: 5879 break; 5880 } 5881 } 5882 5883 // Stop checking the precise nature of the argument if it is value dependent, 5884 // it should be checked when instantiated. 5885 if (Arg->isValueDependent()) { 5886 Converted = TemplateArgument(ArgIn); 5887 return false; 5888 } 5889 5890 if (isa<CXXUuidofExpr>(Arg)) { 5891 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, 5892 ArgIn, Arg, ArgType)) 5893 return true; 5894 5895 Converted = TemplateArgument(ArgIn); 5896 return false; 5897 } 5898 5899 if (!DRE) { 5900 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) 5901 << Arg->getSourceRange(); 5902 S.Diag(Param->getLocation(), diag::note_template_param_here); 5903 return true; 5904 } 5905 5906 // Cannot refer to non-static data members 5907 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) { 5908 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field) 5909 << Entity << Arg->getSourceRange(); 5910 S.Diag(Param->getLocation(), diag::note_template_param_here); 5911 return true; 5912 } 5913 5914 // Cannot refer to non-static member functions 5915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) { 5916 if (!Method->isStatic()) { 5917 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method) 5918 << Method << Arg->getSourceRange(); 5919 S.Diag(Param->getLocation(), diag::note_template_param_here); 5920 return true; 5921 } 5922 } 5923 5924 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity); 5925 VarDecl *Var = dyn_cast<VarDecl>(Entity); 5926 5927 // A non-type template argument must refer to an object or function. 5928 if (!Func && !Var) { 5929 // We found something, but we don't know specifically what it is. 5930 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func) 5931 << Arg->getSourceRange(); 5932 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); 5933 return true; 5934 } 5935 5936 // Address / reference template args must have external linkage in C++98. 5937 if (Entity->getFormalLinkage() == InternalLinkage) { 5938 S.Diag(Arg->getBeginLoc(), 5939 S.getLangOpts().CPlusPlus11 5940 ? diag::warn_cxx98_compat_template_arg_object_internal 5941 : diag::ext_template_arg_object_internal) 5942 << !Func << Entity << Arg->getSourceRange(); 5943 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) 5944 << !Func; 5945 } else if (!Entity->hasLinkage()) { 5946 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage) 5947 << !Func << Entity << Arg->getSourceRange(); 5948 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) 5949 << !Func; 5950 return true; 5951 } 5952 5953 if (Func) { 5954 // If the template parameter has pointer type, the function decays. 5955 if (ParamType->isPointerType() && !AddressTaken) 5956 ArgType = S.Context.getPointerType(Func->getType()); 5957 else if (AddressTaken && ParamType->isReferenceType()) { 5958 // If we originally had an address-of operator, but the 5959 // parameter has reference type, complain and (if things look 5960 // like they will work) drop the address-of operator. 5961 if (!S.Context.hasSameUnqualifiedType(Func->getType(), 5962 ParamType.getNonReferenceType())) { 5963 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 5964 << ParamType; 5965 S.Diag(Param->getLocation(), diag::note_template_param_here); 5966 return true; 5967 } 5968 5969 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 5970 << ParamType 5971 << FixItHint::CreateRemoval(AddrOpLoc); 5972 S.Diag(Param->getLocation(), diag::note_template_param_here); 5973 5974 ArgType = Func->getType(); 5975 } 5976 } else { 5977 // A value of reference type is not an object. 5978 if (Var->getType()->isReferenceType()) { 5979 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var) 5980 << Var->getType() << Arg->getSourceRange(); 5981 S.Diag(Param->getLocation(), diag::note_template_param_here); 5982 return true; 5983 } 5984 5985 // A template argument must have static storage duration. 5986 if (Var->getTLSKind()) { 5987 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local) 5988 << Arg->getSourceRange(); 5989 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here); 5990 return true; 5991 } 5992 5993 // If the template parameter has pointer type, we must have taken 5994 // the address of this object. 5995 if (ParamType->isReferenceType()) { 5996 if (AddressTaken) { 5997 // If we originally had an address-of operator, but the 5998 // parameter has reference type, complain and (if things look 5999 // like they will work) drop the address-of operator. 6000 if (!S.Context.hasSameUnqualifiedType(Var->getType(), 6001 ParamType.getNonReferenceType())) { 6002 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 6003 << ParamType; 6004 S.Diag(Param->getLocation(), diag::note_template_param_here); 6005 return true; 6006 } 6007 6008 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 6009 << ParamType 6010 << FixItHint::CreateRemoval(AddrOpLoc); 6011 S.Diag(Param->getLocation(), diag::note_template_param_here); 6012 6013 ArgType = Var->getType(); 6014 } 6015 } else if (!AddressTaken && ParamType->isPointerType()) { 6016 if (Var->getType()->isArrayType()) { 6017 // Array-to-pointer decay. 6018 ArgType = S.Context.getArrayDecayedType(Var->getType()); 6019 } else { 6020 // If the template parameter has pointer type but the address of 6021 // this object was not taken, complain and (possibly) recover by 6022 // taking the address of the entity. 6023 ArgType = S.Context.getPointerType(Var->getType()); 6024 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) { 6025 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) 6026 << ParamType; 6027 S.Diag(Param->getLocation(), diag::note_template_param_here); 6028 return true; 6029 } 6030 6031 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) 6032 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&"); 6033 6034 S.Diag(Param->getLocation(), diag::note_template_param_here); 6035 } 6036 } 6037 } 6038 6039 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn, 6040 Arg, ArgType)) 6041 return true; 6042 6043 // Create the template argument. 6044 Converted = 6045 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType); 6046 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false); 6047 return false; 6048 } 6049 6050 /// Checks whether the given template argument is a pointer to 6051 /// member constant according to C++ [temp.arg.nontype]p1. 6052 static bool CheckTemplateArgumentPointerToMember(Sema &S, 6053 NonTypeTemplateParmDecl *Param, 6054 QualType ParamType, 6055 Expr *&ResultArg, 6056 TemplateArgument &Converted) { 6057 bool Invalid = false; 6058 6059 Expr *Arg = ResultArg; 6060 bool ObjCLifetimeConversion; 6061 6062 // C++ [temp.arg.nontype]p1: 6063 // 6064 // A template-argument for a non-type, non-template 6065 // template-parameter shall be one of: [...] 6066 // 6067 // -- a pointer to member expressed as described in 5.3.1. 6068 DeclRefExpr *DRE = nullptr; 6069 6070 // In C++98/03 mode, give an extension warning on any extra parentheses. 6071 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 6072 bool ExtraParens = false; 6073 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 6074 if (!Invalid && !ExtraParens) { 6075 S.Diag(Arg->getBeginLoc(), 6076 S.getLangOpts().CPlusPlus11 6077 ? diag::warn_cxx98_compat_template_arg_extra_parens 6078 : diag::ext_template_arg_extra_parens) 6079 << Arg->getSourceRange(); 6080 ExtraParens = true; 6081 } 6082 6083 Arg = Parens->getSubExpr(); 6084 } 6085 6086 while (SubstNonTypeTemplateParmExpr *subst = 6087 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 6088 Arg = subst->getReplacement()->IgnoreImpCasts(); 6089 6090 // A pointer-to-member constant written &Class::member. 6091 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 6092 if (UnOp->getOpcode() == UO_AddrOf) { 6093 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 6094 if (DRE && !DRE->getQualifier()) 6095 DRE = nullptr; 6096 } 6097 } 6098 // A constant of pointer-to-member type. 6099 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 6100 ValueDecl *VD = DRE->getDecl(); 6101 if (VD->getType()->isMemberPointerType()) { 6102 if (isa<NonTypeTemplateParmDecl>(VD)) { 6103 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 6104 Converted = TemplateArgument(Arg); 6105 } else { 6106 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 6107 Converted = TemplateArgument(VD, ParamType); 6108 } 6109 return Invalid; 6110 } 6111 } 6112 6113 DRE = nullptr; 6114 } 6115 6116 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr; 6117 6118 // Check for a null pointer value. 6119 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg, 6120 Entity)) { 6121 case NPV_Error: 6122 return true; 6123 case NPV_NullPointer: 6124 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 6125 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType), 6126 /*isNullPtr*/true); 6127 return false; 6128 case NPV_NotNullPointer: 6129 break; 6130 } 6131 6132 if (S.IsQualificationConversion(ResultArg->getType(), 6133 ParamType.getNonReferenceType(), false, 6134 ObjCLifetimeConversion)) { 6135 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp, 6136 ResultArg->getValueKind()) 6137 .get(); 6138 } else if (!S.Context.hasSameUnqualifiedType( 6139 ResultArg->getType(), ParamType.getNonReferenceType())) { 6140 // We can't perform this conversion. 6141 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible) 6142 << ResultArg->getType() << ParamType << ResultArg->getSourceRange(); 6143 S.Diag(Param->getLocation(), diag::note_template_param_here); 6144 return true; 6145 } 6146 6147 if (!DRE) 6148 return S.Diag(Arg->getBeginLoc(), 6149 diag::err_template_arg_not_pointer_to_member_form) 6150 << Arg->getSourceRange(); 6151 6152 if (isa<FieldDecl>(DRE->getDecl()) || 6153 isa<IndirectFieldDecl>(DRE->getDecl()) || 6154 isa<CXXMethodDecl>(DRE->getDecl())) { 6155 assert((isa<FieldDecl>(DRE->getDecl()) || 6156 isa<IndirectFieldDecl>(DRE->getDecl()) || 6157 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 6158 "Only non-static member pointers can make it here"); 6159 6160 // Okay: this is the address of a non-static member, and therefore 6161 // a member pointer constant. 6162 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 6163 Converted = TemplateArgument(Arg); 6164 } else { 6165 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl()); 6166 Converted = TemplateArgument(D, ParamType); 6167 } 6168 return Invalid; 6169 } 6170 6171 // We found something else, but we don't know specifically what it is. 6172 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form) 6173 << Arg->getSourceRange(); 6174 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); 6175 return true; 6176 } 6177 6178 /// Check a template argument against its corresponding 6179 /// non-type template parameter. 6180 /// 6181 /// This routine implements the semantics of C++ [temp.arg.nontype]. 6182 /// If an error occurred, it returns ExprError(); otherwise, it 6183 /// returns the converted template argument. \p ParamType is the 6184 /// type of the non-type template parameter after it has been instantiated. 6185 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 6186 QualType ParamType, Expr *Arg, 6187 TemplateArgument &Converted, 6188 CheckTemplateArgumentKind CTAK) { 6189 SourceLocation StartLoc = Arg->getBeginLoc(); 6190 6191 // If the parameter type somehow involves auto, deduce the type now. 6192 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) { 6193 // During template argument deduction, we allow 'decltype(auto)' to 6194 // match an arbitrary dependent argument. 6195 // FIXME: The language rules don't say what happens in this case. 6196 // FIXME: We get an opaque dependent type out of decltype(auto) if the 6197 // expression is merely instantiation-dependent; is this enough? 6198 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) { 6199 auto *AT = dyn_cast<AutoType>(ParamType); 6200 if (AT && AT->isDecltypeAuto()) { 6201 Converted = TemplateArgument(Arg); 6202 return Arg; 6203 } 6204 } 6205 6206 // When checking a deduced template argument, deduce from its type even if 6207 // the type is dependent, in order to check the types of non-type template 6208 // arguments line up properly in partial ordering. 6209 Optional<unsigned> Depth; 6210 if (CTAK != CTAK_Specified) 6211 Depth = Param->getDepth() + 1; 6212 if (DeduceAutoType( 6213 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()), 6214 Arg, ParamType, Depth) == DAR_Failed) { 6215 Diag(Arg->getExprLoc(), 6216 diag::err_non_type_template_parm_type_deduction_failure) 6217 << Param->getDeclName() << Param->getType() << Arg->getType() 6218 << Arg->getSourceRange(); 6219 Diag(Param->getLocation(), diag::note_template_param_here); 6220 return ExprError(); 6221 } 6222 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's 6223 // an error. The error message normally references the parameter 6224 // declaration, but here we'll pass the argument location because that's 6225 // where the parameter type is deduced. 6226 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc()); 6227 if (ParamType.isNull()) { 6228 Diag(Param->getLocation(), diag::note_template_param_here); 6229 return ExprError(); 6230 } 6231 } 6232 6233 // We should have already dropped all cv-qualifiers by now. 6234 assert(!ParamType.hasQualifiers() && 6235 "non-type template parameter type cannot be qualified"); 6236 6237 if (CTAK == CTAK_Deduced && 6238 !Context.hasSameType(ParamType.getNonLValueExprType(Context), 6239 Arg->getType())) { 6240 // FIXME: If either type is dependent, we skip the check. This isn't 6241 // correct, since during deduction we're supposed to have replaced each 6242 // template parameter with some unique (non-dependent) placeholder. 6243 // FIXME: If the argument type contains 'auto', we carry on and fail the 6244 // type check in order to force specific types to be more specialized than 6245 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to 6246 // work. 6247 if ((ParamType->isDependentType() || Arg->isTypeDependent()) && 6248 !Arg->getType()->getContainedAutoType()) { 6249 Converted = TemplateArgument(Arg); 6250 return Arg; 6251 } 6252 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770, 6253 // we should actually be checking the type of the template argument in P, 6254 // not the type of the template argument deduced from A, against the 6255 // template parameter type. 6256 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch) 6257 << Arg->getType() 6258 << ParamType.getUnqualifiedType(); 6259 Diag(Param->getLocation(), diag::note_template_param_here); 6260 return ExprError(); 6261 } 6262 6263 // If either the parameter has a dependent type or the argument is 6264 // type-dependent, there's nothing we can check now. 6265 if (ParamType->isDependentType() || Arg->isTypeDependent()) { 6266 // FIXME: Produce a cloned, canonical expression? 6267 Converted = TemplateArgument(Arg); 6268 return Arg; 6269 } 6270 6271 // The initialization of the parameter from the argument is 6272 // a constant-evaluated context. 6273 EnterExpressionEvaluationContext ConstantEvaluated( 6274 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); 6275 6276 if (getLangOpts().CPlusPlus17) { 6277 // C++17 [temp.arg.nontype]p1: 6278 // A template-argument for a non-type template parameter shall be 6279 // a converted constant expression of the type of the template-parameter. 6280 APValue Value; 6281 ExprResult ArgResult = CheckConvertedConstantExpression( 6282 Arg, ParamType, Value, CCEK_TemplateArg); 6283 if (ArgResult.isInvalid()) 6284 return ExprError(); 6285 6286 // For a value-dependent argument, CheckConvertedConstantExpression is 6287 // permitted (and expected) to be unable to determine a value. 6288 if (ArgResult.get()->isValueDependent()) { 6289 Converted = TemplateArgument(ArgResult.get()); 6290 return ArgResult; 6291 } 6292 6293 QualType CanonParamType = Context.getCanonicalType(ParamType); 6294 6295 // Convert the APValue to a TemplateArgument. 6296 switch (Value.getKind()) { 6297 case APValue::Uninitialized: 6298 assert(ParamType->isNullPtrType()); 6299 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true); 6300 break; 6301 case APValue::Int: 6302 assert(ParamType->isIntegralOrEnumerationType()); 6303 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType); 6304 break; 6305 case APValue::MemberPointer: { 6306 assert(ParamType->isMemberPointerType()); 6307 6308 // FIXME: We need TemplateArgument representation and mangling for these. 6309 if (!Value.getMemberPointerPath().empty()) { 6310 Diag(Arg->getBeginLoc(), 6311 diag::err_template_arg_member_ptr_base_derived_not_supported) 6312 << Value.getMemberPointerDecl() << ParamType 6313 << Arg->getSourceRange(); 6314 return ExprError(); 6315 } 6316 6317 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl()); 6318 Converted = VD ? TemplateArgument(VD, CanonParamType) 6319 : TemplateArgument(CanonParamType, /*isNullPtr*/true); 6320 break; 6321 } 6322 case APValue::LValue: { 6323 // For a non-type template-parameter of pointer or reference type, 6324 // the value of the constant expression shall not refer to 6325 assert(ParamType->isPointerType() || ParamType->isReferenceType() || 6326 ParamType->isNullPtrType()); 6327 // -- a temporary object 6328 // -- a string literal 6329 // -- the result of a typeid expression, or 6330 // -- a predefined __func__ variable 6331 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) { 6332 if (isa<CXXUuidofExpr>(E)) { 6333 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts()); 6334 break; 6335 } 6336 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) 6337 << Arg->getSourceRange(); 6338 return ExprError(); 6339 } 6340 auto *VD = const_cast<ValueDecl *>( 6341 Value.getLValueBase().dyn_cast<const ValueDecl *>()); 6342 // -- a subobject 6343 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && 6344 VD && VD->getType()->isArrayType() && 6345 Value.getLValuePath()[0].ArrayIndex == 0 && 6346 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) { 6347 // Per defect report (no number yet): 6348 // ... other than a pointer to the first element of a complete array 6349 // object. 6350 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() || 6351 Value.isLValueOnePastTheEnd()) { 6352 Diag(StartLoc, diag::err_non_type_template_arg_subobject) 6353 << Value.getAsString(Context, ParamType); 6354 return ExprError(); 6355 } 6356 assert((VD || !ParamType->isReferenceType()) && 6357 "null reference should not be a constant expression"); 6358 assert((!VD || !ParamType->isNullPtrType()) && 6359 "non-null value of type nullptr_t?"); 6360 Converted = VD ? TemplateArgument(VD, CanonParamType) 6361 : TemplateArgument(CanonParamType, /*isNullPtr*/true); 6362 break; 6363 } 6364 case APValue::AddrLabelDiff: 6365 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff); 6366 case APValue::FixedPoint: 6367 case APValue::Float: 6368 case APValue::ComplexInt: 6369 case APValue::ComplexFloat: 6370 case APValue::Vector: 6371 case APValue::Array: 6372 case APValue::Struct: 6373 case APValue::Union: 6374 llvm_unreachable("invalid kind for template argument"); 6375 } 6376 6377 return ArgResult.get(); 6378 } 6379 6380 // C++ [temp.arg.nontype]p5: 6381 // The following conversions are performed on each expression used 6382 // as a non-type template-argument. If a non-type 6383 // template-argument cannot be converted to the type of the 6384 // corresponding template-parameter then the program is 6385 // ill-formed. 6386 if (ParamType->isIntegralOrEnumerationType()) { 6387 // C++11: 6388 // -- for a non-type template-parameter of integral or 6389 // enumeration type, conversions permitted in a converted 6390 // constant expression are applied. 6391 // 6392 // C++98: 6393 // -- for a non-type template-parameter of integral or 6394 // enumeration type, integral promotions (4.5) and integral 6395 // conversions (4.7) are applied. 6396 6397 if (getLangOpts().CPlusPlus11) { 6398 // C++ [temp.arg.nontype]p1: 6399 // A template-argument for a non-type, non-template template-parameter 6400 // shall be one of: 6401 // 6402 // -- for a non-type template-parameter of integral or enumeration 6403 // type, a converted constant expression of the type of the 6404 // template-parameter; or 6405 llvm::APSInt Value; 6406 ExprResult ArgResult = 6407 CheckConvertedConstantExpression(Arg, ParamType, Value, 6408 CCEK_TemplateArg); 6409 if (ArgResult.isInvalid()) 6410 return ExprError(); 6411 6412 // We can't check arbitrary value-dependent arguments. 6413 if (ArgResult.get()->isValueDependent()) { 6414 Converted = TemplateArgument(ArgResult.get()); 6415 return ArgResult; 6416 } 6417 6418 // Widen the argument value to sizeof(parameter type). This is almost 6419 // always a no-op, except when the parameter type is bool. In 6420 // that case, this may extend the argument from 1 bit to 8 bits. 6421 QualType IntegerType = ParamType; 6422 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 6423 IntegerType = Enum->getDecl()->getIntegerType(); 6424 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType)); 6425 6426 Converted = TemplateArgument(Context, Value, 6427 Context.getCanonicalType(ParamType)); 6428 return ArgResult; 6429 } 6430 6431 ExprResult ArgResult = DefaultLvalueConversion(Arg); 6432 if (ArgResult.isInvalid()) 6433 return ExprError(); 6434 Arg = ArgResult.get(); 6435 6436 QualType ArgType = Arg->getType(); 6437 6438 // C++ [temp.arg.nontype]p1: 6439 // A template-argument for a non-type, non-template 6440 // template-parameter shall be one of: 6441 // 6442 // -- an integral constant-expression of integral or enumeration 6443 // type; or 6444 // -- the name of a non-type template-parameter; or 6445 llvm::APSInt Value; 6446 if (!ArgType->isIntegralOrEnumerationType()) { 6447 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral) 6448 << ArgType << Arg->getSourceRange(); 6449 Diag(Param->getLocation(), diag::note_template_param_here); 6450 return ExprError(); 6451 } else if (!Arg->isValueDependent()) { 6452 class TmplArgICEDiagnoser : public VerifyICEDiagnoser { 6453 QualType T; 6454 6455 public: 6456 TmplArgICEDiagnoser(QualType T) : T(T) { } 6457 6458 void diagnoseNotICE(Sema &S, SourceLocation Loc, 6459 SourceRange SR) override { 6460 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR; 6461 } 6462 } Diagnoser(ArgType); 6463 6464 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser, 6465 false).get(); 6466 if (!Arg) 6467 return ExprError(); 6468 } 6469 6470 // From here on out, all we care about is the unqualified form 6471 // of the argument type. 6472 ArgType = ArgType.getUnqualifiedType(); 6473 6474 // Try to convert the argument to the parameter's type. 6475 if (Context.hasSameType(ParamType, ArgType)) { 6476 // Okay: no conversion necessary 6477 } else if (ParamType->isBooleanType()) { 6478 // This is an integral-to-boolean conversion. 6479 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get(); 6480 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 6481 !ParamType->isEnumeralType()) { 6482 // This is an integral promotion or conversion. 6483 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get(); 6484 } else { 6485 // We can't perform this conversion. 6486 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) 6487 << Arg->getType() << ParamType << Arg->getSourceRange(); 6488 Diag(Param->getLocation(), diag::note_template_param_here); 6489 return ExprError(); 6490 } 6491 6492 // Add the value of this argument to the list of converted 6493 // arguments. We use the bitwidth and signedness of the template 6494 // parameter. 6495 if (Arg->isValueDependent()) { 6496 // The argument is value-dependent. Create a new 6497 // TemplateArgument with the converted expression. 6498 Converted = TemplateArgument(Arg); 6499 return Arg; 6500 } 6501 6502 QualType IntegerType = Context.getCanonicalType(ParamType); 6503 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 6504 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 6505 6506 if (ParamType->isBooleanType()) { 6507 // Value must be zero or one. 6508 Value = Value != 0; 6509 unsigned AllowedBits = Context.getTypeSize(IntegerType); 6510 if (Value.getBitWidth() != AllowedBits) 6511 Value = Value.extOrTrunc(AllowedBits); 6512 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 6513 } else { 6514 llvm::APSInt OldValue = Value; 6515 6516 // Coerce the template argument's value to the value it will have 6517 // based on the template parameter's type. 6518 unsigned AllowedBits = Context.getTypeSize(IntegerType); 6519 if (Value.getBitWidth() != AllowedBits) 6520 Value = Value.extOrTrunc(AllowedBits); 6521 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 6522 6523 // Complain if an unsigned parameter received a negative value. 6524 if (IntegerType->isUnsignedIntegerOrEnumerationType() 6525 && (OldValue.isSigned() && OldValue.isNegative())) { 6526 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative) 6527 << OldValue.toString(10) << Value.toString(10) << Param->getType() 6528 << Arg->getSourceRange(); 6529 Diag(Param->getLocation(), diag::note_template_param_here); 6530 } 6531 6532 // Complain if we overflowed the template parameter's type. 6533 unsigned RequiredBits; 6534 if (IntegerType->isUnsignedIntegerOrEnumerationType()) 6535 RequiredBits = OldValue.getActiveBits(); 6536 else if (OldValue.isUnsigned()) 6537 RequiredBits = OldValue.getActiveBits() + 1; 6538 else 6539 RequiredBits = OldValue.getMinSignedBits(); 6540 if (RequiredBits > AllowedBits) { 6541 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large) 6542 << OldValue.toString(10) << Value.toString(10) << Param->getType() 6543 << Arg->getSourceRange(); 6544 Diag(Param->getLocation(), diag::note_template_param_here); 6545 } 6546 } 6547 6548 Converted = TemplateArgument(Context, Value, 6549 ParamType->isEnumeralType() 6550 ? Context.getCanonicalType(ParamType) 6551 : IntegerType); 6552 return Arg; 6553 } 6554 6555 QualType ArgType = Arg->getType(); 6556 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction 6557 6558 // Handle pointer-to-function, reference-to-function, and 6559 // pointer-to-member-function all in (roughly) the same way. 6560 if (// -- For a non-type template-parameter of type pointer to 6561 // function, only the function-to-pointer conversion (4.3) is 6562 // applied. If the template-argument represents a set of 6563 // overloaded functions (or a pointer to such), the matching 6564 // function is selected from the set (13.4). 6565 (ParamType->isPointerType() && 6566 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) || 6567 // -- For a non-type template-parameter of type reference to 6568 // function, no conversions apply. If the template-argument 6569 // represents a set of overloaded functions, the matching 6570 // function is selected from the set (13.4). 6571 (ParamType->isReferenceType() && 6572 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 6573 // -- For a non-type template-parameter of type pointer to 6574 // member function, no conversions apply. If the 6575 // template-argument represents a set of overloaded member 6576 // functions, the matching member function is selected from 6577 // the set (13.4). 6578 (ParamType->isMemberPointerType() && 6579 ParamType->getAs<MemberPointerType>()->getPointeeType() 6580 ->isFunctionType())) { 6581 6582 if (Arg->getType() == Context.OverloadTy) { 6583 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, 6584 true, 6585 FoundResult)) { 6586 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) 6587 return ExprError(); 6588 6589 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 6590 ArgType = Arg->getType(); 6591 } else 6592 return ExprError(); 6593 } 6594 6595 if (!ParamType->isMemberPointerType()) { 6596 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 6597 ParamType, 6598 Arg, Converted)) 6599 return ExprError(); 6600 return Arg; 6601 } 6602 6603 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg, 6604 Converted)) 6605 return ExprError(); 6606 return Arg; 6607 } 6608 6609 if (ParamType->isPointerType()) { 6610 // -- for a non-type template-parameter of type pointer to 6611 // object, qualification conversions (4.4) and the 6612 // array-to-pointer conversion (4.2) are applied. 6613 // C++0x also allows a value of std::nullptr_t. 6614 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && 6615 "Only object pointers allowed here"); 6616 6617 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 6618 ParamType, 6619 Arg, Converted)) 6620 return ExprError(); 6621 return Arg; 6622 } 6623 6624 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 6625 // -- For a non-type template-parameter of type reference to 6626 // object, no conversions apply. The type referred to by the 6627 // reference may be more cv-qualified than the (otherwise 6628 // identical) type of the template-argument. The 6629 // template-parameter is bound directly to the 6630 // template-argument, which must be an lvalue. 6631 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() && 6632 "Only object references allowed here"); 6633 6634 if (Arg->getType() == Context.OverloadTy) { 6635 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, 6636 ParamRefType->getPointeeType(), 6637 true, 6638 FoundResult)) { 6639 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) 6640 return ExprError(); 6641 6642 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 6643 ArgType = Arg->getType(); 6644 } else 6645 return ExprError(); 6646 } 6647 6648 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 6649 ParamType, 6650 Arg, Converted)) 6651 return ExprError(); 6652 return Arg; 6653 } 6654 6655 // Deal with parameters of type std::nullptr_t. 6656 if (ParamType->isNullPtrType()) { 6657 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 6658 Converted = TemplateArgument(Arg); 6659 return Arg; 6660 } 6661 6662 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) { 6663 case NPV_NotNullPointer: 6664 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible) 6665 << Arg->getType() << ParamType; 6666 Diag(Param->getLocation(), diag::note_template_param_here); 6667 return ExprError(); 6668 6669 case NPV_Error: 6670 return ExprError(); 6671 6672 case NPV_NullPointer: 6673 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 6674 Converted = TemplateArgument(Context.getCanonicalType(ParamType), 6675 /*isNullPtr*/true); 6676 return Arg; 6677 } 6678 } 6679 6680 // -- For a non-type template-parameter of type pointer to data 6681 // member, qualification conversions (4.4) are applied. 6682 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 6683 6684 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg, 6685 Converted)) 6686 return ExprError(); 6687 return Arg; 6688 } 6689 6690 static void DiagnoseTemplateParameterListArityMismatch( 6691 Sema &S, TemplateParameterList *New, TemplateParameterList *Old, 6692 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc); 6693 6694 /// Check a template argument against its corresponding 6695 /// template template parameter. 6696 /// 6697 /// This routine implements the semantics of C++ [temp.arg.template]. 6698 /// It returns true if an error occurred, and false otherwise. 6699 bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params, 6700 TemplateArgumentLoc &Arg) { 6701 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern(); 6702 TemplateDecl *Template = Name.getAsTemplateDecl(); 6703 if (!Template) { 6704 // Any dependent template name is fine. 6705 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 6706 return false; 6707 } 6708 6709 if (Template->isInvalidDecl()) 6710 return true; 6711 6712 // C++0x [temp.arg.template]p1: 6713 // A template-argument for a template template-parameter shall be 6714 // the name of a class template or an alias template, expressed as an 6715 // id-expression. When the template-argument names a class template, only 6716 // primary class templates are considered when matching the 6717 // template template argument with the corresponding parameter; 6718 // partial specializations are not considered even if their 6719 // parameter lists match that of the template template parameter. 6720 // 6721 // Note that we also allow template template parameters here, which 6722 // will happen when we are dealing with, e.g., class template 6723 // partial specializations. 6724 if (!isa<ClassTemplateDecl>(Template) && 6725 !isa<TemplateTemplateParmDecl>(Template) && 6726 !isa<TypeAliasTemplateDecl>(Template) && 6727 !isa<BuiltinTemplateDecl>(Template)) { 6728 assert(isa<FunctionTemplateDecl>(Template) && 6729 "Only function templates are possible here"); 6730 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template); 6731 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 6732 << Template; 6733 } 6734 6735 // C++1z [temp.arg.template]p3: (DR 150) 6736 // A template-argument matches a template template-parameter P when P 6737 // is at least as specialized as the template-argument A. 6738 if (getLangOpts().RelaxedTemplateTemplateArgs) { 6739 // Quick check for the common case: 6740 // If P contains a parameter pack, then A [...] matches P if each of A's 6741 // template parameters matches the corresponding template parameter in 6742 // the template-parameter-list of P. 6743 if (TemplateParameterListsAreEqual( 6744 Template->getTemplateParameters(), Params, false, 6745 TPL_TemplateTemplateArgumentMatch, Arg.getLocation())) 6746 return false; 6747 6748 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template, 6749 Arg.getLocation())) 6750 return false; 6751 // FIXME: Produce better diagnostics for deduction failures. 6752 } 6753 6754 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 6755 Params, 6756 true, 6757 TPL_TemplateTemplateArgumentMatch, 6758 Arg.getLocation()); 6759 } 6760 6761 /// Given a non-type template argument that refers to a 6762 /// declaration and the type of its corresponding non-type template 6763 /// parameter, produce an expression that properly refers to that 6764 /// declaration. 6765 ExprResult 6766 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 6767 QualType ParamType, 6768 SourceLocation Loc) { 6769 // C++ [temp.param]p8: 6770 // 6771 // A non-type template-parameter of type "array of T" or 6772 // "function returning T" is adjusted to be of type "pointer to 6773 // T" or "pointer to function returning T", respectively. 6774 if (ParamType->isArrayType()) 6775 ParamType = Context.getArrayDecayedType(ParamType); 6776 else if (ParamType->isFunctionType()) 6777 ParamType = Context.getPointerType(ParamType); 6778 6779 // For a NULL non-type template argument, return nullptr casted to the 6780 // parameter's type. 6781 if (Arg.getKind() == TemplateArgument::NullPtr) { 6782 return ImpCastExprToType( 6783 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc), 6784 ParamType, 6785 ParamType->getAs<MemberPointerType>() 6786 ? CK_NullToMemberPointer 6787 : CK_NullToPointer); 6788 } 6789 assert(Arg.getKind() == TemplateArgument::Declaration && 6790 "Only declaration template arguments permitted here"); 6791 6792 ValueDecl *VD = Arg.getAsDecl(); 6793 6794 if (VD->getDeclContext()->isRecord() && 6795 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) || 6796 isa<IndirectFieldDecl>(VD))) { 6797 // If the value is a class member, we might have a pointer-to-member. 6798 // Determine whether the non-type template template parameter is of 6799 // pointer-to-member type. If so, we need to build an appropriate 6800 // expression for a pointer-to-member, since a "normal" DeclRefExpr 6801 // would refer to the member itself. 6802 if (ParamType->isMemberPointerType()) { 6803 QualType ClassType 6804 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext())); 6805 NestedNameSpecifier *Qualifier 6806 = NestedNameSpecifier::Create(Context, nullptr, false, 6807 ClassType.getTypePtr()); 6808 CXXScopeSpec SS; 6809 SS.MakeTrivial(Context, Qualifier, Loc); 6810 6811 // The actual value-ness of this is unimportant, but for 6812 // internal consistency's sake, references to instance methods 6813 // are r-values. 6814 ExprValueKind VK = VK_LValue; 6815 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance()) 6816 VK = VK_RValue; 6817 6818 ExprResult RefExpr = BuildDeclRefExpr(VD, 6819 VD->getType().getNonReferenceType(), 6820 VK, 6821 Loc, 6822 &SS); 6823 if (RefExpr.isInvalid()) 6824 return ExprError(); 6825 6826 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 6827 6828 // We might need to perform a trailing qualification conversion, since 6829 // the element type on the parameter could be more qualified than the 6830 // element type in the expression we constructed. 6831 bool ObjCLifetimeConversion; 6832 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(), 6833 ParamType.getUnqualifiedType(), false, 6834 ObjCLifetimeConversion)) 6835 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp); 6836 6837 assert(!RefExpr.isInvalid() && 6838 Context.hasSameType(((Expr*) RefExpr.get())->getType(), 6839 ParamType.getUnqualifiedType())); 6840 return RefExpr; 6841 } 6842 } 6843 6844 QualType T = VD->getType().getNonReferenceType(); 6845 6846 if (ParamType->isPointerType()) { 6847 // When the non-type template parameter is a pointer, take the 6848 // address of the declaration. 6849 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc); 6850 if (RefExpr.isInvalid()) 6851 return ExprError(); 6852 6853 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) && 6854 (T->isFunctionType() || T->isArrayType())) { 6855 // Decay functions and arrays unless we're forming a pointer to array. 6856 RefExpr = DefaultFunctionArrayConversion(RefExpr.get()); 6857 if (RefExpr.isInvalid()) 6858 return ExprError(); 6859 6860 return RefExpr; 6861 } 6862 6863 // Take the address of everything else 6864 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 6865 } 6866 6867 ExprValueKind VK = VK_RValue; 6868 6869 // If the non-type template parameter has reference type, qualify the 6870 // resulting declaration reference with the extra qualifiers on the 6871 // type that the reference refers to. 6872 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) { 6873 VK = VK_LValue; 6874 T = Context.getQualifiedType(T, 6875 TargetRef->getPointeeType().getQualifiers()); 6876 } else if (isa<FunctionDecl>(VD)) { 6877 // References to functions are always lvalues. 6878 VK = VK_LValue; 6879 } 6880 6881 return BuildDeclRefExpr(VD, T, VK, Loc); 6882 } 6883 6884 /// Construct a new expression that refers to the given 6885 /// integral template argument with the given source-location 6886 /// information. 6887 /// 6888 /// This routine takes care of the mapping from an integral template 6889 /// argument (which may have any integral type) to the appropriate 6890 /// literal value. 6891 ExprResult 6892 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 6893 SourceLocation Loc) { 6894 assert(Arg.getKind() == TemplateArgument::Integral && 6895 "Operation is only valid for integral template arguments"); 6896 QualType OrigT = Arg.getIntegralType(); 6897 6898 // If this is an enum type that we're instantiating, we need to use an integer 6899 // type the same size as the enumerator. We don't want to build an 6900 // IntegerLiteral with enum type. The integer type of an enum type can be of 6901 // any integral type with C++11 enum classes, make sure we create the right 6902 // type of literal for it. 6903 QualType T = OrigT; 6904 if (const EnumType *ET = OrigT->getAs<EnumType>()) 6905 T = ET->getDecl()->getIntegerType(); 6906 6907 Expr *E; 6908 if (T->isAnyCharacterType()) { 6909 CharacterLiteral::CharacterKind Kind; 6910 if (T->isWideCharType()) 6911 Kind = CharacterLiteral::Wide; 6912 else if (T->isChar8Type() && getLangOpts().Char8) 6913 Kind = CharacterLiteral::UTF8; 6914 else if (T->isChar16Type()) 6915 Kind = CharacterLiteral::UTF16; 6916 else if (T->isChar32Type()) 6917 Kind = CharacterLiteral::UTF32; 6918 else 6919 Kind = CharacterLiteral::Ascii; 6920 6921 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(), 6922 Kind, T, Loc); 6923 } else if (T->isBooleanType()) { 6924 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(), 6925 T, Loc); 6926 } else if (T->isNullPtrType()) { 6927 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 6928 } else { 6929 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc); 6930 } 6931 6932 if (OrigT->isEnumeralType()) { 6933 // FIXME: This is a hack. We need a better way to handle substituted 6934 // non-type template parameters. 6935 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E, 6936 nullptr, 6937 Context.getTrivialTypeSourceInfo(OrigT, Loc), 6938 Loc, Loc); 6939 } 6940 6941 return E; 6942 } 6943 6944 /// Match two template parameters within template parameter lists. 6945 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old, 6946 bool Complain, 6947 Sema::TemplateParameterListEqualKind Kind, 6948 SourceLocation TemplateArgLoc) { 6949 // Check the actual kind (type, non-type, template). 6950 if (Old->getKind() != New->getKind()) { 6951 if (Complain) { 6952 unsigned NextDiag = diag::err_template_param_different_kind; 6953 if (TemplateArgLoc.isValid()) { 6954 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 6955 NextDiag = diag::note_template_param_different_kind; 6956 } 6957 S.Diag(New->getLocation(), NextDiag) 6958 << (Kind != Sema::TPL_TemplateMatch); 6959 S.Diag(Old->getLocation(), diag::note_template_prev_declaration) 6960 << (Kind != Sema::TPL_TemplateMatch); 6961 } 6962 6963 return false; 6964 } 6965 6966 // Check that both are parameter packs or neither are parameter packs. 6967 // However, if we are matching a template template argument to a 6968 // template template parameter, the template template parameter can have 6969 // a parameter pack where the template template argument does not. 6970 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() && 6971 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch && 6972 Old->isTemplateParameterPack())) { 6973 if (Complain) { 6974 unsigned NextDiag = diag::err_template_parameter_pack_non_pack; 6975 if (TemplateArgLoc.isValid()) { 6976 S.Diag(TemplateArgLoc, 6977 diag::err_template_arg_template_params_mismatch); 6978 NextDiag = diag::note_template_parameter_pack_non_pack; 6979 } 6980 6981 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0 6982 : isa<NonTypeTemplateParmDecl>(New)? 1 6983 : 2; 6984 S.Diag(New->getLocation(), NextDiag) 6985 << ParamKind << New->isParameterPack(); 6986 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here) 6987 << ParamKind << Old->isParameterPack(); 6988 } 6989 6990 return false; 6991 } 6992 6993 // For non-type template parameters, check the type of the parameter. 6994 if (NonTypeTemplateParmDecl *OldNTTP 6995 = dyn_cast<NonTypeTemplateParmDecl>(Old)) { 6996 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New); 6997 6998 // If we are matching a template template argument to a template 6999 // template parameter and one of the non-type template parameter types 7000 // is dependent, then we must wait until template instantiation time 7001 // to actually compare the arguments. 7002 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch && 7003 (OldNTTP->getType()->isDependentType() || 7004 NewNTTP->getType()->isDependentType())) 7005 return true; 7006 7007 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) { 7008 if (Complain) { 7009 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 7010 if (TemplateArgLoc.isValid()) { 7011 S.Diag(TemplateArgLoc, 7012 diag::err_template_arg_template_params_mismatch); 7013 NextDiag = diag::note_template_nontype_parm_different_type; 7014 } 7015 S.Diag(NewNTTP->getLocation(), NextDiag) 7016 << NewNTTP->getType() 7017 << (Kind != Sema::TPL_TemplateMatch); 7018 S.Diag(OldNTTP->getLocation(), 7019 diag::note_template_nontype_parm_prev_declaration) 7020 << OldNTTP->getType(); 7021 } 7022 7023 return false; 7024 } 7025 7026 return true; 7027 } 7028 7029 // For template template parameters, check the template parameter types. 7030 // The template parameter lists of template template 7031 // parameters must agree. 7032 if (TemplateTemplateParmDecl *OldTTP 7033 = dyn_cast<TemplateTemplateParmDecl>(Old)) { 7034 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New); 7035 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 7036 OldTTP->getTemplateParameters(), 7037 Complain, 7038 (Kind == Sema::TPL_TemplateMatch 7039 ? Sema::TPL_TemplateTemplateParmMatch 7040 : Kind), 7041 TemplateArgLoc); 7042 } 7043 7044 return true; 7045 } 7046 7047 /// Diagnose a known arity mismatch when comparing template argument 7048 /// lists. 7049 static 7050 void DiagnoseTemplateParameterListArityMismatch(Sema &S, 7051 TemplateParameterList *New, 7052 TemplateParameterList *Old, 7053 Sema::TemplateParameterListEqualKind Kind, 7054 SourceLocation TemplateArgLoc) { 7055 unsigned NextDiag = diag::err_template_param_list_different_arity; 7056 if (TemplateArgLoc.isValid()) { 7057 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 7058 NextDiag = diag::note_template_param_list_different_arity; 7059 } 7060 S.Diag(New->getTemplateLoc(), NextDiag) 7061 << (New->size() > Old->size()) 7062 << (Kind != Sema::TPL_TemplateMatch) 7063 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 7064 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 7065 << (Kind != Sema::TPL_TemplateMatch) 7066 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 7067 } 7068 7069 /// Determine whether the given template parameter lists are 7070 /// equivalent. 7071 /// 7072 /// \param New The new template parameter list, typically written in the 7073 /// source code as part of a new template declaration. 7074 /// 7075 /// \param Old The old template parameter list, typically found via 7076 /// name lookup of the template declared with this template parameter 7077 /// list. 7078 /// 7079 /// \param Complain If true, this routine will produce a diagnostic if 7080 /// the template parameter lists are not equivalent. 7081 /// 7082 /// \param Kind describes how we are to match the template parameter lists. 7083 /// 7084 /// \param TemplateArgLoc If this source location is valid, then we 7085 /// are actually checking the template parameter list of a template 7086 /// argument (New) against the template parameter list of its 7087 /// corresponding template template parameter (Old). We produce 7088 /// slightly different diagnostics in this scenario. 7089 /// 7090 /// \returns True if the template parameter lists are equal, false 7091 /// otherwise. 7092 bool 7093 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 7094 TemplateParameterList *Old, 7095 bool Complain, 7096 TemplateParameterListEqualKind Kind, 7097 SourceLocation TemplateArgLoc) { 7098 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) { 7099 if (Complain) 7100 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 7101 TemplateArgLoc); 7102 7103 return false; 7104 } 7105 7106 // C++0x [temp.arg.template]p3: 7107 // A template-argument matches a template template-parameter (call it P) 7108 // when each of the template parameters in the template-parameter-list of 7109 // the template-argument's corresponding class template or alias template 7110 // (call it A) matches the corresponding template parameter in the 7111 // template-parameter-list of P. [...] 7112 TemplateParameterList::iterator NewParm = New->begin(); 7113 TemplateParameterList::iterator NewParmEnd = New->end(); 7114 for (TemplateParameterList::iterator OldParm = Old->begin(), 7115 OldParmEnd = Old->end(); 7116 OldParm != OldParmEnd; ++OldParm) { 7117 if (Kind != TPL_TemplateTemplateArgumentMatch || 7118 !(*OldParm)->isTemplateParameterPack()) { 7119 if (NewParm == NewParmEnd) { 7120 if (Complain) 7121 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 7122 TemplateArgLoc); 7123 7124 return false; 7125 } 7126 7127 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 7128 Kind, TemplateArgLoc)) 7129 return false; 7130 7131 ++NewParm; 7132 continue; 7133 } 7134 7135 // C++0x [temp.arg.template]p3: 7136 // [...] When P's template- parameter-list contains a template parameter 7137 // pack (14.5.3), the template parameter pack will match zero or more 7138 // template parameters or template parameter packs in the 7139 // template-parameter-list of A with the same type and form as the 7140 // template parameter pack in P (ignoring whether those template 7141 // parameters are template parameter packs). 7142 for (; NewParm != NewParmEnd; ++NewParm) { 7143 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 7144 Kind, TemplateArgLoc)) 7145 return false; 7146 } 7147 } 7148 7149 // Make sure we exhausted all of the arguments. 7150 if (NewParm != NewParmEnd) { 7151 if (Complain) 7152 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 7153 TemplateArgLoc); 7154 7155 return false; 7156 } 7157 7158 return true; 7159 } 7160 7161 /// Check whether a template can be declared within this scope. 7162 /// 7163 /// If the template declaration is valid in this scope, returns 7164 /// false. Otherwise, issues a diagnostic and returns true. 7165 bool 7166 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 7167 if (!S) 7168 return false; 7169 7170 // Find the nearest enclosing declaration scope. 7171 while ((S->getFlags() & Scope::DeclScope) == 0 || 7172 (S->getFlags() & Scope::TemplateParamScope) != 0) 7173 S = S->getParent(); 7174 7175 // C++ [temp]p4: 7176 // A template [...] shall not have C linkage. 7177 DeclContext *Ctx = S->getEntity(); 7178 if (Ctx && Ctx->isExternCContext()) { 7179 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 7180 << TemplateParams->getSourceRange(); 7181 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext()) 7182 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 7183 return true; 7184 } 7185 Ctx = Ctx->getRedeclContext(); 7186 7187 // C++ [temp]p2: 7188 // A template-declaration can appear only as a namespace scope or 7189 // class scope declaration. 7190 if (Ctx) { 7191 if (Ctx->isFileContext()) 7192 return false; 7193 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) { 7194 // C++ [temp.mem]p2: 7195 // A local class shall not have member templates. 7196 if (RD->isLocalClass()) 7197 return Diag(TemplateParams->getTemplateLoc(), 7198 diag::err_template_inside_local_class) 7199 << TemplateParams->getSourceRange(); 7200 else 7201 return false; 7202 } 7203 } 7204 7205 return Diag(TemplateParams->getTemplateLoc(), 7206 diag::err_template_outside_namespace_or_class_scope) 7207 << TemplateParams->getSourceRange(); 7208 } 7209 7210 /// Determine what kind of template specialization the given declaration 7211 /// is. 7212 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) { 7213 if (!D) 7214 return TSK_Undeclared; 7215 7216 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 7217 return Record->getTemplateSpecializationKind(); 7218 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 7219 return Function->getTemplateSpecializationKind(); 7220 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 7221 return Var->getTemplateSpecializationKind(); 7222 7223 return TSK_Undeclared; 7224 } 7225 7226 /// Check whether a specialization is well-formed in the current 7227 /// context. 7228 /// 7229 /// This routine determines whether a template specialization can be declared 7230 /// in the current context (C++ [temp.expl.spec]p2). 7231 /// 7232 /// \param S the semantic analysis object for which this check is being 7233 /// performed. 7234 /// 7235 /// \param Specialized the entity being specialized or instantiated, which 7236 /// may be a kind of template (class template, function template, etc.) or 7237 /// a member of a class template (member function, static data member, 7238 /// member class). 7239 /// 7240 /// \param PrevDecl the previous declaration of this entity, if any. 7241 /// 7242 /// \param Loc the location of the explicit specialization or instantiation of 7243 /// this entity. 7244 /// 7245 /// \param IsPartialSpecialization whether this is a partial specialization of 7246 /// a class template. 7247 /// 7248 /// \returns true if there was an error that we cannot recover from, false 7249 /// otherwise. 7250 static bool CheckTemplateSpecializationScope(Sema &S, 7251 NamedDecl *Specialized, 7252 NamedDecl *PrevDecl, 7253 SourceLocation Loc, 7254 bool IsPartialSpecialization) { 7255 // Keep these "kind" numbers in sync with the %select statements in the 7256 // various diagnostics emitted by this routine. 7257 int EntityKind = 0; 7258 if (isa<ClassTemplateDecl>(Specialized)) 7259 EntityKind = IsPartialSpecialization? 1 : 0; 7260 else if (isa<VarTemplateDecl>(Specialized)) 7261 EntityKind = IsPartialSpecialization ? 3 : 2; 7262 else if (isa<FunctionTemplateDecl>(Specialized)) 7263 EntityKind = 4; 7264 else if (isa<CXXMethodDecl>(Specialized)) 7265 EntityKind = 5; 7266 else if (isa<VarDecl>(Specialized)) 7267 EntityKind = 6; 7268 else if (isa<RecordDecl>(Specialized)) 7269 EntityKind = 7; 7270 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11) 7271 EntityKind = 8; 7272 else { 7273 S.Diag(Loc, diag::err_template_spec_unknown_kind) 7274 << S.getLangOpts().CPlusPlus11; 7275 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 7276 return true; 7277 } 7278 7279 // C++ [temp.expl.spec]p2: 7280 // An explicit specialization may be declared in any scope in which 7281 // the corresponding primary template may be defined. 7282 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7283 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 7284 << Specialized; 7285 return true; 7286 } 7287 7288 // C++ [temp.class.spec]p6: 7289 // A class template partial specialization may be declared in any 7290 // scope in which the primary template may be defined. 7291 DeclContext *SpecializedContext = 7292 Specialized->getDeclContext()->getRedeclContext(); 7293 DeclContext *DC = S.CurContext->getRedeclContext(); 7294 7295 // Make sure that this redeclaration (or definition) occurs in the same 7296 // scope or an enclosing namespace. 7297 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext) 7298 : DC->Equals(SpecializedContext))) { 7299 if (isa<TranslationUnitDecl>(SpecializedContext)) 7300 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 7301 << EntityKind << Specialized; 7302 else { 7303 auto *ND = cast<NamedDecl>(SpecializedContext); 7304 int Diag = diag::err_template_spec_redecl_out_of_scope; 7305 if (S.getLangOpts().MicrosoftExt && !DC->isRecord()) 7306 Diag = diag::ext_ms_template_spec_redecl_out_of_scope; 7307 S.Diag(Loc, Diag) << EntityKind << Specialized 7308 << ND << isa<CXXRecordDecl>(ND); 7309 } 7310 7311 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 7312 7313 // Don't allow specializing in the wrong class during error recovery. 7314 // Otherwise, things can go horribly wrong. 7315 if (DC->isRecord()) 7316 return true; 7317 } 7318 7319 return false; 7320 } 7321 7322 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) { 7323 if (!E->isTypeDependent()) 7324 return SourceLocation(); 7325 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); 7326 Checker.TraverseStmt(E); 7327 if (Checker.MatchLoc.isInvalid()) 7328 return E->getSourceRange(); 7329 return Checker.MatchLoc; 7330 } 7331 7332 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) { 7333 if (!TL.getType()->isDependentType()) 7334 return SourceLocation(); 7335 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); 7336 Checker.TraverseTypeLoc(TL); 7337 if (Checker.MatchLoc.isInvalid()) 7338 return TL.getSourceRange(); 7339 return Checker.MatchLoc; 7340 } 7341 7342 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs 7343 /// that checks non-type template partial specialization arguments. 7344 static bool CheckNonTypeTemplatePartialSpecializationArgs( 7345 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, 7346 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) { 7347 for (unsigned I = 0; I != NumArgs; ++I) { 7348 if (Args[I].getKind() == TemplateArgument::Pack) { 7349 if (CheckNonTypeTemplatePartialSpecializationArgs( 7350 S, TemplateNameLoc, Param, Args[I].pack_begin(), 7351 Args[I].pack_size(), IsDefaultArgument)) 7352 return true; 7353 7354 continue; 7355 } 7356 7357 if (Args[I].getKind() != TemplateArgument::Expression) 7358 continue; 7359 7360 Expr *ArgExpr = Args[I].getAsExpr(); 7361 7362 // We can have a pack expansion of any of the bullets below. 7363 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr)) 7364 ArgExpr = Expansion->getPattern(); 7365 7366 // Strip off any implicit casts we added as part of type checking. 7367 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 7368 ArgExpr = ICE->getSubExpr(); 7369 7370 // C++ [temp.class.spec]p8: 7371 // A non-type argument is non-specialized if it is the name of a 7372 // non-type parameter. All other non-type arguments are 7373 // specialized. 7374 // 7375 // Below, we check the two conditions that only apply to 7376 // specialized non-type arguments, so skip any non-specialized 7377 // arguments. 7378 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 7379 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl())) 7380 continue; 7381 7382 // C++ [temp.class.spec]p9: 7383 // Within the argument list of a class template partial 7384 // specialization, the following restrictions apply: 7385 // -- A partially specialized non-type argument expression 7386 // shall not involve a template parameter of the partial 7387 // specialization except when the argument expression is a 7388 // simple identifier. 7389 // -- The type of a template parameter corresponding to a 7390 // specialized non-type argument shall not be dependent on a 7391 // parameter of the specialization. 7392 // DR1315 removes the first bullet, leaving an incoherent set of rules. 7393 // We implement a compromise between the original rules and DR1315: 7394 // -- A specialized non-type template argument shall not be 7395 // type-dependent and the corresponding template parameter 7396 // shall have a non-dependent type. 7397 SourceRange ParamUseRange = 7398 findTemplateParameterInType(Param->getDepth(), ArgExpr); 7399 if (ParamUseRange.isValid()) { 7400 if (IsDefaultArgument) { 7401 S.Diag(TemplateNameLoc, 7402 diag::err_dependent_non_type_arg_in_partial_spec); 7403 S.Diag(ParamUseRange.getBegin(), 7404 diag::note_dependent_non_type_default_arg_in_partial_spec) 7405 << ParamUseRange; 7406 } else { 7407 S.Diag(ParamUseRange.getBegin(), 7408 diag::err_dependent_non_type_arg_in_partial_spec) 7409 << ParamUseRange; 7410 } 7411 return true; 7412 } 7413 7414 ParamUseRange = findTemplateParameter( 7415 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc()); 7416 if (ParamUseRange.isValid()) { 7417 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(), 7418 diag::err_dependent_typed_non_type_arg_in_partial_spec) 7419 << Param->getType(); 7420 S.Diag(Param->getLocation(), diag::note_template_param_here) 7421 << (IsDefaultArgument ? ParamUseRange : SourceRange()) 7422 << ParamUseRange; 7423 return true; 7424 } 7425 } 7426 7427 return false; 7428 } 7429 7430 /// Check the non-type template arguments of a class template 7431 /// partial specialization according to C++ [temp.class.spec]p9. 7432 /// 7433 /// \param TemplateNameLoc the location of the template name. 7434 /// \param PrimaryTemplate the template parameters of the primary class 7435 /// template. 7436 /// \param NumExplicit the number of explicitly-specified template arguments. 7437 /// \param TemplateArgs the template arguments of the class template 7438 /// partial specialization. 7439 /// 7440 /// \returns \c true if there was an error, \c false otherwise. 7441 bool Sema::CheckTemplatePartialSpecializationArgs( 7442 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate, 7443 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) { 7444 // We have to be conservative when checking a template in a dependent 7445 // context. 7446 if (PrimaryTemplate->getDeclContext()->isDependentContext()) 7447 return false; 7448 7449 TemplateParameterList *TemplateParams = 7450 PrimaryTemplate->getTemplateParameters(); 7451 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 7452 NonTypeTemplateParmDecl *Param 7453 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 7454 if (!Param) 7455 continue; 7456 7457 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc, 7458 Param, &TemplateArgs[I], 7459 1, I >= NumExplicit)) 7460 return true; 7461 } 7462 7463 return false; 7464 } 7465 7466 DeclResult Sema::ActOnClassTemplateSpecialization( 7467 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 7468 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, 7469 const ParsedAttributesView &Attr, 7470 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) { 7471 assert(TUK != TUK_Reference && "References are not specializations"); 7472 7473 CXXScopeSpec &SS = TemplateId.SS; 7474 7475 // NOTE: KWLoc is the location of the tag keyword. This will instead 7476 // store the location of the outermost template keyword in the declaration. 7477 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0 7478 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc; 7479 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc; 7480 SourceLocation LAngleLoc = TemplateId.LAngleLoc; 7481 SourceLocation RAngleLoc = TemplateId.RAngleLoc; 7482 7483 // Find the class template we're specializing 7484 TemplateName Name = TemplateId.Template.get(); 7485 ClassTemplateDecl *ClassTemplate 7486 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); 7487 7488 if (!ClassTemplate) { 7489 Diag(TemplateNameLoc, diag::err_not_class_template_specialization) 7490 << (Name.getAsTemplateDecl() && 7491 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); 7492 return true; 7493 } 7494 7495 bool isMemberSpecialization = false; 7496 bool isPartialSpecialization = false; 7497 7498 // Check the validity of the template headers that introduce this 7499 // template. 7500 // FIXME: We probably shouldn't complain about these headers for 7501 // friend declarations. 7502 bool Invalid = false; 7503 TemplateParameterList *TemplateParams = 7504 MatchTemplateParametersToScopeSpecifier( 7505 KWLoc, TemplateNameLoc, SS, &TemplateId, 7506 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization, 7507 Invalid); 7508 if (Invalid) 7509 return true; 7510 7511 if (TemplateParams && TemplateParams->size() > 0) { 7512 isPartialSpecialization = true; 7513 7514 if (TUK == TUK_Friend) { 7515 Diag(KWLoc, diag::err_partial_specialization_friend) 7516 << SourceRange(LAngleLoc, RAngleLoc); 7517 return true; 7518 } 7519 7520 // C++ [temp.class.spec]p10: 7521 // The template parameter list of a specialization shall not 7522 // contain default template argument values. 7523 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 7524 Decl *Param = TemplateParams->getParam(I); 7525 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 7526 if (TTP->hasDefaultArgument()) { 7527 Diag(TTP->getDefaultArgumentLoc(), 7528 diag::err_default_arg_in_partial_spec); 7529 TTP->removeDefaultArgument(); 7530 } 7531 } else if (NonTypeTemplateParmDecl *NTTP 7532 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 7533 if (Expr *DefArg = NTTP->getDefaultArgument()) { 7534 Diag(NTTP->getDefaultArgumentLoc(), 7535 diag::err_default_arg_in_partial_spec) 7536 << DefArg->getSourceRange(); 7537 NTTP->removeDefaultArgument(); 7538 } 7539 } else { 7540 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 7541 if (TTP->hasDefaultArgument()) { 7542 Diag(TTP->getDefaultArgument().getLocation(), 7543 diag::err_default_arg_in_partial_spec) 7544 << TTP->getDefaultArgument().getSourceRange(); 7545 TTP->removeDefaultArgument(); 7546 } 7547 } 7548 } 7549 } else if (TemplateParams) { 7550 if (TUK == TUK_Friend) 7551 Diag(KWLoc, diag::err_template_spec_friend) 7552 << FixItHint::CreateRemoval( 7553 SourceRange(TemplateParams->getTemplateLoc(), 7554 TemplateParams->getRAngleLoc())) 7555 << SourceRange(LAngleLoc, RAngleLoc); 7556 } else { 7557 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl"); 7558 } 7559 7560 // Check that the specialization uses the same tag kind as the 7561 // original template. 7562 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 7563 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!"); 7564 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 7565 Kind, TUK == TUK_Definition, KWLoc, 7566 ClassTemplate->getIdentifier())) { 7567 Diag(KWLoc, diag::err_use_with_wrong_tag) 7568 << ClassTemplate 7569 << FixItHint::CreateReplacement(KWLoc, 7570 ClassTemplate->getTemplatedDecl()->getKindName()); 7571 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 7572 diag::note_previous_use); 7573 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 7574 } 7575 7576 // Translate the parser's template argument list in our AST format. 7577 TemplateArgumentListInfo TemplateArgs = 7578 makeTemplateArgumentListInfo(*this, TemplateId); 7579 7580 // Check for unexpanded parameter packs in any of the template arguments. 7581 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 7582 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 7583 UPPC_PartialSpecialization)) 7584 return true; 7585 7586 // Check that the template argument list is well-formed for this 7587 // template. 7588 SmallVector<TemplateArgument, 4> Converted; 7589 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 7590 TemplateArgs, false, Converted)) 7591 return true; 7592 7593 // Find the class template (partial) specialization declaration that 7594 // corresponds to these arguments. 7595 if (isPartialSpecialization) { 7596 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate, 7597 TemplateArgs.size(), Converted)) 7598 return true; 7599 7600 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we 7601 // also do it during instantiation. 7602 bool InstantiationDependent; 7603 if (!Name.isDependent() && 7604 !TemplateSpecializationType::anyDependentTemplateArguments( 7605 TemplateArgs.arguments(), InstantiationDependent)) { 7606 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 7607 << ClassTemplate->getDeclName(); 7608 isPartialSpecialization = false; 7609 } 7610 } 7611 7612 void *InsertPos = nullptr; 7613 ClassTemplateSpecializationDecl *PrevDecl = nullptr; 7614 7615 if (isPartialSpecialization) 7616 // FIXME: Template parameter list matters, too 7617 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos); 7618 else 7619 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos); 7620 7621 ClassTemplateSpecializationDecl *Specialization = nullptr; 7622 7623 // Check whether we can declare a class template specialization in 7624 // the current scope. 7625 if (TUK != TUK_Friend && 7626 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 7627 TemplateNameLoc, 7628 isPartialSpecialization)) 7629 return true; 7630 7631 // The canonical type 7632 QualType CanonType; 7633 if (isPartialSpecialization) { 7634 // Build the canonical type that describes the converted template 7635 // arguments of the class template partial specialization. 7636 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 7637 CanonType = Context.getTemplateSpecializationType(CanonTemplate, 7638 Converted); 7639 7640 if (Context.hasSameType(CanonType, 7641 ClassTemplate->getInjectedClassNameSpecialization())) { 7642 // C++ [temp.class.spec]p9b3: 7643 // 7644 // -- The argument list of the specialization shall not be identical 7645 // to the implicit argument list of the primary template. 7646 // 7647 // This rule has since been removed, because it's redundant given DR1495, 7648 // but we keep it because it produces better diagnostics and recovery. 7649 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 7650 << /*class template*/0 << (TUK == TUK_Definition) 7651 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 7652 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 7653 ClassTemplate->getIdentifier(), 7654 TemplateNameLoc, 7655 Attr, 7656 TemplateParams, 7657 AS_none, /*ModulePrivateLoc=*/SourceLocation(), 7658 /*FriendLoc*/SourceLocation(), 7659 TemplateParameterLists.size() - 1, 7660 TemplateParameterLists.data()); 7661 } 7662 7663 // Create a new class template partial specialization declaration node. 7664 ClassTemplatePartialSpecializationDecl *PrevPartial 7665 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 7666 ClassTemplatePartialSpecializationDecl *Partial 7667 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind, 7668 ClassTemplate->getDeclContext(), 7669 KWLoc, TemplateNameLoc, 7670 TemplateParams, 7671 ClassTemplate, 7672 Converted, 7673 TemplateArgs, 7674 CanonType, 7675 PrevPartial); 7676 SetNestedNameSpecifier(*this, Partial, SS); 7677 if (TemplateParameterLists.size() > 1 && SS.isSet()) { 7678 Partial->setTemplateParameterListsInfo( 7679 Context, TemplateParameterLists.drop_back(1)); 7680 } 7681 7682 if (!PrevPartial) 7683 ClassTemplate->AddPartialSpecialization(Partial, InsertPos); 7684 Specialization = Partial; 7685 7686 // If we are providing an explicit specialization of a member class 7687 // template specialization, make a note of that. 7688 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 7689 PrevPartial->setMemberSpecialization(); 7690 7691 CheckTemplatePartialSpecialization(Partial); 7692 } else { 7693 // Create a new class template specialization declaration node for 7694 // this explicit specialization or friend declaration. 7695 Specialization 7696 = ClassTemplateSpecializationDecl::Create(Context, Kind, 7697 ClassTemplate->getDeclContext(), 7698 KWLoc, TemplateNameLoc, 7699 ClassTemplate, 7700 Converted, 7701 PrevDecl); 7702 SetNestedNameSpecifier(*this, Specialization, SS); 7703 if (TemplateParameterLists.size() > 0) { 7704 Specialization->setTemplateParameterListsInfo(Context, 7705 TemplateParameterLists); 7706 } 7707 7708 if (!PrevDecl) 7709 ClassTemplate->AddSpecialization(Specialization, InsertPos); 7710 7711 if (CurContext->isDependentContext()) { 7712 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 7713 CanonType = Context.getTemplateSpecializationType( 7714 CanonTemplate, Converted); 7715 } else { 7716 CanonType = Context.getTypeDeclType(Specialization); 7717 } 7718 } 7719 7720 // C++ [temp.expl.spec]p6: 7721 // If a template, a member template or the member of a class template is 7722 // explicitly specialized then that specialization shall be declared 7723 // before the first use of that specialization that would cause an implicit 7724 // instantiation to take place, in every translation unit in which such a 7725 // use occurs; no diagnostic is required. 7726 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 7727 bool Okay = false; 7728 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 7729 // Is there any previous explicit specialization declaration? 7730 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 7731 Okay = true; 7732 break; 7733 } 7734 } 7735 7736 if (!Okay) { 7737 SourceRange Range(TemplateNameLoc, RAngleLoc); 7738 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 7739 << Context.getTypeDeclType(Specialization) << Range; 7740 7741 Diag(PrevDecl->getPointOfInstantiation(), 7742 diag::note_instantiation_required_here) 7743 << (PrevDecl->getTemplateSpecializationKind() 7744 != TSK_ImplicitInstantiation); 7745 return true; 7746 } 7747 } 7748 7749 // If this is not a friend, note that this is an explicit specialization. 7750 if (TUK != TUK_Friend) 7751 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 7752 7753 // Check that this isn't a redefinition of this specialization. 7754 if (TUK == TUK_Definition) { 7755 RecordDecl *Def = Specialization->getDefinition(); 7756 NamedDecl *Hidden = nullptr; 7757 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 7758 SkipBody->ShouldSkip = true; 7759 SkipBody->Previous = Def; 7760 makeMergedDefinitionVisible(Hidden); 7761 } else if (Def) { 7762 SourceRange Range(TemplateNameLoc, RAngleLoc); 7763 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range; 7764 Diag(Def->getLocation(), diag::note_previous_definition); 7765 Specialization->setInvalidDecl(); 7766 return true; 7767 } 7768 } 7769 7770 ProcessDeclAttributeList(S, Specialization, Attr); 7771 7772 // Add alignment attributes if necessary; these attributes are checked when 7773 // the ASTContext lays out the structure. 7774 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 7775 AddAlignmentAttributesForRecord(Specialization); 7776 AddMsStructLayoutForRecord(Specialization); 7777 } 7778 7779 if (ModulePrivateLoc.isValid()) 7780 Diag(Specialization->getLocation(), diag::err_module_private_specialization) 7781 << (isPartialSpecialization? 1 : 0) 7782 << FixItHint::CreateRemoval(ModulePrivateLoc); 7783 7784 // Build the fully-sugared type for this class template 7785 // specialization as the user wrote in the specialization 7786 // itself. This means that we'll pretty-print the type retrieved 7787 // from the specialization's declaration the way that the user 7788 // actually wrote the specialization, rather than formatting the 7789 // name based on the "canonical" representation used to store the 7790 // template arguments in the specialization. 7791 TypeSourceInfo *WrittenTy 7792 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 7793 TemplateArgs, CanonType); 7794 if (TUK != TUK_Friend) { 7795 Specialization->setTypeAsWritten(WrittenTy); 7796 Specialization->setTemplateKeywordLoc(TemplateKWLoc); 7797 } 7798 7799 // C++ [temp.expl.spec]p9: 7800 // A template explicit specialization is in the scope of the 7801 // namespace in which the template was defined. 7802 // 7803 // We actually implement this paragraph where we set the semantic 7804 // context (in the creation of the ClassTemplateSpecializationDecl), 7805 // but we also maintain the lexical context where the actual 7806 // definition occurs. 7807 Specialization->setLexicalDeclContext(CurContext); 7808 7809 // We may be starting the definition of this specialization. 7810 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 7811 Specialization->startDefinition(); 7812 7813 if (TUK == TUK_Friend) { 7814 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 7815 TemplateNameLoc, 7816 WrittenTy, 7817 /*FIXME:*/KWLoc); 7818 Friend->setAccess(AS_public); 7819 CurContext->addDecl(Friend); 7820 } else { 7821 // Add the specialization into its lexical context, so that it can 7822 // be seen when iterating through the list of declarations in that 7823 // context. However, specializations are not found by name lookup. 7824 CurContext->addDecl(Specialization); 7825 } 7826 7827 if (SkipBody && SkipBody->ShouldSkip) 7828 return SkipBody->Previous; 7829 7830 return Specialization; 7831 } 7832 7833 Decl *Sema::ActOnTemplateDeclarator(Scope *S, 7834 MultiTemplateParamsArg TemplateParameterLists, 7835 Declarator &D) { 7836 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists); 7837 ActOnDocumentableDecl(NewDecl); 7838 return NewDecl; 7839 } 7840 7841 /// Strips various properties off an implicit instantiation 7842 /// that has just been explicitly specialized. 7843 static void StripImplicitInstantiation(NamedDecl *D) { 7844 D->dropAttr<DLLImportAttr>(); 7845 D->dropAttr<DLLExportAttr>(); 7846 7847 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 7848 FD->setInlineSpecified(false); 7849 } 7850 7851 /// Compute the diagnostic location for an explicit instantiation 7852 // declaration or definition. 7853 static SourceLocation DiagLocForExplicitInstantiation( 7854 NamedDecl* D, SourceLocation PointOfInstantiation) { 7855 // Explicit instantiations following a specialization have no effect and 7856 // hence no PointOfInstantiation. In that case, walk decl backwards 7857 // until a valid name loc is found. 7858 SourceLocation PrevDiagLoc = PointOfInstantiation; 7859 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid(); 7860 Prev = Prev->getPreviousDecl()) { 7861 PrevDiagLoc = Prev->getLocation(); 7862 } 7863 assert(PrevDiagLoc.isValid() && 7864 "Explicit instantiation without point of instantiation?"); 7865 return PrevDiagLoc; 7866 } 7867 7868 /// Diagnose cases where we have an explicit template specialization 7869 /// before/after an explicit template instantiation, producing diagnostics 7870 /// for those cases where they are required and determining whether the 7871 /// new specialization/instantiation will have any effect. 7872 /// 7873 /// \param NewLoc the location of the new explicit specialization or 7874 /// instantiation. 7875 /// 7876 /// \param NewTSK the kind of the new explicit specialization or instantiation. 7877 /// 7878 /// \param PrevDecl the previous declaration of the entity. 7879 /// 7880 /// \param PrevTSK the kind of the old explicit specialization or instantiatin. 7881 /// 7882 /// \param PrevPointOfInstantiation if valid, indicates where the previus 7883 /// declaration was instantiated (either implicitly or explicitly). 7884 /// 7885 /// \param HasNoEffect will be set to true to indicate that the new 7886 /// specialization or instantiation has no effect and should be ignored. 7887 /// 7888 /// \returns true if there was an error that should prevent the introduction of 7889 /// the new declaration into the AST, false otherwise. 7890 bool 7891 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 7892 TemplateSpecializationKind NewTSK, 7893 NamedDecl *PrevDecl, 7894 TemplateSpecializationKind PrevTSK, 7895 SourceLocation PrevPointOfInstantiation, 7896 bool &HasNoEffect) { 7897 HasNoEffect = false; 7898 7899 switch (NewTSK) { 7900 case TSK_Undeclared: 7901 case TSK_ImplicitInstantiation: 7902 assert( 7903 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && 7904 "previous declaration must be implicit!"); 7905 return false; 7906 7907 case TSK_ExplicitSpecialization: 7908 switch (PrevTSK) { 7909 case TSK_Undeclared: 7910 case TSK_ExplicitSpecialization: 7911 // Okay, we're just specializing something that is either already 7912 // explicitly specialized or has merely been mentioned without any 7913 // instantiation. 7914 return false; 7915 7916 case TSK_ImplicitInstantiation: 7917 if (PrevPointOfInstantiation.isInvalid()) { 7918 // The declaration itself has not actually been instantiated, so it is 7919 // still okay to specialize it. 7920 StripImplicitInstantiation(PrevDecl); 7921 return false; 7922 } 7923 // Fall through 7924 LLVM_FALLTHROUGH; 7925 7926 case TSK_ExplicitInstantiationDeclaration: 7927 case TSK_ExplicitInstantiationDefinition: 7928 assert((PrevTSK == TSK_ImplicitInstantiation || 7929 PrevPointOfInstantiation.isValid()) && 7930 "Explicit instantiation without point of instantiation?"); 7931 7932 // C++ [temp.expl.spec]p6: 7933 // If a template, a member template or the member of a class template 7934 // is explicitly specialized then that specialization shall be declared 7935 // before the first use of that specialization that would cause an 7936 // implicit instantiation to take place, in every translation unit in 7937 // which such a use occurs; no diagnostic is required. 7938 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 7939 // Is there any previous explicit specialization declaration? 7940 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) 7941 return false; 7942 } 7943 7944 Diag(NewLoc, diag::err_specialization_after_instantiation) 7945 << PrevDecl; 7946 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) 7947 << (PrevTSK != TSK_ImplicitInstantiation); 7948 7949 return true; 7950 } 7951 llvm_unreachable("The switch over PrevTSK must be exhaustive."); 7952 7953 case TSK_ExplicitInstantiationDeclaration: 7954 switch (PrevTSK) { 7955 case TSK_ExplicitInstantiationDeclaration: 7956 // This explicit instantiation declaration is redundant (that's okay). 7957 HasNoEffect = true; 7958 return false; 7959 7960 case TSK_Undeclared: 7961 case TSK_ImplicitInstantiation: 7962 // We're explicitly instantiating something that may have already been 7963 // implicitly instantiated; that's fine. 7964 return false; 7965 7966 case TSK_ExplicitSpecialization: 7967 // C++0x [temp.explicit]p4: 7968 // For a given set of template parameters, if an explicit instantiation 7969 // of a template appears after a declaration of an explicit 7970 // specialization for that template, the explicit instantiation has no 7971 // effect. 7972 HasNoEffect = true; 7973 return false; 7974 7975 case TSK_ExplicitInstantiationDefinition: 7976 // C++0x [temp.explicit]p10: 7977 // If an entity is the subject of both an explicit instantiation 7978 // declaration and an explicit instantiation definition in the same 7979 // translation unit, the definition shall follow the declaration. 7980 Diag(NewLoc, 7981 diag::err_explicit_instantiation_declaration_after_definition); 7982 7983 // Explicit instantiations following a specialization have no effect and 7984 // hence no PrevPointOfInstantiation. In that case, walk decl backwards 7985 // until a valid name loc is found. 7986 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), 7987 diag::note_explicit_instantiation_definition_here); 7988 HasNoEffect = true; 7989 return false; 7990 } 7991 llvm_unreachable("Unexpected TemplateSpecializationKind!"); 7992 7993 case TSK_ExplicitInstantiationDefinition: 7994 switch (PrevTSK) { 7995 case TSK_Undeclared: 7996 case TSK_ImplicitInstantiation: 7997 // We're explicitly instantiating something that may have already been 7998 // implicitly instantiated; that's fine. 7999 return false; 8000 8001 case TSK_ExplicitSpecialization: 8002 // C++ DR 259, C++0x [temp.explicit]p4: 8003 // For a given set of template parameters, if an explicit 8004 // instantiation of a template appears after a declaration of 8005 // an explicit specialization for that template, the explicit 8006 // instantiation has no effect. 8007 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization) 8008 << PrevDecl; 8009 Diag(PrevDecl->getLocation(), 8010 diag::note_previous_template_specialization); 8011 HasNoEffect = true; 8012 return false; 8013 8014 case TSK_ExplicitInstantiationDeclaration: 8015 // We're explicitly instantiating a definition for something for which we 8016 // were previously asked to suppress instantiations. That's fine. 8017 8018 // C++0x [temp.explicit]p4: 8019 // For a given set of template parameters, if an explicit instantiation 8020 // of a template appears after a declaration of an explicit 8021 // specialization for that template, the explicit instantiation has no 8022 // effect. 8023 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 8024 // Is there any previous explicit specialization declaration? 8025 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 8026 HasNoEffect = true; 8027 break; 8028 } 8029 } 8030 8031 return false; 8032 8033 case TSK_ExplicitInstantiationDefinition: 8034 // C++0x [temp.spec]p5: 8035 // For a given template and a given set of template-arguments, 8036 // - an explicit instantiation definition shall appear at most once 8037 // in a program, 8038 8039 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations. 8040 Diag(NewLoc, (getLangOpts().MSVCCompat) 8041 ? diag::ext_explicit_instantiation_duplicate 8042 : diag::err_explicit_instantiation_duplicate) 8043 << PrevDecl; 8044 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), 8045 diag::note_previous_explicit_instantiation); 8046 HasNoEffect = true; 8047 return false; 8048 } 8049 } 8050 8051 llvm_unreachable("Missing specialization/instantiation case?"); 8052 } 8053 8054 /// Perform semantic analysis for the given dependent function 8055 /// template specialization. 8056 /// 8057 /// The only possible way to get a dependent function template specialization 8058 /// is with a friend declaration, like so: 8059 /// 8060 /// \code 8061 /// template \<class T> void foo(T); 8062 /// template \<class T> class A { 8063 /// friend void foo<>(T); 8064 /// }; 8065 /// \endcode 8066 /// 8067 /// There really isn't any useful analysis we can do here, so we 8068 /// just store the information. 8069 bool 8070 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 8071 const TemplateArgumentListInfo &ExplicitTemplateArgs, 8072 LookupResult &Previous) { 8073 // Remove anything from Previous that isn't a function template in 8074 // the correct context. 8075 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 8076 LookupResult::Filter F = Previous.makeFilter(); 8077 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing }; 8078 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates; 8079 while (F.hasNext()) { 8080 NamedDecl *D = F.next()->getUnderlyingDecl(); 8081 if (!isa<FunctionTemplateDecl>(D)) { 8082 F.erase(); 8083 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D)); 8084 continue; 8085 } 8086 8087 if (!FDLookupContext->InEnclosingNamespaceSetOf( 8088 D->getDeclContext()->getRedeclContext())) { 8089 F.erase(); 8090 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D)); 8091 continue; 8092 } 8093 } 8094 F.done(); 8095 8096 if (Previous.empty()) { 8097 Diag(FD->getLocation(), 8098 diag::err_dependent_function_template_spec_no_match); 8099 for (auto &P : DiscardedCandidates) 8100 Diag(P.second->getLocation(), 8101 diag::note_dependent_function_template_spec_discard_reason) 8102 << P.first; 8103 return true; 8104 } 8105 8106 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(), 8107 ExplicitTemplateArgs); 8108 return false; 8109 } 8110 8111 /// Perform semantic analysis for the given function template 8112 /// specialization. 8113 /// 8114 /// This routine performs all of the semantic analysis required for an 8115 /// explicit function template specialization. On successful completion, 8116 /// the function declaration \p FD will become a function template 8117 /// specialization. 8118 /// 8119 /// \param FD the function declaration, which will be updated to become a 8120 /// function template specialization. 8121 /// 8122 /// \param ExplicitTemplateArgs the explicitly-provided template arguments, 8123 /// if any. Note that this may be valid info even when 0 arguments are 8124 /// explicitly provided as in, e.g., \c void sort<>(char*, char*); 8125 /// as it anyway contains info on the angle brackets locations. 8126 /// 8127 /// \param Previous the set of declarations that may be specialized by 8128 /// this function specialization. 8129 /// 8130 /// \param QualifiedFriend whether this is a lookup for a qualified friend 8131 /// declaration with no explicit template argument list that might be 8132 /// befriending a function template specialization. 8133 bool Sema::CheckFunctionTemplateSpecialization( 8134 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, 8135 LookupResult &Previous, bool QualifiedFriend) { 8136 // The set of function template specializations that could match this 8137 // explicit function template specialization. 8138 UnresolvedSet<8> Candidates; 8139 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(), 8140 /*ForTakingAddress=*/false); 8141 8142 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8> 8143 ConvertedTemplateArgs; 8144 8145 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 8146 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8147 I != E; ++I) { 8148 NamedDecl *Ovl = (*I)->getUnderlyingDecl(); 8149 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { 8150 // Only consider templates found within the same semantic lookup scope as 8151 // FD. 8152 if (!FDLookupContext->InEnclosingNamespaceSetOf( 8153 Ovl->getDeclContext()->getRedeclContext())) 8154 continue; 8155 8156 // When matching a constexpr member function template specialization 8157 // against the primary template, we don't yet know whether the 8158 // specialization has an implicit 'const' (because we don't know whether 8159 // it will be a static member function until we know which template it 8160 // specializes), so adjust it now assuming it specializes this template. 8161 QualType FT = FD->getType(); 8162 if (FD->isConstexpr()) { 8163 CXXMethodDecl *OldMD = 8164 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 8165 if (OldMD && OldMD->isConst()) { 8166 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>(); 8167 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8168 EPI.TypeQuals.addConst(); 8169 FT = Context.getFunctionType(FPT->getReturnType(), 8170 FPT->getParamTypes(), EPI); 8171 } 8172 } 8173 8174 TemplateArgumentListInfo Args; 8175 if (ExplicitTemplateArgs) 8176 Args = *ExplicitTemplateArgs; 8177 8178 // C++ [temp.expl.spec]p11: 8179 // A trailing template-argument can be left unspecified in the 8180 // template-id naming an explicit function template specialization 8181 // provided it can be deduced from the function argument type. 8182 // Perform template argument deduction to determine whether we may be 8183 // specializing this template. 8184 // FIXME: It is somewhat wasteful to build 8185 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 8186 FunctionDecl *Specialization = nullptr; 8187 if (TemplateDeductionResult TDK = DeduceTemplateArguments( 8188 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()), 8189 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, 8190 Info)) { 8191 // Template argument deduction failed; record why it failed, so 8192 // that we can provide nifty diagnostics. 8193 FailedCandidates.addCandidate().set( 8194 I.getPair(), FunTmpl->getTemplatedDecl(), 8195 MakeDeductionFailureInfo(Context, TDK, Info)); 8196 (void)TDK; 8197 continue; 8198 } 8199 8200 // Target attributes are part of the cuda function signature, so 8201 // the deduced template's cuda target must match that of the 8202 // specialization. Given that C++ template deduction does not 8203 // take target attributes into account, we reject candidates 8204 // here that have a different target. 8205 if (LangOpts.CUDA && 8206 IdentifyCUDATarget(Specialization, 8207 /* IgnoreImplicitHDAttributes = */ true) != 8208 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) { 8209 FailedCandidates.addCandidate().set( 8210 I.getPair(), FunTmpl->getTemplatedDecl(), 8211 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info)); 8212 continue; 8213 } 8214 8215 // Record this candidate. 8216 if (ExplicitTemplateArgs) 8217 ConvertedTemplateArgs[Specialization] = std::move(Args); 8218 Candidates.addDecl(Specialization, I.getAccess()); 8219 } 8220 } 8221 8222 // For a qualified friend declaration (with no explicit marker to indicate 8223 // that a template specialization was intended), note all (template and 8224 // non-template) candidates. 8225 if (QualifiedFriend && Candidates.empty()) { 8226 Diag(FD->getLocation(), diag::err_qualified_friend_no_match) 8227 << FD->getDeclName() << FDLookupContext; 8228 // FIXME: We should form a single candidate list and diagnose all 8229 // candidates at once, to get proper sorting and limiting. 8230 for (auto *OldND : Previous) { 8231 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl())) 8232 NoteOverloadCandidate(OldND, OldFD, FD->getType(), false); 8233 } 8234 FailedCandidates.NoteCandidates(*this, FD->getLocation()); 8235 return true; 8236 } 8237 8238 // Find the most specialized function template. 8239 UnresolvedSetIterator Result = getMostSpecialized( 8240 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(), 8241 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(), 8242 PDiag(diag::err_function_template_spec_ambiguous) 8243 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr), 8244 PDiag(diag::note_function_template_spec_matched)); 8245 8246 if (Result == Candidates.end()) 8247 return true; 8248 8249 // Ignore access information; it doesn't figure into redeclaration checking. 8250 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 8251 8252 FunctionTemplateSpecializationInfo *SpecInfo 8253 = Specialization->getTemplateSpecializationInfo(); 8254 assert(SpecInfo && "Function template specialization info missing?"); 8255 8256 // Note: do not overwrite location info if previous template 8257 // specialization kind was explicit. 8258 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind(); 8259 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) { 8260 Specialization->setLocation(FD->getLocation()); 8261 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext()); 8262 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr 8263 // function can differ from the template declaration with respect to 8264 // the constexpr specifier. 8265 // FIXME: We need an update record for this AST mutation. 8266 // FIXME: What if there are multiple such prior declarations (for instance, 8267 // from different modules)? 8268 Specialization->setConstexpr(FD->isConstexpr()); 8269 } 8270 8271 // FIXME: Check if the prior specialization has a point of instantiation. 8272 // If so, we have run afoul of . 8273 8274 // If this is a friend declaration, then we're not really declaring 8275 // an explicit specialization. 8276 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None); 8277 8278 // Check the scope of this explicit specialization. 8279 if (!isFriend && 8280 CheckTemplateSpecializationScope(*this, 8281 Specialization->getPrimaryTemplate(), 8282 Specialization, FD->getLocation(), 8283 false)) 8284 return true; 8285 8286 // C++ [temp.expl.spec]p6: 8287 // If a template, a member template or the member of a class template is 8288 // explicitly specialized then that specialization shall be declared 8289 // before the first use of that specialization that would cause an implicit 8290 // instantiation to take place, in every translation unit in which such a 8291 // use occurs; no diagnostic is required. 8292 bool HasNoEffect = false; 8293 if (!isFriend && 8294 CheckSpecializationInstantiationRedecl(FD->getLocation(), 8295 TSK_ExplicitSpecialization, 8296 Specialization, 8297 SpecInfo->getTemplateSpecializationKind(), 8298 SpecInfo->getPointOfInstantiation(), 8299 HasNoEffect)) 8300 return true; 8301 8302 // Mark the prior declaration as an explicit specialization, so that later 8303 // clients know that this is an explicit specialization. 8304 if (!isFriend) { 8305 // Since explicit specializations do not inherit '=delete' from their 8306 // primary function template - check if the 'specialization' that was 8307 // implicitly generated (during template argument deduction for partial 8308 // ordering) from the most specialized of all the function templates that 8309 // 'FD' could have been specializing, has a 'deleted' definition. If so, 8310 // first check that it was implicitly generated during template argument 8311 // deduction by making sure it wasn't referenced, and then reset the deleted 8312 // flag to not-deleted, so that we can inherit that information from 'FD'. 8313 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() && 8314 !Specialization->getCanonicalDecl()->isReferenced()) { 8315 // FIXME: This assert will not hold in the presence of modules. 8316 assert( 8317 Specialization->getCanonicalDecl() == Specialization && 8318 "This must be the only existing declaration of this specialization"); 8319 // FIXME: We need an update record for this AST mutation. 8320 Specialization->setDeletedAsWritten(false); 8321 } 8322 // FIXME: We need an update record for this AST mutation. 8323 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 8324 MarkUnusedFileScopedDecl(Specialization); 8325 } 8326 8327 // Turn the given function declaration into a function template 8328 // specialization, with the template arguments from the previous 8329 // specialization. 8330 // Take copies of (semantic and syntactic) template argument lists. 8331 const TemplateArgumentList* TemplArgs = new (Context) 8332 TemplateArgumentList(Specialization->getTemplateSpecializationArgs()); 8333 FD->setFunctionTemplateSpecialization( 8334 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr, 8335 SpecInfo->getTemplateSpecializationKind(), 8336 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr); 8337 8338 // A function template specialization inherits the target attributes 8339 // of its template. (We require the attributes explicitly in the 8340 // code to match, but a template may have implicit attributes by 8341 // virtue e.g. of being constexpr, and it passes these implicit 8342 // attributes on to its specializations.) 8343 if (LangOpts.CUDA) 8344 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate()); 8345 8346 // The "previous declaration" for this function template specialization is 8347 // the prior function template specialization. 8348 Previous.clear(); 8349 Previous.addDecl(Specialization); 8350 return false; 8351 } 8352 8353 /// Perform semantic analysis for the given non-template member 8354 /// specialization. 8355 /// 8356 /// This routine performs all of the semantic analysis required for an 8357 /// explicit member function specialization. On successful completion, 8358 /// the function declaration \p FD will become a member function 8359 /// specialization. 8360 /// 8361 /// \param Member the member declaration, which will be updated to become a 8362 /// specialization. 8363 /// 8364 /// \param Previous the set of declarations, one of which may be specialized 8365 /// by this function specialization; the set will be modified to contain the 8366 /// redeclared member. 8367 bool 8368 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { 8369 assert(!isa<TemplateDecl>(Member) && "Only for non-template members"); 8370 8371 // Try to find the member we are instantiating. 8372 NamedDecl *FoundInstantiation = nullptr; 8373 NamedDecl *Instantiation = nullptr; 8374 NamedDecl *InstantiatedFrom = nullptr; 8375 MemberSpecializationInfo *MSInfo = nullptr; 8376 8377 if (Previous.empty()) { 8378 // Nowhere to look anyway. 8379 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { 8380 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8381 I != E; ++I) { 8382 NamedDecl *D = (*I)->getUnderlyingDecl(); 8383 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 8384 QualType Adjusted = Function->getType(); 8385 if (!hasExplicitCallingConv(Adjusted)) 8386 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType()); 8387 // This doesn't handle deduced return types, but both function 8388 // declarations should be undeduced at this point. 8389 if (Context.hasSameType(Adjusted, Method->getType())) { 8390 FoundInstantiation = *I; 8391 Instantiation = Method; 8392 InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); 8393 MSInfo = Method->getMemberSpecializationInfo(); 8394 break; 8395 } 8396 } 8397 } 8398 } else if (isa<VarDecl>(Member)) { 8399 VarDecl *PrevVar; 8400 if (Previous.isSingleResult() && 8401 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) 8402 if (PrevVar->isStaticDataMember()) { 8403 FoundInstantiation = Previous.getRepresentativeDecl(); 8404 Instantiation = PrevVar; 8405 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); 8406 MSInfo = PrevVar->getMemberSpecializationInfo(); 8407 } 8408 } else if (isa<RecordDecl>(Member)) { 8409 CXXRecordDecl *PrevRecord; 8410 if (Previous.isSingleResult() && 8411 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { 8412 FoundInstantiation = Previous.getRepresentativeDecl(); 8413 Instantiation = PrevRecord; 8414 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); 8415 MSInfo = PrevRecord->getMemberSpecializationInfo(); 8416 } 8417 } else if (isa<EnumDecl>(Member)) { 8418 EnumDecl *PrevEnum; 8419 if (Previous.isSingleResult() && 8420 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) { 8421 FoundInstantiation = Previous.getRepresentativeDecl(); 8422 Instantiation = PrevEnum; 8423 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum(); 8424 MSInfo = PrevEnum->getMemberSpecializationInfo(); 8425 } 8426 } 8427 8428 if (!Instantiation) { 8429 // There is no previous declaration that matches. Since member 8430 // specializations are always out-of-line, the caller will complain about 8431 // this mismatch later. 8432 return false; 8433 } 8434 8435 // A member specialization in a friend declaration isn't really declaring 8436 // an explicit specialization, just identifying a specific (possibly implicit) 8437 // specialization. Don't change the template specialization kind. 8438 // 8439 // FIXME: Is this really valid? Other compilers reject. 8440 if (Member->getFriendObjectKind() != Decl::FOK_None) { 8441 // Preserve instantiation information. 8442 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) { 8443 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction( 8444 cast<CXXMethodDecl>(InstantiatedFrom), 8445 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind()); 8446 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) { 8447 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 8448 cast<CXXRecordDecl>(InstantiatedFrom), 8449 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind()); 8450 } 8451 8452 Previous.clear(); 8453 Previous.addDecl(FoundInstantiation); 8454 return false; 8455 } 8456 8457 // Make sure that this is a specialization of a member. 8458 if (!InstantiatedFrom) { 8459 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) 8460 << Member; 8461 Diag(Instantiation->getLocation(), diag::note_specialized_decl); 8462 return true; 8463 } 8464 8465 // C++ [temp.expl.spec]p6: 8466 // If a template, a member template or the member of a class template is 8467 // explicitly specialized then that specialization shall be declared 8468 // before the first use of that specialization that would cause an implicit 8469 // instantiation to take place, in every translation unit in which such a 8470 // use occurs; no diagnostic is required. 8471 assert(MSInfo && "Member specialization info missing?"); 8472 8473 bool HasNoEffect = false; 8474 if (CheckSpecializationInstantiationRedecl(Member->getLocation(), 8475 TSK_ExplicitSpecialization, 8476 Instantiation, 8477 MSInfo->getTemplateSpecializationKind(), 8478 MSInfo->getPointOfInstantiation(), 8479 HasNoEffect)) 8480 return true; 8481 8482 // Check the scope of this explicit specialization. 8483 if (CheckTemplateSpecializationScope(*this, 8484 InstantiatedFrom, 8485 Instantiation, Member->getLocation(), 8486 false)) 8487 return true; 8488 8489 // Note that this member specialization is an "instantiation of" the 8490 // corresponding member of the original template. 8491 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) { 8492 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); 8493 if (InstantiationFunction->getTemplateSpecializationKind() == 8494 TSK_ImplicitInstantiation) { 8495 // Explicit specializations of member functions of class templates do not 8496 // inherit '=delete' from the member function they are specializing. 8497 if (InstantiationFunction->isDeleted()) { 8498 // FIXME: This assert will not hold in the presence of modules. 8499 assert(InstantiationFunction->getCanonicalDecl() == 8500 InstantiationFunction); 8501 // FIXME: We need an update record for this AST mutation. 8502 InstantiationFunction->setDeletedAsWritten(false); 8503 } 8504 } 8505 8506 MemberFunction->setInstantiationOfMemberFunction( 8507 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 8508 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) { 8509 MemberVar->setInstantiationOfStaticDataMember( 8510 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 8511 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) { 8512 MemberClass->setInstantiationOfMemberClass( 8513 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 8514 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) { 8515 MemberEnum->setInstantiationOfMemberEnum( 8516 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 8517 } else { 8518 llvm_unreachable("unknown member specialization kind"); 8519 } 8520 8521 // Save the caller the trouble of having to figure out which declaration 8522 // this specialization matches. 8523 Previous.clear(); 8524 Previous.addDecl(FoundInstantiation); 8525 return false; 8526 } 8527 8528 /// Complete the explicit specialization of a member of a class template by 8529 /// updating the instantiated member to be marked as an explicit specialization. 8530 /// 8531 /// \param OrigD The member declaration instantiated from the template. 8532 /// \param Loc The location of the explicit specialization of the member. 8533 template<typename DeclT> 8534 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, 8535 SourceLocation Loc) { 8536 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 8537 return; 8538 8539 // FIXME: Inform AST mutation listeners of this AST mutation. 8540 // FIXME: If there are multiple in-class declarations of the member (from 8541 // multiple modules, or a declaration and later definition of a member type), 8542 // should we update all of them? 8543 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 8544 OrigD->setLocation(Loc); 8545 } 8546 8547 void Sema::CompleteMemberSpecialization(NamedDecl *Member, 8548 LookupResult &Previous) { 8549 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl()); 8550 if (Instantiation == Member) 8551 return; 8552 8553 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation)) 8554 completeMemberSpecializationImpl(*this, Function, Member->getLocation()); 8555 else if (auto *Var = dyn_cast<VarDecl>(Instantiation)) 8556 completeMemberSpecializationImpl(*this, Var, Member->getLocation()); 8557 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation)) 8558 completeMemberSpecializationImpl(*this, Record, Member->getLocation()); 8559 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation)) 8560 completeMemberSpecializationImpl(*this, Enum, Member->getLocation()); 8561 else 8562 llvm_unreachable("unknown member specialization kind"); 8563 } 8564 8565 /// Check the scope of an explicit instantiation. 8566 /// 8567 /// \returns true if a serious error occurs, false otherwise. 8568 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, 8569 SourceLocation InstLoc, 8570 bool WasQualifiedName) { 8571 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext(); 8572 DeclContext *CurContext = S.CurContext->getRedeclContext(); 8573 8574 if (CurContext->isRecord()) { 8575 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class) 8576 << D; 8577 return true; 8578 } 8579 8580 // C++11 [temp.explicit]p3: 8581 // An explicit instantiation shall appear in an enclosing namespace of its 8582 // template. If the name declared in the explicit instantiation is an 8583 // unqualified name, the explicit instantiation shall appear in the 8584 // namespace where its template is declared or, if that namespace is inline 8585 // (7.3.1), any namespace from its enclosing namespace set. 8586 // 8587 // This is DR275, which we do not retroactively apply to C++98/03. 8588 if (WasQualifiedName) { 8589 if (CurContext->Encloses(OrigContext)) 8590 return false; 8591 } else { 8592 if (CurContext->InEnclosingNamespaceSetOf(OrigContext)) 8593 return false; 8594 } 8595 8596 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) { 8597 if (WasQualifiedName) 8598 S.Diag(InstLoc, 8599 S.getLangOpts().CPlusPlus11? 8600 diag::err_explicit_instantiation_out_of_scope : 8601 diag::warn_explicit_instantiation_out_of_scope_0x) 8602 << D << NS; 8603 else 8604 S.Diag(InstLoc, 8605 S.getLangOpts().CPlusPlus11? 8606 diag::err_explicit_instantiation_unqualified_wrong_namespace : 8607 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x) 8608 << D << NS; 8609 } else 8610 S.Diag(InstLoc, 8611 S.getLangOpts().CPlusPlus11? 8612 diag::err_explicit_instantiation_must_be_global : 8613 diag::warn_explicit_instantiation_must_be_global_0x) 8614 << D; 8615 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 8616 return false; 8617 } 8618 8619 /// Determine whether the given scope specifier has a template-id in it. 8620 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { 8621 if (!SS.isSet()) 8622 return false; 8623 8624 // C++11 [temp.explicit]p3: 8625 // If the explicit instantiation is for a member function, a member class 8626 // or a static data member of a class template specialization, the name of 8627 // the class template specialization in the qualified-id for the member 8628 // name shall be a simple-template-id. 8629 // 8630 // C++98 has the same restriction, just worded differently. 8631 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS; 8632 NNS = NNS->getPrefix()) 8633 if (const Type *T = NNS->getAsType()) 8634 if (isa<TemplateSpecializationType>(T)) 8635 return true; 8636 8637 return false; 8638 } 8639 8640 /// Make a dllexport or dllimport attr on a class template specialization take 8641 /// effect. 8642 static void dllExportImportClassTemplateSpecialization( 8643 Sema &S, ClassTemplateSpecializationDecl *Def) { 8644 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def)); 8645 assert(A && "dllExportImportClassTemplateSpecialization called " 8646 "on Def without dllexport or dllimport"); 8647 8648 // We reject explicit instantiations in class scope, so there should 8649 // never be any delayed exported classes to worry about. 8650 assert(S.DelayedDllExportClasses.empty() && 8651 "delayed exports present at explicit instantiation"); 8652 S.checkClassLevelDLLAttribute(Def); 8653 8654 // Propagate attribute to base class templates. 8655 for (auto &B : Def->bases()) { 8656 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 8657 B.getType()->getAsCXXRecordDecl())) 8658 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc()); 8659 } 8660 8661 S.referenceDLLExportedClassMethods(); 8662 } 8663 8664 // Explicit instantiation of a class template specialization 8665 DeclResult Sema::ActOnExplicitInstantiation( 8666 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, 8667 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, 8668 TemplateTy TemplateD, SourceLocation TemplateNameLoc, 8669 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, 8670 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) { 8671 // Find the class template we're specializing 8672 TemplateName Name = TemplateD.get(); 8673 TemplateDecl *TD = Name.getAsTemplateDecl(); 8674 // Check that the specialization uses the same tag kind as the 8675 // original template. 8676 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 8677 assert(Kind != TTK_Enum && 8678 "Invalid enum tag in class template explicit instantiation!"); 8679 8680 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD); 8681 8682 if (!ClassTemplate) { 8683 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind); 8684 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind; 8685 Diag(TD->getLocation(), diag::note_previous_use); 8686 return true; 8687 } 8688 8689 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 8690 Kind, /*isDefinition*/false, KWLoc, 8691 ClassTemplate->getIdentifier())) { 8692 Diag(KWLoc, diag::err_use_with_wrong_tag) 8693 << ClassTemplate 8694 << FixItHint::CreateReplacement(KWLoc, 8695 ClassTemplate->getTemplatedDecl()->getKindName()); 8696 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 8697 diag::note_previous_use); 8698 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 8699 } 8700 8701 // C++0x [temp.explicit]p2: 8702 // There are two forms of explicit instantiation: an explicit instantiation 8703 // definition and an explicit instantiation declaration. An explicit 8704 // instantiation declaration begins with the extern keyword. [...] 8705 TemplateSpecializationKind TSK = ExternLoc.isInvalid() 8706 ? TSK_ExplicitInstantiationDefinition 8707 : TSK_ExplicitInstantiationDeclaration; 8708 8709 if (TSK == TSK_ExplicitInstantiationDeclaration) { 8710 // Check for dllexport class template instantiation declarations. 8711 for (const ParsedAttr &AL : Attr) { 8712 if (AL.getKind() == ParsedAttr::AT_DLLExport) { 8713 Diag(ExternLoc, 8714 diag::warn_attribute_dllexport_explicit_instantiation_decl); 8715 Diag(AL.getLoc(), diag::note_attribute); 8716 break; 8717 } 8718 } 8719 8720 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) { 8721 Diag(ExternLoc, 8722 diag::warn_attribute_dllexport_explicit_instantiation_decl); 8723 Diag(A->getLocation(), diag::note_attribute); 8724 } 8725 } 8726 8727 // In MSVC mode, dllimported explicit instantiation definitions are treated as 8728 // instantiation declarations for most purposes. 8729 bool DLLImportExplicitInstantiationDef = false; 8730 if (TSK == TSK_ExplicitInstantiationDefinition && 8731 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 8732 // Check for dllimport class template instantiation definitions. 8733 bool DLLImport = 8734 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>(); 8735 for (const ParsedAttr &AL : Attr) { 8736 if (AL.getKind() == ParsedAttr::AT_DLLImport) 8737 DLLImport = true; 8738 if (AL.getKind() == ParsedAttr::AT_DLLExport) { 8739 // dllexport trumps dllimport here. 8740 DLLImport = false; 8741 break; 8742 } 8743 } 8744 if (DLLImport) { 8745 TSK = TSK_ExplicitInstantiationDeclaration; 8746 DLLImportExplicitInstantiationDef = true; 8747 } 8748 } 8749 8750 // Translate the parser's template argument list in our AST format. 8751 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 8752 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 8753 8754 // Check that the template argument list is well-formed for this 8755 // template. 8756 SmallVector<TemplateArgument, 4> Converted; 8757 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 8758 TemplateArgs, false, Converted)) 8759 return true; 8760 8761 // Find the class template specialization declaration that 8762 // corresponds to these arguments. 8763 void *InsertPos = nullptr; 8764 ClassTemplateSpecializationDecl *PrevDecl 8765 = ClassTemplate->findSpecialization(Converted, InsertPos); 8766 8767 TemplateSpecializationKind PrevDecl_TSK 8768 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared; 8769 8770 // C++0x [temp.explicit]p2: 8771 // [...] An explicit instantiation shall appear in an enclosing 8772 // namespace of its template. [...] 8773 // 8774 // This is C++ DR 275. 8775 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc, 8776 SS.isSet())) 8777 return true; 8778 8779 ClassTemplateSpecializationDecl *Specialization = nullptr; 8780 8781 bool HasNoEffect = false; 8782 if (PrevDecl) { 8783 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, 8784 PrevDecl, PrevDecl_TSK, 8785 PrevDecl->getPointOfInstantiation(), 8786 HasNoEffect)) 8787 return PrevDecl; 8788 8789 // Even though HasNoEffect == true means that this explicit instantiation 8790 // has no effect on semantics, we go on to put its syntax in the AST. 8791 8792 if (PrevDecl_TSK == TSK_ImplicitInstantiation || 8793 PrevDecl_TSK == TSK_Undeclared) { 8794 // Since the only prior class template specialization with these 8795 // arguments was referenced but not declared, reuse that 8796 // declaration node as our own, updating the source location 8797 // for the template name to reflect our new declaration. 8798 // (Other source locations will be updated later.) 8799 Specialization = PrevDecl; 8800 Specialization->setLocation(TemplateNameLoc); 8801 PrevDecl = nullptr; 8802 } 8803 8804 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration && 8805 DLLImportExplicitInstantiationDef) { 8806 // The new specialization might add a dllimport attribute. 8807 HasNoEffect = false; 8808 } 8809 } 8810 8811 if (!Specialization) { 8812 // Create a new class template specialization declaration node for 8813 // this explicit specialization. 8814 Specialization 8815 = ClassTemplateSpecializationDecl::Create(Context, Kind, 8816 ClassTemplate->getDeclContext(), 8817 KWLoc, TemplateNameLoc, 8818 ClassTemplate, 8819 Converted, 8820 PrevDecl); 8821 SetNestedNameSpecifier(*this, Specialization, SS); 8822 8823 if (!HasNoEffect && !PrevDecl) { 8824 // Insert the new specialization. 8825 ClassTemplate->AddSpecialization(Specialization, InsertPos); 8826 } 8827 } 8828 8829 // Build the fully-sugared type for this explicit instantiation as 8830 // the user wrote in the explicit instantiation itself. This means 8831 // that we'll pretty-print the type retrieved from the 8832 // specialization's declaration the way that the user actually wrote 8833 // the explicit instantiation, rather than formatting the name based 8834 // on the "canonical" representation used to store the template 8835 // arguments in the specialization. 8836 TypeSourceInfo *WrittenTy 8837 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 8838 TemplateArgs, 8839 Context.getTypeDeclType(Specialization)); 8840 Specialization->setTypeAsWritten(WrittenTy); 8841 8842 // Set source locations for keywords. 8843 Specialization->setExternLoc(ExternLoc); 8844 Specialization->setTemplateKeywordLoc(TemplateLoc); 8845 Specialization->setBraceRange(SourceRange()); 8846 8847 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>(); 8848 ProcessDeclAttributeList(S, Specialization, Attr); 8849 8850 // Add the explicit instantiation into its lexical context. However, 8851 // since explicit instantiations are never found by name lookup, we 8852 // just put it into the declaration context directly. 8853 Specialization->setLexicalDeclContext(CurContext); 8854 CurContext->addDecl(Specialization); 8855 8856 // Syntax is now OK, so return if it has no other effect on semantics. 8857 if (HasNoEffect) { 8858 // Set the template specialization kind. 8859 Specialization->setTemplateSpecializationKind(TSK); 8860 return Specialization; 8861 } 8862 8863 // C++ [temp.explicit]p3: 8864 // A definition of a class template or class member template 8865 // shall be in scope at the point of the explicit instantiation of 8866 // the class template or class member template. 8867 // 8868 // This check comes when we actually try to perform the 8869 // instantiation. 8870 ClassTemplateSpecializationDecl *Def 8871 = cast_or_null<ClassTemplateSpecializationDecl>( 8872 Specialization->getDefinition()); 8873 if (!Def) 8874 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); 8875 else if (TSK == TSK_ExplicitInstantiationDefinition) { 8876 MarkVTableUsed(TemplateNameLoc, Specialization, true); 8877 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation()); 8878 } 8879 8880 // Instantiate the members of this class template specialization. 8881 Def = cast_or_null<ClassTemplateSpecializationDecl>( 8882 Specialization->getDefinition()); 8883 if (Def) { 8884 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind(); 8885 // Fix a TSK_ExplicitInstantiationDeclaration followed by a 8886 // TSK_ExplicitInstantiationDefinition 8887 if (Old_TSK == TSK_ExplicitInstantiationDeclaration && 8888 (TSK == TSK_ExplicitInstantiationDefinition || 8889 DLLImportExplicitInstantiationDef)) { 8890 // FIXME: Need to notify the ASTMutationListener that we did this. 8891 Def->setTemplateSpecializationKind(TSK); 8892 8893 if (!getDLLAttr(Def) && getDLLAttr(Specialization) && 8894 (Context.getTargetInfo().getCXXABI().isMicrosoft() || 8895 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) { 8896 // In the MS ABI, an explicit instantiation definition can add a dll 8897 // attribute to a template with a previous instantiation declaration. 8898 // MinGW doesn't allow this. 8899 auto *A = cast<InheritableAttr>( 8900 getDLLAttr(Specialization)->clone(getASTContext())); 8901 A->setInherited(true); 8902 Def->addAttr(A); 8903 dllExportImportClassTemplateSpecialization(*this, Def); 8904 } 8905 } 8906 8907 // Fix a TSK_ImplicitInstantiation followed by a 8908 // TSK_ExplicitInstantiationDefinition 8909 bool NewlyDLLExported = 8910 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>(); 8911 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported && 8912 (Context.getTargetInfo().getCXXABI().isMicrosoft() || 8913 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) { 8914 // In the MS ABI, an explicit instantiation definition can add a dll 8915 // attribute to a template with a previous implicit instantiation. 8916 // MinGW doesn't allow this. We limit clang to only adding dllexport, to 8917 // avoid potentially strange codegen behavior. For example, if we extend 8918 // this conditional to dllimport, and we have a source file calling a 8919 // method on an implicitly instantiated template class instance and then 8920 // declaring a dllimport explicit instantiation definition for the same 8921 // template class, the codegen for the method call will not respect the 8922 // dllimport, while it will with cl. The Def will already have the DLL 8923 // attribute, since the Def and Specialization will be the same in the 8924 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the 8925 // attribute to the Specialization; we just need to make it take effect. 8926 assert(Def == Specialization && 8927 "Def and Specialization should match for implicit instantiation"); 8928 dllExportImportClassTemplateSpecialization(*this, Def); 8929 } 8930 8931 // Set the template specialization kind. Make sure it is set before 8932 // instantiating the members which will trigger ASTConsumer callbacks. 8933 Specialization->setTemplateSpecializationKind(TSK); 8934 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); 8935 } else { 8936 8937 // Set the template specialization kind. 8938 Specialization->setTemplateSpecializationKind(TSK); 8939 } 8940 8941 return Specialization; 8942 } 8943 8944 // Explicit instantiation of a member class of a class template. 8945 DeclResult 8946 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 8947 SourceLocation TemplateLoc, unsigned TagSpec, 8948 SourceLocation KWLoc, CXXScopeSpec &SS, 8949 IdentifierInfo *Name, SourceLocation NameLoc, 8950 const ParsedAttributesView &Attr) { 8951 8952 bool Owned = false; 8953 bool IsDependent = false; 8954 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, 8955 KWLoc, SS, Name, NameLoc, Attr, AS_none, 8956 /*ModulePrivateLoc=*/SourceLocation(), 8957 MultiTemplateParamsArg(), Owned, IsDependent, 8958 SourceLocation(), false, TypeResult(), 8959 /*IsTypeSpecifier*/false, 8960 /*IsTemplateParamOrArg*/false); 8961 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 8962 8963 if (!TagD) 8964 return true; 8965 8966 TagDecl *Tag = cast<TagDecl>(TagD); 8967 assert(!Tag->isEnum() && "shouldn't see enumerations here"); 8968 8969 if (Tag->isInvalidDecl()) 8970 return true; 8971 8972 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 8973 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 8974 if (!Pattern) { 8975 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 8976 << Context.getTypeDeclType(Record); 8977 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 8978 return true; 8979 } 8980 8981 // C++0x [temp.explicit]p2: 8982 // If the explicit instantiation is for a class or member class, the 8983 // elaborated-type-specifier in the declaration shall include a 8984 // simple-template-id. 8985 // 8986 // C++98 has the same restriction, just worded differently. 8987 if (!ScopeSpecifierHasTemplateId(SS)) 8988 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id) 8989 << Record << SS.getRange(); 8990 8991 // C++0x [temp.explicit]p2: 8992 // There are two forms of explicit instantiation: an explicit instantiation 8993 // definition and an explicit instantiation declaration. An explicit 8994 // instantiation declaration begins with the extern keyword. [...] 8995 TemplateSpecializationKind TSK 8996 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 8997 : TSK_ExplicitInstantiationDeclaration; 8998 8999 // C++0x [temp.explicit]p2: 9000 // [...] An explicit instantiation shall appear in an enclosing 9001 // namespace of its template. [...] 9002 // 9003 // This is C++ DR 275. 9004 CheckExplicitInstantiationScope(*this, Record, NameLoc, true); 9005 9006 // Verify that it is okay to explicitly instantiate here. 9007 CXXRecordDecl *PrevDecl 9008 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl()); 9009 if (!PrevDecl && Record->getDefinition()) 9010 PrevDecl = Record; 9011 if (PrevDecl) { 9012 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); 9013 bool HasNoEffect = false; 9014 assert(MSInfo && "No member specialization information?"); 9015 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 9016 PrevDecl, 9017 MSInfo->getTemplateSpecializationKind(), 9018 MSInfo->getPointOfInstantiation(), 9019 HasNoEffect)) 9020 return true; 9021 if (HasNoEffect) 9022 return TagD; 9023 } 9024 9025 CXXRecordDecl *RecordDef 9026 = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 9027 if (!RecordDef) { 9028 // C++ [temp.explicit]p3: 9029 // A definition of a member class of a class template shall be in scope 9030 // at the point of an explicit instantiation of the member class. 9031 CXXRecordDecl *Def 9032 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 9033 if (!Def) { 9034 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) 9035 << 0 << Record->getDeclName() << Record->getDeclContext(); 9036 Diag(Pattern->getLocation(), diag::note_forward_declaration) 9037 << Pattern; 9038 return true; 9039 } else { 9040 if (InstantiateClass(NameLoc, Record, Def, 9041 getTemplateInstantiationArgs(Record), 9042 TSK)) 9043 return true; 9044 9045 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 9046 if (!RecordDef) 9047 return true; 9048 } 9049 } 9050 9051 // Instantiate all of the members of the class. 9052 InstantiateClassMembers(NameLoc, RecordDef, 9053 getTemplateInstantiationArgs(Record), TSK); 9054 9055 if (TSK == TSK_ExplicitInstantiationDefinition) 9056 MarkVTableUsed(NameLoc, RecordDef, true); 9057 9058 // FIXME: We don't have any representation for explicit instantiations of 9059 // member classes. Such a representation is not needed for compilation, but it 9060 // should be available for clients that want to see all of the declarations in 9061 // the source code. 9062 return TagD; 9063 } 9064 9065 DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 9066 SourceLocation ExternLoc, 9067 SourceLocation TemplateLoc, 9068 Declarator &D) { 9069 // Explicit instantiations always require a name. 9070 // TODO: check if/when DNInfo should replace Name. 9071 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 9072 DeclarationName Name = NameInfo.getName(); 9073 if (!Name) { 9074 if (!D.isInvalidType()) 9075 Diag(D.getDeclSpec().getBeginLoc(), 9076 diag::err_explicit_instantiation_requires_name) 9077 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 9078 9079 return true; 9080 } 9081 9082 // The scope passed in may not be a decl scope. Zip up the scope tree until 9083 // we find one that is. 9084 while ((S->getFlags() & Scope::DeclScope) == 0 || 9085 (S->getFlags() & Scope::TemplateParamScope) != 0) 9086 S = S->getParent(); 9087 9088 // Determine the type of the declaration. 9089 TypeSourceInfo *T = GetTypeForDeclarator(D, S); 9090 QualType R = T->getType(); 9091 if (R.isNull()) 9092 return true; 9093 9094 // C++ [dcl.stc]p1: 9095 // A storage-class-specifier shall not be specified in [...] an explicit 9096 // instantiation (14.7.2) directive. 9097 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 9098 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 9099 << Name; 9100 return true; 9101 } else if (D.getDeclSpec().getStorageClassSpec() 9102 != DeclSpec::SCS_unspecified) { 9103 // Complain about then remove the storage class specifier. 9104 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class) 9105 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9106 9107 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9108 } 9109 9110 // C++0x [temp.explicit]p1: 9111 // [...] An explicit instantiation of a function template shall not use the 9112 // inline or constexpr specifiers. 9113 // Presumably, this also applies to member functions of class templates as 9114 // well. 9115 if (D.getDeclSpec().isInlineSpecified()) 9116 Diag(D.getDeclSpec().getInlineSpecLoc(), 9117 getLangOpts().CPlusPlus11 ? 9118 diag::err_explicit_instantiation_inline : 9119 diag::warn_explicit_instantiation_inline_0x) 9120 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9121 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType()) 9122 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is 9123 // not already specified. 9124 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9125 diag::err_explicit_instantiation_constexpr); 9126 9127 // A deduction guide is not on the list of entities that can be explicitly 9128 // instantiated. 9129 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 9130 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized) 9131 << /*explicit instantiation*/ 0; 9132 return true; 9133 } 9134 9135 // C++0x [temp.explicit]p2: 9136 // There are two forms of explicit instantiation: an explicit instantiation 9137 // definition and an explicit instantiation declaration. An explicit 9138 // instantiation declaration begins with the extern keyword. [...] 9139 TemplateSpecializationKind TSK 9140 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 9141 : TSK_ExplicitInstantiationDeclaration; 9142 9143 LookupResult Previous(*this, NameInfo, LookupOrdinaryName); 9144 LookupParsedName(Previous, S, &D.getCXXScopeSpec()); 9145 9146 if (!R->isFunctionType()) { 9147 // C++ [temp.explicit]p1: 9148 // A [...] static data member of a class template can be explicitly 9149 // instantiated from the member definition associated with its class 9150 // template. 9151 // C++1y [temp.explicit]p1: 9152 // A [...] variable [...] template specialization can be explicitly 9153 // instantiated from its template. 9154 if (Previous.isAmbiguous()) 9155 return true; 9156 9157 VarDecl *Prev = Previous.getAsSingle<VarDecl>(); 9158 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>(); 9159 9160 if (!PrevTemplate) { 9161 if (!Prev || !Prev->isStaticDataMember()) { 9162 // We expect to see a data data member here. 9163 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 9164 << Name; 9165 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 9166 P != PEnd; ++P) 9167 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); 9168 return true; 9169 } 9170 9171 if (!Prev->getInstantiatedFromStaticDataMember()) { 9172 // FIXME: Check for explicit specialization? 9173 Diag(D.getIdentifierLoc(), 9174 diag::err_explicit_instantiation_data_member_not_instantiated) 9175 << Prev; 9176 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 9177 // FIXME: Can we provide a note showing where this was declared? 9178 return true; 9179 } 9180 } else { 9181 // Explicitly instantiate a variable template. 9182 9183 // C++1y [dcl.spec.auto]p6: 9184 // ... A program that uses auto or decltype(auto) in a context not 9185 // explicitly allowed in this section is ill-formed. 9186 // 9187 // This includes auto-typed variable template instantiations. 9188 if (R->isUndeducedType()) { 9189 Diag(T->getTypeLoc().getBeginLoc(), 9190 diag::err_auto_not_allowed_var_inst); 9191 return true; 9192 } 9193 9194 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 9195 // C++1y [temp.explicit]p3: 9196 // If the explicit instantiation is for a variable, the unqualified-id 9197 // in the declaration shall be a template-id. 9198 Diag(D.getIdentifierLoc(), 9199 diag::err_explicit_instantiation_without_template_id) 9200 << PrevTemplate; 9201 Diag(PrevTemplate->getLocation(), 9202 diag::note_explicit_instantiation_here); 9203 return true; 9204 } 9205 9206 // Translate the parser's template argument list into our AST format. 9207 TemplateArgumentListInfo TemplateArgs = 9208 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId); 9209 9210 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc, 9211 D.getIdentifierLoc(), TemplateArgs); 9212 if (Res.isInvalid()) 9213 return true; 9214 9215 // Ignore access control bits, we don't need them for redeclaration 9216 // checking. 9217 Prev = cast<VarDecl>(Res.get()); 9218 } 9219 9220 // C++0x [temp.explicit]p2: 9221 // If the explicit instantiation is for a member function, a member class 9222 // or a static data member of a class template specialization, the name of 9223 // the class template specialization in the qualified-id for the member 9224 // name shall be a simple-template-id. 9225 // 9226 // C++98 has the same restriction, just worded differently. 9227 // 9228 // This does not apply to variable template specializations, where the 9229 // template-id is in the unqualified-id instead. 9230 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate) 9231 Diag(D.getIdentifierLoc(), 9232 diag::ext_explicit_instantiation_without_qualified_id) 9233 << Prev << D.getCXXScopeSpec().getRange(); 9234 9235 // Check the scope of this explicit instantiation. 9236 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true); 9237 9238 // Verify that it is okay to explicitly instantiate here. 9239 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind(); 9240 SourceLocation POI = Prev->getPointOfInstantiation(); 9241 bool HasNoEffect = false; 9242 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, 9243 PrevTSK, POI, HasNoEffect)) 9244 return true; 9245 9246 if (!HasNoEffect) { 9247 // Instantiate static data member or variable template. 9248 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 9249 // Merge attributes. 9250 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes()); 9251 if (TSK == TSK_ExplicitInstantiationDefinition) 9252 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev); 9253 } 9254 9255 // Check the new variable specialization against the parsed input. 9256 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) { 9257 Diag(T->getTypeLoc().getBeginLoc(), 9258 diag::err_invalid_var_template_spec_type) 9259 << 0 << PrevTemplate << R << Prev->getType(); 9260 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here) 9261 << 2 << PrevTemplate->getDeclName(); 9262 return true; 9263 } 9264 9265 // FIXME: Create an ExplicitInstantiation node? 9266 return (Decl*) nullptr; 9267 } 9268 9269 // If the declarator is a template-id, translate the parser's template 9270 // argument list into our AST format. 9271 bool HasExplicitTemplateArgs = false; 9272 TemplateArgumentListInfo TemplateArgs; 9273 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9274 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId); 9275 HasExplicitTemplateArgs = true; 9276 } 9277 9278 // C++ [temp.explicit]p1: 9279 // A [...] function [...] can be explicitly instantiated from its template. 9280 // A member function [...] of a class template can be explicitly 9281 // instantiated from the member definition associated with its class 9282 // template. 9283 UnresolvedSet<8> TemplateMatches; 9284 FunctionDecl *NonTemplateMatch = nullptr; 9285 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc()); 9286 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 9287 P != PEnd; ++P) { 9288 NamedDecl *Prev = *P; 9289 if (!HasExplicitTemplateArgs) { 9290 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 9291 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(), 9292 /*AdjustExceptionSpec*/true); 9293 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) { 9294 if (Method->getPrimaryTemplate()) { 9295 TemplateMatches.addDecl(Method, P.getAccess()); 9296 } else { 9297 // FIXME: Can this assert ever happen? Needs a test. 9298 assert(!NonTemplateMatch && "Multiple NonTemplateMatches"); 9299 NonTemplateMatch = Method; 9300 } 9301 } 9302 } 9303 } 9304 9305 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 9306 if (!FunTmpl) 9307 continue; 9308 9309 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9310 FunctionDecl *Specialization = nullptr; 9311 if (TemplateDeductionResult TDK 9312 = DeduceTemplateArguments(FunTmpl, 9313 (HasExplicitTemplateArgs ? &TemplateArgs 9314 : nullptr), 9315 R, Specialization, Info)) { 9316 // Keep track of almost-matches. 9317 FailedCandidates.addCandidate() 9318 .set(P.getPair(), FunTmpl->getTemplatedDecl(), 9319 MakeDeductionFailureInfo(Context, TDK, Info)); 9320 (void)TDK; 9321 continue; 9322 } 9323 9324 // Target attributes are part of the cuda function signature, so 9325 // the cuda target of the instantiated function must match that of its 9326 // template. Given that C++ template deduction does not take 9327 // target attributes into account, we reject candidates here that 9328 // have a different target. 9329 if (LangOpts.CUDA && 9330 IdentifyCUDATarget(Specialization, 9331 /* IgnoreImplicitHDAttributes = */ true) != 9332 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) { 9333 FailedCandidates.addCandidate().set( 9334 P.getPair(), FunTmpl->getTemplatedDecl(), 9335 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info)); 9336 continue; 9337 } 9338 9339 TemplateMatches.addDecl(Specialization, P.getAccess()); 9340 } 9341 9342 FunctionDecl *Specialization = NonTemplateMatch; 9343 if (!Specialization) { 9344 // Find the most specialized function template specialization. 9345 UnresolvedSetIterator Result = getMostSpecialized( 9346 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates, 9347 D.getIdentifierLoc(), 9348 PDiag(diag::err_explicit_instantiation_not_known) << Name, 9349 PDiag(diag::err_explicit_instantiation_ambiguous) << Name, 9350 PDiag(diag::note_explicit_instantiation_candidate)); 9351 9352 if (Result == TemplateMatches.end()) 9353 return true; 9354 9355 // Ignore access control bits, we don't need them for redeclaration checking. 9356 Specialization = cast<FunctionDecl>(*Result); 9357 } 9358 9359 // C++11 [except.spec]p4 9360 // In an explicit instantiation an exception-specification may be specified, 9361 // but is not required. 9362 // If an exception-specification is specified in an explicit instantiation 9363 // directive, it shall be compatible with the exception-specifications of 9364 // other declarations of that function. 9365 if (auto *FPT = R->getAs<FunctionProtoType>()) 9366 if (FPT->hasExceptionSpec()) { 9367 unsigned DiagID = 9368 diag::err_mismatched_exception_spec_explicit_instantiation; 9369 if (getLangOpts().MicrosoftExt) 9370 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation; 9371 bool Result = CheckEquivalentExceptionSpec( 9372 PDiag(DiagID) << Specialization->getType(), 9373 PDiag(diag::note_explicit_instantiation_here), 9374 Specialization->getType()->getAs<FunctionProtoType>(), 9375 Specialization->getLocation(), FPT, D.getBeginLoc()); 9376 // In Microsoft mode, mismatching exception specifications just cause a 9377 // warning. 9378 if (!getLangOpts().MicrosoftExt && Result) 9379 return true; 9380 } 9381 9382 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { 9383 Diag(D.getIdentifierLoc(), 9384 diag::err_explicit_instantiation_member_function_not_instantiated) 9385 << Specialization 9386 << (Specialization->getTemplateSpecializationKind() == 9387 TSK_ExplicitSpecialization); 9388 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 9389 return true; 9390 } 9391 9392 FunctionDecl *PrevDecl = Specialization->getPreviousDecl(); 9393 if (!PrevDecl && Specialization->isThisDeclarationADefinition()) 9394 PrevDecl = Specialization; 9395 9396 if (PrevDecl) { 9397 bool HasNoEffect = false; 9398 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, 9399 PrevDecl, 9400 PrevDecl->getTemplateSpecializationKind(), 9401 PrevDecl->getPointOfInstantiation(), 9402 HasNoEffect)) 9403 return true; 9404 9405 // FIXME: We may still want to build some representation of this 9406 // explicit specialization. 9407 if (HasNoEffect) 9408 return (Decl*) nullptr; 9409 } 9410 9411 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes()); 9412 9413 // In MSVC mode, dllimported explicit instantiation definitions are treated as 9414 // instantiation declarations. 9415 if (TSK == TSK_ExplicitInstantiationDefinition && 9416 Specialization->hasAttr<DLLImportAttr>() && 9417 Context.getTargetInfo().getCXXABI().isMicrosoft()) 9418 TSK = TSK_ExplicitInstantiationDeclaration; 9419 9420 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 9421 9422 if (Specialization->isDefined()) { 9423 // Let the ASTConsumer know that this function has been explicitly 9424 // instantiated now, and its linkage might have changed. 9425 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization)); 9426 } else if (TSK == TSK_ExplicitInstantiationDefinition) 9427 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization); 9428 9429 // C++0x [temp.explicit]p2: 9430 // If the explicit instantiation is for a member function, a member class 9431 // or a static data member of a class template specialization, the name of 9432 // the class template specialization in the qualified-id for the member 9433 // name shall be a simple-template-id. 9434 // 9435 // C++98 has the same restriction, just worded differently. 9436 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); 9437 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl && 9438 D.getCXXScopeSpec().isSet() && 9439 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 9440 Diag(D.getIdentifierLoc(), 9441 diag::ext_explicit_instantiation_without_qualified_id) 9442 << Specialization << D.getCXXScopeSpec().getRange(); 9443 9444 CheckExplicitInstantiationScope(*this, 9445 FunTmpl? (NamedDecl *)FunTmpl 9446 : Specialization->getInstantiatedFromMemberFunction(), 9447 D.getIdentifierLoc(), 9448 D.getCXXScopeSpec().isSet()); 9449 9450 // FIXME: Create some kind of ExplicitInstantiationDecl here. 9451 return (Decl*) nullptr; 9452 } 9453 9454 TypeResult 9455 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 9456 const CXXScopeSpec &SS, IdentifierInfo *Name, 9457 SourceLocation TagLoc, SourceLocation NameLoc) { 9458 // This has to hold, because SS is expected to be defined. 9459 assert(Name && "Expected a name in a dependent tag"); 9460 9461 NestedNameSpecifier *NNS = SS.getScopeRep(); 9462 if (!NNS) 9463 return true; 9464 9465 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 9466 9467 if (TUK == TUK_Declaration || TUK == TUK_Definition) { 9468 Diag(NameLoc, diag::err_dependent_tag_decl) 9469 << (TUK == TUK_Definition) << Kind << SS.getRange(); 9470 return true; 9471 } 9472 9473 // Create the resulting type. 9474 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 9475 QualType Result = Context.getDependentNameType(Kwd, NNS, Name); 9476 9477 // Create type-source location information for this type. 9478 TypeLocBuilder TLB; 9479 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result); 9480 TL.setElaboratedKeywordLoc(TagLoc); 9481 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 9482 TL.setNameLoc(NameLoc); 9483 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 9484 } 9485 9486 TypeResult 9487 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 9488 const CXXScopeSpec &SS, const IdentifierInfo &II, 9489 SourceLocation IdLoc) { 9490 if (SS.isInvalid()) 9491 return true; 9492 9493 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) 9494 Diag(TypenameLoc, 9495 getLangOpts().CPlusPlus11 ? 9496 diag::warn_cxx98_compat_typename_outside_of_template : 9497 diag::ext_typename_outside_of_template) 9498 << FixItHint::CreateRemoval(TypenameLoc); 9499 9500 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9501 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None, 9502 TypenameLoc, QualifierLoc, II, IdLoc); 9503 if (T.isNull()) 9504 return true; 9505 9506 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 9507 if (isa<DependentNameType>(T)) { 9508 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 9509 TL.setElaboratedKeywordLoc(TypenameLoc); 9510 TL.setQualifierLoc(QualifierLoc); 9511 TL.setNameLoc(IdLoc); 9512 } else { 9513 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 9514 TL.setElaboratedKeywordLoc(TypenameLoc); 9515 TL.setQualifierLoc(QualifierLoc); 9516 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 9517 } 9518 9519 return CreateParsedType(T, TSI); 9520 } 9521 9522 TypeResult 9523 Sema::ActOnTypenameType(Scope *S, 9524 SourceLocation TypenameLoc, 9525 const CXXScopeSpec &SS, 9526 SourceLocation TemplateKWLoc, 9527 TemplateTy TemplateIn, 9528 IdentifierInfo *TemplateII, 9529 SourceLocation TemplateIILoc, 9530 SourceLocation LAngleLoc, 9531 ASTTemplateArgsPtr TemplateArgsIn, 9532 SourceLocation RAngleLoc) { 9533 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) 9534 Diag(TypenameLoc, 9535 getLangOpts().CPlusPlus11 ? 9536 diag::warn_cxx98_compat_typename_outside_of_template : 9537 diag::ext_typename_outside_of_template) 9538 << FixItHint::CreateRemoval(TypenameLoc); 9539 9540 // Strangely, non-type results are not ignored by this lookup, so the 9541 // program is ill-formed if it finds an injected-class-name. 9542 if (TypenameLoc.isValid()) { 9543 auto *LookupRD = 9544 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false)); 9545 if (LookupRD && LookupRD->getIdentifier() == TemplateII) { 9546 Diag(TemplateIILoc, 9547 diag::ext_out_of_line_qualified_id_type_names_constructor) 9548 << TemplateII << 0 /*injected-class-name used as template name*/ 9549 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/); 9550 } 9551 } 9552 9553 // Translate the parser's template argument list in our AST format. 9554 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 9555 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 9556 9557 TemplateName Template = TemplateIn.get(); 9558 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 9559 // Construct a dependent template specialization type. 9560 assert(DTN && "dependent template has non-dependent name?"); 9561 assert(DTN->getQualifier() == SS.getScopeRep()); 9562 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename, 9563 DTN->getQualifier(), 9564 DTN->getIdentifier(), 9565 TemplateArgs); 9566 9567 // Create source-location information for this type. 9568 TypeLocBuilder Builder; 9569 DependentTemplateSpecializationTypeLoc SpecTL 9570 = Builder.push<DependentTemplateSpecializationTypeLoc>(T); 9571 SpecTL.setElaboratedKeywordLoc(TypenameLoc); 9572 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 9573 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 9574 SpecTL.setTemplateNameLoc(TemplateIILoc); 9575 SpecTL.setLAngleLoc(LAngleLoc); 9576 SpecTL.setRAngleLoc(RAngleLoc); 9577 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 9578 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 9579 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 9580 } 9581 9582 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); 9583 if (T.isNull()) 9584 return true; 9585 9586 // Provide source-location information for the template specialization type. 9587 TypeLocBuilder Builder; 9588 TemplateSpecializationTypeLoc SpecTL 9589 = Builder.push<TemplateSpecializationTypeLoc>(T); 9590 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 9591 SpecTL.setTemplateNameLoc(TemplateIILoc); 9592 SpecTL.setLAngleLoc(LAngleLoc); 9593 SpecTL.setRAngleLoc(RAngleLoc); 9594 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 9595 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 9596 9597 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T); 9598 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T); 9599 TL.setElaboratedKeywordLoc(TypenameLoc); 9600 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 9601 9602 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); 9603 return CreateParsedType(T, TSI); 9604 } 9605 9606 9607 /// Determine whether this failed name lookup should be treated as being 9608 /// disabled by a usage of std::enable_if. 9609 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, 9610 SourceRange &CondRange, Expr *&Cond) { 9611 // We must be looking for a ::type... 9612 if (!II.isStr("type")) 9613 return false; 9614 9615 // ... within an explicitly-written template specialization... 9616 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType()) 9617 return false; 9618 TypeLoc EnableIfTy = NNS.getTypeLoc(); 9619 TemplateSpecializationTypeLoc EnableIfTSTLoc = 9620 EnableIfTy.getAs<TemplateSpecializationTypeLoc>(); 9621 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0) 9622 return false; 9623 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr(); 9624 9625 // ... which names a complete class template declaration... 9626 const TemplateDecl *EnableIfDecl = 9627 EnableIfTST->getTemplateName().getAsTemplateDecl(); 9628 if (!EnableIfDecl || EnableIfTST->isIncompleteType()) 9629 return false; 9630 9631 // ... called "enable_if". 9632 const IdentifierInfo *EnableIfII = 9633 EnableIfDecl->getDeclName().getAsIdentifierInfo(); 9634 if (!EnableIfII || !EnableIfII->isStr("enable_if")) 9635 return false; 9636 9637 // Assume the first template argument is the condition. 9638 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange(); 9639 9640 // Dig out the condition. 9641 Cond = nullptr; 9642 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind() 9643 != TemplateArgument::Expression) 9644 return true; 9645 9646 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression(); 9647 9648 // Ignore Boolean literals; they add no value. 9649 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts())) 9650 Cond = nullptr; 9651 9652 return true; 9653 } 9654 9655 /// Build the type that describes a C++ typename specifier, 9656 /// e.g., "typename T::type". 9657 QualType 9658 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 9659 SourceLocation KeywordLoc, 9660 NestedNameSpecifierLoc QualifierLoc, 9661 const IdentifierInfo &II, 9662 SourceLocation IILoc) { 9663 CXXScopeSpec SS; 9664 SS.Adopt(QualifierLoc); 9665 9666 DeclContext *Ctx = computeDeclContext(SS); 9667 if (!Ctx) { 9668 // If the nested-name-specifier is dependent and couldn't be 9669 // resolved to a type, build a typename type. 9670 assert(QualifierLoc.getNestedNameSpecifier()->isDependent()); 9671 return Context.getDependentNameType(Keyword, 9672 QualifierLoc.getNestedNameSpecifier(), 9673 &II); 9674 } 9675 9676 // If the nested-name-specifier refers to the current instantiation, 9677 // the "typename" keyword itself is superfluous. In C++03, the 9678 // program is actually ill-formed. However, DR 382 (in C++0x CD1) 9679 // allows such extraneous "typename" keywords, and we retroactively 9680 // apply this DR to C++03 code with only a warning. In any case we continue. 9681 9682 if (RequireCompleteDeclContext(SS, Ctx)) 9683 return QualType(); 9684 9685 DeclarationName Name(&II); 9686 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName); 9687 LookupQualifiedName(Result, Ctx, SS); 9688 unsigned DiagID = 0; 9689 Decl *Referenced = nullptr; 9690 switch (Result.getResultKind()) { 9691 case LookupResult::NotFound: { 9692 // If we're looking up 'type' within a template named 'enable_if', produce 9693 // a more specific diagnostic. 9694 SourceRange CondRange; 9695 Expr *Cond = nullptr; 9696 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) { 9697 // If we have a condition, narrow it down to the specific failed 9698 // condition. 9699 if (Cond) { 9700 Expr *FailedCond; 9701 std::string FailedDescription; 9702 std::tie(FailedCond, FailedDescription) = 9703 findFailedBooleanCondition(Cond); 9704 9705 Diag(FailedCond->getExprLoc(), 9706 diag::err_typename_nested_not_found_requirement) 9707 << FailedDescription 9708 << FailedCond->getSourceRange(); 9709 return QualType(); 9710 } 9711 9712 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if) 9713 << Ctx << CondRange; 9714 return QualType(); 9715 } 9716 9717 DiagID = diag::err_typename_nested_not_found; 9718 break; 9719 } 9720 9721 case LookupResult::FoundUnresolvedValue: { 9722 // We found a using declaration that is a value. Most likely, the using 9723 // declaration itself is meant to have the 'typename' keyword. 9724 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 9725 IILoc); 9726 Diag(IILoc, diag::err_typename_refers_to_using_value_decl) 9727 << Name << Ctx << FullRange; 9728 if (UnresolvedUsingValueDecl *Using 9729 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){ 9730 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc(); 9731 Diag(Loc, diag::note_using_value_decl_missing_typename) 9732 << FixItHint::CreateInsertion(Loc, "typename "); 9733 } 9734 } 9735 // Fall through to create a dependent typename type, from which we can recover 9736 // better. 9737 LLVM_FALLTHROUGH; 9738 9739 case LookupResult::NotFoundInCurrentInstantiation: 9740 // Okay, it's a member of an unknown instantiation. 9741 return Context.getDependentNameType(Keyword, 9742 QualifierLoc.getNestedNameSpecifier(), 9743 &II); 9744 9745 case LookupResult::Found: 9746 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { 9747 // C++ [class.qual]p2: 9748 // In a lookup in which function names are not ignored and the 9749 // nested-name-specifier nominates a class C, if the name specified 9750 // after the nested-name-specifier, when looked up in C, is the 9751 // injected-class-name of C [...] then the name is instead considered 9752 // to name the constructor of class C. 9753 // 9754 // Unlike in an elaborated-type-specifier, function names are not ignored 9755 // in typename-specifier lookup. However, they are ignored in all the 9756 // contexts where we form a typename type with no keyword (that is, in 9757 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers). 9758 // 9759 // FIXME: That's not strictly true: mem-initializer-id lookup does not 9760 // ignore functions, but that appears to be an oversight. 9761 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx); 9762 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type); 9763 if (Keyword == ETK_Typename && LookupRD && FoundRD && 9764 FoundRD->isInjectedClassName() && 9765 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 9766 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor) 9767 << &II << 1 << 0 /*'typename' keyword used*/; 9768 9769 // We found a type. Build an ElaboratedType, since the 9770 // typename-specifier was just sugar. 9771 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 9772 return Context.getElaboratedType(Keyword, 9773 QualifierLoc.getNestedNameSpecifier(), 9774 Context.getTypeDeclType(Type)); 9775 } 9776 9777 // C++ [dcl.type.simple]p2: 9778 // A type-specifier of the form 9779 // typename[opt] nested-name-specifier[opt] template-name 9780 // is a placeholder for a deduced class type [...]. 9781 if (getLangOpts().CPlusPlus17) { 9782 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) { 9783 return Context.getElaboratedType( 9784 Keyword, QualifierLoc.getNestedNameSpecifier(), 9785 Context.getDeducedTemplateSpecializationType(TemplateName(TD), 9786 QualType(), false)); 9787 } 9788 } 9789 9790 DiagID = diag::err_typename_nested_not_type; 9791 Referenced = Result.getFoundDecl(); 9792 break; 9793 9794 case LookupResult::FoundOverloaded: 9795 DiagID = diag::err_typename_nested_not_type; 9796 Referenced = *Result.begin(); 9797 break; 9798 9799 case LookupResult::Ambiguous: 9800 return QualType(); 9801 } 9802 9803 // If we get here, it's because name lookup did not find a 9804 // type. Emit an appropriate diagnostic and return an error. 9805 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 9806 IILoc); 9807 Diag(IILoc, DiagID) << FullRange << Name << Ctx; 9808 if (Referenced) 9809 Diag(Referenced->getLocation(), diag::note_typename_refers_here) 9810 << Name; 9811 return QualType(); 9812 } 9813 9814 namespace { 9815 // See Sema::RebuildTypeInCurrentInstantiation 9816 class CurrentInstantiationRebuilder 9817 : public TreeTransform<CurrentInstantiationRebuilder> { 9818 SourceLocation Loc; 9819 DeclarationName Entity; 9820 9821 public: 9822 typedef TreeTransform<CurrentInstantiationRebuilder> inherited; 9823 9824 CurrentInstantiationRebuilder(Sema &SemaRef, 9825 SourceLocation Loc, 9826 DeclarationName Entity) 9827 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 9828 Loc(Loc), Entity(Entity) { } 9829 9830 /// Determine whether the given type \p T has already been 9831 /// transformed. 9832 /// 9833 /// For the purposes of type reconstruction, a type has already been 9834 /// transformed if it is NULL or if it is not dependent. 9835 bool AlreadyTransformed(QualType T) { 9836 return T.isNull() || !T->isDependentType(); 9837 } 9838 9839 /// Returns the location of the entity whose type is being 9840 /// rebuilt. 9841 SourceLocation getBaseLocation() { return Loc; } 9842 9843 /// Returns the name of the entity whose type is being rebuilt. 9844 DeclarationName getBaseEntity() { return Entity; } 9845 9846 /// Sets the "base" location and entity when that 9847 /// information is known based on another transformation. 9848 void setBase(SourceLocation Loc, DeclarationName Entity) { 9849 this->Loc = Loc; 9850 this->Entity = Entity; 9851 } 9852 9853 ExprResult TransformLambdaExpr(LambdaExpr *E) { 9854 // Lambdas never need to be transformed. 9855 return E; 9856 } 9857 }; 9858 } // end anonymous namespace 9859 9860 /// Rebuilds a type within the context of the current instantiation. 9861 /// 9862 /// The type \p T is part of the type of an out-of-line member definition of 9863 /// a class template (or class template partial specialization) that was parsed 9864 /// and constructed before we entered the scope of the class template (or 9865 /// partial specialization thereof). This routine will rebuild that type now 9866 /// that we have entered the declarator's scope, which may produce different 9867 /// canonical types, e.g., 9868 /// 9869 /// \code 9870 /// template<typename T> 9871 /// struct X { 9872 /// typedef T* pointer; 9873 /// pointer data(); 9874 /// }; 9875 /// 9876 /// template<typename T> 9877 /// typename X<T>::pointer X<T>::data() { ... } 9878 /// \endcode 9879 /// 9880 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType, 9881 /// since we do not know that we can look into X<T> when we parsed the type. 9882 /// This function will rebuild the type, performing the lookup of "pointer" 9883 /// in X<T> and returning an ElaboratedType whose canonical type is the same 9884 /// as the canonical type of T*, allowing the return types of the out-of-line 9885 /// definition and the declaration to match. 9886 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 9887 SourceLocation Loc, 9888 DeclarationName Name) { 9889 if (!T || !T->getType()->isDependentType()) 9890 return T; 9891 9892 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 9893 return Rebuilder.TransformType(T); 9894 } 9895 9896 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) { 9897 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(), 9898 DeclarationName()); 9899 return Rebuilder.TransformExpr(E); 9900 } 9901 9902 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) { 9903 if (SS.isInvalid()) 9904 return true; 9905 9906 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 9907 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(), 9908 DeclarationName()); 9909 NestedNameSpecifierLoc Rebuilt 9910 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc); 9911 if (!Rebuilt) 9912 return true; 9913 9914 SS.Adopt(Rebuilt); 9915 return false; 9916 } 9917 9918 /// Rebuild the template parameters now that we know we're in a current 9919 /// instantiation. 9920 bool Sema::RebuildTemplateParamsInCurrentInstantiation( 9921 TemplateParameterList *Params) { 9922 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 9923 Decl *Param = Params->getParam(I); 9924 9925 // There is nothing to rebuild in a type parameter. 9926 if (isa<TemplateTypeParmDecl>(Param)) 9927 continue; 9928 9929 // Rebuild the template parameter list of a template template parameter. 9930 if (TemplateTemplateParmDecl *TTP 9931 = dyn_cast<TemplateTemplateParmDecl>(Param)) { 9932 if (RebuildTemplateParamsInCurrentInstantiation( 9933 TTP->getTemplateParameters())) 9934 return true; 9935 9936 continue; 9937 } 9938 9939 // Rebuild the type of a non-type template parameter. 9940 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param); 9941 TypeSourceInfo *NewTSI 9942 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(), 9943 NTTP->getLocation(), 9944 NTTP->getDeclName()); 9945 if (!NewTSI) 9946 return true; 9947 9948 if (NewTSI->getType()->isUndeducedType()) { 9949 // C++17 [temp.dep.expr]p3: 9950 // An id-expression is type-dependent if it contains 9951 // - an identifier associated by name lookup with a non-type 9952 // template-parameter declared with a type that contains a 9953 // placeholder type (7.1.7.4), 9954 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy); 9955 } 9956 9957 if (NewTSI != NTTP->getTypeSourceInfo()) { 9958 NTTP->setTypeSourceInfo(NewTSI); 9959 NTTP->setType(NewTSI->getType()); 9960 } 9961 } 9962 9963 return false; 9964 } 9965 9966 /// Produces a formatted string that describes the binding of 9967 /// template parameters to template arguments. 9968 std::string 9969 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 9970 const TemplateArgumentList &Args) { 9971 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size()); 9972 } 9973 9974 std::string 9975 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 9976 const TemplateArgument *Args, 9977 unsigned NumArgs) { 9978 SmallString<128> Str; 9979 llvm::raw_svector_ostream Out(Str); 9980 9981 if (!Params || Params->size() == 0 || NumArgs == 0) 9982 return std::string(); 9983 9984 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 9985 if (I >= NumArgs) 9986 break; 9987 9988 if (I == 0) 9989 Out << "[with "; 9990 else 9991 Out << ", "; 9992 9993 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 9994 Out << Id->getName(); 9995 } else { 9996 Out << '$' << I; 9997 } 9998 9999 Out << " = "; 10000 Args[I].print(getPrintingPolicy(), Out); 10001 } 10002 10003 Out << ']'; 10004 return Out.str(); 10005 } 10006 10007 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 10008 CachedTokens &Toks) { 10009 if (!FD) 10010 return; 10011 10012 auto LPT = llvm::make_unique<LateParsedTemplate>(); 10013 10014 // Take tokens to avoid allocations 10015 LPT->Toks.swap(Toks); 10016 LPT->D = FnD; 10017 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT))); 10018 10019 FD->setLateTemplateParsed(true); 10020 } 10021 10022 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) { 10023 if (!FD) 10024 return; 10025 FD->setLateTemplateParsed(false); 10026 } 10027 10028 bool Sema::IsInsideALocalClassWithinATemplateFunction() { 10029 DeclContext *DC = CurContext; 10030 10031 while (DC) { 10032 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { 10033 const FunctionDecl *FD = RD->isLocalClass(); 10034 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate); 10035 } else if (DC->isTranslationUnit() || DC->isNamespace()) 10036 return false; 10037 10038 DC = DC->getParent(); 10039 } 10040 return false; 10041 } 10042 10043 namespace { 10044 /// Walk the path from which a declaration was instantiated, and check 10045 /// that every explicit specialization along that path is visible. This enforces 10046 /// C++ [temp.expl.spec]/6: 10047 /// 10048 /// If a template, a member template or a member of a class template is 10049 /// explicitly specialized then that specialization shall be declared before 10050 /// the first use of that specialization that would cause an implicit 10051 /// instantiation to take place, in every translation unit in which such a 10052 /// use occurs; no diagnostic is required. 10053 /// 10054 /// and also C++ [temp.class.spec]/1: 10055 /// 10056 /// A partial specialization shall be declared before the first use of a 10057 /// class template specialization that would make use of the partial 10058 /// specialization as the result of an implicit or explicit instantiation 10059 /// in every translation unit in which such a use occurs; no diagnostic is 10060 /// required. 10061 class ExplicitSpecializationVisibilityChecker { 10062 Sema &S; 10063 SourceLocation Loc; 10064 llvm::SmallVector<Module *, 8> Modules; 10065 10066 public: 10067 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc) 10068 : S(S), Loc(Loc) {} 10069 10070 void check(NamedDecl *ND) { 10071 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10072 return checkImpl(FD); 10073 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) 10074 return checkImpl(RD); 10075 if (auto *VD = dyn_cast<VarDecl>(ND)) 10076 return checkImpl(VD); 10077 if (auto *ED = dyn_cast<EnumDecl>(ND)) 10078 return checkImpl(ED); 10079 } 10080 10081 private: 10082 void diagnose(NamedDecl *D, bool IsPartialSpec) { 10083 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization 10084 : Sema::MissingImportKind::ExplicitSpecialization; 10085 const bool Recover = true; 10086 10087 // If we got a custom set of modules (because only a subset of the 10088 // declarations are interesting), use them, otherwise let 10089 // diagnoseMissingImport intelligently pick some. 10090 if (Modules.empty()) 10091 S.diagnoseMissingImport(Loc, D, Kind, Recover); 10092 else 10093 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover); 10094 } 10095 10096 // Check a specific declaration. There are three problematic cases: 10097 // 10098 // 1) The declaration is an explicit specialization of a template 10099 // specialization. 10100 // 2) The declaration is an explicit specialization of a member of an 10101 // templated class. 10102 // 3) The declaration is an instantiation of a template, and that template 10103 // is an explicit specialization of a member of a templated class. 10104 // 10105 // We don't need to go any deeper than that, as the instantiation of the 10106 // surrounding class / etc is not triggered by whatever triggered this 10107 // instantiation, and thus should be checked elsewhere. 10108 template<typename SpecDecl> 10109 void checkImpl(SpecDecl *Spec) { 10110 bool IsHiddenExplicitSpecialization = false; 10111 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { 10112 IsHiddenExplicitSpecialization = 10113 Spec->getMemberSpecializationInfo() 10114 ? !S.hasVisibleMemberSpecialization(Spec, &Modules) 10115 : !S.hasVisibleExplicitSpecialization(Spec, &Modules); 10116 } else { 10117 checkInstantiated(Spec); 10118 } 10119 10120 if (IsHiddenExplicitSpecialization) 10121 diagnose(Spec->getMostRecentDecl(), false); 10122 } 10123 10124 void checkInstantiated(FunctionDecl *FD) { 10125 if (auto *TD = FD->getPrimaryTemplate()) 10126 checkTemplate(TD); 10127 } 10128 10129 void checkInstantiated(CXXRecordDecl *RD) { 10130 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD); 10131 if (!SD) 10132 return; 10133 10134 auto From = SD->getSpecializedTemplateOrPartial(); 10135 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>()) 10136 checkTemplate(TD); 10137 else if (auto *TD = 10138 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { 10139 if (!S.hasVisibleDeclaration(TD)) 10140 diagnose(TD, true); 10141 checkTemplate(TD); 10142 } 10143 } 10144 10145 void checkInstantiated(VarDecl *RD) { 10146 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD); 10147 if (!SD) 10148 return; 10149 10150 auto From = SD->getSpecializedTemplateOrPartial(); 10151 if (auto *TD = From.dyn_cast<VarTemplateDecl *>()) 10152 checkTemplate(TD); 10153 else if (auto *TD = 10154 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 10155 if (!S.hasVisibleDeclaration(TD)) 10156 diagnose(TD, true); 10157 checkTemplate(TD); 10158 } 10159 } 10160 10161 void checkInstantiated(EnumDecl *FD) {} 10162 10163 template<typename TemplDecl> 10164 void checkTemplate(TemplDecl *TD) { 10165 if (TD->isMemberSpecialization()) { 10166 if (!S.hasVisibleMemberSpecialization(TD, &Modules)) 10167 diagnose(TD->getMostRecentDecl(), false); 10168 } 10169 } 10170 }; 10171 } // end anonymous namespace 10172 10173 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) { 10174 if (!getLangOpts().Modules) 10175 return; 10176 10177 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec); 10178 } 10179 10180 /// Check whether a template partial specialization that we've discovered 10181 /// is hidden, and produce suitable diagnostics if so. 10182 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc, 10183 NamedDecl *Spec) { 10184 llvm::SmallVector<Module *, 8> Modules; 10185 if (!hasVisibleDeclaration(Spec, &Modules)) 10186 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules, 10187 MissingImportKind::PartialSpecialization, 10188 /*Recover*/true); 10189 } 10190