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