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