SemaTemplate.cpp revision a97d24f2ca50f318f62a6cf2a621e7842dd63b4a
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 "clang/Sema/SemaInternal.h" 13#include "clang/Sema/Lookup.h" 14#include "clang/Sema/Scope.h" 15#include "clang/Sema/Template.h" 16#include "clang/Sema/TemplateDeduction.h" 17#include "TreeTransform.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/Expr.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/AST/DeclFriend.h" 22#include "clang/AST/DeclTemplate.h" 23#include "clang/AST/RecursiveASTVisitor.h" 24#include "clang/AST/TypeVisitor.h" 25#include "clang/Sema/DeclSpec.h" 26#include "clang/Sema/ParsedTemplate.h" 27#include "clang/Basic/LangOptions.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "llvm/ADT/StringExtras.h" 30using namespace clang; 31using namespace sema; 32 33// Exported for use by Parser. 34SourceRange 35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, 36 unsigned N) { 37 if (!N) return SourceRange(); 38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); 39} 40 41/// \brief Determine whether the declaration found is acceptable as the name 42/// of a template and, if so, return that template declaration. Otherwise, 43/// returns NULL. 44static NamedDecl *isAcceptableTemplateName(ASTContext &Context, 45 NamedDecl *Orig) { 46 NamedDecl *D = Orig->getUnderlyingDecl(); 47 48 if (isa<TemplateDecl>(D)) 49 return Orig; 50 51 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 52 // C++ [temp.local]p1: 53 // Like normal (non-template) classes, class templates have an 54 // injected-class-name (Clause 9). The injected-class-name 55 // can be used with or without a template-argument-list. When 56 // it is used without a template-argument-list, it is 57 // equivalent to the injected-class-name followed by the 58 // template-parameters of the class template enclosed in 59 // <>. When it is used with a template-argument-list, it 60 // refers to the specified class template specialization, 61 // which could be the current specialization or another 62 // specialization. 63 if (Record->isInjectedClassName()) { 64 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 65 if (Record->getDescribedClassTemplate()) 66 return Record->getDescribedClassTemplate(); 67 68 if (ClassTemplateSpecializationDecl *Spec 69 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 70 return Spec->getSpecializedTemplate(); 71 } 72 73 return 0; 74 } 75 76 return 0; 77} 78 79void Sema::FilterAcceptableTemplateNames(LookupResult &R) { 80 // The set of class templates we've already seen. 81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates; 82 LookupResult::Filter filter = R.makeFilter(); 83 while (filter.hasNext()) { 84 NamedDecl *Orig = filter.next(); 85 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig); 86 if (!Repl) 87 filter.erase(); 88 else if (Repl != Orig) { 89 90 // C++ [temp.local]p3: 91 // A lookup that finds an injected-class-name (10.2) can result in an 92 // ambiguity in certain cases (for example, if it is found in more than 93 // one base class). If all of the injected-class-names that are found 94 // refer to specializations of the same class template, and if the name 95 // is followed by a template-argument-list, the reference refers to the 96 // class template itself and not a specialization thereof, and is not 97 // ambiguous. 98 // 99 // FIXME: Will we eventually have to do the same for alias templates? 100 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl)) 101 if (!ClassTemplates.insert(ClassTmpl)) { 102 filter.erase(); 103 continue; 104 } 105 106 // FIXME: we promote access to public here as a workaround to 107 // the fact that LookupResult doesn't let us remember that we 108 // found this template through a particular injected class name, 109 // which means we end up doing nasty things to the invariants. 110 // Pretending that access is public is *much* safer. 111 filter.replace(Repl, AS_public); 112 } 113 } 114 filter.done(); 115} 116 117bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R) { 118 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) 119 if (isAcceptableTemplateName(Context, *I)) 120 return true; 121 122 return false; 123} 124 125TemplateNameKind Sema::isTemplateName(Scope *S, 126 CXXScopeSpec &SS, 127 bool hasTemplateKeyword, 128 UnqualifiedId &Name, 129 ParsedType ObjectTypePtr, 130 bool EnteringContext, 131 TemplateTy &TemplateResult, 132 bool &MemberOfUnknownSpecialization) { 133 assert(getLangOptions().CPlusPlus && "No template names in C!"); 134 135 DeclarationName TName; 136 MemberOfUnknownSpecialization = false; 137 138 switch (Name.getKind()) { 139 case UnqualifiedId::IK_Identifier: 140 TName = DeclarationName(Name.Identifier); 141 break; 142 143 case UnqualifiedId::IK_OperatorFunctionId: 144 TName = Context.DeclarationNames.getCXXOperatorName( 145 Name.OperatorFunctionId.Operator); 146 break; 147 148 case UnqualifiedId::IK_LiteralOperatorId: 149 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); 150 break; 151 152 default: 153 return TNK_Non_template; 154 } 155 156 QualType ObjectType = ObjectTypePtr.get(); 157 158 LookupResult R(*this, TName, Name.getSourceRange().getBegin(), 159 LookupOrdinaryName); 160 LookupTemplateName(R, S, SS, ObjectType, EnteringContext, 161 MemberOfUnknownSpecialization); 162 if (R.empty()) return TNK_Non_template; 163 if (R.isAmbiguous()) { 164 // Suppress diagnostics; we'll redo this lookup later. 165 R.suppressDiagnostics(); 166 167 // FIXME: we might have ambiguous templates, in which case we 168 // should at least parse them properly! 169 return TNK_Non_template; 170 } 171 172 TemplateName Template; 173 TemplateNameKind TemplateKind; 174 175 unsigned ResultCount = R.end() - R.begin(); 176 if (ResultCount > 1) { 177 // We assume that we'll preserve the qualifier from a function 178 // template name in other ways. 179 Template = Context.getOverloadedTemplateName(R.begin(), R.end()); 180 TemplateKind = TNK_Function_template; 181 182 // We'll do this lookup again later. 183 R.suppressDiagnostics(); 184 } else { 185 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl()); 186 187 if (SS.isSet() && !SS.isInvalid()) { 188 NestedNameSpecifier *Qualifier 189 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 190 Template = Context.getQualifiedTemplateName(Qualifier, 191 hasTemplateKeyword, TD); 192 } else { 193 Template = TemplateName(TD); 194 } 195 196 if (isa<FunctionTemplateDecl>(TD)) { 197 TemplateKind = TNK_Function_template; 198 199 // We'll do this lookup again later. 200 R.suppressDiagnostics(); 201 } else { 202 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD)); 203 TemplateKind = TNK_Type_template; 204 } 205 } 206 207 TemplateResult = TemplateTy::make(Template); 208 return TemplateKind; 209} 210 211bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, 212 SourceLocation IILoc, 213 Scope *S, 214 const CXXScopeSpec *SS, 215 TemplateTy &SuggestedTemplate, 216 TemplateNameKind &SuggestedKind) { 217 // We can't recover unless there's a dependent scope specifier preceding the 218 // template name. 219 // FIXME: Typo correction? 220 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || 221 computeDeclContext(*SS)) 222 return false; 223 224 // The code is missing a 'template' keyword prior to the dependent template 225 // name. 226 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); 227 Diag(IILoc, diag::err_template_kw_missing) 228 << Qualifier << II.getName() 229 << FixItHint::CreateInsertion(IILoc, "template "); 230 SuggestedTemplate 231 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); 232 SuggestedKind = TNK_Dependent_template_name; 233 return true; 234} 235 236void Sema::LookupTemplateName(LookupResult &Found, 237 Scope *S, CXXScopeSpec &SS, 238 QualType ObjectType, 239 bool EnteringContext, 240 bool &MemberOfUnknownSpecialization) { 241 // Determine where to perform name lookup 242 MemberOfUnknownSpecialization = false; 243 DeclContext *LookupCtx = 0; 244 bool isDependent = false; 245 if (!ObjectType.isNull()) { 246 // This nested-name-specifier occurs in a member access expression, e.g., 247 // x->B::f, and we are looking into the type of the object. 248 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 249 LookupCtx = computeDeclContext(ObjectType); 250 isDependent = ObjectType->isDependentType(); 251 assert((isDependent || !ObjectType->isIncompleteType()) && 252 "Caller should have completed object type"); 253 } else if (SS.isSet()) { 254 // This nested-name-specifier occurs after another nested-name-specifier, 255 // so long into the context associated with the prior nested-name-specifier. 256 LookupCtx = computeDeclContext(SS, EnteringContext); 257 isDependent = isDependentScopeSpecifier(SS); 258 259 // The declaration context must be complete. 260 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) 261 return; 262 } 263 264 bool ObjectTypeSearchedInScope = false; 265 if (LookupCtx) { 266 // Perform "qualified" name lookup into the declaration context we 267 // computed, which is either the type of the base of a member access 268 // expression or the declaration context associated with a prior 269 // nested-name-specifier. 270 LookupQualifiedName(Found, LookupCtx); 271 272 if (!ObjectType.isNull() && Found.empty()) { 273 // C++ [basic.lookup.classref]p1: 274 // In a class member access expression (5.2.5), if the . or -> token is 275 // immediately followed by an identifier followed by a <, the 276 // identifier must be looked up to determine whether the < is the 277 // beginning of a template argument list (14.2) or a less-than operator. 278 // The identifier is first looked up in the class of the object 279 // expression. If the identifier is not found, it is then looked up in 280 // the context of the entire postfix-expression and shall name a class 281 // or function template. 282 if (S) LookupName(Found, S); 283 ObjectTypeSearchedInScope = true; 284 } 285 } else if (isDependent && (!S || ObjectType.isNull())) { 286 // We cannot look into a dependent object type or nested nme 287 // specifier. 288 MemberOfUnknownSpecialization = true; 289 return; 290 } else { 291 // Perform unqualified name lookup in the current scope. 292 LookupName(Found, S); 293 } 294 295 if (Found.empty() && !isDependent) { 296 // If we did not find any names, attempt to correct any typos. 297 DeclarationName Name = Found.getLookupName(); 298 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx, 299 false, CTC_CXXCasts)) { 300 FilterAcceptableTemplateNames(Found); 301 if (!Found.empty()) { 302 if (LookupCtx) 303 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest) 304 << Name << LookupCtx << Found.getLookupName() << SS.getRange() 305 << FixItHint::CreateReplacement(Found.getNameLoc(), 306 Found.getLookupName().getAsString()); 307 else 308 Diag(Found.getNameLoc(), diag::err_no_template_suggest) 309 << Name << Found.getLookupName() 310 << FixItHint::CreateReplacement(Found.getNameLoc(), 311 Found.getLookupName().getAsString()); 312 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>()) 313 Diag(Template->getLocation(), diag::note_previous_decl) 314 << Template->getDeclName(); 315 } 316 } else { 317 Found.clear(); 318 Found.setLookupName(Name); 319 } 320 } 321 322 FilterAcceptableTemplateNames(Found); 323 if (Found.empty()) { 324 if (isDependent) 325 MemberOfUnknownSpecialization = true; 326 return; 327 } 328 329 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) { 330 // C++ [basic.lookup.classref]p1: 331 // [...] If the lookup in the class of the object expression finds a 332 // template, the name is also looked up in the context of the entire 333 // postfix-expression and [...] 334 // 335 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 336 LookupOrdinaryName); 337 LookupName(FoundOuter, S); 338 FilterAcceptableTemplateNames(FoundOuter); 339 340 if (FoundOuter.empty()) { 341 // - if the name is not found, the name found in the class of the 342 // object expression is used, otherwise 343 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) { 344 // - if the name is found in the context of the entire 345 // postfix-expression and does not name a class template, the name 346 // found in the class of the object expression is used, otherwise 347 } else if (!Found.isSuppressingDiagnostics()) { 348 // - if the name found is a class template, it must refer to the same 349 // entity as the one found in the class of the object expression, 350 // otherwise the program is ill-formed. 351 if (!Found.isSingleResult() || 352 Found.getFoundDecl()->getCanonicalDecl() 353 != FoundOuter.getFoundDecl()->getCanonicalDecl()) { 354 Diag(Found.getNameLoc(), 355 diag::ext_nested_name_member_ref_lookup_ambiguous) 356 << Found.getLookupName() 357 << ObjectType; 358 Diag(Found.getRepresentativeDecl()->getLocation(), 359 diag::note_ambig_member_ref_object_type) 360 << ObjectType; 361 Diag(FoundOuter.getFoundDecl()->getLocation(), 362 diag::note_ambig_member_ref_scope); 363 364 // Recover by taking the template that we found in the object 365 // expression's type. 366 } 367 } 368 } 369} 370 371/// ActOnDependentIdExpression - Handle a dependent id-expression that 372/// was just parsed. This is only possible with an explicit scope 373/// specifier naming a dependent type. 374ExprResult 375Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 376 const DeclarationNameInfo &NameInfo, 377 bool isAddressOfOperand, 378 const TemplateArgumentListInfo *TemplateArgs) { 379 DeclContext *DC = getFunctionLevelDeclContext(); 380 381 if (!isAddressOfOperand && 382 isa<CXXMethodDecl>(DC) && 383 cast<CXXMethodDecl>(DC)->isInstance()) { 384 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context); 385 386 // Since the 'this' expression is synthesized, we don't need to 387 // perform the double-lookup check. 388 NamedDecl *FirstQualifierInScope = 0; 389 390 return Owned(CXXDependentScopeMemberExpr::Create(Context, 391 /*This*/ 0, ThisType, 392 /*IsArrow*/ true, 393 /*Op*/ SourceLocation(), 394 SS.getWithLocInContext(Context), 395 FirstQualifierInScope, 396 NameInfo, 397 TemplateArgs)); 398 } 399 400 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs); 401} 402 403ExprResult 404Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 405 const DeclarationNameInfo &NameInfo, 406 const TemplateArgumentListInfo *TemplateArgs) { 407 return Owned(DependentScopeDeclRefExpr::Create(Context, 408 SS.getWithLocInContext(Context), 409 NameInfo, 410 TemplateArgs)); 411} 412 413/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 414/// that the template parameter 'PrevDecl' is being shadowed by a new 415/// declaration at location Loc. Returns true to indicate that this is 416/// an error, and false otherwise. 417bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 418 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 419 420 // Microsoft Visual C++ permits template parameters to be shadowed. 421 if (getLangOptions().Microsoft) 422 return false; 423 424 // C++ [temp.local]p4: 425 // A template-parameter shall not be redeclared within its 426 // scope (including nested scopes). 427 Diag(Loc, diag::err_template_param_shadow) 428 << cast<NamedDecl>(PrevDecl)->getDeclName(); 429 Diag(PrevDecl->getLocation(), diag::note_template_param_here); 430 return true; 431} 432 433/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 434/// the parameter D to reference the templated declaration and return a pointer 435/// to the template declaration. Otherwise, do nothing to D and return null. 436TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { 437 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { 438 D = Temp->getTemplatedDecl(); 439 return Temp; 440 } 441 return 0; 442} 443 444ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( 445 SourceLocation EllipsisLoc) const { 446 assert(Kind == Template && 447 "Only template template arguments can be pack expansions here"); 448 assert(getAsTemplate().get().containsUnexpandedParameterPack() && 449 "Template template argument pack expansion without packs"); 450 ParsedTemplateArgument Result(*this); 451 Result.EllipsisLoc = EllipsisLoc; 452 return Result; 453} 454 455static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 456 const ParsedTemplateArgument &Arg) { 457 458 switch (Arg.getKind()) { 459 case ParsedTemplateArgument::Type: { 460 TypeSourceInfo *DI; 461 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 462 if (!DI) 463 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); 464 return TemplateArgumentLoc(TemplateArgument(T), DI); 465 } 466 467 case ParsedTemplateArgument::NonType: { 468 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 469 return TemplateArgumentLoc(TemplateArgument(E), E); 470 } 471 472 case ParsedTemplateArgument::Template: { 473 TemplateName Template = Arg.getAsTemplate().get(); 474 TemplateArgument TArg; 475 if (Arg.getEllipsisLoc().isValid()) 476 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>()); 477 else 478 TArg = Template; 479 return TemplateArgumentLoc(TArg, 480 Arg.getScopeSpec().getWithLocInContext( 481 SemaRef.Context), 482 Arg.getLocation(), 483 Arg.getEllipsisLoc()); 484 } 485 } 486 487 llvm_unreachable("Unhandled parsed template argument"); 488 return TemplateArgumentLoc(); 489} 490 491/// \brief Translates template arguments as provided by the parser 492/// into template arguments used by semantic analysis. 493void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 494 TemplateArgumentListInfo &TemplateArgs) { 495 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 496 TemplateArgs.addArgument(translateTemplateArgument(*this, 497 TemplateArgsIn[I])); 498} 499 500/// ActOnTypeParameter - Called when a C++ template type parameter 501/// (e.g., "typename T") has been parsed. Typename specifies whether 502/// the keyword "typename" was used to declare the type parameter 503/// (otherwise, "class" was used), and KeyLoc is the location of the 504/// "class" or "typename" keyword. ParamName is the name of the 505/// parameter (NULL indicates an unnamed template parameter) and 506/// ParamName is the location of the parameter name (if any). 507/// If the type parameter has a default argument, it will be added 508/// later via ActOnTypeParameterDefault. 509Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 510 SourceLocation EllipsisLoc, 511 SourceLocation KeyLoc, 512 IdentifierInfo *ParamName, 513 SourceLocation ParamNameLoc, 514 unsigned Depth, unsigned Position, 515 SourceLocation EqualLoc, 516 ParsedType DefaultArg) { 517 assert(S->isTemplateParamScope() && 518 "Template type parameter not in template parameter scope!"); 519 bool Invalid = false; 520 521 if (ParamName) { 522 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc, 523 LookupOrdinaryName, 524 ForRedeclaration); 525 if (PrevDecl && PrevDecl->isTemplateParameter()) 526 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc, 527 PrevDecl); 528 } 529 530 SourceLocation Loc = ParamNameLoc; 531 if (!ParamName) 532 Loc = KeyLoc; 533 534 TemplateTypeParmDecl *Param 535 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), 536 KeyLoc, Loc, Depth, Position, ParamName, 537 Typename, Ellipsis); 538 Param->setAccess(AS_public); 539 if (Invalid) 540 Param->setInvalidDecl(); 541 542 if (ParamName) { 543 // Add the template parameter into the current scope. 544 S->AddDecl(Param); 545 IdResolver.AddDecl(Param); 546 } 547 548 // C++0x [temp.param]p9: 549 // A default template-argument may be specified for any kind of 550 // template-parameter that is not a template parameter pack. 551 if (DefaultArg && Ellipsis) { 552 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 553 DefaultArg = ParsedType(); 554 } 555 556 // Handle the default argument, if provided. 557 if (DefaultArg) { 558 TypeSourceInfo *DefaultTInfo; 559 GetTypeFromParser(DefaultArg, &DefaultTInfo); 560 561 assert(DefaultTInfo && "expected source information for type"); 562 563 // Check for unexpanded parameter packs. 564 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo, 565 UPPC_DefaultArgument)) 566 return Param; 567 568 // Check the template argument itself. 569 if (CheckTemplateArgument(Param, DefaultTInfo)) { 570 Param->setInvalidDecl(); 571 return Param; 572 } 573 574 Param->setDefaultArgument(DefaultTInfo, false); 575 } 576 577 return Param; 578} 579 580/// \brief Check that the type of a non-type template parameter is 581/// well-formed. 582/// 583/// \returns the (possibly-promoted) parameter type if valid; 584/// otherwise, produces a diagnostic and returns a NULL type. 585QualType 586Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) { 587 // We don't allow variably-modified types as the type of non-type template 588 // parameters. 589 if (T->isVariablyModifiedType()) { 590 Diag(Loc, diag::err_variably_modified_nontype_template_param) 591 << T; 592 return QualType(); 593 } 594 595 // C++ [temp.param]p4: 596 // 597 // A non-type template-parameter shall have one of the following 598 // (optionally cv-qualified) types: 599 // 600 // -- integral or enumeration type, 601 if (T->isIntegralOrEnumerationType() || 602 // -- pointer to object or pointer to function, 603 T->isPointerType() || 604 // -- reference to object or reference to function, 605 T->isReferenceType() || 606 // -- pointer to member. 607 T->isMemberPointerType() || 608 // If T is a dependent type, we can't do the check now, so we 609 // assume that it is well-formed. 610 T->isDependentType()) 611 return T; 612 // C++ [temp.param]p8: 613 // 614 // A non-type template-parameter of type "array of T" or 615 // "function returning T" is adjusted to be of type "pointer to 616 // T" or "pointer to function returning T", respectively. 617 else if (T->isArrayType()) 618 // FIXME: Keep the type prior to promotion? 619 return Context.getArrayDecayedType(T); 620 else if (T->isFunctionType()) 621 // FIXME: Keep the type prior to promotion? 622 return Context.getPointerType(T); 623 624 Diag(Loc, diag::err_template_nontype_parm_bad_type) 625 << T; 626 627 return QualType(); 628} 629 630Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 631 unsigned Depth, 632 unsigned Position, 633 SourceLocation EqualLoc, 634 Expr *Default) { 635 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 636 QualType T = TInfo->getType(); 637 638 assert(S->isTemplateParamScope() && 639 "Non-type template parameter not in template parameter scope!"); 640 bool Invalid = false; 641 642 IdentifierInfo *ParamName = D.getIdentifier(); 643 if (ParamName) { 644 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(), 645 LookupOrdinaryName, 646 ForRedeclaration); 647 if (PrevDecl && PrevDecl->isTemplateParameter()) 648 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 649 PrevDecl); 650 } 651 652 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); 653 if (T.isNull()) { 654 T = Context.IntTy; // Recover with an 'int' type. 655 Invalid = true; 656 } 657 658 bool IsParameterPack = D.hasEllipsis(); 659 NonTypeTemplateParmDecl *Param 660 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 661 D.getSourceRange().getBegin(), 662 D.getIdentifierLoc(), 663 Depth, Position, ParamName, T, 664 IsParameterPack, TInfo); 665 Param->setAccess(AS_public); 666 667 if (Invalid) 668 Param->setInvalidDecl(); 669 670 if (D.getIdentifier()) { 671 // Add the template parameter into the current scope. 672 S->AddDecl(Param); 673 IdResolver.AddDecl(Param); 674 } 675 676 // C++0x [temp.param]p9: 677 // A default template-argument may be specified for any kind of 678 // template-parameter that is not a template parameter pack. 679 if (Default && IsParameterPack) { 680 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 681 Default = 0; 682 } 683 684 // Check the well-formedness of the default template argument, if provided. 685 if (Default) { 686 // Check for unexpanded parameter packs. 687 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) 688 return Param; 689 690 TemplateArgument Converted; 691 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted); 692 if (DefaultRes.isInvalid()) { 693 Param->setInvalidDecl(); 694 return Param; 695 } 696 Default = DefaultRes.take(); 697 698 Param->setDefaultArgument(Default, false); 699 } 700 701 return Param; 702} 703 704/// ActOnTemplateTemplateParameter - Called when a C++ template template 705/// parameter (e.g. T in template <template <typename> class T> class array) 706/// has been parsed. S is the current scope. 707Decl *Sema::ActOnTemplateTemplateParameter(Scope* S, 708 SourceLocation TmpLoc, 709 TemplateParamsTy *Params, 710 SourceLocation EllipsisLoc, 711 IdentifierInfo *Name, 712 SourceLocation NameLoc, 713 unsigned Depth, 714 unsigned Position, 715 SourceLocation EqualLoc, 716 ParsedTemplateArgument Default) { 717 assert(S->isTemplateParamScope() && 718 "Template template parameter not in template parameter scope!"); 719 720 // Construct the parameter object. 721 bool IsParameterPack = EllipsisLoc.isValid(); 722 TemplateTemplateParmDecl *Param = 723 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 724 NameLoc.isInvalid()? TmpLoc : NameLoc, 725 Depth, Position, IsParameterPack, 726 Name, Params); 727 Param->setAccess(AS_public); 728 729 // If the template template parameter has a name, then link the identifier 730 // into the scope and lookup mechanisms. 731 if (Name) { 732 S->AddDecl(Param); 733 IdResolver.AddDecl(Param); 734 } 735 736 if (Params->size() == 0) { 737 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) 738 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); 739 Param->setInvalidDecl(); 740 } 741 742 // C++0x [temp.param]p9: 743 // A default template-argument may be specified for any kind of 744 // template-parameter that is not a template parameter pack. 745 if (IsParameterPack && !Default.isInvalid()) { 746 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 747 Default = ParsedTemplateArgument(); 748 } 749 750 if (!Default.isInvalid()) { 751 // Check only that we have a template template argument. We don't want to 752 // try to check well-formedness now, because our template template parameter 753 // might have dependent types in its template parameters, which we wouldn't 754 // be able to match now. 755 // 756 // If none of the template template parameter's template arguments mention 757 // other template parameters, we could actually perform more checking here. 758 // However, it isn't worth doing. 759 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 760 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 761 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template) 762 << DefaultArg.getSourceRange(); 763 return Param; 764 } 765 766 // Check for unexpanded parameter packs. 767 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), 768 DefaultArg.getArgument().getAsTemplate(), 769 UPPC_DefaultArgument)) 770 return Param; 771 772 Param->setDefaultArgument(DefaultArg, false); 773 } 774 775 return Param; 776} 777 778/// ActOnTemplateParameterList - Builds a TemplateParameterList that 779/// contains the template parameters in Params/NumParams. 780Sema::TemplateParamsTy * 781Sema::ActOnTemplateParameterList(unsigned Depth, 782 SourceLocation ExportLoc, 783 SourceLocation TemplateLoc, 784 SourceLocation LAngleLoc, 785 Decl **Params, unsigned NumParams, 786 SourceLocation RAngleLoc) { 787 if (ExportLoc.isValid()) 788 Diag(ExportLoc, diag::warn_template_export_unsupported); 789 790 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 791 (NamedDecl**)Params, NumParams, 792 RAngleLoc); 793} 794 795static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) { 796 if (SS.isSet()) 797 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext())); 798} 799 800DeclResult 801Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 802 SourceLocation KWLoc, CXXScopeSpec &SS, 803 IdentifierInfo *Name, SourceLocation NameLoc, 804 AttributeList *Attr, 805 TemplateParameterList *TemplateParams, 806 AccessSpecifier AS, 807 unsigned NumOuterTemplateParamLists, 808 TemplateParameterList** OuterTemplateParamLists) { 809 assert(TemplateParams && TemplateParams->size() > 0 && 810 "No template parameters"); 811 assert(TUK != TUK_Reference && "Can only declare or define class templates"); 812 bool Invalid = false; 813 814 // Check that we can declare a template here. 815 if (CheckTemplateDeclScope(S, TemplateParams)) 816 return true; 817 818 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 819 assert(Kind != TTK_Enum && "can't build template of enumerated type"); 820 821 // There is no such thing as an unnamed class template. 822 if (!Name) { 823 Diag(KWLoc, diag::err_template_unnamed_class); 824 return true; 825 } 826 827 // Find any previous declaration with this name. 828 DeclContext *SemanticContext; 829 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName, 830 ForRedeclaration); 831 if (SS.isNotEmpty() && !SS.isInvalid()) { 832 SemanticContext = computeDeclContext(SS, true); 833 if (!SemanticContext) { 834 // FIXME: Produce a reasonable diagnostic here 835 return true; 836 } 837 838 if (RequireCompleteDeclContext(SS, SemanticContext)) 839 return true; 840 841 LookupQualifiedName(Previous, SemanticContext); 842 } else { 843 SemanticContext = CurContext; 844 LookupName(Previous, S); 845 } 846 847 if (Previous.isAmbiguous()) 848 return true; 849 850 NamedDecl *PrevDecl = 0; 851 if (Previous.begin() != Previous.end()) 852 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 853 854 // If there is a previous declaration with the same name, check 855 // whether this is a valid redeclaration. 856 ClassTemplateDecl *PrevClassTemplate 857 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 858 859 // We may have found the injected-class-name of a class template, 860 // class template partial specialization, or class template specialization. 861 // In these cases, grab the template that is being defined or specialized. 862 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 863 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { 864 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); 865 PrevClassTemplate 866 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); 867 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { 868 PrevClassTemplate 869 = cast<ClassTemplateSpecializationDecl>(PrevDecl) 870 ->getSpecializedTemplate(); 871 } 872 } 873 874 if (TUK == TUK_Friend) { 875 // C++ [namespace.memdef]p3: 876 // [...] When looking for a prior declaration of a class or a function 877 // declared as a friend, and when the name of the friend class or 878 // function is neither a qualified name nor a template-id, scopes outside 879 // the innermost enclosing namespace scope are not considered. 880 if (!SS.isSet()) { 881 DeclContext *OutermostContext = CurContext; 882 while (!OutermostContext->isFileContext()) 883 OutermostContext = OutermostContext->getLookupParent(); 884 885 if (PrevDecl && 886 (OutermostContext->Equals(PrevDecl->getDeclContext()) || 887 OutermostContext->Encloses(PrevDecl->getDeclContext()))) { 888 SemanticContext = PrevDecl->getDeclContext(); 889 } else { 890 // Declarations in outer scopes don't matter. However, the outermost 891 // context we computed is the semantic context for our new 892 // declaration. 893 PrevDecl = PrevClassTemplate = 0; 894 SemanticContext = OutermostContext; 895 } 896 } 897 898 if (CurContext->isDependentContext()) { 899 // If this is a dependent context, we don't want to link the friend 900 // class template to the template in scope, because that would perform 901 // checking of the template parameter lists that can't be performed 902 // until the outer context is instantiated. 903 PrevDecl = PrevClassTemplate = 0; 904 } 905 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S)) 906 PrevDecl = PrevClassTemplate = 0; 907 908 if (PrevClassTemplate) { 909 // Ensure that the template parameter lists are compatible. 910 if (!TemplateParameterListsAreEqual(TemplateParams, 911 PrevClassTemplate->getTemplateParameters(), 912 /*Complain=*/true, 913 TPL_TemplateMatch)) 914 return true; 915 916 // C++ [temp.class]p4: 917 // In a redeclaration, partial specialization, explicit 918 // specialization or explicit instantiation of a class template, 919 // the class-key shall agree in kind with the original class 920 // template declaration (7.1.5.3). 921 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 922 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) { 923 Diag(KWLoc, diag::err_use_with_wrong_tag) 924 << Name 925 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); 926 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 927 Kind = PrevRecordDecl->getTagKind(); 928 } 929 930 // Check for redefinition of this class template. 931 if (TUK == TUK_Definition) { 932 if (TagDecl *Def = PrevRecordDecl->getDefinition()) { 933 Diag(NameLoc, diag::err_redefinition) << Name; 934 Diag(Def->getLocation(), diag::note_previous_definition); 935 // FIXME: Would it make sense to try to "forget" the previous 936 // definition, as part of error recovery? 937 return true; 938 } 939 } 940 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 941 // Maybe we will complain about the shadowed template parameter. 942 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 943 // Just pretend that we didn't see the previous declaration. 944 PrevDecl = 0; 945 } else if (PrevDecl) { 946 // C++ [temp]p5: 947 // A class template shall not have the same name as any other 948 // template, class, function, object, enumeration, enumerator, 949 // namespace, or type in the same scope (3.3), except as specified 950 // in (14.5.4). 951 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 952 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 953 return true; 954 } 955 956 // Check the template parameter list of this declaration, possibly 957 // merging in the template parameter list from the previous class 958 // template declaration. 959 if (CheckTemplateParameterList(TemplateParams, 960 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0, 961 (SS.isSet() && SemanticContext && 962 SemanticContext->isRecord() && 963 SemanticContext->isDependentContext()) 964 ? TPC_ClassTemplateMember 965 : TPC_ClassTemplate)) 966 Invalid = true; 967 968 if (SS.isSet()) { 969 // If the name of the template was qualified, we must be defining the 970 // template out-of-line. 971 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate && 972 !(TUK == TUK_Friend && CurContext->isDependentContext())) 973 Diag(NameLoc, diag::err_member_def_does_not_match) 974 << Name << SemanticContext << SS.getRange(); 975 } 976 977 CXXRecordDecl *NewClass = 978 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name, 979 PrevClassTemplate? 980 PrevClassTemplate->getTemplatedDecl() : 0, 981 /*DelayTypeCreation=*/true); 982 SetNestedNameSpecifier(NewClass, SS); 983 if (NumOuterTemplateParamLists > 0) 984 NewClass->setTemplateParameterListsInfo(Context, 985 NumOuterTemplateParamLists, 986 OuterTemplateParamLists); 987 988 ClassTemplateDecl *NewTemplate 989 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 990 DeclarationName(Name), TemplateParams, 991 NewClass, PrevClassTemplate); 992 NewClass->setDescribedClassTemplate(NewTemplate); 993 994 // Build the type for the class template declaration now. 995 QualType T = NewTemplate->getInjectedClassNameSpecialization(); 996 T = Context.getInjectedClassNameType(NewClass, T); 997 assert(T->isDependentType() && "Class template type is not dependent?"); 998 (void)T; 999 1000 // If we are providing an explicit specialization of a member that is a 1001 // class template, make a note of that. 1002 if (PrevClassTemplate && 1003 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 1004 PrevClassTemplate->setMemberSpecialization(); 1005 1006 // Set the access specifier. 1007 if (!Invalid && TUK != TUK_Friend) 1008 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 1009 1010 // Set the lexical context of these templates 1011 NewClass->setLexicalDeclContext(CurContext); 1012 NewTemplate->setLexicalDeclContext(CurContext); 1013 1014 if (TUK == TUK_Definition) 1015 NewClass->startDefinition(); 1016 1017 if (Attr) 1018 ProcessDeclAttributeList(S, NewClass, Attr); 1019 1020 if (TUK != TUK_Friend) 1021 PushOnScopeChains(NewTemplate, S); 1022 else { 1023 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 1024 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 1025 NewClass->setAccess(PrevClassTemplate->getAccess()); 1026 } 1027 1028 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */ 1029 PrevClassTemplate != NULL); 1030 1031 // Friend templates are visible in fairly strange ways. 1032 if (!CurContext->isDependentContext()) { 1033 DeclContext *DC = SemanticContext->getRedeclContext(); 1034 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false); 1035 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 1036 PushOnScopeChains(NewTemplate, EnclosingScope, 1037 /* AddToContext = */ false); 1038 } 1039 1040 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 1041 NewClass->getLocation(), 1042 NewTemplate, 1043 /*FIXME:*/NewClass->getLocation()); 1044 Friend->setAccess(AS_public); 1045 CurContext->addDecl(Friend); 1046 } 1047 1048 if (Invalid) { 1049 NewTemplate->setInvalidDecl(); 1050 NewClass->setInvalidDecl(); 1051 } 1052 return NewTemplate; 1053} 1054 1055/// \brief Diagnose the presence of a default template argument on a 1056/// template parameter, which is ill-formed in certain contexts. 1057/// 1058/// \returns true if the default template argument should be dropped. 1059static bool DiagnoseDefaultTemplateArgument(Sema &S, 1060 Sema::TemplateParamListContext TPC, 1061 SourceLocation ParamLoc, 1062 SourceRange DefArgRange) { 1063 switch (TPC) { 1064 case Sema::TPC_ClassTemplate: 1065 return false; 1066 1067 case Sema::TPC_FunctionTemplate: 1068 case Sema::TPC_FriendFunctionTemplateDefinition: 1069 // C++ [temp.param]p9: 1070 // A default template-argument shall not be specified in a 1071 // function template declaration or a function template 1072 // definition [...] 1073 // If a friend function template declaration specifies a default 1074 // template-argument, that declaration shall be a definition and shall be 1075 // the only declaration of the function template in the translation unit. 1076 // (C++98/03 doesn't have this wording; see DR226). 1077 if (!S.getLangOptions().CPlusPlus0x) 1078 S.Diag(ParamLoc, 1079 diag::ext_template_parameter_default_in_function_template) 1080 << DefArgRange; 1081 return false; 1082 1083 case Sema::TPC_ClassTemplateMember: 1084 // C++0x [temp.param]p9: 1085 // A default template-argument shall not be specified in the 1086 // template-parameter-lists of the definition of a member of a 1087 // class template that appears outside of the member's class. 1088 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) 1089 << DefArgRange; 1090 return true; 1091 1092 case Sema::TPC_FriendFunctionTemplate: 1093 // C++ [temp.param]p9: 1094 // A default template-argument shall not be specified in a 1095 // friend template declaration. 1096 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) 1097 << DefArgRange; 1098 return true; 1099 1100 // FIXME: C++0x [temp.param]p9 allows default template-arguments 1101 // for friend function templates if there is only a single 1102 // declaration (and it is a definition). Strange! 1103 } 1104 1105 return false; 1106} 1107 1108/// \brief Check for unexpanded parameter packs within the template parameters 1109/// of a template template parameter, recursively. 1110static bool DiagnoseUnexpandedParameterPacks(Sema &S, 1111 TemplateTemplateParmDecl *TTP) { 1112 TemplateParameterList *Params = TTP->getTemplateParameters(); 1113 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 1114 NamedDecl *P = Params->getParam(I); 1115 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 1116 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), 1117 NTTP->getTypeSourceInfo(), 1118 Sema::UPPC_NonTypeTemplateParameterType)) 1119 return true; 1120 1121 continue; 1122 } 1123 1124 if (TemplateTemplateParmDecl *InnerTTP 1125 = dyn_cast<TemplateTemplateParmDecl>(P)) 1126 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) 1127 return true; 1128 } 1129 1130 return false; 1131} 1132 1133/// \brief Checks the validity of a template parameter list, possibly 1134/// considering the template parameter list from a previous 1135/// declaration. 1136/// 1137/// If an "old" template parameter list is provided, it must be 1138/// equivalent (per TemplateParameterListsAreEqual) to the "new" 1139/// template parameter list. 1140/// 1141/// \param NewParams Template parameter list for a new template 1142/// declaration. This template parameter list will be updated with any 1143/// default arguments that are carried through from the previous 1144/// template parameter list. 1145/// 1146/// \param OldParams If provided, template parameter list from a 1147/// previous declaration of the same template. Default template 1148/// arguments will be merged from the old template parameter list to 1149/// the new template parameter list. 1150/// 1151/// \param TPC Describes the context in which we are checking the given 1152/// template parameter list. 1153/// 1154/// \returns true if an error occurred, false otherwise. 1155bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 1156 TemplateParameterList *OldParams, 1157 TemplateParamListContext TPC) { 1158 bool Invalid = false; 1159 1160 // C++ [temp.param]p10: 1161 // The set of default template-arguments available for use with a 1162 // template declaration or definition is obtained by merging the 1163 // default arguments from the definition (if in scope) and all 1164 // declarations in scope in the same way default function 1165 // arguments are (8.3.6). 1166 bool SawDefaultArgument = false; 1167 SourceLocation PreviousDefaultArgLoc; 1168 1169 bool SawParameterPack = false; 1170 SourceLocation ParameterPackLoc; 1171 1172 // Dummy initialization to avoid warnings. 1173 TemplateParameterList::iterator OldParam = NewParams->end(); 1174 if (OldParams) 1175 OldParam = OldParams->begin(); 1176 1177 bool RemoveDefaultArguments = false; 1178 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1179 NewParamEnd = NewParams->end(); 1180 NewParam != NewParamEnd; ++NewParam) { 1181 // Variables used to diagnose redundant default arguments 1182 bool RedundantDefaultArg = false; 1183 SourceLocation OldDefaultLoc; 1184 SourceLocation NewDefaultLoc; 1185 1186 // Variables used to diagnose missing default arguments 1187 bool MissingDefaultArg = false; 1188 1189 // C++0x [temp.param]p11: 1190 // If a template parameter of a primary class template is a template 1191 // parameter pack, it shall be the last template parameter. 1192 if (SawParameterPack && TPC == TPC_ClassTemplate) { 1193 Diag(ParameterPackLoc, 1194 diag::err_template_param_pack_must_be_last_template_parameter); 1195 Invalid = true; 1196 } 1197 1198 if (TemplateTypeParmDecl *NewTypeParm 1199 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 1200 // Check the presence of a default argument here. 1201 if (NewTypeParm->hasDefaultArgument() && 1202 DiagnoseDefaultTemplateArgument(*this, TPC, 1203 NewTypeParm->getLocation(), 1204 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() 1205 .getSourceRange())) 1206 NewTypeParm->removeDefaultArgument(); 1207 1208 // Merge default arguments for template type parameters. 1209 TemplateTypeParmDecl *OldTypeParm 1210 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0; 1211 1212 if (NewTypeParm->isParameterPack()) { 1213 assert(!NewTypeParm->hasDefaultArgument() && 1214 "Parameter packs can't have a default argument!"); 1215 SawParameterPack = true; 1216 ParameterPackLoc = NewTypeParm->getLocation(); 1217 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() && 1218 NewTypeParm->hasDefaultArgument()) { 1219 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 1220 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 1221 SawDefaultArgument = true; 1222 RedundantDefaultArg = true; 1223 PreviousDefaultArgLoc = NewDefaultLoc; 1224 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 1225 // Merge the default argument from the old declaration to the 1226 // new declaration. 1227 SawDefaultArgument = true; 1228 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(), 1229 true); 1230 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 1231 } else if (NewTypeParm->hasDefaultArgument()) { 1232 SawDefaultArgument = true; 1233 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 1234 } else if (SawDefaultArgument) 1235 MissingDefaultArg = true; 1236 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 1237 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 1238 // Check for unexpanded parameter packs. 1239 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), 1240 NewNonTypeParm->getTypeSourceInfo(), 1241 UPPC_NonTypeTemplateParameterType)) { 1242 Invalid = true; 1243 continue; 1244 } 1245 1246 // Check the presence of a default argument here. 1247 if (NewNonTypeParm->hasDefaultArgument() && 1248 DiagnoseDefaultTemplateArgument(*this, TPC, 1249 NewNonTypeParm->getLocation(), 1250 NewNonTypeParm->getDefaultArgument()->getSourceRange())) { 1251 NewNonTypeParm->removeDefaultArgument(); 1252 } 1253 1254 // Merge default arguments for non-type template parameters 1255 NonTypeTemplateParmDecl *OldNonTypeParm 1256 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0; 1257 if (NewNonTypeParm->isParameterPack()) { 1258 assert(!NewNonTypeParm->hasDefaultArgument() && 1259 "Parameter packs can't have a default argument!"); 1260 SawParameterPack = true; 1261 ParameterPackLoc = NewNonTypeParm->getLocation(); 1262 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() && 1263 NewNonTypeParm->hasDefaultArgument()) { 1264 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1265 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1266 SawDefaultArgument = true; 1267 RedundantDefaultArg = true; 1268 PreviousDefaultArgLoc = NewDefaultLoc; 1269 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 1270 // Merge the default argument from the old declaration to the 1271 // new declaration. 1272 SawDefaultArgument = true; 1273 // FIXME: We need to create a new kind of "default argument" 1274 // expression that points to a previous non-type template 1275 // parameter. 1276 NewNonTypeParm->setDefaultArgument( 1277 OldNonTypeParm->getDefaultArgument(), 1278 /*Inherited=*/ true); 1279 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1280 } else if (NewNonTypeParm->hasDefaultArgument()) { 1281 SawDefaultArgument = true; 1282 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1283 } else if (SawDefaultArgument) 1284 MissingDefaultArg = true; 1285 } else { 1286 // Check the presence of a default argument here. 1287 TemplateTemplateParmDecl *NewTemplateParm 1288 = cast<TemplateTemplateParmDecl>(*NewParam); 1289 1290 // Check for unexpanded parameter packs, recursively. 1291 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { 1292 Invalid = true; 1293 continue; 1294 } 1295 1296 if (NewTemplateParm->hasDefaultArgument() && 1297 DiagnoseDefaultTemplateArgument(*this, TPC, 1298 NewTemplateParm->getLocation(), 1299 NewTemplateParm->getDefaultArgument().getSourceRange())) 1300 NewTemplateParm->removeDefaultArgument(); 1301 1302 // Merge default arguments for template template parameters 1303 TemplateTemplateParmDecl *OldTemplateParm 1304 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0; 1305 if (NewTemplateParm->isParameterPack()) { 1306 assert(!NewTemplateParm->hasDefaultArgument() && 1307 "Parameter packs can't have a default argument!"); 1308 SawParameterPack = true; 1309 ParameterPackLoc = NewTemplateParm->getLocation(); 1310 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() && 1311 NewTemplateParm->hasDefaultArgument()) { 1312 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 1313 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 1314 SawDefaultArgument = true; 1315 RedundantDefaultArg = true; 1316 PreviousDefaultArgLoc = NewDefaultLoc; 1317 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 1318 // Merge the default argument from the old declaration to the 1319 // new declaration. 1320 SawDefaultArgument = true; 1321 // FIXME: We need to create a new kind of "default argument" expression 1322 // that points to a previous template template parameter. 1323 NewTemplateParm->setDefaultArgument( 1324 OldTemplateParm->getDefaultArgument(), 1325 /*Inherited=*/ true); 1326 PreviousDefaultArgLoc 1327 = OldTemplateParm->getDefaultArgument().getLocation(); 1328 } else if (NewTemplateParm->hasDefaultArgument()) { 1329 SawDefaultArgument = true; 1330 PreviousDefaultArgLoc 1331 = NewTemplateParm->getDefaultArgument().getLocation(); 1332 } else if (SawDefaultArgument) 1333 MissingDefaultArg = true; 1334 } 1335 1336 if (RedundantDefaultArg) { 1337 // C++ [temp.param]p12: 1338 // A template-parameter shall not be given default arguments 1339 // by two different declarations in the same scope. 1340 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 1341 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 1342 Invalid = true; 1343 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { 1344 // C++ [temp.param]p11: 1345 // If a template-parameter of a class template has a default 1346 // template-argument, each subsequent template-parameter shall either 1347 // have a default template-argument supplied or be a template parameter 1348 // pack. 1349 Diag((*NewParam)->getLocation(), 1350 diag::err_template_param_default_arg_missing); 1351 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 1352 Invalid = true; 1353 RemoveDefaultArguments = true; 1354 } 1355 1356 // If we have an old template parameter list that we're merging 1357 // in, move on to the next parameter. 1358 if (OldParams) 1359 ++OldParam; 1360 } 1361 1362 // We were missing some default arguments at the end of the list, so remove 1363 // all of the default arguments. 1364 if (RemoveDefaultArguments) { 1365 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1366 NewParamEnd = NewParams->end(); 1367 NewParam != NewParamEnd; ++NewParam) { 1368 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) 1369 TTP->removeDefaultArgument(); 1370 else if (NonTypeTemplateParmDecl *NTTP 1371 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) 1372 NTTP->removeDefaultArgument(); 1373 else 1374 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); 1375 } 1376 } 1377 1378 return Invalid; 1379} 1380 1381namespace { 1382 1383/// A class which looks for a use of a certain level of template 1384/// parameter. 1385struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { 1386 typedef RecursiveASTVisitor<DependencyChecker> super; 1387 1388 unsigned Depth; 1389 bool Match; 1390 1391 DependencyChecker(TemplateParameterList *Params) : Match(false) { 1392 NamedDecl *ND = Params->getParam(0); 1393 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { 1394 Depth = PD->getDepth(); 1395 } else if (NonTypeTemplateParmDecl *PD = 1396 dyn_cast<NonTypeTemplateParmDecl>(ND)) { 1397 Depth = PD->getDepth(); 1398 } else { 1399 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); 1400 } 1401 } 1402 1403 bool Matches(unsigned ParmDepth) { 1404 if (ParmDepth >= Depth) { 1405 Match = true; 1406 return true; 1407 } 1408 return false; 1409 } 1410 1411 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 1412 return !Matches(T->getDepth()); 1413 } 1414 1415 bool TraverseTemplateName(TemplateName N) { 1416 if (TemplateTemplateParmDecl *PD = 1417 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) 1418 if (Matches(PD->getDepth())) return false; 1419 return super::TraverseTemplateName(N); 1420 } 1421 1422 bool VisitDeclRefExpr(DeclRefExpr *E) { 1423 if (NonTypeTemplateParmDecl *PD = 1424 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) { 1425 if (PD->getDepth() == Depth) { 1426 Match = true; 1427 return false; 1428 } 1429 } 1430 return super::VisitDeclRefExpr(E); 1431 } 1432}; 1433} 1434 1435/// Determines whether a template-id depends on the given parameter 1436/// list. 1437static bool 1438DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId, 1439 TemplateParameterList *Params) { 1440 DependencyChecker Checker(Params); 1441 Checker.TraverseType(QualType(TemplateId, 0)); 1442 return Checker.Match; 1443} 1444 1445/// \brief Match the given template parameter lists to the given scope 1446/// specifier, returning the template parameter list that applies to the 1447/// name. 1448/// 1449/// \param DeclStartLoc the start of the declaration that has a scope 1450/// specifier or a template parameter list. 1451/// 1452/// \param SS the scope specifier that will be matched to the given template 1453/// parameter lists. This scope specifier precedes a qualified name that is 1454/// being declared. 1455/// 1456/// \param ParamLists the template parameter lists, from the outermost to the 1457/// innermost template parameter lists. 1458/// 1459/// \param NumParamLists the number of template parameter lists in ParamLists. 1460/// 1461/// \param IsFriend Whether to apply the slightly different rules for 1462/// matching template parameters to scope specifiers in friend 1463/// declarations. 1464/// 1465/// \param IsExplicitSpecialization will be set true if the entity being 1466/// declared is an explicit specialization, false otherwise. 1467/// 1468/// \returns the template parameter list, if any, that corresponds to the 1469/// name that is preceded by the scope specifier @p SS. This template 1470/// parameter list may have template parameters (if we're declaring a 1471/// template) or may have no template parameters (if we're declaring a 1472/// template specialization), or may be NULL (if what we're declaring isn't 1473/// itself a template). 1474TemplateParameterList * 1475Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 1476 const CXXScopeSpec &SS, 1477 TemplateParameterList **ParamLists, 1478 unsigned NumParamLists, 1479 bool IsFriend, 1480 bool &IsExplicitSpecialization, 1481 bool &Invalid) { 1482 IsExplicitSpecialization = false; 1483 1484 // Find the template-ids that occur within the nested-name-specifier. These 1485 // template-ids will match up with the template parameter lists. 1486 llvm::SmallVector<const TemplateSpecializationType *, 4> 1487 TemplateIdsInSpecifier; 1488 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4> 1489 ExplicitSpecializationsInSpecifier; 1490 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 1491 NNS; NNS = NNS->getPrefix()) { 1492 const Type *T = NNS->getAsType(); 1493 if (!T) break; 1494 1495 // C++0x [temp.expl.spec]p17: 1496 // A member or a member template may be nested within many 1497 // enclosing class templates. In an explicit specialization for 1498 // such a member, the member declaration shall be preceded by a 1499 // template<> for each enclosing class template that is 1500 // explicitly specialized. 1501 // 1502 // Following the existing practice of GNU and EDG, we allow a typedef of a 1503 // template specialization type. 1504 while (const TypedefType *TT = dyn_cast<TypedefType>(T)) 1505 T = TT->getDecl()->getUnderlyingType().getTypePtr(); 1506 1507 if (const TemplateSpecializationType *SpecType 1508 = dyn_cast<TemplateSpecializationType>(T)) { 1509 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl(); 1510 if (!Template) 1511 continue; // FIXME: should this be an error? probably... 1512 1513 if (const RecordType *Record = SpecType->getAs<RecordType>()) { 1514 ClassTemplateSpecializationDecl *SpecDecl 1515 = cast<ClassTemplateSpecializationDecl>(Record->getDecl()); 1516 // If the nested name specifier refers to an explicit specialization, 1517 // we don't need a template<> header. 1518 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) { 1519 ExplicitSpecializationsInSpecifier.push_back(SpecDecl); 1520 continue; 1521 } 1522 } 1523 1524 TemplateIdsInSpecifier.push_back(SpecType); 1525 } 1526 } 1527 1528 // Reverse the list of template-ids in the scope specifier, so that we can 1529 // more easily match up the template-ids and the template parameter lists. 1530 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end()); 1531 1532 SourceLocation FirstTemplateLoc = DeclStartLoc; 1533 if (NumParamLists) 1534 FirstTemplateLoc = ParamLists[0]->getTemplateLoc(); 1535 1536 // Match the template-ids found in the specifier to the template parameter 1537 // lists. 1538 unsigned ParamIdx = 0, TemplateIdx = 0; 1539 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size(); 1540 TemplateIdx != NumTemplateIds; ++TemplateIdx) { 1541 const TemplateSpecializationType *TemplateId 1542 = TemplateIdsInSpecifier[TemplateIdx]; 1543 bool DependentTemplateId = TemplateId->isDependentType(); 1544 1545 // In friend declarations we can have template-ids which don't 1546 // depend on the corresponding template parameter lists. But 1547 // assume that empty parameter lists are supposed to match this 1548 // template-id. 1549 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) { 1550 if (!DependentTemplateId || 1551 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx])) 1552 continue; 1553 } 1554 1555 if (ParamIdx >= NumParamLists) { 1556 // We have a template-id without a corresponding template parameter 1557 // list. 1558 1559 // ...which is fine if this is a friend declaration. 1560 if (IsFriend) { 1561 IsExplicitSpecialization = true; 1562 break; 1563 } 1564 1565 if (DependentTemplateId) { 1566 // FIXME: the location information here isn't great. 1567 Diag(SS.getRange().getBegin(), 1568 diag::err_template_spec_needs_template_parameters) 1569 << QualType(TemplateId, 0) 1570 << SS.getRange(); 1571 Invalid = true; 1572 } else { 1573 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header) 1574 << SS.getRange() 1575 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> "); 1576 IsExplicitSpecialization = true; 1577 } 1578 return 0; 1579 } 1580 1581 // Check the template parameter list against its corresponding template-id. 1582 if (DependentTemplateId) { 1583 TemplateParameterList *ExpectedTemplateParams = 0; 1584 1585 // Are there cases in (e.g.) friends where this won't match? 1586 if (const InjectedClassNameType *Injected 1587 = TemplateId->getAs<InjectedClassNameType>()) { 1588 CXXRecordDecl *Record = Injected->getDecl(); 1589 if (ClassTemplatePartialSpecializationDecl *Partial = 1590 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 1591 ExpectedTemplateParams = Partial->getTemplateParameters(); 1592 else 1593 ExpectedTemplateParams = Record->getDescribedClassTemplate() 1594 ->getTemplateParameters(); 1595 } 1596 1597 if (ExpectedTemplateParams) 1598 TemplateParameterListsAreEqual(ParamLists[ParamIdx], 1599 ExpectedTemplateParams, 1600 true, TPL_TemplateMatch); 1601 1602 CheckTemplateParameterList(ParamLists[ParamIdx], 0, 1603 TPC_ClassTemplateMember); 1604 } else if (ParamLists[ParamIdx]->size() > 0) 1605 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 1606 diag::err_template_param_list_matches_nontemplate) 1607 << TemplateId 1608 << ParamLists[ParamIdx]->getSourceRange(); 1609 else 1610 IsExplicitSpecialization = true; 1611 1612 ++ParamIdx; 1613 } 1614 1615 // If there were at least as many template-ids as there were template 1616 // parameter lists, then there are no template parameter lists remaining for 1617 // the declaration itself. 1618 if (ParamIdx >= NumParamLists) 1619 return 0; 1620 1621 // If there were too many template parameter lists, complain about that now. 1622 if (ParamIdx != NumParamLists - 1) { 1623 while (ParamIdx < NumParamLists - 1) { 1624 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0; 1625 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 1626 isExplicitSpecHeader? diag::warn_template_spec_extra_headers 1627 : diag::err_template_spec_extra_headers) 1628 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), 1629 ParamLists[ParamIdx]->getRAngleLoc()); 1630 1631 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) { 1632 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(), 1633 diag::note_explicit_template_spec_does_not_need_header) 1634 << ExplicitSpecializationsInSpecifier.back(); 1635 ExplicitSpecializationsInSpecifier.pop_back(); 1636 } 1637 1638 // We have a template parameter list with no corresponding scope, which 1639 // means that the resulting template declaration can't be instantiated 1640 // properly (we'll end up with dependent nodes when we shouldn't). 1641 if (!isExplicitSpecHeader) 1642 Invalid = true; 1643 1644 ++ParamIdx; 1645 } 1646 } 1647 1648 // Return the last template parameter list, which corresponds to the 1649 // entity being declared. 1650 return ParamLists[NumParamLists - 1]; 1651} 1652 1653void Sema::NoteAllFoundTemplates(TemplateName Name) { 1654 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 1655 Diag(Template->getLocation(), diag::note_template_declared_here) 1656 << (isa<FunctionTemplateDecl>(Template)? 0 1657 : isa<ClassTemplateDecl>(Template)? 1 1658 : 2) 1659 << Template->getDeclName(); 1660 return; 1661 } 1662 1663 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { 1664 for (OverloadedTemplateStorage::iterator I = OST->begin(), 1665 IEnd = OST->end(); 1666 I != IEnd; ++I) 1667 Diag((*I)->getLocation(), diag::note_template_declared_here) 1668 << 0 << (*I)->getDeclName(); 1669 1670 return; 1671 } 1672} 1673 1674 1675QualType Sema::CheckTemplateIdType(TemplateName Name, 1676 SourceLocation TemplateLoc, 1677 TemplateArgumentListInfo &TemplateArgs) { 1678 TemplateDecl *Template = Name.getAsTemplateDecl(); 1679 if (!Template || isa<FunctionTemplateDecl>(Template)) { 1680 // We might have a substituted template template parameter pack. If so, 1681 // build a template specialization type for it. 1682 if (Name.getAsSubstTemplateTemplateParmPack()) 1683 return Context.getTemplateSpecializationType(Name, TemplateArgs); 1684 1685 Diag(TemplateLoc, diag::err_template_id_not_a_type) 1686 << Name; 1687 NoteAllFoundTemplates(Name); 1688 return QualType(); 1689 } 1690 1691 // Check that the template argument list is well-formed for this 1692 // template. 1693 llvm::SmallVector<TemplateArgument, 4> Converted; 1694 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, 1695 false, Converted)) 1696 return QualType(); 1697 1698 assert((Converted.size() == Template->getTemplateParameters()->size()) && 1699 "Converted template argument list is too short!"); 1700 1701 QualType CanonType; 1702 1703 if (Name.isDependent() || 1704 TemplateSpecializationType::anyDependentTemplateArguments( 1705 TemplateArgs)) { 1706 // This class template specialization is a dependent 1707 // type. Therefore, its canonical type is another class template 1708 // specialization type that contains all of the converted 1709 // arguments in canonical form. This ensures that, e.g., A<T> and 1710 // A<T, T> have identical types when A is declared as: 1711 // 1712 // template<typename T, typename U = T> struct A; 1713 TemplateName CanonName = Context.getCanonicalTemplateName(Name); 1714 CanonType = Context.getTemplateSpecializationType(CanonName, 1715 Converted.data(), 1716 Converted.size()); 1717 1718 // FIXME: CanonType is not actually the canonical type, and unfortunately 1719 // it is a TemplateSpecializationType that we will never use again. 1720 // In the future, we need to teach getTemplateSpecializationType to only 1721 // build the canonical type and return that to us. 1722 CanonType = Context.getCanonicalType(CanonType); 1723 1724 // This might work out to be a current instantiation, in which 1725 // case the canonical type needs to be the InjectedClassNameType. 1726 // 1727 // TODO: in theory this could be a simple hashtable lookup; most 1728 // changes to CurContext don't change the set of current 1729 // instantiations. 1730 if (isa<ClassTemplateDecl>(Template)) { 1731 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { 1732 // If we get out to a namespace, we're done. 1733 if (Ctx->isFileContext()) break; 1734 1735 // If this isn't a record, keep looking. 1736 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); 1737 if (!Record) continue; 1738 1739 // Look for one of the two cases with InjectedClassNameTypes 1740 // and check whether it's the same template. 1741 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && 1742 !Record->getDescribedClassTemplate()) 1743 continue; 1744 1745 // Fetch the injected class name type and check whether its 1746 // injected type is equal to the type we just built. 1747 QualType ICNT = Context.getTypeDeclType(Record); 1748 QualType Injected = cast<InjectedClassNameType>(ICNT) 1749 ->getInjectedSpecializationType(); 1750 1751 if (CanonType != Injected->getCanonicalTypeInternal()) 1752 continue; 1753 1754 // If so, the canonical type of this TST is the injected 1755 // class name type of the record we just found. 1756 assert(ICNT.isCanonical()); 1757 CanonType = ICNT; 1758 break; 1759 } 1760 } 1761 } else if (ClassTemplateDecl *ClassTemplate 1762 = dyn_cast<ClassTemplateDecl>(Template)) { 1763 // Find the class template specialization declaration that 1764 // corresponds to these arguments. 1765 void *InsertPos = 0; 1766 ClassTemplateSpecializationDecl *Decl 1767 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(), 1768 InsertPos); 1769 if (!Decl) { 1770 // This is the first time we have referenced this class template 1771 // specialization. Create the canonical declaration and add it to 1772 // the set of specializations. 1773 Decl = ClassTemplateSpecializationDecl::Create(Context, 1774 ClassTemplate->getTemplatedDecl()->getTagKind(), 1775 ClassTemplate->getDeclContext(), 1776 ClassTemplate->getLocation(), 1777 ClassTemplate->getLocation(), 1778 ClassTemplate, 1779 Converted.data(), 1780 Converted.size(), 0); 1781 ClassTemplate->AddSpecialization(Decl, InsertPos); 1782 Decl->setLexicalDeclContext(CurContext); 1783 } 1784 1785 CanonType = Context.getTypeDeclType(Decl); 1786 assert(isa<RecordType>(CanonType) && 1787 "type of non-dependent specialization is not a RecordType"); 1788 } 1789 1790 // Build the fully-sugared type for this class template 1791 // specialization, which refers back to the class template 1792 // specialization we created or found. 1793 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 1794} 1795 1796TypeResult 1797Sema::ActOnTemplateIdType(CXXScopeSpec &SS, 1798 TemplateTy TemplateD, SourceLocation TemplateLoc, 1799 SourceLocation LAngleLoc, 1800 ASTTemplateArgsPtr TemplateArgsIn, 1801 SourceLocation RAngleLoc) { 1802 if (SS.isInvalid()) 1803 return true; 1804 1805 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 1806 1807 // Translate the parser's template argument list in our AST format. 1808 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 1809 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 1810 1811 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 1812 QualType T = Context.getDependentTemplateSpecializationType(ETK_None, 1813 DTN->getQualifier(), 1814 DTN->getIdentifier(), 1815 TemplateArgs); 1816 1817 // Build type-source information. 1818 TypeLocBuilder TLB; 1819 DependentTemplateSpecializationTypeLoc SpecTL 1820 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 1821 SpecTL.setKeywordLoc(SourceLocation()); 1822 SpecTL.setNameLoc(TemplateLoc); 1823 SpecTL.setLAngleLoc(LAngleLoc); 1824 SpecTL.setRAngleLoc(RAngleLoc); 1825 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 1826 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 1827 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 1828 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 1829 } 1830 1831 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 1832 TemplateArgsIn.release(); 1833 1834 if (Result.isNull()) 1835 return true; 1836 1837 // Build type-source information. 1838 TypeLocBuilder TLB; 1839 TemplateSpecializationTypeLoc SpecTL 1840 = TLB.push<TemplateSpecializationTypeLoc>(Result); 1841 SpecTL.setTemplateNameLoc(TemplateLoc); 1842 SpecTL.setLAngleLoc(LAngleLoc); 1843 SpecTL.setRAngleLoc(RAngleLoc); 1844 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 1845 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 1846 1847 if (SS.isNotEmpty()) { 1848 // Create an elaborated-type-specifier containing the nested-name-specifier. 1849 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result); 1850 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 1851 ElabTL.setKeywordLoc(SourceLocation()); 1852 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 1853 } 1854 1855 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 1856} 1857 1858TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, 1859 TypeSpecifierType TagSpec, 1860 SourceLocation TagLoc, 1861 CXXScopeSpec &SS, 1862 TemplateTy TemplateD, 1863 SourceLocation TemplateLoc, 1864 SourceLocation LAngleLoc, 1865 ASTTemplateArgsPtr TemplateArgsIn, 1866 SourceLocation RAngleLoc) { 1867 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 1868 1869 // Translate the parser's template argument list in our AST format. 1870 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 1871 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 1872 1873 // Determine the tag kind 1874 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 1875 ElaboratedTypeKeyword Keyword 1876 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); 1877 1878 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 1879 QualType T = Context.getDependentTemplateSpecializationType(Keyword, 1880 DTN->getQualifier(), 1881 DTN->getIdentifier(), 1882 TemplateArgs); 1883 1884 // Build type-source information. 1885 TypeLocBuilder TLB; 1886 DependentTemplateSpecializationTypeLoc SpecTL 1887 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 1888 SpecTL.setKeywordLoc(TagLoc); 1889 SpecTL.setNameLoc(TemplateLoc); 1890 SpecTL.setLAngleLoc(LAngleLoc); 1891 SpecTL.setRAngleLoc(RAngleLoc); 1892 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 1893 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 1894 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 1895 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 1896 } 1897 1898 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 1899 if (Result.isNull()) 1900 return TypeResult(); 1901 1902 // Check the tag kind 1903 if (const RecordType *RT = Result->getAs<RecordType>()) { 1904 RecordDecl *D = RT->getDecl(); 1905 1906 IdentifierInfo *Id = D->getIdentifier(); 1907 assert(Id && "templated class must have an identifier"); 1908 1909 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) { 1910 Diag(TagLoc, diag::err_use_with_wrong_tag) 1911 << Result 1912 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); 1913 Diag(D->getLocation(), diag::note_previous_use); 1914 } 1915 } 1916 1917 // Provide source-location information for the template specialization. 1918 TypeLocBuilder TLB; 1919 TemplateSpecializationTypeLoc SpecTL 1920 = TLB.push<TemplateSpecializationTypeLoc>(Result); 1921 SpecTL.setTemplateNameLoc(TemplateLoc); 1922 SpecTL.setLAngleLoc(LAngleLoc); 1923 SpecTL.setRAngleLoc(RAngleLoc); 1924 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 1925 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 1926 1927 // Construct an elaborated type containing the nested-name-specifier (if any) 1928 // and keyword. 1929 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); 1930 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 1931 ElabTL.setKeywordLoc(TagLoc); 1932 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 1933 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 1934} 1935 1936ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 1937 LookupResult &R, 1938 bool RequiresADL, 1939 const TemplateArgumentListInfo &TemplateArgs) { 1940 // FIXME: Can we do any checking at this point? I guess we could check the 1941 // template arguments that we have against the template name, if the template 1942 // name refers to a single template. That's not a terribly common case, 1943 // though. 1944 // foo<int> could identify a single function unambiguously 1945 // This approach does NOT work, since f<int>(1); 1946 // gets resolved prior to resorting to overload resolution 1947 // i.e., template<class T> void f(double); 1948 // vs template<class T, class U> void f(U); 1949 1950 // These should be filtered out by our callers. 1951 assert(!R.empty() && "empty lookup results when building templateid"); 1952 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 1953 1954 // We don't want lookup warnings at this point. 1955 R.suppressDiagnostics(); 1956 1957 UnresolvedLookupExpr *ULE 1958 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 1959 SS.getWithLocInContext(Context), 1960 R.getLookupNameInfo(), 1961 RequiresADL, TemplateArgs, 1962 R.begin(), R.end()); 1963 1964 return Owned(ULE); 1965} 1966 1967// We actually only call this from template instantiation. 1968ExprResult 1969Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 1970 const DeclarationNameInfo &NameInfo, 1971 const TemplateArgumentListInfo &TemplateArgs) { 1972 DeclContext *DC; 1973 if (!(DC = computeDeclContext(SS, false)) || 1974 DC->isDependentContext() || 1975 RequireCompleteDeclContext(SS, DC)) 1976 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs); 1977 1978 bool MemberOfUnknownSpecialization; 1979 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1980 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false, 1981 MemberOfUnknownSpecialization); 1982 1983 if (R.isAmbiguous()) 1984 return ExprError(); 1985 1986 if (R.empty()) { 1987 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template) 1988 << NameInfo.getName() << SS.getRange(); 1989 return ExprError(); 1990 } 1991 1992 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { 1993 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template) 1994 << (NestedNameSpecifier*) SS.getScopeRep() 1995 << NameInfo.getName() << SS.getRange(); 1996 Diag(Temp->getLocation(), diag::note_referenced_class_template); 1997 return ExprError(); 1998 } 1999 2000 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs); 2001} 2002 2003/// \brief Form a dependent template name. 2004/// 2005/// This action forms a dependent template name given the template 2006/// name and its (presumably dependent) scope specifier. For 2007/// example, given "MetaFun::template apply", the scope specifier \p 2008/// SS will be "MetaFun::", \p TemplateKWLoc contains the location 2009/// of the "template" keyword, and "apply" is the \p Name. 2010TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S, 2011 SourceLocation TemplateKWLoc, 2012 CXXScopeSpec &SS, 2013 UnqualifiedId &Name, 2014 ParsedType ObjectType, 2015 bool EnteringContext, 2016 TemplateTy &Result) { 2017 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() && 2018 !getLangOptions().CPlusPlus0x) 2019 Diag(TemplateKWLoc, diag::ext_template_outside_of_template) 2020 << FixItHint::CreateRemoval(TemplateKWLoc); 2021 2022 DeclContext *LookupCtx = 0; 2023 if (SS.isSet()) 2024 LookupCtx = computeDeclContext(SS, EnteringContext); 2025 if (!LookupCtx && ObjectType) 2026 LookupCtx = computeDeclContext(ObjectType.get()); 2027 if (LookupCtx) { 2028 // C++0x [temp.names]p5: 2029 // If a name prefixed by the keyword template is not the name of 2030 // a template, the program is ill-formed. [Note: the keyword 2031 // template may not be applied to non-template members of class 2032 // templates. -end note ] [ Note: as is the case with the 2033 // typename prefix, the template prefix is allowed in cases 2034 // where it is not strictly necessary; i.e., when the 2035 // nested-name-specifier or the expression on the left of the -> 2036 // or . is not dependent on a template-parameter, or the use 2037 // does not appear in the scope of a template. -end note] 2038 // 2039 // Note: C++03 was more strict here, because it banned the use of 2040 // the "template" keyword prior to a template-name that was not a 2041 // dependent name. C++ DR468 relaxed this requirement (the 2042 // "template" keyword is now permitted). We follow the C++0x 2043 // rules, even in C++03 mode with a warning, retroactively applying the DR. 2044 bool MemberOfUnknownSpecialization; 2045 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name, 2046 ObjectType, EnteringContext, Result, 2047 MemberOfUnknownSpecialization); 2048 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() && 2049 isa<CXXRecordDecl>(LookupCtx) && 2050 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() || 2051 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) { 2052 // This is a dependent template. Handle it below. 2053 } else if (TNK == TNK_Non_template) { 2054 Diag(Name.getSourceRange().getBegin(), 2055 diag::err_template_kw_refers_to_non_template) 2056 << GetNameFromUnqualifiedId(Name).getName() 2057 << Name.getSourceRange() 2058 << TemplateKWLoc; 2059 return TNK_Non_template; 2060 } else { 2061 // We found something; return it. 2062 return TNK; 2063 } 2064 } 2065 2066 NestedNameSpecifier *Qualifier 2067 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2068 2069 switch (Name.getKind()) { 2070 case UnqualifiedId::IK_Identifier: 2071 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 2072 Name.Identifier)); 2073 return TNK_Dependent_template_name; 2074 2075 case UnqualifiedId::IK_OperatorFunctionId: 2076 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 2077 Name.OperatorFunctionId.Operator)); 2078 return TNK_Dependent_template_name; 2079 2080 case UnqualifiedId::IK_LiteralOperatorId: 2081 assert(false && "We don't support these; Parse shouldn't have allowed propagation"); 2082 2083 default: 2084 break; 2085 } 2086 2087 Diag(Name.getSourceRange().getBegin(), 2088 diag::err_template_kw_refers_to_non_template) 2089 << GetNameFromUnqualifiedId(Name).getName() 2090 << Name.getSourceRange() 2091 << TemplateKWLoc; 2092 return TNK_Non_template; 2093} 2094 2095bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 2096 const TemplateArgumentLoc &AL, 2097 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2098 const TemplateArgument &Arg = AL.getArgument(); 2099 2100 // Check template type parameter. 2101 switch(Arg.getKind()) { 2102 case TemplateArgument::Type: 2103 // C++ [temp.arg.type]p1: 2104 // A template-argument for a template-parameter which is a 2105 // type shall be a type-id. 2106 break; 2107 case TemplateArgument::Template: { 2108 // We have a template type parameter but the template argument 2109 // is a template without any arguments. 2110 SourceRange SR = AL.getSourceRange(); 2111 TemplateName Name = Arg.getAsTemplate(); 2112 Diag(SR.getBegin(), diag::err_template_missing_args) 2113 << Name << SR; 2114 if (TemplateDecl *Decl = Name.getAsTemplateDecl()) 2115 Diag(Decl->getLocation(), diag::note_template_decl_here); 2116 2117 return true; 2118 } 2119 default: { 2120 // We have a template type parameter but the template argument 2121 // is not a type. 2122 SourceRange SR = AL.getSourceRange(); 2123 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 2124 Diag(Param->getLocation(), diag::note_template_param_here); 2125 2126 return true; 2127 } 2128 } 2129 2130 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo())) 2131 return true; 2132 2133 // Add the converted template type argument. 2134 Converted.push_back( 2135 TemplateArgument(Context.getCanonicalType(Arg.getAsType()))); 2136 return false; 2137} 2138 2139/// \brief Substitute template arguments into the default template argument for 2140/// the given template type parameter. 2141/// 2142/// \param SemaRef the semantic analysis object for which we are performing 2143/// the substitution. 2144/// 2145/// \param Template the template that we are synthesizing template arguments 2146/// for. 2147/// 2148/// \param TemplateLoc the location of the template name that started the 2149/// template-id we are checking. 2150/// 2151/// \param RAngleLoc the location of the right angle bracket ('>') that 2152/// terminates the template-id. 2153/// 2154/// \param Param the template template parameter whose default we are 2155/// substituting into. 2156/// 2157/// \param Converted the list of template arguments provided for template 2158/// parameters that precede \p Param in the template parameter list. 2159/// \returns the substituted template argument, or NULL if an error occurred. 2160static TypeSourceInfo * 2161SubstDefaultTemplateArgument(Sema &SemaRef, 2162 TemplateDecl *Template, 2163 SourceLocation TemplateLoc, 2164 SourceLocation RAngleLoc, 2165 TemplateTypeParmDecl *Param, 2166 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2167 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); 2168 2169 // If the argument type is dependent, instantiate it now based 2170 // on the previously-computed template arguments. 2171 if (ArgType->getType()->isDependentType()) { 2172 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2173 Converted.data(), Converted.size()); 2174 2175 MultiLevelTemplateArgumentList AllTemplateArgs 2176 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 2177 2178 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 2179 Template, Converted.data(), 2180 Converted.size(), 2181 SourceRange(TemplateLoc, RAngleLoc)); 2182 2183 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs, 2184 Param->getDefaultArgumentLoc(), 2185 Param->getDeclName()); 2186 } 2187 2188 return ArgType; 2189} 2190 2191/// \brief Substitute template arguments into the default template argument for 2192/// the given non-type template parameter. 2193/// 2194/// \param SemaRef the semantic analysis object for which we are performing 2195/// the substitution. 2196/// 2197/// \param Template the template that we are synthesizing template arguments 2198/// for. 2199/// 2200/// \param TemplateLoc the location of the template name that started the 2201/// template-id we are checking. 2202/// 2203/// \param RAngleLoc the location of the right angle bracket ('>') that 2204/// terminates the template-id. 2205/// 2206/// \param Param the non-type template parameter whose default we are 2207/// substituting into. 2208/// 2209/// \param Converted the list of template arguments provided for template 2210/// parameters that precede \p Param in the template parameter list. 2211/// 2212/// \returns the substituted template argument, or NULL if an error occurred. 2213static ExprResult 2214SubstDefaultTemplateArgument(Sema &SemaRef, 2215 TemplateDecl *Template, 2216 SourceLocation TemplateLoc, 2217 SourceLocation RAngleLoc, 2218 NonTypeTemplateParmDecl *Param, 2219 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2220 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2221 Converted.data(), Converted.size()); 2222 2223 MultiLevelTemplateArgumentList AllTemplateArgs 2224 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 2225 2226 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 2227 Template, Converted.data(), 2228 Converted.size(), 2229 SourceRange(TemplateLoc, RAngleLoc)); 2230 2231 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs); 2232} 2233 2234/// \brief Substitute template arguments into the default template argument for 2235/// the given template template parameter. 2236/// 2237/// \param SemaRef the semantic analysis object for which we are performing 2238/// the substitution. 2239/// 2240/// \param Template the template that we are synthesizing template arguments 2241/// for. 2242/// 2243/// \param TemplateLoc the location of the template name that started the 2244/// template-id we are checking. 2245/// 2246/// \param RAngleLoc the location of the right angle bracket ('>') that 2247/// terminates the template-id. 2248/// 2249/// \param Param the template template parameter whose default we are 2250/// substituting into. 2251/// 2252/// \param Converted the list of template arguments provided for template 2253/// parameters that precede \p Param in the template parameter list. 2254/// 2255/// \param QualifierLoc Will be set to the nested-name-specifier (with 2256/// source-location information) that precedes the template name. 2257/// 2258/// \returns the substituted template argument, or NULL if an error occurred. 2259static TemplateName 2260SubstDefaultTemplateArgument(Sema &SemaRef, 2261 TemplateDecl *Template, 2262 SourceLocation TemplateLoc, 2263 SourceLocation RAngleLoc, 2264 TemplateTemplateParmDecl *Param, 2265 llvm::SmallVectorImpl<TemplateArgument> &Converted, 2266 NestedNameSpecifierLoc &QualifierLoc) { 2267 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2268 Converted.data(), Converted.size()); 2269 2270 MultiLevelTemplateArgumentList AllTemplateArgs 2271 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 2272 2273 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 2274 Template, Converted.data(), 2275 Converted.size(), 2276 SourceRange(TemplateLoc, RAngleLoc)); 2277 2278 // Substitute into the nested-name-specifier first, 2279 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc(); 2280 if (QualifierLoc) { 2281 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 2282 AllTemplateArgs); 2283 if (!QualifierLoc) 2284 return TemplateName(); 2285 } 2286 2287 return SemaRef.SubstTemplateName(QualifierLoc, 2288 Param->getDefaultArgument().getArgument().getAsTemplate(), 2289 Param->getDefaultArgument().getTemplateNameLoc(), 2290 AllTemplateArgs); 2291} 2292 2293/// \brief If the given template parameter has a default template 2294/// argument, substitute into that default template argument and 2295/// return the corresponding template argument. 2296TemplateArgumentLoc 2297Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 2298 SourceLocation TemplateLoc, 2299 SourceLocation RAngleLoc, 2300 Decl *Param, 2301 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2302 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { 2303 if (!TypeParm->hasDefaultArgument()) 2304 return TemplateArgumentLoc(); 2305 2306 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template, 2307 TemplateLoc, 2308 RAngleLoc, 2309 TypeParm, 2310 Converted); 2311 if (DI) 2312 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); 2313 2314 return TemplateArgumentLoc(); 2315 } 2316 2317 if (NonTypeTemplateParmDecl *NonTypeParm 2318 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2319 if (!NonTypeParm->hasDefaultArgument()) 2320 return TemplateArgumentLoc(); 2321 2322 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template, 2323 TemplateLoc, 2324 RAngleLoc, 2325 NonTypeParm, 2326 Converted); 2327 if (Arg.isInvalid()) 2328 return TemplateArgumentLoc(); 2329 2330 Expr *ArgE = Arg.takeAs<Expr>(); 2331 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); 2332 } 2333 2334 TemplateTemplateParmDecl *TempTempParm 2335 = cast<TemplateTemplateParmDecl>(Param); 2336 if (!TempTempParm->hasDefaultArgument()) 2337 return TemplateArgumentLoc(); 2338 2339 2340 NestedNameSpecifierLoc QualifierLoc; 2341 TemplateName TName = SubstDefaultTemplateArgument(*this, Template, 2342 TemplateLoc, 2343 RAngleLoc, 2344 TempTempParm, 2345 Converted, 2346 QualifierLoc); 2347 if (TName.isNull()) 2348 return TemplateArgumentLoc(); 2349 2350 return TemplateArgumentLoc(TemplateArgument(TName), 2351 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(), 2352 TempTempParm->getDefaultArgument().getTemplateNameLoc()); 2353} 2354 2355/// \brief Check that the given template argument corresponds to the given 2356/// template parameter. 2357/// 2358/// \param Param The template parameter against which the argument will be 2359/// checked. 2360/// 2361/// \param Arg The template argument. 2362/// 2363/// \param Template The template in which the template argument resides. 2364/// 2365/// \param TemplateLoc The location of the template name for the template 2366/// whose argument list we're matching. 2367/// 2368/// \param RAngleLoc The location of the right angle bracket ('>') that closes 2369/// the template argument list. 2370/// 2371/// \param ArgumentPackIndex The index into the argument pack where this 2372/// argument will be placed. Only valid if the parameter is a parameter pack. 2373/// 2374/// \param Converted The checked, converted argument will be added to the 2375/// end of this small vector. 2376/// 2377/// \param CTAK Describes how we arrived at this particular template argument: 2378/// explicitly written, deduced, etc. 2379/// 2380/// \returns true on error, false otherwise. 2381bool Sema::CheckTemplateArgument(NamedDecl *Param, 2382 const TemplateArgumentLoc &Arg, 2383 NamedDecl *Template, 2384 SourceLocation TemplateLoc, 2385 SourceLocation RAngleLoc, 2386 unsigned ArgumentPackIndex, 2387 llvm::SmallVectorImpl<TemplateArgument> &Converted, 2388 CheckTemplateArgumentKind CTAK) { 2389 // Check template type parameters. 2390 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 2391 return CheckTemplateTypeArgument(TTP, Arg, Converted); 2392 2393 // Check non-type template parameters. 2394 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2395 // Do substitution on the type of the non-type template parameter 2396 // with the template arguments we've seen thus far. But if the 2397 // template has a dependent context then we cannot substitute yet. 2398 QualType NTTPType = NTTP->getType(); 2399 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) 2400 NTTPType = NTTP->getExpansionType(ArgumentPackIndex); 2401 2402 if (NTTPType->isDependentType() && 2403 !isa<TemplateTemplateParmDecl>(Template) && 2404 !Template->getDeclContext()->isDependentContext()) { 2405 // Do substitution on the type of the non-type template parameter. 2406 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 2407 NTTP, Converted.data(), Converted.size(), 2408 SourceRange(TemplateLoc, RAngleLoc)); 2409 2410 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2411 Converted.data(), Converted.size()); 2412 NTTPType = SubstType(NTTPType, 2413 MultiLevelTemplateArgumentList(TemplateArgs), 2414 NTTP->getLocation(), 2415 NTTP->getDeclName()); 2416 // If that worked, check the non-type template parameter type 2417 // for validity. 2418 if (!NTTPType.isNull()) 2419 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 2420 NTTP->getLocation()); 2421 if (NTTPType.isNull()) 2422 return true; 2423 } 2424 2425 switch (Arg.getArgument().getKind()) { 2426 case TemplateArgument::Null: 2427 assert(false && "Should never see a NULL template argument here"); 2428 return true; 2429 2430 case TemplateArgument::Expression: { 2431 TemplateArgument Result; 2432 ExprResult Res = 2433 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(), 2434 Result, CTAK); 2435 if (Res.isInvalid()) 2436 return true; 2437 2438 Converted.push_back(Result); 2439 break; 2440 } 2441 2442 case TemplateArgument::Declaration: 2443 case TemplateArgument::Integral: 2444 // We've already checked this template argument, so just copy 2445 // it to the list of converted arguments. 2446 Converted.push_back(Arg.getArgument()); 2447 break; 2448 2449 case TemplateArgument::Template: 2450 case TemplateArgument::TemplateExpansion: 2451 // We were given a template template argument. It may not be ill-formed; 2452 // see below. 2453 if (DependentTemplateName *DTN 2454 = Arg.getArgument().getAsTemplateOrTemplatePattern() 2455 .getAsDependentTemplateName()) { 2456 // We have a template argument such as \c T::template X, which we 2457 // parsed as a template template argument. However, since we now 2458 // know that we need a non-type template argument, convert this 2459 // template name into an expression. 2460 2461 DeclarationNameInfo NameInfo(DTN->getIdentifier(), 2462 Arg.getTemplateNameLoc()); 2463 2464 CXXScopeSpec SS; 2465 SS.Adopt(Arg.getTemplateQualifierLoc()); 2466 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context, 2467 SS.getWithLocInContext(Context), 2468 NameInfo)); 2469 2470 // If we parsed the template argument as a pack expansion, create a 2471 // pack expansion expression. 2472 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ 2473 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc()); 2474 if (E.isInvalid()) 2475 return true; 2476 } 2477 2478 TemplateArgument Result; 2479 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result); 2480 if (E.isInvalid()) 2481 return true; 2482 2483 Converted.push_back(Result); 2484 break; 2485 } 2486 2487 // We have a template argument that actually does refer to a class 2488 // template, template alias, or template template parameter, and 2489 // therefore cannot be a non-type template argument. 2490 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 2491 << Arg.getSourceRange(); 2492 2493 Diag(Param->getLocation(), diag::note_template_param_here); 2494 return true; 2495 2496 case TemplateArgument::Type: { 2497 // We have a non-type template parameter but the template 2498 // argument is a type. 2499 2500 // C++ [temp.arg]p2: 2501 // In a template-argument, an ambiguity between a type-id and 2502 // an expression is resolved to a type-id, regardless of the 2503 // form of the corresponding template-parameter. 2504 // 2505 // We warn specifically about this case, since it can be rather 2506 // confusing for users. 2507 QualType T = Arg.getArgument().getAsType(); 2508 SourceRange SR = Arg.getSourceRange(); 2509 if (T->isFunctionType()) 2510 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 2511 else 2512 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 2513 Diag(Param->getLocation(), diag::note_template_param_here); 2514 return true; 2515 } 2516 2517 case TemplateArgument::Pack: 2518 llvm_unreachable("Caller must expand template argument packs"); 2519 break; 2520 } 2521 2522 return false; 2523 } 2524 2525 2526 // Check template template parameters. 2527 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 2528 2529 // Substitute into the template parameter list of the template 2530 // template parameter, since previously-supplied template arguments 2531 // may appear within the template template parameter. 2532 { 2533 // Set up a template instantiation context. 2534 LocalInstantiationScope Scope(*this); 2535 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 2536 TempParm, Converted.data(), Converted.size(), 2537 SourceRange(TemplateLoc, RAngleLoc)); 2538 2539 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2540 Converted.data(), Converted.size()); 2541 TempParm = cast_or_null<TemplateTemplateParmDecl>( 2542 SubstDecl(TempParm, CurContext, 2543 MultiLevelTemplateArgumentList(TemplateArgs))); 2544 if (!TempParm) 2545 return true; 2546 } 2547 2548 switch (Arg.getArgument().getKind()) { 2549 case TemplateArgument::Null: 2550 assert(false && "Should never see a NULL template argument here"); 2551 return true; 2552 2553 case TemplateArgument::Template: 2554 case TemplateArgument::TemplateExpansion: 2555 if (CheckTemplateArgument(TempParm, Arg)) 2556 return true; 2557 2558 Converted.push_back(Arg.getArgument()); 2559 break; 2560 2561 case TemplateArgument::Expression: 2562 case TemplateArgument::Type: 2563 // We have a template template parameter but the template 2564 // argument does not refer to a template. 2565 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template); 2566 return true; 2567 2568 case TemplateArgument::Declaration: 2569 llvm_unreachable( 2570 "Declaration argument with template template parameter"); 2571 break; 2572 case TemplateArgument::Integral: 2573 llvm_unreachable( 2574 "Integral argument with template template parameter"); 2575 break; 2576 2577 case TemplateArgument::Pack: 2578 llvm_unreachable("Caller must expand template argument packs"); 2579 break; 2580 } 2581 2582 return false; 2583} 2584 2585/// \brief Check that the given template argument list is well-formed 2586/// for specializing the given template. 2587bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, 2588 SourceLocation TemplateLoc, 2589 TemplateArgumentListInfo &TemplateArgs, 2590 bool PartialTemplateArgs, 2591 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2592 TemplateParameterList *Params = Template->getTemplateParameters(); 2593 unsigned NumParams = Params->size(); 2594 unsigned NumArgs = TemplateArgs.size(); 2595 bool Invalid = false; 2596 2597 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc(); 2598 2599 bool HasParameterPack = 2600 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack(); 2601 2602 if ((NumArgs > NumParams && !HasParameterPack) || 2603 (NumArgs < Params->getMinRequiredArguments() && 2604 !PartialTemplateArgs)) { 2605 // FIXME: point at either the first arg beyond what we can handle, 2606 // or the '>', depending on whether we have too many or too few 2607 // arguments. 2608 SourceRange Range; 2609 if (NumArgs > NumParams) 2610 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc); 2611 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 2612 << (NumArgs > NumParams) 2613 << (isa<ClassTemplateDecl>(Template)? 0 : 2614 isa<FunctionTemplateDecl>(Template)? 1 : 2615 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 2616 << Template << Range; 2617 Diag(Template->getLocation(), diag::note_template_decl_here) 2618 << Params->getSourceRange(); 2619 Invalid = true; 2620 } 2621 2622 // C++ [temp.arg]p1: 2623 // [...] The type and form of each template-argument specified in 2624 // a template-id shall match the type and form specified for the 2625 // corresponding parameter declared by the template in its 2626 // template-parameter-list. 2627 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template); 2628 llvm::SmallVector<TemplateArgument, 2> ArgumentPack; 2629 TemplateParameterList::iterator Param = Params->begin(), 2630 ParamEnd = Params->end(); 2631 unsigned ArgIdx = 0; 2632 LocalInstantiationScope InstScope(*this, true); 2633 while (Param != ParamEnd) { 2634 if (ArgIdx > NumArgs && PartialTemplateArgs) 2635 break; 2636 2637 if (ArgIdx < NumArgs) { 2638 // If we have an expanded parameter pack, make sure we don't have too 2639 // many arguments. 2640 if (NonTypeTemplateParmDecl *NTTP 2641 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 2642 if (NTTP->isExpandedParameterPack() && 2643 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) { 2644 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 2645 << true 2646 << (isa<ClassTemplateDecl>(Template)? 0 : 2647 isa<FunctionTemplateDecl>(Template)? 1 : 2648 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 2649 << Template; 2650 Diag(Template->getLocation(), diag::note_template_decl_here) 2651 << Params->getSourceRange(); 2652 return true; 2653 } 2654 } 2655 2656 // Check the template argument we were given. 2657 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 2658 TemplateLoc, RAngleLoc, 2659 ArgumentPack.size(), Converted)) 2660 return true; 2661 2662 if ((*Param)->isTemplateParameterPack()) { 2663 // The template parameter was a template parameter pack, so take the 2664 // deduced argument and place it on the argument pack. Note that we 2665 // stay on the same template parameter so that we can deduce more 2666 // arguments. 2667 ArgumentPack.push_back(Converted.back()); 2668 Converted.pop_back(); 2669 } else { 2670 // Move to the next template parameter. 2671 ++Param; 2672 } 2673 ++ArgIdx; 2674 continue; 2675 } 2676 2677 // If we have a template parameter pack with no more corresponding 2678 // arguments, just break out now and we'll fill in the argument pack below. 2679 if ((*Param)->isTemplateParameterPack()) 2680 break; 2681 2682 // We have a default template argument that we will use. 2683 TemplateArgumentLoc Arg; 2684 2685 // Retrieve the default template argument from the template 2686 // parameter. For each kind of template parameter, we substitute the 2687 // template arguments provided thus far and any "outer" template arguments 2688 // (when the template parameter was part of a nested template) into 2689 // the default argument. 2690 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 2691 if (!TTP->hasDefaultArgument()) { 2692 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2693 break; 2694 } 2695 2696 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this, 2697 Template, 2698 TemplateLoc, 2699 RAngleLoc, 2700 TTP, 2701 Converted); 2702 if (!ArgType) 2703 return true; 2704 2705 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 2706 ArgType); 2707 } else if (NonTypeTemplateParmDecl *NTTP 2708 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 2709 if (!NTTP->hasDefaultArgument()) { 2710 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2711 break; 2712 } 2713 2714 ExprResult E = SubstDefaultTemplateArgument(*this, Template, 2715 TemplateLoc, 2716 RAngleLoc, 2717 NTTP, 2718 Converted); 2719 if (E.isInvalid()) 2720 return true; 2721 2722 Expr *Ex = E.takeAs<Expr>(); 2723 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 2724 } else { 2725 TemplateTemplateParmDecl *TempParm 2726 = cast<TemplateTemplateParmDecl>(*Param); 2727 2728 if (!TempParm->hasDefaultArgument()) { 2729 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2730 break; 2731 } 2732 2733 NestedNameSpecifierLoc QualifierLoc; 2734 TemplateName Name = SubstDefaultTemplateArgument(*this, Template, 2735 TemplateLoc, 2736 RAngleLoc, 2737 TempParm, 2738 Converted, 2739 QualifierLoc); 2740 if (Name.isNull()) 2741 return true; 2742 2743 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc, 2744 TempParm->getDefaultArgument().getTemplateNameLoc()); 2745 } 2746 2747 // Introduce an instantiation record that describes where we are using 2748 // the default template argument. 2749 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param, 2750 Converted.data(), Converted.size(), 2751 SourceRange(TemplateLoc, RAngleLoc)); 2752 2753 // Check the default template argument. 2754 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, 2755 RAngleLoc, 0, Converted)) 2756 return true; 2757 2758 // Core issue 150 (assumed resolution): if this is a template template 2759 // parameter, keep track of the default template arguments from the 2760 // template definition. 2761 if (isTemplateTemplateParameter) 2762 TemplateArgs.addArgument(Arg); 2763 2764 // Move to the next template parameter and argument. 2765 ++Param; 2766 ++ArgIdx; 2767 } 2768 2769 // Form argument packs for each of the parameter packs remaining. 2770 while (Param != ParamEnd) { 2771 // If we're checking a partial list of template arguments, don't fill 2772 // in arguments for non-template parameter packs. 2773 2774 if ((*Param)->isTemplateParameterPack()) { 2775 if (PartialTemplateArgs && ArgumentPack.empty()) { 2776 Converted.push_back(TemplateArgument()); 2777 } else if (ArgumentPack.empty()) 2778 Converted.push_back(TemplateArgument(0, 0)); 2779 else { 2780 Converted.push_back(TemplateArgument::CreatePackCopy(Context, 2781 ArgumentPack.data(), 2782 ArgumentPack.size())); 2783 ArgumentPack.clear(); 2784 } 2785 } 2786 2787 ++Param; 2788 } 2789 2790 return Invalid; 2791} 2792 2793namespace { 2794 class UnnamedLocalNoLinkageFinder 2795 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool> 2796 { 2797 Sema &S; 2798 SourceRange SR; 2799 2800 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited; 2801 2802 public: 2803 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { } 2804 2805 bool Visit(QualType T) { 2806 return inherited::Visit(T.getTypePtr()); 2807 } 2808 2809#define TYPE(Class, Parent) \ 2810 bool Visit##Class##Type(const Class##Type *); 2811#define ABSTRACT_TYPE(Class, Parent) \ 2812 bool Visit##Class##Type(const Class##Type *) { return false; } 2813#define NON_CANONICAL_TYPE(Class, Parent) \ 2814 bool Visit##Class##Type(const Class##Type *) { return false; } 2815#include "clang/AST/TypeNodes.def" 2816 2817 bool VisitTagDecl(const TagDecl *Tag); 2818 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS); 2819 }; 2820} 2821 2822bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) { 2823 return false; 2824} 2825 2826bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) { 2827 return Visit(T->getElementType()); 2828} 2829 2830bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) { 2831 return Visit(T->getPointeeType()); 2832} 2833 2834bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType( 2835 const BlockPointerType* T) { 2836 return Visit(T->getPointeeType()); 2837} 2838 2839bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType( 2840 const LValueReferenceType* T) { 2841 return Visit(T->getPointeeType()); 2842} 2843 2844bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType( 2845 const RValueReferenceType* T) { 2846 return Visit(T->getPointeeType()); 2847} 2848 2849bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType( 2850 const MemberPointerType* T) { 2851 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0)); 2852} 2853 2854bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType( 2855 const ConstantArrayType* T) { 2856 return Visit(T->getElementType()); 2857} 2858 2859bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType( 2860 const IncompleteArrayType* T) { 2861 return Visit(T->getElementType()); 2862} 2863 2864bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType( 2865 const VariableArrayType* T) { 2866 return Visit(T->getElementType()); 2867} 2868 2869bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType( 2870 const DependentSizedArrayType* T) { 2871 return Visit(T->getElementType()); 2872} 2873 2874bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType( 2875 const DependentSizedExtVectorType* T) { 2876 return Visit(T->getElementType()); 2877} 2878 2879bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) { 2880 return Visit(T->getElementType()); 2881} 2882 2883bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) { 2884 return Visit(T->getElementType()); 2885} 2886 2887bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType( 2888 const FunctionProtoType* T) { 2889 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(), 2890 AEnd = T->arg_type_end(); 2891 A != AEnd; ++A) { 2892 if (Visit(*A)) 2893 return true; 2894 } 2895 2896 return Visit(T->getResultType()); 2897} 2898 2899bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType( 2900 const FunctionNoProtoType* T) { 2901 return Visit(T->getResultType()); 2902} 2903 2904bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType( 2905 const UnresolvedUsingType*) { 2906 return false; 2907} 2908 2909bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) { 2910 return false; 2911} 2912 2913bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) { 2914 return Visit(T->getUnderlyingType()); 2915} 2916 2917bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { 2918 return false; 2919} 2920 2921bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) { 2922 return Visit(T->getDeducedType()); 2923} 2924 2925bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) { 2926 return VisitTagDecl(T->getDecl()); 2927} 2928 2929bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) { 2930 return VisitTagDecl(T->getDecl()); 2931} 2932 2933bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType( 2934 const TemplateTypeParmType*) { 2935 return false; 2936} 2937 2938bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType( 2939 const SubstTemplateTypeParmPackType *) { 2940 return false; 2941} 2942 2943bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType( 2944 const TemplateSpecializationType*) { 2945 return false; 2946} 2947 2948bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType( 2949 const InjectedClassNameType* T) { 2950 return VisitTagDecl(T->getDecl()); 2951} 2952 2953bool UnnamedLocalNoLinkageFinder::VisitDependentNameType( 2954 const DependentNameType* T) { 2955 return VisitNestedNameSpecifier(T->getQualifier()); 2956} 2957 2958bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType( 2959 const DependentTemplateSpecializationType* T) { 2960 return VisitNestedNameSpecifier(T->getQualifier()); 2961} 2962 2963bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType( 2964 const PackExpansionType* T) { 2965 return Visit(T->getPattern()); 2966} 2967 2968bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) { 2969 return false; 2970} 2971 2972bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType( 2973 const ObjCInterfaceType *) { 2974 return false; 2975} 2976 2977bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType( 2978 const ObjCObjectPointerType *) { 2979 return false; 2980} 2981 2982bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) { 2983 if (Tag->getDeclContext()->isFunctionOrMethod()) { 2984 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type) 2985 << S.Context.getTypeDeclType(Tag) << SR; 2986 return true; 2987 } 2988 2989 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) { 2990 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR; 2991 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here); 2992 return true; 2993 } 2994 2995 return false; 2996} 2997 2998bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier( 2999 NestedNameSpecifier *NNS) { 3000 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix())) 3001 return true; 3002 3003 switch (NNS->getKind()) { 3004 case NestedNameSpecifier::Identifier: 3005 case NestedNameSpecifier::Namespace: 3006 case NestedNameSpecifier::NamespaceAlias: 3007 case NestedNameSpecifier::Global: 3008 return false; 3009 3010 case NestedNameSpecifier::TypeSpec: 3011 case NestedNameSpecifier::TypeSpecWithTemplate: 3012 return Visit(QualType(NNS->getAsType(), 0)); 3013 } 3014 return false; 3015} 3016 3017 3018/// \brief Check a template argument against its corresponding 3019/// template type parameter. 3020/// 3021/// This routine implements the semantics of C++ [temp.arg.type]. It 3022/// returns true if an error occurred, and false otherwise. 3023bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 3024 TypeSourceInfo *ArgInfo) { 3025 assert(ArgInfo && "invalid TypeSourceInfo"); 3026 QualType Arg = ArgInfo->getType(); 3027 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange(); 3028 3029 if (Arg->isVariablyModifiedType()) { 3030 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg; 3031 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) { 3032 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; 3033 } 3034 3035 // C++03 [temp.arg.type]p2: 3036 // A local type, a type with no linkage, an unnamed type or a type 3037 // compounded from any of these types shall not be used as a 3038 // template-argument for a template type-parameter. 3039 // 3040 // C++0x allows these, and even in C++03 we allow them as an extension with 3041 // a warning. 3042 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) { 3043 UnnamedLocalNoLinkageFinder Finder(*this, SR); 3044 (void)Finder.Visit(Context.getCanonicalType(Arg)); 3045 } 3046 3047 return false; 3048} 3049 3050/// \brief Checks whether the given template argument is the address 3051/// of an object or function according to C++ [temp.arg.nontype]p1. 3052static bool 3053CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, 3054 NonTypeTemplateParmDecl *Param, 3055 QualType ParamType, 3056 Expr *ArgIn, 3057 TemplateArgument &Converted) { 3058 bool Invalid = false; 3059 Expr *Arg = ArgIn; 3060 QualType ArgType = Arg->getType(); 3061 3062 // See through any implicit casts we added to fix the type. 3063 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 3064 Arg = Cast->getSubExpr(); 3065 3066 // C++ [temp.arg.nontype]p1: 3067 // 3068 // A template-argument for a non-type, non-template 3069 // template-parameter shall be one of: [...] 3070 // 3071 // -- the address of an object or function with external 3072 // linkage, including function templates and function 3073 // template-ids but excluding non-static class members, 3074 // expressed as & id-expression where the & is optional if 3075 // the name refers to a function or array, or if the 3076 // corresponding template-parameter is a reference; or 3077 DeclRefExpr *DRE = 0; 3078 3079 // In C++98/03 mode, give an extension warning on any extra parentheses. 3080 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 3081 bool ExtraParens = false; 3082 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 3083 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) { 3084 S.Diag(Arg->getSourceRange().getBegin(), 3085 diag::ext_template_arg_extra_parens) 3086 << Arg->getSourceRange(); 3087 ExtraParens = true; 3088 } 3089 3090 Arg = Parens->getSubExpr(); 3091 } 3092 3093 bool AddressTaken = false; 3094 SourceLocation AddrOpLoc; 3095 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 3096 3097 // Support &__uuidof(class_with_uuid) as a non-type template argument. 3098 // Very common in Microsoft COM headers. 3099 if (S.getLangOptions().Microsoft && 3100 isa<CXXUuidofExpr>(UnOp->getSubExpr())) { 3101 Converted = TemplateArgument(ArgIn); 3102 return false; 3103 } 3104 3105 if (UnOp->getOpcode() == UO_AddrOf) { 3106 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 3107 AddressTaken = true; 3108 AddrOpLoc = UnOp->getOperatorLoc(); 3109 } 3110 } else 3111 DRE = dyn_cast<DeclRefExpr>(Arg); 3112 3113 if (!DRE) { 3114 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref) 3115 << Arg->getSourceRange(); 3116 S.Diag(Param->getLocation(), diag::note_template_param_here); 3117 return true; 3118 } 3119 3120 // Stop checking the precise nature of the argument if it is value dependent, 3121 // it should be checked when instantiated. 3122 if (Arg->isValueDependent()) { 3123 Converted = TemplateArgument(ArgIn); 3124 return false; 3125 } 3126 3127 if (!isa<ValueDecl>(DRE->getDecl())) { 3128 S.Diag(Arg->getSourceRange().getBegin(), 3129 diag::err_template_arg_not_object_or_func_form) 3130 << Arg->getSourceRange(); 3131 S.Diag(Param->getLocation(), diag::note_template_param_here); 3132 return true; 3133 } 3134 3135 NamedDecl *Entity = 0; 3136 3137 // Cannot refer to non-static data members 3138 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) { 3139 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field) 3140 << Field << Arg->getSourceRange(); 3141 S.Diag(Param->getLocation(), diag::note_template_param_here); 3142 return true; 3143 } 3144 3145 // Cannot refer to non-static member functions 3146 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl())) 3147 if (!Method->isStatic()) { 3148 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method) 3149 << Method << Arg->getSourceRange(); 3150 S.Diag(Param->getLocation(), diag::note_template_param_here); 3151 return true; 3152 } 3153 3154 // Functions must have external linkage. 3155 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) { 3156 if (!isExternalLinkage(Func->getLinkage())) { 3157 S.Diag(Arg->getSourceRange().getBegin(), 3158 diag::err_template_arg_function_not_extern) 3159 << Func << Arg->getSourceRange(); 3160 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object) 3161 << true; 3162 return true; 3163 } 3164 3165 // Okay: we've named a function with external linkage. 3166 Entity = Func; 3167 3168 // If the template parameter has pointer type, the function decays. 3169 if (ParamType->isPointerType() && !AddressTaken) 3170 ArgType = S.Context.getPointerType(Func->getType()); 3171 else if (AddressTaken && ParamType->isReferenceType()) { 3172 // If we originally had an address-of operator, but the 3173 // parameter has reference type, complain and (if things look 3174 // like they will work) drop the address-of operator. 3175 if (!S.Context.hasSameUnqualifiedType(Func->getType(), 3176 ParamType.getNonReferenceType())) { 3177 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3178 << ParamType; 3179 S.Diag(Param->getLocation(), diag::note_template_param_here); 3180 return true; 3181 } 3182 3183 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3184 << ParamType 3185 << FixItHint::CreateRemoval(AddrOpLoc); 3186 S.Diag(Param->getLocation(), diag::note_template_param_here); 3187 3188 ArgType = Func->getType(); 3189 } 3190 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 3191 if (!isExternalLinkage(Var->getLinkage())) { 3192 S.Diag(Arg->getSourceRange().getBegin(), 3193 diag::err_template_arg_object_not_extern) 3194 << Var << Arg->getSourceRange(); 3195 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object) 3196 << true; 3197 return true; 3198 } 3199 3200 // A value of reference type is not an object. 3201 if (Var->getType()->isReferenceType()) { 3202 S.Diag(Arg->getSourceRange().getBegin(), 3203 diag::err_template_arg_reference_var) 3204 << Var->getType() << Arg->getSourceRange(); 3205 S.Diag(Param->getLocation(), diag::note_template_param_here); 3206 return true; 3207 } 3208 3209 // Okay: we've named an object with external linkage 3210 Entity = Var; 3211 3212 // If the template parameter has pointer type, we must have taken 3213 // the address of this object. 3214 if (ParamType->isReferenceType()) { 3215 if (AddressTaken) { 3216 // If we originally had an address-of operator, but the 3217 // parameter has reference type, complain and (if things look 3218 // like they will work) drop the address-of operator. 3219 if (!S.Context.hasSameUnqualifiedType(Var->getType(), 3220 ParamType.getNonReferenceType())) { 3221 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3222 << ParamType; 3223 S.Diag(Param->getLocation(), diag::note_template_param_here); 3224 return true; 3225 } 3226 3227 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3228 << ParamType 3229 << FixItHint::CreateRemoval(AddrOpLoc); 3230 S.Diag(Param->getLocation(), diag::note_template_param_here); 3231 3232 ArgType = Var->getType(); 3233 } 3234 } else if (!AddressTaken && ParamType->isPointerType()) { 3235 if (Var->getType()->isArrayType()) { 3236 // Array-to-pointer decay. 3237 ArgType = S.Context.getArrayDecayedType(Var->getType()); 3238 } else { 3239 // If the template parameter has pointer type but the address of 3240 // this object was not taken, complain and (possibly) recover by 3241 // taking the address of the entity. 3242 ArgType = S.Context.getPointerType(Var->getType()); 3243 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) { 3244 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of) 3245 << ParamType; 3246 S.Diag(Param->getLocation(), diag::note_template_param_here); 3247 return true; 3248 } 3249 3250 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of) 3251 << ParamType 3252 << FixItHint::CreateInsertion(Arg->getLocStart(), "&"); 3253 3254 S.Diag(Param->getLocation(), diag::note_template_param_here); 3255 } 3256 } 3257 } else { 3258 // We found something else, but we don't know specifically what it is. 3259 S.Diag(Arg->getSourceRange().getBegin(), 3260 diag::err_template_arg_not_object_or_func) 3261 << Arg->getSourceRange(); 3262 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); 3263 return true; 3264 } 3265 3266 if (ParamType->isPointerType() && 3267 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() && 3268 S.IsQualificationConversion(ArgType, ParamType, false)) { 3269 // For pointer-to-object types, qualification conversions are 3270 // permitted. 3271 } else { 3272 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) { 3273 if (!ParamRef->getPointeeType()->isFunctionType()) { 3274 // C++ [temp.arg.nontype]p5b3: 3275 // For a non-type template-parameter of type reference to 3276 // object, no conversions apply. The type referred to by the 3277 // reference may be more cv-qualified than the (otherwise 3278 // identical) type of the template- argument. The 3279 // template-parameter is bound directly to the 3280 // template-argument, which shall be an lvalue. 3281 3282 // FIXME: Other qualifiers? 3283 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers(); 3284 unsigned ArgQuals = ArgType.getCVRQualifiers(); 3285 3286 if ((ParamQuals | ArgQuals) != ParamQuals) { 3287 S.Diag(Arg->getSourceRange().getBegin(), 3288 diag::err_template_arg_ref_bind_ignores_quals) 3289 << ParamType << Arg->getType() 3290 << Arg->getSourceRange(); 3291 S.Diag(Param->getLocation(), diag::note_template_param_here); 3292 return true; 3293 } 3294 } 3295 } 3296 3297 // At this point, the template argument refers to an object or 3298 // function with external linkage. We now need to check whether the 3299 // argument and parameter types are compatible. 3300 if (!S.Context.hasSameUnqualifiedType(ArgType, 3301 ParamType.getNonReferenceType())) { 3302 // We can't perform this conversion or binding. 3303 if (ParamType->isReferenceType()) 3304 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind) 3305 << ParamType << Arg->getType() << Arg->getSourceRange(); 3306 else 3307 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible) 3308 << Arg->getType() << ParamType << Arg->getSourceRange(); 3309 S.Diag(Param->getLocation(), diag::note_template_param_here); 3310 return true; 3311 } 3312 } 3313 3314 // Create the template argument. 3315 Converted = TemplateArgument(Entity->getCanonicalDecl()); 3316 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity); 3317 return false; 3318} 3319 3320/// \brief Checks whether the given template argument is a pointer to 3321/// member constant according to C++ [temp.arg.nontype]p1. 3322bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, 3323 TemplateArgument &Converted) { 3324 bool Invalid = false; 3325 3326 // See through any implicit casts we added to fix the type. 3327 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 3328 Arg = Cast->getSubExpr(); 3329 3330 // C++ [temp.arg.nontype]p1: 3331 // 3332 // A template-argument for a non-type, non-template 3333 // template-parameter shall be one of: [...] 3334 // 3335 // -- a pointer to member expressed as described in 5.3.1. 3336 DeclRefExpr *DRE = 0; 3337 3338 // In C++98/03 mode, give an extension warning on any extra parentheses. 3339 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 3340 bool ExtraParens = false; 3341 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 3342 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) { 3343 Diag(Arg->getSourceRange().getBegin(), 3344 diag::ext_template_arg_extra_parens) 3345 << Arg->getSourceRange(); 3346 ExtraParens = true; 3347 } 3348 3349 Arg = Parens->getSubExpr(); 3350 } 3351 3352 // A pointer-to-member constant written &Class::member. 3353 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 3354 if (UnOp->getOpcode() == UO_AddrOf) { 3355 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 3356 if (DRE && !DRE->getQualifier()) 3357 DRE = 0; 3358 } 3359 } 3360 // A constant of pointer-to-member type. 3361 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 3362 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) { 3363 if (VD->getType()->isMemberPointerType()) { 3364 if (isa<NonTypeTemplateParmDecl>(VD) || 3365 (isa<VarDecl>(VD) && 3366 Context.getCanonicalType(VD->getType()).isConstQualified())) { 3367 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3368 Converted = TemplateArgument(Arg); 3369 else 3370 Converted = TemplateArgument(VD->getCanonicalDecl()); 3371 return Invalid; 3372 } 3373 } 3374 } 3375 3376 DRE = 0; 3377 } 3378 3379 if (!DRE) 3380 return Diag(Arg->getSourceRange().getBegin(), 3381 diag::err_template_arg_not_pointer_to_member_form) 3382 << Arg->getSourceRange(); 3383 3384 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) { 3385 assert((isa<FieldDecl>(DRE->getDecl()) || 3386 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 3387 "Only non-static member pointers can make it here"); 3388 3389 // Okay: this is the address of a non-static member, and therefore 3390 // a member pointer constant. 3391 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3392 Converted = TemplateArgument(Arg); 3393 else 3394 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl()); 3395 return Invalid; 3396 } 3397 3398 // We found something else, but we don't know specifically what it is. 3399 Diag(Arg->getSourceRange().getBegin(), 3400 diag::err_template_arg_not_pointer_to_member_form) 3401 << Arg->getSourceRange(); 3402 Diag(DRE->getDecl()->getLocation(), 3403 diag::note_template_arg_refers_here); 3404 return true; 3405} 3406 3407/// \brief Check a template argument against its corresponding 3408/// non-type template parameter. 3409/// 3410/// This routine implements the semantics of C++ [temp.arg.nontype]. 3411/// If an error occurred, it returns ExprError(); otherwise, it 3412/// returns the converted template argument. \p 3413/// InstantiatedParamType is the type of the non-type template 3414/// parameter after it has been instantiated. 3415ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 3416 QualType InstantiatedParamType, Expr *Arg, 3417 TemplateArgument &Converted, 3418 CheckTemplateArgumentKind CTAK) { 3419 SourceLocation StartLoc = Arg->getSourceRange().getBegin(); 3420 3421 // If either the parameter has a dependent type or the argument is 3422 // type-dependent, there's nothing we can check now. 3423 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { 3424 // FIXME: Produce a cloned, canonical expression? 3425 Converted = TemplateArgument(Arg); 3426 return Owned(Arg); 3427 } 3428 3429 // C++ [temp.arg.nontype]p5: 3430 // The following conversions are performed on each expression used 3431 // as a non-type template-argument. If a non-type 3432 // template-argument cannot be converted to the type of the 3433 // corresponding template-parameter then the program is 3434 // ill-formed. 3435 // 3436 // -- for a non-type template-parameter of integral or 3437 // enumeration type, integral promotions (4.5) and integral 3438 // conversions (4.7) are applied. 3439 QualType ParamType = InstantiatedParamType; 3440 QualType ArgType = Arg->getType(); 3441 if (ParamType->isIntegralOrEnumerationType()) { 3442 // C++ [temp.arg.nontype]p1: 3443 // A template-argument for a non-type, non-template 3444 // template-parameter shall be one of: 3445 // 3446 // -- an integral constant-expression of integral or enumeration 3447 // type; or 3448 // -- the name of a non-type template-parameter; or 3449 SourceLocation NonConstantLoc; 3450 llvm::APSInt Value; 3451 if (!ArgType->isIntegralOrEnumerationType()) { 3452 Diag(Arg->getSourceRange().getBegin(), 3453 diag::err_template_arg_not_integral_or_enumeral) 3454 << ArgType << Arg->getSourceRange(); 3455 Diag(Param->getLocation(), diag::note_template_param_here); 3456 return ExprError(); 3457 } else if (!Arg->isValueDependent() && 3458 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) { 3459 Diag(NonConstantLoc, diag::err_template_arg_not_ice) 3460 << ArgType << Arg->getSourceRange(); 3461 return ExprError(); 3462 } 3463 3464 // From here on out, all we care about are the unqualified forms 3465 // of the parameter and argument types. 3466 ParamType = ParamType.getUnqualifiedType(); 3467 ArgType = ArgType.getUnqualifiedType(); 3468 3469 // Try to convert the argument to the parameter's type. 3470 if (Context.hasSameType(ParamType, ArgType)) { 3471 // Okay: no conversion necessary 3472 } else if (CTAK == CTAK_Deduced) { 3473 // C++ [temp.deduct.type]p17: 3474 // If, in the declaration of a function template with a non-type 3475 // template-parameter, the non-type template- parameter is used 3476 // in an expression in the function parameter-list and, if the 3477 // corresponding template-argument is deduced, the 3478 // template-argument type shall match the type of the 3479 // template-parameter exactly, except that a template-argument 3480 // deduced from an array bound may be of any integral type. 3481 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch) 3482 << ArgType << ParamType; 3483 Diag(Param->getLocation(), diag::note_template_param_here); 3484 return ExprError(); 3485 } else if (ParamType->isBooleanType()) { 3486 // This is an integral-to-boolean conversion. 3487 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take(); 3488 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 3489 !ParamType->isEnumeralType()) { 3490 // This is an integral promotion or conversion. 3491 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take(); 3492 } else { 3493 // We can't perform this conversion. 3494 Diag(Arg->getSourceRange().getBegin(), 3495 diag::err_template_arg_not_convertible) 3496 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 3497 Diag(Param->getLocation(), diag::note_template_param_here); 3498 return ExprError(); 3499 } 3500 3501 QualType IntegerType = Context.getCanonicalType(ParamType); 3502 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 3503 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 3504 3505 if (!Arg->isValueDependent()) { 3506 llvm::APSInt OldValue = Value; 3507 3508 // Coerce the template argument's value to the value it will have 3509 // based on the template parameter's type. 3510 unsigned AllowedBits = Context.getTypeSize(IntegerType); 3511 if (Value.getBitWidth() != AllowedBits) 3512 Value = Value.extOrTrunc(AllowedBits); 3513 Value.setIsSigned(IntegerType->isSignedIntegerType()); 3514 3515 // Complain if an unsigned parameter received a negative value. 3516 if (IntegerType->isUnsignedIntegerType() 3517 && (OldValue.isSigned() && OldValue.isNegative())) { 3518 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative) 3519 << OldValue.toString(10) << Value.toString(10) << Param->getType() 3520 << Arg->getSourceRange(); 3521 Diag(Param->getLocation(), diag::note_template_param_here); 3522 } 3523 3524 // Complain if we overflowed the template parameter's type. 3525 unsigned RequiredBits; 3526 if (IntegerType->isUnsignedIntegerType()) 3527 RequiredBits = OldValue.getActiveBits(); 3528 else if (OldValue.isUnsigned()) 3529 RequiredBits = OldValue.getActiveBits() + 1; 3530 else 3531 RequiredBits = OldValue.getMinSignedBits(); 3532 if (RequiredBits > AllowedBits) { 3533 Diag(Arg->getSourceRange().getBegin(), 3534 diag::warn_template_arg_too_large) 3535 << OldValue.toString(10) << Value.toString(10) << Param->getType() 3536 << Arg->getSourceRange(); 3537 Diag(Param->getLocation(), diag::note_template_param_here); 3538 } 3539 } 3540 3541 // Add the value of this argument to the list of converted 3542 // arguments. We use the bitwidth and signedness of the template 3543 // parameter. 3544 if (Arg->isValueDependent()) { 3545 // The argument is value-dependent. Create a new 3546 // TemplateArgument with the converted expression. 3547 Converted = TemplateArgument(Arg); 3548 return Owned(Arg); 3549 } 3550 3551 Converted = TemplateArgument(Value, 3552 ParamType->isEnumeralType() ? ParamType 3553 : IntegerType); 3554 return Owned(Arg); 3555 } 3556 3557 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction 3558 3559 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion 3560 // from a template argument of type std::nullptr_t to a non-type 3561 // template parameter of type pointer to object, pointer to 3562 // function, or pointer-to-member, respectively. 3563 if (ArgType->isNullPtrType() && 3564 (ParamType->isPointerType() || ParamType->isMemberPointerType())) { 3565 Converted = TemplateArgument((NamedDecl *)0); 3566 return Owned(Arg); 3567 } 3568 3569 // Handle pointer-to-function, reference-to-function, and 3570 // pointer-to-member-function all in (roughly) the same way. 3571 if (// -- For a non-type template-parameter of type pointer to 3572 // function, only the function-to-pointer conversion (4.3) is 3573 // applied. If the template-argument represents a set of 3574 // overloaded functions (or a pointer to such), the matching 3575 // function is selected from the set (13.4). 3576 (ParamType->isPointerType() && 3577 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) || 3578 // -- For a non-type template-parameter of type reference to 3579 // function, no conversions apply. If the template-argument 3580 // represents a set of overloaded functions, the matching 3581 // function is selected from the set (13.4). 3582 (ParamType->isReferenceType() && 3583 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 3584 // -- For a non-type template-parameter of type pointer to 3585 // member function, no conversions apply. If the 3586 // template-argument represents a set of overloaded member 3587 // functions, the matching member function is selected from 3588 // the set (13.4). 3589 (ParamType->isMemberPointerType() && 3590 ParamType->getAs<MemberPointerType>()->getPointeeType() 3591 ->isFunctionType())) { 3592 3593 if (Arg->getType() == Context.OverloadTy) { 3594 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, 3595 true, 3596 FoundResult)) { 3597 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 3598 return ExprError(); 3599 3600 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 3601 ArgType = Arg->getType(); 3602 } else 3603 return ExprError(); 3604 } 3605 3606 if (!ParamType->isMemberPointerType()) { 3607 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 3608 ParamType, 3609 Arg, Converted)) 3610 return ExprError(); 3611 return Owned(Arg); 3612 } 3613 3614 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(), 3615 false)) { 3616 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg)).take(); 3617 } else if (!Context.hasSameUnqualifiedType(ArgType, 3618 ParamType.getNonReferenceType())) { 3619 // We can't perform this conversion. 3620 Diag(Arg->getSourceRange().getBegin(), 3621 diag::err_template_arg_not_convertible) 3622 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 3623 Diag(Param->getLocation(), diag::note_template_param_here); 3624 return ExprError(); 3625 } 3626 3627 if (CheckTemplateArgumentPointerToMember(Arg, Converted)) 3628 return ExprError(); 3629 return Owned(Arg); 3630 } 3631 3632 if (ParamType->isPointerType()) { 3633 // -- for a non-type template-parameter of type pointer to 3634 // object, qualification conversions (4.4) and the 3635 // array-to-pointer conversion (4.2) are applied. 3636 // C++0x also allows a value of std::nullptr_t. 3637 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && 3638 "Only object pointers allowed here"); 3639 3640 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 3641 ParamType, 3642 Arg, Converted)) 3643 return ExprError(); 3644 return Owned(Arg); 3645 } 3646 3647 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 3648 // -- For a non-type template-parameter of type reference to 3649 // object, no conversions apply. The type referred to by the 3650 // reference may be more cv-qualified than the (otherwise 3651 // identical) type of the template-argument. The 3652 // template-parameter is bound directly to the 3653 // template-argument, which must be an lvalue. 3654 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() && 3655 "Only object references allowed here"); 3656 3657 if (Arg->getType() == Context.OverloadTy) { 3658 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, 3659 ParamRefType->getPointeeType(), 3660 true, 3661 FoundResult)) { 3662 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 3663 return ExprError(); 3664 3665 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 3666 ArgType = Arg->getType(); 3667 } else 3668 return ExprError(); 3669 } 3670 3671 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 3672 ParamType, 3673 Arg, Converted)) 3674 return ExprError(); 3675 return Owned(Arg); 3676 } 3677 3678 // -- For a non-type template-parameter of type pointer to data 3679 // member, qualification conversions (4.4) are applied. 3680 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 3681 3682 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) { 3683 // Types match exactly: nothing more to do here. 3684 } else if (IsQualificationConversion(ArgType, ParamType, false)) { 3685 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg)).take(); 3686 } else { 3687 // We can't perform this conversion. 3688 Diag(Arg->getSourceRange().getBegin(), 3689 diag::err_template_arg_not_convertible) 3690 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 3691 Diag(Param->getLocation(), diag::note_template_param_here); 3692 return ExprError(); 3693 } 3694 3695 if (CheckTemplateArgumentPointerToMember(Arg, Converted)) 3696 return ExprError(); 3697 return Owned(Arg); 3698} 3699 3700/// \brief Check a template argument against its corresponding 3701/// template template parameter. 3702/// 3703/// This routine implements the semantics of C++ [temp.arg.template]. 3704/// It returns true if an error occurred, and false otherwise. 3705bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 3706 const TemplateArgumentLoc &Arg) { 3707 TemplateName Name = Arg.getArgument().getAsTemplate(); 3708 TemplateDecl *Template = Name.getAsTemplateDecl(); 3709 if (!Template) { 3710 // Any dependent template name is fine. 3711 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 3712 return false; 3713 } 3714 3715 // C++ [temp.arg.template]p1: 3716 // A template-argument for a template template-parameter shall be 3717 // the name of a class template, expressed as id-expression. Only 3718 // primary class templates are considered when matching the 3719 // template template argument with the corresponding parameter; 3720 // partial specializations are not considered even if their 3721 // parameter lists match that of the template template parameter. 3722 // 3723 // Note that we also allow template template parameters here, which 3724 // will happen when we are dealing with, e.g., class template 3725 // partial specializations. 3726 if (!isa<ClassTemplateDecl>(Template) && 3727 !isa<TemplateTemplateParmDecl>(Template)) { 3728 assert(isa<FunctionTemplateDecl>(Template) && 3729 "Only function templates are possible here"); 3730 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template); 3731 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 3732 << Template; 3733 } 3734 3735 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 3736 Param->getTemplateParameters(), 3737 true, 3738 TPL_TemplateTemplateArgumentMatch, 3739 Arg.getLocation()); 3740} 3741 3742/// \brief Given a non-type template argument that refers to a 3743/// declaration and the type of its corresponding non-type template 3744/// parameter, produce an expression that properly refers to that 3745/// declaration. 3746ExprResult 3747Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 3748 QualType ParamType, 3749 SourceLocation Loc) { 3750 assert(Arg.getKind() == TemplateArgument::Declaration && 3751 "Only declaration template arguments permitted here"); 3752 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl()); 3753 3754 if (VD->getDeclContext()->isRecord() && 3755 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) { 3756 // If the value is a class member, we might have a pointer-to-member. 3757 // Determine whether the non-type template template parameter is of 3758 // pointer-to-member type. If so, we need to build an appropriate 3759 // expression for a pointer-to-member, since a "normal" DeclRefExpr 3760 // would refer to the member itself. 3761 if (ParamType->isMemberPointerType()) { 3762 QualType ClassType 3763 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext())); 3764 NestedNameSpecifier *Qualifier 3765 = NestedNameSpecifier::Create(Context, 0, false, 3766 ClassType.getTypePtr()); 3767 CXXScopeSpec SS; 3768 SS.MakeTrivial(Context, Qualifier, Loc); 3769 3770 // The actual value-ness of this is unimportant, but for 3771 // internal consistency's sake, references to instance methods 3772 // are r-values. 3773 ExprValueKind VK = VK_LValue; 3774 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance()) 3775 VK = VK_RValue; 3776 3777 ExprResult RefExpr = BuildDeclRefExpr(VD, 3778 VD->getType().getNonReferenceType(), 3779 VK, 3780 Loc, 3781 &SS); 3782 if (RefExpr.isInvalid()) 3783 return ExprError(); 3784 3785 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 3786 3787 // We might need to perform a trailing qualification conversion, since 3788 // the element type on the parameter could be more qualified than the 3789 // element type in the expression we constructed. 3790 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(), 3791 ParamType.getUnqualifiedType(), false)) 3792 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp); 3793 3794 assert(!RefExpr.isInvalid() && 3795 Context.hasSameType(((Expr*) RefExpr.get())->getType(), 3796 ParamType.getUnqualifiedType())); 3797 return move(RefExpr); 3798 } 3799 } 3800 3801 QualType T = VD->getType().getNonReferenceType(); 3802 if (ParamType->isPointerType()) { 3803 // When the non-type template parameter is a pointer, take the 3804 // address of the declaration. 3805 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc); 3806 if (RefExpr.isInvalid()) 3807 return ExprError(); 3808 3809 if (T->isFunctionType() || T->isArrayType()) { 3810 // Decay functions and arrays. 3811 RefExpr = DefaultFunctionArrayConversion(RefExpr.take()); 3812 if (RefExpr.isInvalid()) 3813 return ExprError(); 3814 3815 return move(RefExpr); 3816 } 3817 3818 // Take the address of everything else 3819 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 3820 } 3821 3822 ExprValueKind VK = VK_RValue; 3823 3824 // If the non-type template parameter has reference type, qualify the 3825 // resulting declaration reference with the extra qualifiers on the 3826 // type that the reference refers to. 3827 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) { 3828 VK = VK_LValue; 3829 T = Context.getQualifiedType(T, 3830 TargetRef->getPointeeType().getQualifiers()); 3831 } 3832 3833 return BuildDeclRefExpr(VD, T, VK, Loc); 3834} 3835 3836/// \brief Construct a new expression that refers to the given 3837/// integral template argument with the given source-location 3838/// information. 3839/// 3840/// This routine takes care of the mapping from an integral template 3841/// argument (which may have any integral type) to the appropriate 3842/// literal value. 3843ExprResult 3844Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 3845 SourceLocation Loc) { 3846 assert(Arg.getKind() == TemplateArgument::Integral && 3847 "Operation is only valid for integral template arguments"); 3848 QualType T = Arg.getIntegralType(); 3849 if (T->isCharType() || T->isWideCharType()) 3850 return Owned(new (Context) CharacterLiteral( 3851 Arg.getAsIntegral()->getZExtValue(), 3852 T->isWideCharType(), T, Loc)); 3853 if (T->isBooleanType()) 3854 return Owned(new (Context) CXXBoolLiteralExpr( 3855 Arg.getAsIntegral()->getBoolValue(), 3856 T, Loc)); 3857 3858 // If this is an enum type that we're instantiating, we need to use an integer 3859 // type the same size as the enumerator. We don't want to build an 3860 // IntegerLiteral with enum type. 3861 QualType BT; 3862 if (const EnumType *ET = T->getAs<EnumType>()) 3863 BT = ET->getDecl()->getIntegerType(); 3864 else 3865 BT = T; 3866 3867 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc); 3868 if (T->isEnumeralType()) { 3869 // FIXME: This is a hack. We need a better way to handle substituted 3870 // non-type template parameters. 3871 E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast, E, 0, 3872 Context.getTrivialTypeSourceInfo(T, Loc), 3873 Loc, Loc); 3874 } 3875 3876 return Owned(E); 3877} 3878 3879/// \brief Match two template parameters within template parameter lists. 3880static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old, 3881 bool Complain, 3882 Sema::TemplateParameterListEqualKind Kind, 3883 SourceLocation TemplateArgLoc) { 3884 // Check the actual kind (type, non-type, template). 3885 if (Old->getKind() != New->getKind()) { 3886 if (Complain) { 3887 unsigned NextDiag = diag::err_template_param_different_kind; 3888 if (TemplateArgLoc.isValid()) { 3889 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 3890 NextDiag = diag::note_template_param_different_kind; 3891 } 3892 S.Diag(New->getLocation(), NextDiag) 3893 << (Kind != Sema::TPL_TemplateMatch); 3894 S.Diag(Old->getLocation(), diag::note_template_prev_declaration) 3895 << (Kind != Sema::TPL_TemplateMatch); 3896 } 3897 3898 return false; 3899 } 3900 3901 // Check that both are parameter packs are neither are parameter packs. 3902 // However, if we are matching a template template argument to a 3903 // template template parameter, the template template parameter can have 3904 // a parameter pack where the template template argument does not. 3905 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() && 3906 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch && 3907 Old->isTemplateParameterPack())) { 3908 if (Complain) { 3909 unsigned NextDiag = diag::err_template_parameter_pack_non_pack; 3910 if (TemplateArgLoc.isValid()) { 3911 S.Diag(TemplateArgLoc, 3912 diag::err_template_arg_template_params_mismatch); 3913 NextDiag = diag::note_template_parameter_pack_non_pack; 3914 } 3915 3916 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0 3917 : isa<NonTypeTemplateParmDecl>(New)? 1 3918 : 2; 3919 S.Diag(New->getLocation(), NextDiag) 3920 << ParamKind << New->isParameterPack(); 3921 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here) 3922 << ParamKind << Old->isParameterPack(); 3923 } 3924 3925 return false; 3926 } 3927 3928 // For non-type template parameters, check the type of the parameter. 3929 if (NonTypeTemplateParmDecl *OldNTTP 3930 = dyn_cast<NonTypeTemplateParmDecl>(Old)) { 3931 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New); 3932 3933 // If we are matching a template template argument to a template 3934 // template parameter and one of the non-type template parameter types 3935 // is dependent, then we must wait until template instantiation time 3936 // to actually compare the arguments. 3937 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch && 3938 (OldNTTP->getType()->isDependentType() || 3939 NewNTTP->getType()->isDependentType())) 3940 return true; 3941 3942 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) { 3943 if (Complain) { 3944 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 3945 if (TemplateArgLoc.isValid()) { 3946 S.Diag(TemplateArgLoc, 3947 diag::err_template_arg_template_params_mismatch); 3948 NextDiag = diag::note_template_nontype_parm_different_type; 3949 } 3950 S.Diag(NewNTTP->getLocation(), NextDiag) 3951 << NewNTTP->getType() 3952 << (Kind != Sema::TPL_TemplateMatch); 3953 S.Diag(OldNTTP->getLocation(), 3954 diag::note_template_nontype_parm_prev_declaration) 3955 << OldNTTP->getType(); 3956 } 3957 3958 return false; 3959 } 3960 3961 return true; 3962 } 3963 3964 // For template template parameters, check the template parameter types. 3965 // The template parameter lists of template template 3966 // parameters must agree. 3967 if (TemplateTemplateParmDecl *OldTTP 3968 = dyn_cast<TemplateTemplateParmDecl>(Old)) { 3969 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New); 3970 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 3971 OldTTP->getTemplateParameters(), 3972 Complain, 3973 (Kind == Sema::TPL_TemplateMatch 3974 ? Sema::TPL_TemplateTemplateParmMatch 3975 : Kind), 3976 TemplateArgLoc); 3977 } 3978 3979 return true; 3980} 3981 3982/// \brief Diagnose a known arity mismatch when comparing template argument 3983/// lists. 3984static 3985void DiagnoseTemplateParameterListArityMismatch(Sema &S, 3986 TemplateParameterList *New, 3987 TemplateParameterList *Old, 3988 Sema::TemplateParameterListEqualKind Kind, 3989 SourceLocation TemplateArgLoc) { 3990 unsigned NextDiag = diag::err_template_param_list_different_arity; 3991 if (TemplateArgLoc.isValid()) { 3992 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 3993 NextDiag = diag::note_template_param_list_different_arity; 3994 } 3995 S.Diag(New->getTemplateLoc(), NextDiag) 3996 << (New->size() > Old->size()) 3997 << (Kind != Sema::TPL_TemplateMatch) 3998 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 3999 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 4000 << (Kind != Sema::TPL_TemplateMatch) 4001 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 4002} 4003 4004/// \brief Determine whether the given template parameter lists are 4005/// equivalent. 4006/// 4007/// \param New The new template parameter list, typically written in the 4008/// source code as part of a new template declaration. 4009/// 4010/// \param Old The old template parameter list, typically found via 4011/// name lookup of the template declared with this template parameter 4012/// list. 4013/// 4014/// \param Complain If true, this routine will produce a diagnostic if 4015/// the template parameter lists are not equivalent. 4016/// 4017/// \param Kind describes how we are to match the template parameter lists. 4018/// 4019/// \param TemplateArgLoc If this source location is valid, then we 4020/// are actually checking the template parameter list of a template 4021/// argument (New) against the template parameter list of its 4022/// corresponding template template parameter (Old). We produce 4023/// slightly different diagnostics in this scenario. 4024/// 4025/// \returns True if the template parameter lists are equal, false 4026/// otherwise. 4027bool 4028Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 4029 TemplateParameterList *Old, 4030 bool Complain, 4031 TemplateParameterListEqualKind Kind, 4032 SourceLocation TemplateArgLoc) { 4033 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) { 4034 if (Complain) 4035 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 4036 TemplateArgLoc); 4037 4038 return false; 4039 } 4040 4041 // C++0x [temp.arg.template]p3: 4042 // A template-argument matches a template template-parameter (call it P) 4043 // when each of the template parameters in the template-parameter-list of 4044 // the template-argument's corresponding class template or template alias 4045 // (call it A) matches the corresponding template parameter in the 4046 // template-parameter-list of P. [...] 4047 TemplateParameterList::iterator NewParm = New->begin(); 4048 TemplateParameterList::iterator NewParmEnd = New->end(); 4049 for (TemplateParameterList::iterator OldParm = Old->begin(), 4050 OldParmEnd = Old->end(); 4051 OldParm != OldParmEnd; ++OldParm) { 4052 if (Kind != TPL_TemplateTemplateArgumentMatch || 4053 !(*OldParm)->isTemplateParameterPack()) { 4054 if (NewParm == NewParmEnd) { 4055 if (Complain) 4056 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 4057 TemplateArgLoc); 4058 4059 return false; 4060 } 4061 4062 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 4063 Kind, TemplateArgLoc)) 4064 return false; 4065 4066 ++NewParm; 4067 continue; 4068 } 4069 4070 // C++0x [temp.arg.template]p3: 4071 // [...] When P's template- parameter-list contains a template parameter 4072 // pack (14.5.3), the template parameter pack will match zero or more 4073 // template parameters or template parameter packs in the 4074 // template-parameter-list of A with the same type and form as the 4075 // template parameter pack in P (ignoring whether those template 4076 // parameters are template parameter packs). 4077 for (; NewParm != NewParmEnd; ++NewParm) { 4078 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 4079 Kind, TemplateArgLoc)) 4080 return false; 4081 } 4082 } 4083 4084 // Make sure we exhausted all of the arguments. 4085 if (NewParm != NewParmEnd) { 4086 if (Complain) 4087 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 4088 TemplateArgLoc); 4089 4090 return false; 4091 } 4092 4093 return true; 4094} 4095 4096/// \brief Check whether a template can be declared within this scope. 4097/// 4098/// If the template declaration is valid in this scope, returns 4099/// false. Otherwise, issues a diagnostic and returns true. 4100bool 4101Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 4102 // Find the nearest enclosing declaration scope. 4103 while ((S->getFlags() & Scope::DeclScope) == 0 || 4104 (S->getFlags() & Scope::TemplateParamScope) != 0) 4105 S = S->getParent(); 4106 4107 // C++ [temp]p2: 4108 // A template-declaration can appear only as a namespace scope or 4109 // class scope declaration. 4110 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 4111 if (Ctx && isa<LinkageSpecDecl>(Ctx) && 4112 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) 4113 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 4114 << TemplateParams->getSourceRange(); 4115 4116 while (Ctx && isa<LinkageSpecDecl>(Ctx)) 4117 Ctx = Ctx->getParent(); 4118 4119 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) 4120 return false; 4121 4122 return Diag(TemplateParams->getTemplateLoc(), 4123 diag::err_template_outside_namespace_or_class_scope) 4124 << TemplateParams->getSourceRange(); 4125} 4126 4127/// \brief Determine what kind of template specialization the given declaration 4128/// is. 4129static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) { 4130 if (!D) 4131 return TSK_Undeclared; 4132 4133 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 4134 return Record->getTemplateSpecializationKind(); 4135 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 4136 return Function->getTemplateSpecializationKind(); 4137 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 4138 return Var->getTemplateSpecializationKind(); 4139 4140 return TSK_Undeclared; 4141} 4142 4143/// \brief Check whether a specialization is well-formed in the current 4144/// context. 4145/// 4146/// This routine determines whether a template specialization can be declared 4147/// in the current context (C++ [temp.expl.spec]p2). 4148/// 4149/// \param S the semantic analysis object for which this check is being 4150/// performed. 4151/// 4152/// \param Specialized the entity being specialized or instantiated, which 4153/// may be a kind of template (class template, function template, etc.) or 4154/// a member of a class template (member function, static data member, 4155/// member class). 4156/// 4157/// \param PrevDecl the previous declaration of this entity, if any. 4158/// 4159/// \param Loc the location of the explicit specialization or instantiation of 4160/// this entity. 4161/// 4162/// \param IsPartialSpecialization whether this is a partial specialization of 4163/// a class template. 4164/// 4165/// \returns true if there was an error that we cannot recover from, false 4166/// otherwise. 4167static bool CheckTemplateSpecializationScope(Sema &S, 4168 NamedDecl *Specialized, 4169 NamedDecl *PrevDecl, 4170 SourceLocation Loc, 4171 bool IsPartialSpecialization) { 4172 // Keep these "kind" numbers in sync with the %select statements in the 4173 // various diagnostics emitted by this routine. 4174 int EntityKind = 0; 4175 if (isa<ClassTemplateDecl>(Specialized)) 4176 EntityKind = IsPartialSpecialization? 1 : 0; 4177 else if (isa<FunctionTemplateDecl>(Specialized)) 4178 EntityKind = 2; 4179 else if (isa<CXXMethodDecl>(Specialized)) 4180 EntityKind = 3; 4181 else if (isa<VarDecl>(Specialized)) 4182 EntityKind = 4; 4183 else if (isa<RecordDecl>(Specialized)) 4184 EntityKind = 5; 4185 else { 4186 S.Diag(Loc, diag::err_template_spec_unknown_kind); 4187 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 4188 return true; 4189 } 4190 4191 // C++ [temp.expl.spec]p2: 4192 // An explicit specialization shall be declared in the namespace 4193 // of which the template is a member, or, for member templates, in 4194 // the namespace of which the enclosing class or enclosing class 4195 // template is a member. An explicit specialization of a member 4196 // function, member class or static data member of a class 4197 // template shall be declared in the namespace of which the class 4198 // template is a member. Such a declaration may also be a 4199 // definition. If the declaration is not a definition, the 4200 // specialization may be defined later in the name- space in which 4201 // the explicit specialization was declared, or in a namespace 4202 // that encloses the one in which the explicit specialization was 4203 // declared. 4204 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) { 4205 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 4206 << Specialized; 4207 return true; 4208 } 4209 4210 if (S.CurContext->isRecord() && !IsPartialSpecialization) { 4211 S.Diag(Loc, diag::err_template_spec_decl_class_scope) 4212 << Specialized; 4213 return true; 4214 } 4215 4216 // C++ [temp.class.spec]p6: 4217 // A class template partial specialization may be declared or redeclared 4218 // in any namespace scope in which its definition may be defined (14.5.1 4219 // and 14.5.2). 4220 bool ComplainedAboutScope = false; 4221 DeclContext *SpecializedContext 4222 = Specialized->getDeclContext()->getEnclosingNamespaceContext(); 4223 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext(); 4224 if ((!PrevDecl || 4225 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared || 4226 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){ 4227 // C++ [temp.exp.spec]p2: 4228 // An explicit specialization shall be declared in the namespace of which 4229 // the template is a member, or, for member templates, in the namespace 4230 // of which the enclosing class or enclosing class template is a member. 4231 // An explicit specialization of a member function, member class or 4232 // static data member of a class template shall be declared in the 4233 // namespace of which the class template is a member. 4234 // 4235 // C++0x [temp.expl.spec]p2: 4236 // An explicit specialization shall be declared in a namespace enclosing 4237 // the specialized template. 4238 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) && 4239 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) { 4240 bool IsCPlusPlus0xExtension 4241 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext); 4242 if (isa<TranslationUnitDecl>(SpecializedContext)) 4243 S.Diag(Loc, IsCPlusPlus0xExtension 4244 ? diag::ext_template_spec_decl_out_of_scope_global 4245 : diag::err_template_spec_decl_out_of_scope_global) 4246 << EntityKind << Specialized; 4247 else if (isa<NamespaceDecl>(SpecializedContext)) 4248 S.Diag(Loc, IsCPlusPlus0xExtension 4249 ? diag::ext_template_spec_decl_out_of_scope 4250 : diag::err_template_spec_decl_out_of_scope) 4251 << EntityKind << Specialized 4252 << cast<NamedDecl>(SpecializedContext); 4253 4254 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 4255 ComplainedAboutScope = true; 4256 } 4257 } 4258 4259 // Make sure that this redeclaration (or definition) occurs in an enclosing 4260 // namespace. 4261 // Note that HandleDeclarator() performs this check for explicit 4262 // specializations of function templates, static data members, and member 4263 // functions, so we skip the check here for those kinds of entities. 4264 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though. 4265 // Should we refactor that check, so that it occurs later? 4266 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) && 4267 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) || 4268 isa<FunctionDecl>(Specialized))) { 4269 if (isa<TranslationUnitDecl>(SpecializedContext)) 4270 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 4271 << EntityKind << Specialized; 4272 else if (isa<NamespaceDecl>(SpecializedContext)) 4273 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope) 4274 << EntityKind << Specialized 4275 << cast<NamedDecl>(SpecializedContext); 4276 4277 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 4278 } 4279 4280 // FIXME: check for specialization-after-instantiation errors and such. 4281 4282 return false; 4283} 4284 4285/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs 4286/// that checks non-type template partial specialization arguments. 4287static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S, 4288 NonTypeTemplateParmDecl *Param, 4289 const TemplateArgument *Args, 4290 unsigned NumArgs) { 4291 for (unsigned I = 0; I != NumArgs; ++I) { 4292 if (Args[I].getKind() == TemplateArgument::Pack) { 4293 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param, 4294 Args[I].pack_begin(), 4295 Args[I].pack_size())) 4296 return true; 4297 4298 continue; 4299 } 4300 4301 Expr *ArgExpr = Args[I].getAsExpr(); 4302 if (!ArgExpr) { 4303 continue; 4304 } 4305 4306 // We can have a pack expansion of any of the bullets below. 4307 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr)) 4308 ArgExpr = Expansion->getPattern(); 4309 4310 // Strip off any implicit casts we added as part of type checking. 4311 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 4312 ArgExpr = ICE->getSubExpr(); 4313 4314 // C++ [temp.class.spec]p8: 4315 // A non-type argument is non-specialized if it is the name of a 4316 // non-type parameter. All other non-type arguments are 4317 // specialized. 4318 // 4319 // Below, we check the two conditions that only apply to 4320 // specialized non-type arguments, so skip any non-specialized 4321 // arguments. 4322 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 4323 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl())) 4324 continue; 4325 4326 // C++ [temp.class.spec]p9: 4327 // Within the argument list of a class template partial 4328 // specialization, the following restrictions apply: 4329 // -- A partially specialized non-type argument expression 4330 // shall not involve a template parameter of the partial 4331 // specialization except when the argument expression is a 4332 // simple identifier. 4333 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) { 4334 S.Diag(ArgExpr->getLocStart(), 4335 diag::err_dependent_non_type_arg_in_partial_spec) 4336 << ArgExpr->getSourceRange(); 4337 return true; 4338 } 4339 4340 // -- The type of a template parameter corresponding to a 4341 // specialized non-type argument shall not be dependent on a 4342 // parameter of the specialization. 4343 if (Param->getType()->isDependentType()) { 4344 S.Diag(ArgExpr->getLocStart(), 4345 diag::err_dependent_typed_non_type_arg_in_partial_spec) 4346 << Param->getType() 4347 << ArgExpr->getSourceRange(); 4348 S.Diag(Param->getLocation(), diag::note_template_param_here); 4349 return true; 4350 } 4351 } 4352 4353 return false; 4354} 4355 4356/// \brief Check the non-type template arguments of a class template 4357/// partial specialization according to C++ [temp.class.spec]p9. 4358/// 4359/// \param TemplateParams the template parameters of the primary class 4360/// template. 4361/// 4362/// \param TemplateArg the template arguments of the class template 4363/// partial specialization. 4364/// 4365/// \returns true if there was an error, false otherwise. 4366static bool CheckClassTemplatePartialSpecializationArgs(Sema &S, 4367 TemplateParameterList *TemplateParams, 4368 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) { 4369 const TemplateArgument *ArgList = TemplateArgs.data(); 4370 4371 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 4372 NonTypeTemplateParmDecl *Param 4373 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 4374 if (!Param) 4375 continue; 4376 4377 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param, 4378 &ArgList[I], 1)) 4379 return true; 4380 } 4381 4382 return false; 4383} 4384 4385/// \brief Retrieve the previous declaration of the given declaration. 4386static NamedDecl *getPreviousDecl(NamedDecl *ND) { 4387 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 4388 return VD->getPreviousDeclaration(); 4389 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 4390 return FD->getPreviousDeclaration(); 4391 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) 4392 return TD->getPreviousDeclaration(); 4393 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 4394 return TD->getPreviousDeclaration(); 4395 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 4396 return FTD->getPreviousDeclaration(); 4397 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND)) 4398 return CTD->getPreviousDeclaration(); 4399 return 0; 4400} 4401 4402DeclResult 4403Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, 4404 TagUseKind TUK, 4405 SourceLocation KWLoc, 4406 CXXScopeSpec &SS, 4407 TemplateTy TemplateD, 4408 SourceLocation TemplateNameLoc, 4409 SourceLocation LAngleLoc, 4410 ASTTemplateArgsPtr TemplateArgsIn, 4411 SourceLocation RAngleLoc, 4412 AttributeList *Attr, 4413 MultiTemplateParamsArg TemplateParameterLists) { 4414 assert(TUK != TUK_Reference && "References are not specializations"); 4415 4416 // NOTE: KWLoc is the location of the tag keyword. This will instead 4417 // store the location of the outermost template keyword in the declaration. 4418 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0 4419 ? TemplateParameterLists.get()[0]->getTemplateLoc() : SourceLocation(); 4420 4421 // Find the class template we're specializing 4422 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 4423 ClassTemplateDecl *ClassTemplate 4424 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); 4425 4426 if (!ClassTemplate) { 4427 Diag(TemplateNameLoc, diag::err_not_class_template_specialization) 4428 << (Name.getAsTemplateDecl() && 4429 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); 4430 return true; 4431 } 4432 4433 bool isExplicitSpecialization = false; 4434 bool isPartialSpecialization = false; 4435 4436 // Check the validity of the template headers that introduce this 4437 // template. 4438 // FIXME: We probably shouldn't complain about these headers for 4439 // friend declarations. 4440 bool Invalid = false; 4441 TemplateParameterList *TemplateParams 4442 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS, 4443 (TemplateParameterList**)TemplateParameterLists.get(), 4444 TemplateParameterLists.size(), 4445 TUK == TUK_Friend, 4446 isExplicitSpecialization, 4447 Invalid); 4448 if (Invalid) 4449 return true; 4450 4451 if (TemplateParams && TemplateParams->size() > 0) { 4452 isPartialSpecialization = true; 4453 4454 if (TUK == TUK_Friend) { 4455 Diag(KWLoc, diag::err_partial_specialization_friend) 4456 << SourceRange(LAngleLoc, RAngleLoc); 4457 return true; 4458 } 4459 4460 // C++ [temp.class.spec]p10: 4461 // The template parameter list of a specialization shall not 4462 // contain default template argument values. 4463 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 4464 Decl *Param = TemplateParams->getParam(I); 4465 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4466 if (TTP->hasDefaultArgument()) { 4467 Diag(TTP->getDefaultArgumentLoc(), 4468 diag::err_default_arg_in_partial_spec); 4469 TTP->removeDefaultArgument(); 4470 } 4471 } else if (NonTypeTemplateParmDecl *NTTP 4472 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4473 if (Expr *DefArg = NTTP->getDefaultArgument()) { 4474 Diag(NTTP->getDefaultArgumentLoc(), 4475 diag::err_default_arg_in_partial_spec) 4476 << DefArg->getSourceRange(); 4477 NTTP->removeDefaultArgument(); 4478 } 4479 } else { 4480 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 4481 if (TTP->hasDefaultArgument()) { 4482 Diag(TTP->getDefaultArgument().getLocation(), 4483 diag::err_default_arg_in_partial_spec) 4484 << TTP->getDefaultArgument().getSourceRange(); 4485 TTP->removeDefaultArgument(); 4486 } 4487 } 4488 } 4489 } else if (TemplateParams) { 4490 if (TUK == TUK_Friend) 4491 Diag(KWLoc, diag::err_template_spec_friend) 4492 << FixItHint::CreateRemoval( 4493 SourceRange(TemplateParams->getTemplateLoc(), 4494 TemplateParams->getRAngleLoc())) 4495 << SourceRange(LAngleLoc, RAngleLoc); 4496 else 4497 isExplicitSpecialization = true; 4498 } else if (TUK != TUK_Friend) { 4499 Diag(KWLoc, diag::err_template_spec_needs_header) 4500 << FixItHint::CreateInsertion(KWLoc, "template<> "); 4501 isExplicitSpecialization = true; 4502 } 4503 4504 // Check that the specialization uses the same tag kind as the 4505 // original template. 4506 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 4507 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!"); 4508 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 4509 Kind, KWLoc, 4510 *ClassTemplate->getIdentifier())) { 4511 Diag(KWLoc, diag::err_use_with_wrong_tag) 4512 << ClassTemplate 4513 << FixItHint::CreateReplacement(KWLoc, 4514 ClassTemplate->getTemplatedDecl()->getKindName()); 4515 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 4516 diag::note_previous_use); 4517 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 4518 } 4519 4520 // Translate the parser's template argument list in our AST format. 4521 TemplateArgumentListInfo TemplateArgs; 4522 TemplateArgs.setLAngleLoc(LAngleLoc); 4523 TemplateArgs.setRAngleLoc(RAngleLoc); 4524 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 4525 4526 // Check for unexpanded parameter packs in any of the template arguments. 4527 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 4528 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 4529 UPPC_PartialSpecialization)) 4530 return true; 4531 4532 // Check that the template argument list is well-formed for this 4533 // template. 4534 llvm::SmallVector<TemplateArgument, 4> Converted; 4535 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 4536 TemplateArgs, false, Converted)) 4537 return true; 4538 4539 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) && 4540 "Converted template argument list is too short!"); 4541 4542 // Find the class template (partial) specialization declaration that 4543 // corresponds to these arguments. 4544 if (isPartialSpecialization) { 4545 if (CheckClassTemplatePartialSpecializationArgs(*this, 4546 ClassTemplate->getTemplateParameters(), 4547 Converted)) 4548 return true; 4549 4550 if (!Name.isDependent() && 4551 !TemplateSpecializationType::anyDependentTemplateArguments( 4552 TemplateArgs.getArgumentArray(), 4553 TemplateArgs.size())) { 4554 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 4555 << ClassTemplate->getDeclName(); 4556 isPartialSpecialization = false; 4557 } 4558 } 4559 4560 void *InsertPos = 0; 4561 ClassTemplateSpecializationDecl *PrevDecl = 0; 4562 4563 if (isPartialSpecialization) 4564 // FIXME: Template parameter list matters, too 4565 PrevDecl 4566 = ClassTemplate->findPartialSpecialization(Converted.data(), 4567 Converted.size(), 4568 InsertPos); 4569 else 4570 PrevDecl 4571 = ClassTemplate->findSpecialization(Converted.data(), 4572 Converted.size(), InsertPos); 4573 4574 ClassTemplateSpecializationDecl *Specialization = 0; 4575 4576 // Check whether we can declare a class template specialization in 4577 // the current scope. 4578 if (TUK != TUK_Friend && 4579 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 4580 TemplateNameLoc, 4581 isPartialSpecialization)) 4582 return true; 4583 4584 // The canonical type 4585 QualType CanonType; 4586 if (PrevDecl && 4587 (PrevDecl->getSpecializationKind() == TSK_Undeclared || 4588 TUK == TUK_Friend)) { 4589 // Since the only prior class template specialization with these 4590 // arguments was referenced but not declared, or we're only 4591 // referencing this specialization as a friend, reuse that 4592 // declaration node as our own, updating its source location and 4593 // the list of outer template parameters to reflect our new declaration. 4594 Specialization = PrevDecl; 4595 Specialization->setLocation(TemplateNameLoc); 4596 if (TemplateParameterLists.size() > 0) { 4597 Specialization->setTemplateParameterListsInfo(Context, 4598 TemplateParameterLists.size(), 4599 (TemplateParameterList**) TemplateParameterLists.release()); 4600 } 4601 PrevDecl = 0; 4602 CanonType = Context.getTypeDeclType(Specialization); 4603 } else if (isPartialSpecialization) { 4604 // Build the canonical type that describes the converted template 4605 // arguments of the class template partial specialization. 4606 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 4607 CanonType = Context.getTemplateSpecializationType(CanonTemplate, 4608 Converted.data(), 4609 Converted.size()); 4610 4611 if (Context.hasSameType(CanonType, 4612 ClassTemplate->getInjectedClassNameSpecialization())) { 4613 // C++ [temp.class.spec]p9b3: 4614 // 4615 // -- The argument list of the specialization shall not be identical 4616 // to the implicit argument list of the primary template. 4617 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 4618 << (TUK == TUK_Definition) 4619 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 4620 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 4621 ClassTemplate->getIdentifier(), 4622 TemplateNameLoc, 4623 Attr, 4624 TemplateParams, 4625 AS_none, 4626 TemplateParameterLists.size() - 1, 4627 (TemplateParameterList**) TemplateParameterLists.release()); 4628 } 4629 4630 // Create a new class template partial specialization declaration node. 4631 ClassTemplatePartialSpecializationDecl *PrevPartial 4632 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 4633 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber() 4634 : ClassTemplate->getNextPartialSpecSequenceNumber(); 4635 ClassTemplatePartialSpecializationDecl *Partial 4636 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind, 4637 ClassTemplate->getDeclContext(), 4638 KWLoc, TemplateNameLoc, 4639 TemplateParams, 4640 ClassTemplate, 4641 Converted.data(), 4642 Converted.size(), 4643 TemplateArgs, 4644 CanonType, 4645 PrevPartial, 4646 SequenceNumber); 4647 SetNestedNameSpecifier(Partial, SS); 4648 if (TemplateParameterLists.size() > 1 && SS.isSet()) { 4649 Partial->setTemplateParameterListsInfo(Context, 4650 TemplateParameterLists.size() - 1, 4651 (TemplateParameterList**) TemplateParameterLists.release()); 4652 } 4653 4654 if (!PrevPartial) 4655 ClassTemplate->AddPartialSpecialization(Partial, InsertPos); 4656 Specialization = Partial; 4657 4658 // If we are providing an explicit specialization of a member class 4659 // template specialization, make a note of that. 4660 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 4661 PrevPartial->setMemberSpecialization(); 4662 4663 // Check that all of the template parameters of the class template 4664 // partial specialization are deducible from the template 4665 // arguments. If not, this class template partial specialization 4666 // will never be used. 4667 llvm::SmallVector<bool, 8> DeducibleParams; 4668 DeducibleParams.resize(TemplateParams->size()); 4669 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 4670 TemplateParams->getDepth(), 4671 DeducibleParams); 4672 unsigned NumNonDeducible = 0; 4673 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) 4674 if (!DeducibleParams[I]) 4675 ++NumNonDeducible; 4676 4677 if (NumNonDeducible) { 4678 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) 4679 << (NumNonDeducible > 1) 4680 << SourceRange(TemplateNameLoc, RAngleLoc); 4681 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 4682 if (!DeducibleParams[I]) { 4683 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); 4684 if (Param->getDeclName()) 4685 Diag(Param->getLocation(), 4686 diag::note_partial_spec_unused_parameter) 4687 << Param->getDeclName(); 4688 else 4689 Diag(Param->getLocation(), 4690 diag::note_partial_spec_unused_parameter) 4691 << "<anonymous>"; 4692 } 4693 } 4694 } 4695 } else { 4696 // Create a new class template specialization declaration node for 4697 // this explicit specialization or friend declaration. 4698 Specialization 4699 = ClassTemplateSpecializationDecl::Create(Context, Kind, 4700 ClassTemplate->getDeclContext(), 4701 KWLoc, TemplateNameLoc, 4702 ClassTemplate, 4703 Converted.data(), 4704 Converted.size(), 4705 PrevDecl); 4706 SetNestedNameSpecifier(Specialization, SS); 4707 if (TemplateParameterLists.size() > 0) { 4708 Specialization->setTemplateParameterListsInfo(Context, 4709 TemplateParameterLists.size(), 4710 (TemplateParameterList**) TemplateParameterLists.release()); 4711 } 4712 4713 if (!PrevDecl) 4714 ClassTemplate->AddSpecialization(Specialization, InsertPos); 4715 4716 CanonType = Context.getTypeDeclType(Specialization); 4717 } 4718 4719 // C++ [temp.expl.spec]p6: 4720 // If a template, a member template or the member of a class template is 4721 // explicitly specialized then that specialization shall be declared 4722 // before the first use of that specialization that would cause an implicit 4723 // instantiation to take place, in every translation unit in which such a 4724 // use occurs; no diagnostic is required. 4725 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 4726 bool Okay = false; 4727 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) { 4728 // Is there any previous explicit specialization declaration? 4729 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 4730 Okay = true; 4731 break; 4732 } 4733 } 4734 4735 if (!Okay) { 4736 SourceRange Range(TemplateNameLoc, RAngleLoc); 4737 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 4738 << Context.getTypeDeclType(Specialization) << Range; 4739 4740 Diag(PrevDecl->getPointOfInstantiation(), 4741 diag::note_instantiation_required_here) 4742 << (PrevDecl->getTemplateSpecializationKind() 4743 != TSK_ImplicitInstantiation); 4744 return true; 4745 } 4746 } 4747 4748 // If this is not a friend, note that this is an explicit specialization. 4749 if (TUK != TUK_Friend) 4750 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 4751 4752 // Check that this isn't a redefinition of this specialization. 4753 if (TUK == TUK_Definition) { 4754 if (RecordDecl *Def = Specialization->getDefinition()) { 4755 SourceRange Range(TemplateNameLoc, RAngleLoc); 4756 Diag(TemplateNameLoc, diag::err_redefinition) 4757 << Context.getTypeDeclType(Specialization) << Range; 4758 Diag(Def->getLocation(), diag::note_previous_definition); 4759 Specialization->setInvalidDecl(); 4760 return true; 4761 } 4762 } 4763 4764 if (Attr) 4765 ProcessDeclAttributeList(S, Specialization, Attr); 4766 4767 // Build the fully-sugared type for this class template 4768 // specialization as the user wrote in the specialization 4769 // itself. This means that we'll pretty-print the type retrieved 4770 // from the specialization's declaration the way that the user 4771 // actually wrote the specialization, rather than formatting the 4772 // name based on the "canonical" representation used to store the 4773 // template arguments in the specialization. 4774 TypeSourceInfo *WrittenTy 4775 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 4776 TemplateArgs, CanonType); 4777 if (TUK != TUK_Friend) { 4778 Specialization->setTypeAsWritten(WrittenTy); 4779 Specialization->setTemplateKeywordLoc(TemplateKWLoc); 4780 } 4781 TemplateArgsIn.release(); 4782 4783 // C++ [temp.expl.spec]p9: 4784 // A template explicit specialization is in the scope of the 4785 // namespace in which the template was defined. 4786 // 4787 // We actually implement this paragraph where we set the semantic 4788 // context (in the creation of the ClassTemplateSpecializationDecl), 4789 // but we also maintain the lexical context where the actual 4790 // definition occurs. 4791 Specialization->setLexicalDeclContext(CurContext); 4792 4793 // We may be starting the definition of this specialization. 4794 if (TUK == TUK_Definition) 4795 Specialization->startDefinition(); 4796 4797 if (TUK == TUK_Friend) { 4798 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 4799 TemplateNameLoc, 4800 WrittenTy, 4801 /*FIXME:*/KWLoc); 4802 Friend->setAccess(AS_public); 4803 CurContext->addDecl(Friend); 4804 } else { 4805 // Add the specialization into its lexical context, so that it can 4806 // be seen when iterating through the list of declarations in that 4807 // context. However, specializations are not found by name lookup. 4808 CurContext->addDecl(Specialization); 4809 } 4810 return Specialization; 4811} 4812 4813Decl *Sema::ActOnTemplateDeclarator(Scope *S, 4814 MultiTemplateParamsArg TemplateParameterLists, 4815 Declarator &D) { 4816 return HandleDeclarator(S, D, move(TemplateParameterLists), false); 4817} 4818 4819Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 4820 MultiTemplateParamsArg TemplateParameterLists, 4821 Declarator &D) { 4822 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 4823 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4824 4825 if (FTI.hasPrototype) { 4826 // FIXME: Diagnose arguments without names in C. 4827 } 4828 4829 Scope *ParentScope = FnBodyScope->getParent(); 4830 4831 Decl *DP = HandleDeclarator(ParentScope, D, 4832 move(TemplateParameterLists), 4833 /*IsFunctionDefinition=*/true); 4834 if (FunctionTemplateDecl *FunctionTemplate 4835 = dyn_cast_or_null<FunctionTemplateDecl>(DP)) 4836 return ActOnStartOfFunctionDef(FnBodyScope, 4837 FunctionTemplate->getTemplatedDecl()); 4838 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP)) 4839 return ActOnStartOfFunctionDef(FnBodyScope, Function); 4840 return 0; 4841} 4842 4843/// \brief Strips various properties off an implicit instantiation 4844/// that has just been explicitly specialized. 4845static void StripImplicitInstantiation(NamedDecl *D) { 4846 D->dropAttrs(); 4847 4848 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4849 FD->setInlineSpecified(false); 4850 } 4851} 4852 4853/// \brief Diagnose cases where we have an explicit template specialization 4854/// before/after an explicit template instantiation, producing diagnostics 4855/// for those cases where they are required and determining whether the 4856/// new specialization/instantiation will have any effect. 4857/// 4858/// \param NewLoc the location of the new explicit specialization or 4859/// instantiation. 4860/// 4861/// \param NewTSK the kind of the new explicit specialization or instantiation. 4862/// 4863/// \param PrevDecl the previous declaration of the entity. 4864/// 4865/// \param PrevTSK the kind of the old explicit specialization or instantiatin. 4866/// 4867/// \param PrevPointOfInstantiation if valid, indicates where the previus 4868/// declaration was instantiated (either implicitly or explicitly). 4869/// 4870/// \param HasNoEffect will be set to true to indicate that the new 4871/// specialization or instantiation has no effect and should be ignored. 4872/// 4873/// \returns true if there was an error that should prevent the introduction of 4874/// the new declaration into the AST, false otherwise. 4875bool 4876Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 4877 TemplateSpecializationKind NewTSK, 4878 NamedDecl *PrevDecl, 4879 TemplateSpecializationKind PrevTSK, 4880 SourceLocation PrevPointOfInstantiation, 4881 bool &HasNoEffect) { 4882 HasNoEffect = false; 4883 4884 switch (NewTSK) { 4885 case TSK_Undeclared: 4886 case TSK_ImplicitInstantiation: 4887 assert(false && "Don't check implicit instantiations here"); 4888 return false; 4889 4890 case TSK_ExplicitSpecialization: 4891 switch (PrevTSK) { 4892 case TSK_Undeclared: 4893 case TSK_ExplicitSpecialization: 4894 // Okay, we're just specializing something that is either already 4895 // explicitly specialized or has merely been mentioned without any 4896 // instantiation. 4897 return false; 4898 4899 case TSK_ImplicitInstantiation: 4900 if (PrevPointOfInstantiation.isInvalid()) { 4901 // The declaration itself has not actually been instantiated, so it is 4902 // still okay to specialize it. 4903 StripImplicitInstantiation(PrevDecl); 4904 return false; 4905 } 4906 // Fall through 4907 4908 case TSK_ExplicitInstantiationDeclaration: 4909 case TSK_ExplicitInstantiationDefinition: 4910 assert((PrevTSK == TSK_ImplicitInstantiation || 4911 PrevPointOfInstantiation.isValid()) && 4912 "Explicit instantiation without point of instantiation?"); 4913 4914 // C++ [temp.expl.spec]p6: 4915 // If a template, a member template or the member of a class template 4916 // is explicitly specialized then that specialization shall be declared 4917 // before the first use of that specialization that would cause an 4918 // implicit instantiation to take place, in every translation unit in 4919 // which such a use occurs; no diagnostic is required. 4920 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) { 4921 // Is there any previous explicit specialization declaration? 4922 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) 4923 return false; 4924 } 4925 4926 Diag(NewLoc, diag::err_specialization_after_instantiation) 4927 << PrevDecl; 4928 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) 4929 << (PrevTSK != TSK_ImplicitInstantiation); 4930 4931 return true; 4932 } 4933 break; 4934 4935 case TSK_ExplicitInstantiationDeclaration: 4936 switch (PrevTSK) { 4937 case TSK_ExplicitInstantiationDeclaration: 4938 // This explicit instantiation declaration is redundant (that's okay). 4939 HasNoEffect = true; 4940 return false; 4941 4942 case TSK_Undeclared: 4943 case TSK_ImplicitInstantiation: 4944 // We're explicitly instantiating something that may have already been 4945 // implicitly instantiated; that's fine. 4946 return false; 4947 4948 case TSK_ExplicitSpecialization: 4949 // C++0x [temp.explicit]p4: 4950 // For a given set of template parameters, if an explicit instantiation 4951 // of a template appears after a declaration of an explicit 4952 // specialization for that template, the explicit instantiation has no 4953 // effect. 4954 HasNoEffect = true; 4955 return false; 4956 4957 case TSK_ExplicitInstantiationDefinition: 4958 // C++0x [temp.explicit]p10: 4959 // If an entity is the subject of both an explicit instantiation 4960 // declaration and an explicit instantiation definition in the same 4961 // translation unit, the definition shall follow the declaration. 4962 Diag(NewLoc, 4963 diag::err_explicit_instantiation_declaration_after_definition); 4964 Diag(PrevPointOfInstantiation, 4965 diag::note_explicit_instantiation_definition_here); 4966 assert(PrevPointOfInstantiation.isValid() && 4967 "Explicit instantiation without point of instantiation?"); 4968 HasNoEffect = true; 4969 return false; 4970 } 4971 break; 4972 4973 case TSK_ExplicitInstantiationDefinition: 4974 switch (PrevTSK) { 4975 case TSK_Undeclared: 4976 case TSK_ImplicitInstantiation: 4977 // We're explicitly instantiating something that may have already been 4978 // implicitly instantiated; that's fine. 4979 return false; 4980 4981 case TSK_ExplicitSpecialization: 4982 // C++ DR 259, C++0x [temp.explicit]p4: 4983 // For a given set of template parameters, if an explicit 4984 // instantiation of a template appears after a declaration of 4985 // an explicit specialization for that template, the explicit 4986 // instantiation has no effect. 4987 // 4988 // In C++98/03 mode, we only give an extension warning here, because it 4989 // is not harmful to try to explicitly instantiate something that 4990 // has been explicitly specialized. 4991 if (!getLangOptions().CPlusPlus0x) { 4992 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization) 4993 << PrevDecl; 4994 Diag(PrevDecl->getLocation(), 4995 diag::note_previous_template_specialization); 4996 } 4997 HasNoEffect = true; 4998 return false; 4999 5000 case TSK_ExplicitInstantiationDeclaration: 5001 // We're explicity instantiating a definition for something for which we 5002 // were previously asked to suppress instantiations. That's fine. 5003 return false; 5004 5005 case TSK_ExplicitInstantiationDefinition: 5006 // C++0x [temp.spec]p5: 5007 // For a given template and a given set of template-arguments, 5008 // - an explicit instantiation definition shall appear at most once 5009 // in a program, 5010 Diag(NewLoc, diag::err_explicit_instantiation_duplicate) 5011 << PrevDecl; 5012 Diag(PrevPointOfInstantiation, 5013 diag::note_previous_explicit_instantiation); 5014 HasNoEffect = true; 5015 return false; 5016 } 5017 break; 5018 } 5019 5020 assert(false && "Missing specialization/instantiation case?"); 5021 5022 return false; 5023} 5024 5025/// \brief Perform semantic analysis for the given dependent function 5026/// template specialization. The only possible way to get a dependent 5027/// function template specialization is with a friend declaration, 5028/// like so: 5029/// 5030/// template <class T> void foo(T); 5031/// template <class T> class A { 5032/// friend void foo<>(T); 5033/// }; 5034/// 5035/// There really isn't any useful analysis we can do here, so we 5036/// just store the information. 5037bool 5038Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 5039 const TemplateArgumentListInfo &ExplicitTemplateArgs, 5040 LookupResult &Previous) { 5041 // Remove anything from Previous that isn't a function template in 5042 // the correct context. 5043 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 5044 LookupResult::Filter F = Previous.makeFilter(); 5045 while (F.hasNext()) { 5046 NamedDecl *D = F.next()->getUnderlyingDecl(); 5047 if (!isa<FunctionTemplateDecl>(D) || 5048 !FDLookupContext->InEnclosingNamespaceSetOf( 5049 D->getDeclContext()->getRedeclContext())) 5050 F.erase(); 5051 } 5052 F.done(); 5053 5054 // Should this be diagnosed here? 5055 if (Previous.empty()) return true; 5056 5057 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(), 5058 ExplicitTemplateArgs); 5059 return false; 5060} 5061 5062/// \brief Perform semantic analysis for the given function template 5063/// specialization. 5064/// 5065/// This routine performs all of the semantic analysis required for an 5066/// explicit function template specialization. On successful completion, 5067/// the function declaration \p FD will become a function template 5068/// specialization. 5069/// 5070/// \param FD the function declaration, which will be updated to become a 5071/// function template specialization. 5072/// 5073/// \param ExplicitTemplateArgs the explicitly-provided template arguments, 5074/// if any. Note that this may be valid info even when 0 arguments are 5075/// explicitly provided as in, e.g., \c void sort<>(char*, char*); 5076/// as it anyway contains info on the angle brackets locations. 5077/// 5078/// \param PrevDecl the set of declarations that may be specialized by 5079/// this function specialization. 5080bool 5081Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD, 5082 TemplateArgumentListInfo *ExplicitTemplateArgs, 5083 LookupResult &Previous) { 5084 // The set of function template specializations that could match this 5085 // explicit function template specialization. 5086 UnresolvedSet<8> Candidates; 5087 5088 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 5089 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5090 I != E; ++I) { 5091 NamedDecl *Ovl = (*I)->getUnderlyingDecl(); 5092 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { 5093 // Only consider templates found within the same semantic lookup scope as 5094 // FD. 5095 if (!FDLookupContext->InEnclosingNamespaceSetOf( 5096 Ovl->getDeclContext()->getRedeclContext())) 5097 continue; 5098 5099 // C++ [temp.expl.spec]p11: 5100 // A trailing template-argument can be left unspecified in the 5101 // template-id naming an explicit function template specialization 5102 // provided it can be deduced from the function argument type. 5103 // Perform template argument deduction to determine whether we may be 5104 // specializing this template. 5105 // FIXME: It is somewhat wasteful to build 5106 TemplateDeductionInfo Info(Context, FD->getLocation()); 5107 FunctionDecl *Specialization = 0; 5108 if (TemplateDeductionResult TDK 5109 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs, 5110 FD->getType(), 5111 Specialization, 5112 Info)) { 5113 // FIXME: Template argument deduction failed; record why it failed, so 5114 // that we can provide nifty diagnostics. 5115 (void)TDK; 5116 continue; 5117 } 5118 5119 // Record this candidate. 5120 Candidates.addDecl(Specialization, I.getAccess()); 5121 } 5122 } 5123 5124 // Find the most specialized function template. 5125 UnresolvedSetIterator Result 5126 = getMostSpecialized(Candidates.begin(), Candidates.end(), 5127 TPOC_Other, 0, FD->getLocation(), 5128 PDiag(diag::err_function_template_spec_no_match) 5129 << FD->getDeclName(), 5130 PDiag(diag::err_function_template_spec_ambiguous) 5131 << FD->getDeclName() << (ExplicitTemplateArgs != 0), 5132 PDiag(diag::note_function_template_spec_matched)); 5133 if (Result == Candidates.end()) 5134 return true; 5135 5136 // Ignore access information; it doesn't figure into redeclaration checking. 5137 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 5138 5139 FunctionTemplateSpecializationInfo *SpecInfo 5140 = Specialization->getTemplateSpecializationInfo(); 5141 assert(SpecInfo && "Function template specialization info missing?"); 5142 { 5143 // Note: do not overwrite location info if previous template 5144 // specialization kind was explicit. 5145 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind(); 5146 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) 5147 Specialization->setLocation(FD->getLocation()); 5148 } 5149 5150 // FIXME: Check if the prior specialization has a point of instantiation. 5151 // If so, we have run afoul of . 5152 5153 // If this is a friend declaration, then we're not really declaring 5154 // an explicit specialization. 5155 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None); 5156 5157 // Check the scope of this explicit specialization. 5158 if (!isFriend && 5159 CheckTemplateSpecializationScope(*this, 5160 Specialization->getPrimaryTemplate(), 5161 Specialization, FD->getLocation(), 5162 false)) 5163 return true; 5164 5165 // C++ [temp.expl.spec]p6: 5166 // If a template, a member template or the member of a class template is 5167 // explicitly specialized then that specialization shall be declared 5168 // before the first use of that specialization that would cause an implicit 5169 // instantiation to take place, in every translation unit in which such a 5170 // use occurs; no diagnostic is required. 5171 bool HasNoEffect = false; 5172 if (!isFriend && 5173 CheckSpecializationInstantiationRedecl(FD->getLocation(), 5174 TSK_ExplicitSpecialization, 5175 Specialization, 5176 SpecInfo->getTemplateSpecializationKind(), 5177 SpecInfo->getPointOfInstantiation(), 5178 HasNoEffect)) 5179 return true; 5180 5181 // Mark the prior declaration as an explicit specialization, so that later 5182 // clients know that this is an explicit specialization. 5183 if (!isFriend) { 5184 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 5185 MarkUnusedFileScopedDecl(Specialization); 5186 } 5187 5188 // Turn the given function declaration into a function template 5189 // specialization, with the template arguments from the previous 5190 // specialization. 5191 // Take copies of (semantic and syntactic) template argument lists. 5192 const TemplateArgumentList* TemplArgs = new (Context) 5193 TemplateArgumentList(Specialization->getTemplateSpecializationArgs()); 5194 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs 5195 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0; 5196 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(), 5197 TemplArgs, /*InsertPos=*/0, 5198 SpecInfo->getTemplateSpecializationKind(), 5199 TemplArgsAsWritten); 5200 5201 // The "previous declaration" for this function template specialization is 5202 // the prior function template specialization. 5203 Previous.clear(); 5204 Previous.addDecl(Specialization); 5205 return false; 5206} 5207 5208/// \brief Perform semantic analysis for the given non-template member 5209/// specialization. 5210/// 5211/// This routine performs all of the semantic analysis required for an 5212/// explicit member function specialization. On successful completion, 5213/// the function declaration \p FD will become a member function 5214/// specialization. 5215/// 5216/// \param Member the member declaration, which will be updated to become a 5217/// specialization. 5218/// 5219/// \param Previous the set of declarations, one of which may be specialized 5220/// by this function specialization; the set will be modified to contain the 5221/// redeclared member. 5222bool 5223Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { 5224 assert(!isa<TemplateDecl>(Member) && "Only for non-template members"); 5225 5226 // Try to find the member we are instantiating. 5227 NamedDecl *Instantiation = 0; 5228 NamedDecl *InstantiatedFrom = 0; 5229 MemberSpecializationInfo *MSInfo = 0; 5230 5231 if (Previous.empty()) { 5232 // Nowhere to look anyway. 5233 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { 5234 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5235 I != E; ++I) { 5236 NamedDecl *D = (*I)->getUnderlyingDecl(); 5237 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 5238 if (Context.hasSameType(Function->getType(), Method->getType())) { 5239 Instantiation = Method; 5240 InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); 5241 MSInfo = Method->getMemberSpecializationInfo(); 5242 break; 5243 } 5244 } 5245 } 5246 } else if (isa<VarDecl>(Member)) { 5247 VarDecl *PrevVar; 5248 if (Previous.isSingleResult() && 5249 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) 5250 if (PrevVar->isStaticDataMember()) { 5251 Instantiation = PrevVar; 5252 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); 5253 MSInfo = PrevVar->getMemberSpecializationInfo(); 5254 } 5255 } else if (isa<RecordDecl>(Member)) { 5256 CXXRecordDecl *PrevRecord; 5257 if (Previous.isSingleResult() && 5258 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { 5259 Instantiation = PrevRecord; 5260 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); 5261 MSInfo = PrevRecord->getMemberSpecializationInfo(); 5262 } 5263 } 5264 5265 if (!Instantiation) { 5266 // There is no previous declaration that matches. Since member 5267 // specializations are always out-of-line, the caller will complain about 5268 // this mismatch later. 5269 return false; 5270 } 5271 5272 // If this is a friend, just bail out here before we start turning 5273 // things into explicit specializations. 5274 if (Member->getFriendObjectKind() != Decl::FOK_None) { 5275 // Preserve instantiation information. 5276 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) { 5277 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction( 5278 cast<CXXMethodDecl>(InstantiatedFrom), 5279 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind()); 5280 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) { 5281 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 5282 cast<CXXRecordDecl>(InstantiatedFrom), 5283 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind()); 5284 } 5285 5286 Previous.clear(); 5287 Previous.addDecl(Instantiation); 5288 return false; 5289 } 5290 5291 // Make sure that this is a specialization of a member. 5292 if (!InstantiatedFrom) { 5293 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) 5294 << Member; 5295 Diag(Instantiation->getLocation(), diag::note_specialized_decl); 5296 return true; 5297 } 5298 5299 // C++ [temp.expl.spec]p6: 5300 // If a template, a member template or the member of a class template is 5301 // explicitly specialized then that spe- cialization shall be declared 5302 // before the first use of that specialization that would cause an implicit 5303 // instantiation to take place, in every translation unit in which such a 5304 // use occurs; no diagnostic is required. 5305 assert(MSInfo && "Member specialization info missing?"); 5306 5307 bool HasNoEffect = false; 5308 if (CheckSpecializationInstantiationRedecl(Member->getLocation(), 5309 TSK_ExplicitSpecialization, 5310 Instantiation, 5311 MSInfo->getTemplateSpecializationKind(), 5312 MSInfo->getPointOfInstantiation(), 5313 HasNoEffect)) 5314 return true; 5315 5316 // Check the scope of this explicit specialization. 5317 if (CheckTemplateSpecializationScope(*this, 5318 InstantiatedFrom, 5319 Instantiation, Member->getLocation(), 5320 false)) 5321 return true; 5322 5323 // Note that this is an explicit instantiation of a member. 5324 // the original declaration to note that it is an explicit specialization 5325 // (if it was previously an implicit instantiation). This latter step 5326 // makes bookkeeping easier. 5327 if (isa<FunctionDecl>(Member)) { 5328 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); 5329 if (InstantiationFunction->getTemplateSpecializationKind() == 5330 TSK_ImplicitInstantiation) { 5331 InstantiationFunction->setTemplateSpecializationKind( 5332 TSK_ExplicitSpecialization); 5333 InstantiationFunction->setLocation(Member->getLocation()); 5334 } 5335 5336 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction( 5337 cast<CXXMethodDecl>(InstantiatedFrom), 5338 TSK_ExplicitSpecialization); 5339 MarkUnusedFileScopedDecl(InstantiationFunction); 5340 } else if (isa<VarDecl>(Member)) { 5341 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation); 5342 if (InstantiationVar->getTemplateSpecializationKind() == 5343 TSK_ImplicitInstantiation) { 5344 InstantiationVar->setTemplateSpecializationKind( 5345 TSK_ExplicitSpecialization); 5346 InstantiationVar->setLocation(Member->getLocation()); 5347 } 5348 5349 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member), 5350 cast<VarDecl>(InstantiatedFrom), 5351 TSK_ExplicitSpecialization); 5352 MarkUnusedFileScopedDecl(InstantiationVar); 5353 } else { 5354 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain"); 5355 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation); 5356 if (InstantiationClass->getTemplateSpecializationKind() == 5357 TSK_ImplicitInstantiation) { 5358 InstantiationClass->setTemplateSpecializationKind( 5359 TSK_ExplicitSpecialization); 5360 InstantiationClass->setLocation(Member->getLocation()); 5361 } 5362 5363 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 5364 cast<CXXRecordDecl>(InstantiatedFrom), 5365 TSK_ExplicitSpecialization); 5366 } 5367 5368 // Save the caller the trouble of having to figure out which declaration 5369 // this specialization matches. 5370 Previous.clear(); 5371 Previous.addDecl(Instantiation); 5372 return false; 5373} 5374 5375/// \brief Check the scope of an explicit instantiation. 5376/// 5377/// \returns true if a serious error occurs, false otherwise. 5378static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, 5379 SourceLocation InstLoc, 5380 bool WasQualifiedName) { 5381 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext(); 5382 DeclContext *CurContext = S.CurContext->getRedeclContext(); 5383 5384 if (CurContext->isRecord()) { 5385 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class) 5386 << D; 5387 return true; 5388 } 5389 5390 // C++0x [temp.explicit]p2: 5391 // An explicit instantiation shall appear in an enclosing namespace of its 5392 // template. 5393 // 5394 // This is DR275, which we do not retroactively apply to C++98/03. 5395 if (S.getLangOptions().CPlusPlus0x && 5396 !CurContext->Encloses(OrigContext)) { 5397 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) 5398 S.Diag(InstLoc, 5399 S.getLangOptions().CPlusPlus0x? 5400 diag::err_explicit_instantiation_out_of_scope 5401 : diag::warn_explicit_instantiation_out_of_scope_0x) 5402 << D << NS; 5403 else 5404 S.Diag(InstLoc, 5405 S.getLangOptions().CPlusPlus0x? 5406 diag::err_explicit_instantiation_must_be_global 5407 : diag::warn_explicit_instantiation_out_of_scope_0x) 5408 << D; 5409 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 5410 return false; 5411 } 5412 5413 // C++0x [temp.explicit]p2: 5414 // If the name declared in the explicit instantiation is an unqualified 5415 // name, the explicit instantiation shall appear in the namespace where 5416 // its template is declared or, if that namespace is inline (7.3.1), any 5417 // namespace from its enclosing namespace set. 5418 if (WasQualifiedName) 5419 return false; 5420 5421 if (CurContext->InEnclosingNamespaceSetOf(OrigContext)) 5422 return false; 5423 5424 S.Diag(InstLoc, 5425 S.getLangOptions().CPlusPlus0x? 5426 diag::err_explicit_instantiation_unqualified_wrong_namespace 5427 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x) 5428 << D << OrigContext; 5429 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 5430 return false; 5431} 5432 5433/// \brief Determine whether the given scope specifier has a template-id in it. 5434static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { 5435 if (!SS.isSet()) 5436 return false; 5437 5438 // C++0x [temp.explicit]p2: 5439 // If the explicit instantiation is for a member function, a member class 5440 // or a static data member of a class template specialization, the name of 5441 // the class template specialization in the qualified-id for the member 5442 // name shall be a simple-template-id. 5443 // 5444 // C++98 has the same restriction, just worded differently. 5445 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 5446 NNS; NNS = NNS->getPrefix()) 5447 if (const Type *T = NNS->getAsType()) 5448 if (isa<TemplateSpecializationType>(T)) 5449 return true; 5450 5451 return false; 5452} 5453 5454// Explicit instantiation of a class template specialization 5455DeclResult 5456Sema::ActOnExplicitInstantiation(Scope *S, 5457 SourceLocation ExternLoc, 5458 SourceLocation TemplateLoc, 5459 unsigned TagSpec, 5460 SourceLocation KWLoc, 5461 const CXXScopeSpec &SS, 5462 TemplateTy TemplateD, 5463 SourceLocation TemplateNameLoc, 5464 SourceLocation LAngleLoc, 5465 ASTTemplateArgsPtr TemplateArgsIn, 5466 SourceLocation RAngleLoc, 5467 AttributeList *Attr) { 5468 // Find the class template we're specializing 5469 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 5470 ClassTemplateDecl *ClassTemplate 5471 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 5472 5473 // Check that the specialization uses the same tag kind as the 5474 // original template. 5475 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 5476 assert(Kind != TTK_Enum && 5477 "Invalid enum tag in class template explicit instantiation!"); 5478 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 5479 Kind, KWLoc, 5480 *ClassTemplate->getIdentifier())) { 5481 Diag(KWLoc, diag::err_use_with_wrong_tag) 5482 << ClassTemplate 5483 << FixItHint::CreateReplacement(KWLoc, 5484 ClassTemplate->getTemplatedDecl()->getKindName()); 5485 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 5486 diag::note_previous_use); 5487 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 5488 } 5489 5490 // C++0x [temp.explicit]p2: 5491 // There are two forms of explicit instantiation: an explicit instantiation 5492 // definition and an explicit instantiation declaration. An explicit 5493 // instantiation declaration begins with the extern keyword. [...] 5494 TemplateSpecializationKind TSK 5495 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 5496 : TSK_ExplicitInstantiationDeclaration; 5497 5498 // Translate the parser's template argument list in our AST format. 5499 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 5500 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 5501 5502 // Check that the template argument list is well-formed for this 5503 // template. 5504 llvm::SmallVector<TemplateArgument, 4> Converted; 5505 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 5506 TemplateArgs, false, Converted)) 5507 return true; 5508 5509 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) && 5510 "Converted template argument list is too short!"); 5511 5512 // Find the class template specialization declaration that 5513 // corresponds to these arguments. 5514 void *InsertPos = 0; 5515 ClassTemplateSpecializationDecl *PrevDecl 5516 = ClassTemplate->findSpecialization(Converted.data(), 5517 Converted.size(), InsertPos); 5518 5519 TemplateSpecializationKind PrevDecl_TSK 5520 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared; 5521 5522 // C++0x [temp.explicit]p2: 5523 // [...] An explicit instantiation shall appear in an enclosing 5524 // namespace of its template. [...] 5525 // 5526 // This is C++ DR 275. 5527 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc, 5528 SS.isSet())) 5529 return true; 5530 5531 ClassTemplateSpecializationDecl *Specialization = 0; 5532 5533 bool HasNoEffect = false; 5534 if (PrevDecl) { 5535 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, 5536 PrevDecl, PrevDecl_TSK, 5537 PrevDecl->getPointOfInstantiation(), 5538 HasNoEffect)) 5539 return PrevDecl; 5540 5541 // Even though HasNoEffect == true means that this explicit instantiation 5542 // has no effect on semantics, we go on to put its syntax in the AST. 5543 5544 if (PrevDecl_TSK == TSK_ImplicitInstantiation || 5545 PrevDecl_TSK == TSK_Undeclared) { 5546 // Since the only prior class template specialization with these 5547 // arguments was referenced but not declared, reuse that 5548 // declaration node as our own, updating the source location 5549 // for the template name to reflect our new declaration. 5550 // (Other source locations will be updated later.) 5551 Specialization = PrevDecl; 5552 Specialization->setLocation(TemplateNameLoc); 5553 PrevDecl = 0; 5554 } 5555 } 5556 5557 if (!Specialization) { 5558 // Create a new class template specialization declaration node for 5559 // this explicit specialization. 5560 Specialization 5561 = ClassTemplateSpecializationDecl::Create(Context, Kind, 5562 ClassTemplate->getDeclContext(), 5563 KWLoc, TemplateNameLoc, 5564 ClassTemplate, 5565 Converted.data(), 5566 Converted.size(), 5567 PrevDecl); 5568 SetNestedNameSpecifier(Specialization, SS); 5569 5570 if (!HasNoEffect && !PrevDecl) { 5571 // Insert the new specialization. 5572 ClassTemplate->AddSpecialization(Specialization, InsertPos); 5573 } 5574 } 5575 5576 // Build the fully-sugared type for this explicit instantiation as 5577 // the user wrote in the explicit instantiation itself. This means 5578 // that we'll pretty-print the type retrieved from the 5579 // specialization's declaration the way that the user actually wrote 5580 // the explicit instantiation, rather than formatting the name based 5581 // on the "canonical" representation used to store the template 5582 // arguments in the specialization. 5583 TypeSourceInfo *WrittenTy 5584 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 5585 TemplateArgs, 5586 Context.getTypeDeclType(Specialization)); 5587 Specialization->setTypeAsWritten(WrittenTy); 5588 TemplateArgsIn.release(); 5589 5590 // Set source locations for keywords. 5591 Specialization->setExternLoc(ExternLoc); 5592 Specialization->setTemplateKeywordLoc(TemplateLoc); 5593 5594 // Add the explicit instantiation into its lexical context. However, 5595 // since explicit instantiations are never found by name lookup, we 5596 // just put it into the declaration context directly. 5597 Specialization->setLexicalDeclContext(CurContext); 5598 CurContext->addDecl(Specialization); 5599 5600 // Syntax is now OK, so return if it has no other effect on semantics. 5601 if (HasNoEffect) { 5602 // Set the template specialization kind. 5603 Specialization->setTemplateSpecializationKind(TSK); 5604 return Specialization; 5605 } 5606 5607 // C++ [temp.explicit]p3: 5608 // A definition of a class template or class member template 5609 // shall be in scope at the point of the explicit instantiation of 5610 // the class template or class member template. 5611 // 5612 // This check comes when we actually try to perform the 5613 // instantiation. 5614 ClassTemplateSpecializationDecl *Def 5615 = cast_or_null<ClassTemplateSpecializationDecl>( 5616 Specialization->getDefinition()); 5617 if (!Def) 5618 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); 5619 else if (TSK == TSK_ExplicitInstantiationDefinition) { 5620 MarkVTableUsed(TemplateNameLoc, Specialization, true); 5621 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation()); 5622 } 5623 5624 // Instantiate the members of this class template specialization. 5625 Def = cast_or_null<ClassTemplateSpecializationDecl>( 5626 Specialization->getDefinition()); 5627 if (Def) { 5628 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind(); 5629 5630 // Fix a TSK_ExplicitInstantiationDeclaration followed by a 5631 // TSK_ExplicitInstantiationDefinition 5632 if (Old_TSK == TSK_ExplicitInstantiationDeclaration && 5633 TSK == TSK_ExplicitInstantiationDefinition) 5634 Def->setTemplateSpecializationKind(TSK); 5635 5636 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); 5637 } 5638 5639 // Set the template specialization kind. 5640 Specialization->setTemplateSpecializationKind(TSK); 5641 return Specialization; 5642} 5643 5644// Explicit instantiation of a member class of a class template. 5645DeclResult 5646Sema::ActOnExplicitInstantiation(Scope *S, 5647 SourceLocation ExternLoc, 5648 SourceLocation TemplateLoc, 5649 unsigned TagSpec, 5650 SourceLocation KWLoc, 5651 CXXScopeSpec &SS, 5652 IdentifierInfo *Name, 5653 SourceLocation NameLoc, 5654 AttributeList *Attr) { 5655 5656 bool Owned = false; 5657 bool IsDependent = false; 5658 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, 5659 KWLoc, SS, Name, NameLoc, Attr, AS_none, 5660 MultiTemplateParamsArg(*this, 0, 0), 5661 Owned, IsDependent, false, false, 5662 TypeResult()); 5663 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 5664 5665 if (!TagD) 5666 return true; 5667 5668 TagDecl *Tag = cast<TagDecl>(TagD); 5669 if (Tag->isEnum()) { 5670 Diag(TemplateLoc, diag::err_explicit_instantiation_enum) 5671 << Context.getTypeDeclType(Tag); 5672 return true; 5673 } 5674 5675 if (Tag->isInvalidDecl()) 5676 return true; 5677 5678 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 5679 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 5680 if (!Pattern) { 5681 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 5682 << Context.getTypeDeclType(Record); 5683 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 5684 return true; 5685 } 5686 5687 // C++0x [temp.explicit]p2: 5688 // If the explicit instantiation is for a class or member class, the 5689 // elaborated-type-specifier in the declaration shall include a 5690 // simple-template-id. 5691 // 5692 // C++98 has the same restriction, just worded differently. 5693 if (!ScopeSpecifierHasTemplateId(SS)) 5694 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id) 5695 << Record << SS.getRange(); 5696 5697 // C++0x [temp.explicit]p2: 5698 // There are two forms of explicit instantiation: an explicit instantiation 5699 // definition and an explicit instantiation declaration. An explicit 5700 // instantiation declaration begins with the extern keyword. [...] 5701 TemplateSpecializationKind TSK 5702 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 5703 : TSK_ExplicitInstantiationDeclaration; 5704 5705 // C++0x [temp.explicit]p2: 5706 // [...] An explicit instantiation shall appear in an enclosing 5707 // namespace of its template. [...] 5708 // 5709 // This is C++ DR 275. 5710 CheckExplicitInstantiationScope(*this, Record, NameLoc, true); 5711 5712 // Verify that it is okay to explicitly instantiate here. 5713 CXXRecordDecl *PrevDecl 5714 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration()); 5715 if (!PrevDecl && Record->getDefinition()) 5716 PrevDecl = Record; 5717 if (PrevDecl) { 5718 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); 5719 bool HasNoEffect = false; 5720 assert(MSInfo && "No member specialization information?"); 5721 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 5722 PrevDecl, 5723 MSInfo->getTemplateSpecializationKind(), 5724 MSInfo->getPointOfInstantiation(), 5725 HasNoEffect)) 5726 return true; 5727 if (HasNoEffect) 5728 return TagD; 5729 } 5730 5731 CXXRecordDecl *RecordDef 5732 = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 5733 if (!RecordDef) { 5734 // C++ [temp.explicit]p3: 5735 // A definition of a member class of a class template shall be in scope 5736 // at the point of an explicit instantiation of the member class. 5737 CXXRecordDecl *Def 5738 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 5739 if (!Def) { 5740 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) 5741 << 0 << Record->getDeclName() << Record->getDeclContext(); 5742 Diag(Pattern->getLocation(), diag::note_forward_declaration) 5743 << Pattern; 5744 return true; 5745 } else { 5746 if (InstantiateClass(NameLoc, Record, Def, 5747 getTemplateInstantiationArgs(Record), 5748 TSK)) 5749 return true; 5750 5751 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 5752 if (!RecordDef) 5753 return true; 5754 } 5755 } 5756 5757 // Instantiate all of the members of the class. 5758 InstantiateClassMembers(NameLoc, RecordDef, 5759 getTemplateInstantiationArgs(Record), TSK); 5760 5761 if (TSK == TSK_ExplicitInstantiationDefinition) 5762 MarkVTableUsed(NameLoc, RecordDef, true); 5763 5764 // FIXME: We don't have any representation for explicit instantiations of 5765 // member classes. Such a representation is not needed for compilation, but it 5766 // should be available for clients that want to see all of the declarations in 5767 // the source code. 5768 return TagD; 5769} 5770 5771DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 5772 SourceLocation ExternLoc, 5773 SourceLocation TemplateLoc, 5774 Declarator &D) { 5775 // Explicit instantiations always require a name. 5776 // TODO: check if/when DNInfo should replace Name. 5777 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5778 DeclarationName Name = NameInfo.getName(); 5779 if (!Name) { 5780 if (!D.isInvalidType()) 5781 Diag(D.getDeclSpec().getSourceRange().getBegin(), 5782 diag::err_explicit_instantiation_requires_name) 5783 << D.getDeclSpec().getSourceRange() 5784 << D.getSourceRange(); 5785 5786 return true; 5787 } 5788 5789 // The scope passed in may not be a decl scope. Zip up the scope tree until 5790 // we find one that is. 5791 while ((S->getFlags() & Scope::DeclScope) == 0 || 5792 (S->getFlags() & Scope::TemplateParamScope) != 0) 5793 S = S->getParent(); 5794 5795 // Determine the type of the declaration. 5796 TypeSourceInfo *T = GetTypeForDeclarator(D, S); 5797 QualType R = T->getType(); 5798 if (R.isNull()) 5799 return true; 5800 5801 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5802 // Cannot explicitly instantiate a typedef. 5803 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 5804 << Name; 5805 return true; 5806 } 5807 5808 // C++0x [temp.explicit]p1: 5809 // [...] An explicit instantiation of a function template shall not use the 5810 // inline or constexpr specifiers. 5811 // Presumably, this also applies to member functions of class templates as 5812 // well. 5813 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x) 5814 Diag(D.getDeclSpec().getInlineSpecLoc(), 5815 diag::err_explicit_instantiation_inline) 5816 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 5817 5818 // FIXME: check for constexpr specifier. 5819 5820 // C++0x [temp.explicit]p2: 5821 // There are two forms of explicit instantiation: an explicit instantiation 5822 // definition and an explicit instantiation declaration. An explicit 5823 // instantiation declaration begins with the extern keyword. [...] 5824 TemplateSpecializationKind TSK 5825 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 5826 : TSK_ExplicitInstantiationDeclaration; 5827 5828 LookupResult Previous(*this, NameInfo, LookupOrdinaryName); 5829 LookupParsedName(Previous, S, &D.getCXXScopeSpec()); 5830 5831 if (!R->isFunctionType()) { 5832 // C++ [temp.explicit]p1: 5833 // A [...] static data member of a class template can be explicitly 5834 // instantiated from the member definition associated with its class 5835 // template. 5836 if (Previous.isAmbiguous()) 5837 return true; 5838 5839 VarDecl *Prev = Previous.getAsSingle<VarDecl>(); 5840 if (!Prev || !Prev->isStaticDataMember()) { 5841 // We expect to see a data data member here. 5842 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 5843 << Name; 5844 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 5845 P != PEnd; ++P) 5846 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); 5847 return true; 5848 } 5849 5850 if (!Prev->getInstantiatedFromStaticDataMember()) { 5851 // FIXME: Check for explicit specialization? 5852 Diag(D.getIdentifierLoc(), 5853 diag::err_explicit_instantiation_data_member_not_instantiated) 5854 << Prev; 5855 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 5856 // FIXME: Can we provide a note showing where this was declared? 5857 return true; 5858 } 5859 5860 // C++0x [temp.explicit]p2: 5861 // If the explicit instantiation is for a member function, a member class 5862 // or a static data member of a class template specialization, the name of 5863 // the class template specialization in the qualified-id for the member 5864 // name shall be a simple-template-id. 5865 // 5866 // C++98 has the same restriction, just worded differently. 5867 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 5868 Diag(D.getIdentifierLoc(), 5869 diag::ext_explicit_instantiation_without_qualified_id) 5870 << Prev << D.getCXXScopeSpec().getRange(); 5871 5872 // Check the scope of this explicit instantiation. 5873 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true); 5874 5875 // Verify that it is okay to explicitly instantiate here. 5876 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo(); 5877 assert(MSInfo && "Missing static data member specialization info?"); 5878 bool HasNoEffect = false; 5879 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, 5880 MSInfo->getTemplateSpecializationKind(), 5881 MSInfo->getPointOfInstantiation(), 5882 HasNoEffect)) 5883 return true; 5884 if (HasNoEffect) 5885 return (Decl*) 0; 5886 5887 // Instantiate static data member. 5888 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 5889 if (TSK == TSK_ExplicitInstantiationDefinition) 5890 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev); 5891 5892 // FIXME: Create an ExplicitInstantiation node? 5893 return (Decl*) 0; 5894 } 5895 5896 // If the declarator is a template-id, translate the parser's template 5897 // argument list into our AST format. 5898 bool HasExplicitTemplateArgs = false; 5899 TemplateArgumentListInfo TemplateArgs; 5900 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5901 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5902 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 5903 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 5904 ASTTemplateArgsPtr TemplateArgsPtr(*this, 5905 TemplateId->getTemplateArgs(), 5906 TemplateId->NumArgs); 5907 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 5908 HasExplicitTemplateArgs = true; 5909 TemplateArgsPtr.release(); 5910 } 5911 5912 // C++ [temp.explicit]p1: 5913 // A [...] function [...] can be explicitly instantiated from its template. 5914 // A member function [...] of a class template can be explicitly 5915 // instantiated from the member definition associated with its class 5916 // template. 5917 UnresolvedSet<8> Matches; 5918 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 5919 P != PEnd; ++P) { 5920 NamedDecl *Prev = *P; 5921 if (!HasExplicitTemplateArgs) { 5922 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 5923 if (Context.hasSameUnqualifiedType(Method->getType(), R)) { 5924 Matches.clear(); 5925 5926 Matches.addDecl(Method, P.getAccess()); 5927 if (Method->getTemplateSpecializationKind() == TSK_Undeclared) 5928 break; 5929 } 5930 } 5931 } 5932 5933 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 5934 if (!FunTmpl) 5935 continue; 5936 5937 TemplateDeductionInfo Info(Context, D.getIdentifierLoc()); 5938 FunctionDecl *Specialization = 0; 5939 if (TemplateDeductionResult TDK 5940 = DeduceTemplateArguments(FunTmpl, 5941 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 5942 R, Specialization, Info)) { 5943 // FIXME: Keep track of almost-matches? 5944 (void)TDK; 5945 continue; 5946 } 5947 5948 Matches.addDecl(Specialization, P.getAccess()); 5949 } 5950 5951 // Find the most specialized function template specialization. 5952 UnresolvedSetIterator Result 5953 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0, 5954 D.getIdentifierLoc(), 5955 PDiag(diag::err_explicit_instantiation_not_known) << Name, 5956 PDiag(diag::err_explicit_instantiation_ambiguous) << Name, 5957 PDiag(diag::note_explicit_instantiation_candidate)); 5958 5959 if (Result == Matches.end()) 5960 return true; 5961 5962 // Ignore access control bits, we don't need them for redeclaration checking. 5963 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 5964 5965 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { 5966 Diag(D.getIdentifierLoc(), 5967 diag::err_explicit_instantiation_member_function_not_instantiated) 5968 << Specialization 5969 << (Specialization->getTemplateSpecializationKind() == 5970 TSK_ExplicitSpecialization); 5971 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 5972 return true; 5973 } 5974 5975 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration(); 5976 if (!PrevDecl && Specialization->isThisDeclarationADefinition()) 5977 PrevDecl = Specialization; 5978 5979 if (PrevDecl) { 5980 bool HasNoEffect = false; 5981 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, 5982 PrevDecl, 5983 PrevDecl->getTemplateSpecializationKind(), 5984 PrevDecl->getPointOfInstantiation(), 5985 HasNoEffect)) 5986 return true; 5987 5988 // FIXME: We may still want to build some representation of this 5989 // explicit specialization. 5990 if (HasNoEffect) 5991 return (Decl*) 0; 5992 } 5993 5994 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 5995 5996 if (TSK == TSK_ExplicitInstantiationDefinition) 5997 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization); 5998 5999 // C++0x [temp.explicit]p2: 6000 // If the explicit instantiation is for a member function, a member class 6001 // or a static data member of a class template specialization, the name of 6002 // the class template specialization in the qualified-id for the member 6003 // name shall be a simple-template-id. 6004 // 6005 // C++98 has the same restriction, just worded differently. 6006 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); 6007 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl && 6008 D.getCXXScopeSpec().isSet() && 6009 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 6010 Diag(D.getIdentifierLoc(), 6011 diag::ext_explicit_instantiation_without_qualified_id) 6012 << Specialization << D.getCXXScopeSpec().getRange(); 6013 6014 CheckExplicitInstantiationScope(*this, 6015 FunTmpl? (NamedDecl *)FunTmpl 6016 : Specialization->getInstantiatedFromMemberFunction(), 6017 D.getIdentifierLoc(), 6018 D.getCXXScopeSpec().isSet()); 6019 6020 // FIXME: Create some kind of ExplicitInstantiationDecl here. 6021 return (Decl*) 0; 6022} 6023 6024TypeResult 6025Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 6026 const CXXScopeSpec &SS, IdentifierInfo *Name, 6027 SourceLocation TagLoc, SourceLocation NameLoc) { 6028 // This has to hold, because SS is expected to be defined. 6029 assert(Name && "Expected a name in a dependent tag"); 6030 6031 NestedNameSpecifier *NNS 6032 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6033 if (!NNS) 6034 return true; 6035 6036 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 6037 6038 if (TUK == TUK_Declaration || TUK == TUK_Definition) { 6039 Diag(NameLoc, diag::err_dependent_tag_decl) 6040 << (TUK == TUK_Definition) << Kind << SS.getRange(); 6041 return true; 6042 } 6043 6044 // Create the resulting type. 6045 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 6046 QualType Result = Context.getDependentNameType(Kwd, NNS, Name); 6047 6048 // Create type-source location information for this type. 6049 TypeLocBuilder TLB; 6050 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result); 6051 TL.setKeywordLoc(TagLoc); 6052 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 6053 TL.setNameLoc(NameLoc); 6054 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 6055} 6056 6057TypeResult 6058Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 6059 const CXXScopeSpec &SS, const IdentifierInfo &II, 6060 SourceLocation IdLoc) { 6061 if (SS.isInvalid()) 6062 return true; 6063 6064 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() && 6065 !getLangOptions().CPlusPlus0x) 6066 Diag(TypenameLoc, diag::ext_typename_outside_of_template) 6067 << FixItHint::CreateRemoval(TypenameLoc); 6068 6069 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6070 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None, 6071 TypenameLoc, QualifierLoc, II, IdLoc); 6072 if (T.isNull()) 6073 return true; 6074 6075 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 6076 if (isa<DependentNameType>(T)) { 6077 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 6078 TL.setKeywordLoc(TypenameLoc); 6079 TL.setQualifierLoc(QualifierLoc); 6080 TL.setNameLoc(IdLoc); 6081 } else { 6082 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 6083 TL.setKeywordLoc(TypenameLoc); 6084 TL.setQualifierLoc(QualifierLoc); 6085 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc); 6086 } 6087 6088 return CreateParsedType(T, TSI); 6089} 6090 6091TypeResult 6092Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 6093 const CXXScopeSpec &SS, 6094 SourceLocation TemplateLoc, 6095 TemplateTy TemplateIn, 6096 SourceLocation TemplateNameLoc, 6097 SourceLocation LAngleLoc, 6098 ASTTemplateArgsPtr TemplateArgsIn, 6099 SourceLocation RAngleLoc) { 6100 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() && 6101 !getLangOptions().CPlusPlus0x) 6102 Diag(TypenameLoc, diag::ext_typename_outside_of_template) 6103 << FixItHint::CreateRemoval(TypenameLoc); 6104 6105 // Translate the parser's template argument list in our AST format. 6106 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 6107 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 6108 6109 TemplateName Template = TemplateIn.get(); 6110 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 6111 // Construct a dependent template specialization type. 6112 assert(DTN && "dependent template has non-dependent name?"); 6113 assert(DTN->getQualifier() 6114 == static_cast<NestedNameSpecifier*>(SS.getScopeRep())); 6115 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename, 6116 DTN->getQualifier(), 6117 DTN->getIdentifier(), 6118 TemplateArgs); 6119 6120 // Create source-location information for this type. 6121 TypeLocBuilder Builder; 6122 DependentTemplateSpecializationTypeLoc SpecTL 6123 = Builder.push<DependentTemplateSpecializationTypeLoc>(T); 6124 SpecTL.setLAngleLoc(LAngleLoc); 6125 SpecTL.setRAngleLoc(RAngleLoc); 6126 SpecTL.setKeywordLoc(TypenameLoc); 6127 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 6128 SpecTL.setNameLoc(TemplateNameLoc); 6129 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 6130 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 6131 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 6132 } 6133 6134 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs); 6135 if (T.isNull()) 6136 return true; 6137 6138 // Provide source-location information for the template specialization 6139 // type. 6140 TypeLocBuilder Builder; 6141 TemplateSpecializationTypeLoc SpecTL 6142 = Builder.push<TemplateSpecializationTypeLoc>(T); 6143 6144 // FIXME: No place to set the location of the 'template' keyword! 6145 SpecTL.setLAngleLoc(LAngleLoc); 6146 SpecTL.setRAngleLoc(RAngleLoc); 6147 SpecTL.setTemplateNameLoc(TemplateNameLoc); 6148 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 6149 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 6150 6151 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T); 6152 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T); 6153 TL.setKeywordLoc(TypenameLoc); 6154 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 6155 6156 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); 6157 return CreateParsedType(T, TSI); 6158} 6159 6160 6161/// \brief Build the type that describes a C++ typename specifier, 6162/// e.g., "typename T::type". 6163QualType 6164Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 6165 SourceLocation KeywordLoc, 6166 NestedNameSpecifierLoc QualifierLoc, 6167 const IdentifierInfo &II, 6168 SourceLocation IILoc) { 6169 CXXScopeSpec SS; 6170 SS.Adopt(QualifierLoc); 6171 6172 DeclContext *Ctx = computeDeclContext(SS); 6173 if (!Ctx) { 6174 // If the nested-name-specifier is dependent and couldn't be 6175 // resolved to a type, build a typename type. 6176 assert(QualifierLoc.getNestedNameSpecifier()->isDependent()); 6177 return Context.getDependentNameType(Keyword, 6178 QualifierLoc.getNestedNameSpecifier(), 6179 &II); 6180 } 6181 6182 // If the nested-name-specifier refers to the current instantiation, 6183 // the "typename" keyword itself is superfluous. In C++03, the 6184 // program is actually ill-formed. However, DR 382 (in C++0x CD1) 6185 // allows such extraneous "typename" keywords, and we retroactively 6186 // apply this DR to C++03 code with only a warning. In any case we continue. 6187 6188 if (RequireCompleteDeclContext(SS, Ctx)) 6189 return QualType(); 6190 6191 DeclarationName Name(&II); 6192 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName); 6193 LookupQualifiedName(Result, Ctx); 6194 unsigned DiagID = 0; 6195 Decl *Referenced = 0; 6196 switch (Result.getResultKind()) { 6197 case LookupResult::NotFound: 6198 DiagID = diag::err_typename_nested_not_found; 6199 break; 6200 6201 case LookupResult::FoundUnresolvedValue: { 6202 // We found a using declaration that is a value. Most likely, the using 6203 // declaration itself is meant to have the 'typename' keyword. 6204 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 6205 IILoc); 6206 Diag(IILoc, diag::err_typename_refers_to_using_value_decl) 6207 << Name << Ctx << FullRange; 6208 if (UnresolvedUsingValueDecl *Using 6209 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){ 6210 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc(); 6211 Diag(Loc, diag::note_using_value_decl_missing_typename) 6212 << FixItHint::CreateInsertion(Loc, "typename "); 6213 } 6214 } 6215 // Fall through to create a dependent typename type, from which we can recover 6216 // better. 6217 6218 case LookupResult::NotFoundInCurrentInstantiation: 6219 // Okay, it's a member of an unknown instantiation. 6220 return Context.getDependentNameType(Keyword, 6221 QualifierLoc.getNestedNameSpecifier(), 6222 &II); 6223 6224 case LookupResult::Found: 6225 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { 6226 // We found a type. Build an ElaboratedType, since the 6227 // typename-specifier was just sugar. 6228 return Context.getElaboratedType(ETK_Typename, 6229 QualifierLoc.getNestedNameSpecifier(), 6230 Context.getTypeDeclType(Type)); 6231 } 6232 6233 DiagID = diag::err_typename_nested_not_type; 6234 Referenced = Result.getFoundDecl(); 6235 break; 6236 6237 6238 llvm_unreachable("unresolved using decl in non-dependent context"); 6239 return QualType(); 6240 6241 case LookupResult::FoundOverloaded: 6242 DiagID = diag::err_typename_nested_not_type; 6243 Referenced = *Result.begin(); 6244 break; 6245 6246 case LookupResult::Ambiguous: 6247 return QualType(); 6248 } 6249 6250 // If we get here, it's because name lookup did not find a 6251 // type. Emit an appropriate diagnostic and return an error. 6252 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 6253 IILoc); 6254 Diag(IILoc, DiagID) << FullRange << Name << Ctx; 6255 if (Referenced) 6256 Diag(Referenced->getLocation(), diag::note_typename_refers_here) 6257 << Name; 6258 return QualType(); 6259} 6260 6261namespace { 6262 // See Sema::RebuildTypeInCurrentInstantiation 6263 class CurrentInstantiationRebuilder 6264 : public TreeTransform<CurrentInstantiationRebuilder> { 6265 SourceLocation Loc; 6266 DeclarationName Entity; 6267 6268 public: 6269 typedef TreeTransform<CurrentInstantiationRebuilder> inherited; 6270 6271 CurrentInstantiationRebuilder(Sema &SemaRef, 6272 SourceLocation Loc, 6273 DeclarationName Entity) 6274 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 6275 Loc(Loc), Entity(Entity) { } 6276 6277 /// \brief Determine whether the given type \p T has already been 6278 /// transformed. 6279 /// 6280 /// For the purposes of type reconstruction, a type has already been 6281 /// transformed if it is NULL or if it is not dependent. 6282 bool AlreadyTransformed(QualType T) { 6283 return T.isNull() || !T->isDependentType(); 6284 } 6285 6286 /// \brief Returns the location of the entity whose type is being 6287 /// rebuilt. 6288 SourceLocation getBaseLocation() { return Loc; } 6289 6290 /// \brief Returns the name of the entity whose type is being rebuilt. 6291 DeclarationName getBaseEntity() { return Entity; } 6292 6293 /// \brief Sets the "base" location and entity when that 6294 /// information is known based on another transformation. 6295 void setBase(SourceLocation Loc, DeclarationName Entity) { 6296 this->Loc = Loc; 6297 this->Entity = Entity; 6298 } 6299 }; 6300} 6301 6302/// \brief Rebuilds a type within the context of the current instantiation. 6303/// 6304/// The type \p T is part of the type of an out-of-line member definition of 6305/// a class template (or class template partial specialization) that was parsed 6306/// and constructed before we entered the scope of the class template (or 6307/// partial specialization thereof). This routine will rebuild that type now 6308/// that we have entered the declarator's scope, which may produce different 6309/// canonical types, e.g., 6310/// 6311/// \code 6312/// template<typename T> 6313/// struct X { 6314/// typedef T* pointer; 6315/// pointer data(); 6316/// }; 6317/// 6318/// template<typename T> 6319/// typename X<T>::pointer X<T>::data() { ... } 6320/// \endcode 6321/// 6322/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType, 6323/// since we do not know that we can look into X<T> when we parsed the type. 6324/// This function will rebuild the type, performing the lookup of "pointer" 6325/// in X<T> and returning an ElaboratedType whose canonical type is the same 6326/// as the canonical type of T*, allowing the return types of the out-of-line 6327/// definition and the declaration to match. 6328TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 6329 SourceLocation Loc, 6330 DeclarationName Name) { 6331 if (!T || !T->getType()->isDependentType()) 6332 return T; 6333 6334 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 6335 return Rebuilder.TransformType(T); 6336} 6337 6338ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) { 6339 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(), 6340 DeclarationName()); 6341 return Rebuilder.TransformExpr(E); 6342} 6343 6344bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) { 6345 if (SS.isInvalid()) 6346 return true; 6347 6348 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6349 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(), 6350 DeclarationName()); 6351 NestedNameSpecifierLoc Rebuilt 6352 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc); 6353 if (!Rebuilt) 6354 return true; 6355 6356 SS.Adopt(Rebuilt); 6357 return false; 6358} 6359 6360/// \brief Produces a formatted string that describes the binding of 6361/// template parameters to template arguments. 6362std::string 6363Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 6364 const TemplateArgumentList &Args) { 6365 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size()); 6366} 6367 6368std::string 6369Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 6370 const TemplateArgument *Args, 6371 unsigned NumArgs) { 6372 llvm::SmallString<128> Str; 6373 llvm::raw_svector_ostream Out(Str); 6374 6375 if (!Params || Params->size() == 0 || NumArgs == 0) 6376 return std::string(); 6377 6378 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 6379 if (I >= NumArgs) 6380 break; 6381 6382 if (I == 0) 6383 Out << "[with "; 6384 else 6385 Out << ", "; 6386 6387 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 6388 Out << Id->getName(); 6389 } else { 6390 Out << '$' << I; 6391 } 6392 6393 Out << " = "; 6394 Args[I].print(Context.PrintingPolicy, Out); 6395 } 6396 6397 Out << ']'; 6398 return Out.str(); 6399} 6400 6401void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) { 6402 if (!FD) 6403 return; 6404 FD->setLateTemplateParsed(Flag); 6405} 6406 6407bool Sema::IsInsideALocalClassWithinATemplateFunction() { 6408 DeclContext *DC = CurContext; 6409 6410 while (DC) { 6411 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { 6412 const FunctionDecl *FD = RD->isLocalClass(); 6413 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate); 6414 } else if (DC->isTranslationUnit() || DC->isNamespace()) 6415 return false; 6416 6417 DC = DC->getParent(); 6418 } 6419 return false; 6420} 6421