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