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