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