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