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