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