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