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