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