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