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