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