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