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