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