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