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