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