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