blob: 6be74a089782e117aeebd1ef8ac8b731f026e701 [file] [log] [blame]
Douglas Gregor72c3f312008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Douglas Gregor99ebf652009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregor99ebf652009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor72c3f312008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregor2dd078a2009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Douglas Gregor2dd078a2009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
Mike Stump1eb44332009-09-09 15:08:12 +000036
Douglas Gregor2dd078a2009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor2dd078a2009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump1eb44332009-09-09 15:08:12 +000061
Douglas Gregor2dd078a2009-09-02 22:59:36 +000062 return 0;
63}
64
John McCallf7a1a742009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
71 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
72 if (!Repl)
73 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCallf7a1a742009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor01e56ae2010-04-12 20:54:26 +000093 }
John McCallf7a1a742009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregor2dd078a2009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000100 UnqualifiedId &Name,
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000101 TypeTy *ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000102 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000103 TemplateTy &TemplateResult,
104 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000105 assert(getLangOptions().CPlusPlus && "No template names in C!");
106
Douglas Gregor014e88d2009-11-03 23:16:33 +0000107 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000108 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000109
110 switch (Name.getKind()) {
111 case UnqualifiedId::IK_Identifier:
112 TName = DeclarationName(Name.Identifier);
113 break;
114
115 case UnqualifiedId::IK_OperatorFunctionId:
116 TName = Context.DeclarationNames.getCXXOperatorName(
117 Name.OperatorFunctionId.Operator);
118 break;
119
Sean Hunte6252d12009-11-28 08:58:14 +0000120 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000121 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
122 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000123
Douglas Gregor014e88d2009-11-03 23:16:33 +0000124 default:
125 return TNK_Non_template;
126 }
Mike Stump1eb44332009-09-09 15:08:12 +0000127
John McCallf7a1a742009-11-24 19:00:30 +0000128 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Douglas Gregorbfea2392009-12-31 08:11:17 +0000130 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
131 LookupOrdinaryName);
John McCallf7a1a742009-11-24 19:00:30 +0000132 R.suppressDiagnostics();
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000133 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
134 MemberOfUnknownSpecialization);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000135 if (R.empty() || R.isAmbiguous())
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000136 return TNK_Non_template;
137
John McCall0bd6feb2009-12-02 08:04:21 +0000138 TemplateName Template;
139 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000140
John McCall0bd6feb2009-12-02 08:04:21 +0000141 unsigned ResultCount = R.end() - R.begin();
142 if (ResultCount > 1) {
143 // We assume that we'll preserve the qualifier from a function
144 // template name in other ways.
145 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
146 TemplateKind = TNK_Function_template;
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000147 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000148 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
149
150 if (SS.isSet() && !SS.isInvalid()) {
151 NestedNameSpecifier *Qualifier
152 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
153 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
154 } else {
155 Template = TemplateName(TD);
156 }
157
158 if (isa<FunctionTemplateDecl>(TD))
159 TemplateKind = TNK_Function_template;
160 else {
161 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
162 TemplateKind = TNK_Type_template;
163 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000164 }
Mike Stump1eb44332009-09-09 15:08:12 +0000165
John McCall0bd6feb2009-12-02 08:04:21 +0000166 TemplateResult = TemplateTy::make(Template);
167 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000168}
169
Douglas Gregor84d0a192010-01-12 21:28:44 +0000170bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
171 SourceLocation IILoc,
172 Scope *S,
173 const CXXScopeSpec *SS,
174 TemplateTy &SuggestedTemplate,
175 TemplateNameKind &SuggestedKind) {
176 // We can't recover unless there's a dependent scope specifier preceding the
177 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000178 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000179 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
180 computeDeclContext(*SS))
181 return false;
182
183 // The code is missing a 'template' keyword prior to the dependent template
184 // name.
185 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
186 Diag(IILoc, diag::err_template_kw_missing)
187 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000188 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000189 SuggestedTemplate
190 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
191 SuggestedKind = TNK_Dependent_template_name;
192 return true;
193}
194
John McCallf7a1a742009-11-24 19:00:30 +0000195void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000196 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000197 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000198 bool EnteringContext,
199 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000200 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000201 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000202 DeclContext *LookupCtx = 0;
203 bool isDependent = false;
204 if (!ObjectType.isNull()) {
205 // This nested-name-specifier occurs in a member access expression, e.g.,
206 // x->B::f, and we are looking into the type of the object.
207 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
208 LookupCtx = computeDeclContext(ObjectType);
209 isDependent = ObjectType->isDependentType();
210 assert((isDependent || !ObjectType->isIncompleteType()) &&
211 "Caller should have completed object type");
212 } else if (SS.isSet()) {
213 // This nested-name-specifier occurs after another nested-name-specifier,
214 // so long into the context associated with the prior nested-name-specifier.
215 LookupCtx = computeDeclContext(SS, EnteringContext);
216 isDependent = isDependentScopeSpecifier(SS);
217
218 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000219 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000220 return;
221 }
222
223 bool ObjectTypeSearchedInScope = false;
224 if (LookupCtx) {
225 // Perform "qualified" name lookup into the declaration context we
226 // computed, which is either the type of the base of a member access
227 // expression or the declaration context associated with a prior
228 // nested-name-specifier.
229 LookupQualifiedName(Found, LookupCtx);
230
231 if (!ObjectType.isNull() && Found.empty()) {
232 // C++ [basic.lookup.classref]p1:
233 // In a class member access expression (5.2.5), if the . or -> token is
234 // immediately followed by an identifier followed by a <, the
235 // identifier must be looked up to determine whether the < is the
236 // beginning of a template argument list (14.2) or a less-than operator.
237 // The identifier is first looked up in the class of the object
238 // expression. If the identifier is not found, it is then looked up in
239 // the context of the entire postfix-expression and shall name a class
240 // or function template.
241 //
242 // FIXME: When we're instantiating a template, do we actually have to
243 // look in the scope of the template? Seems fishy...
244 if (S) LookupName(Found, S);
245 ObjectTypeSearchedInScope = true;
246 }
247 } else if (isDependent) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000248 // We cannot look into a dependent object type or nested nme
249 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000250 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000251 return;
252 } else {
253 // Perform unqualified name lookup in the current scope.
254 LookupName(Found, S);
255 }
256
Douglas Gregor2e933882010-01-12 17:06:20 +0000257 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000258 // If we did not find any names, attempt to correct any typos.
259 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000260 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
261 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000262 FilterAcceptableTemplateNames(Context, Found);
263 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
264 if (LookupCtx)
265 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
266 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000267 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000268 Found.getLookupName().getAsString());
269 else
270 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
271 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000272 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000273 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000274 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
275 Diag(Template->getLocation(), diag::note_previous_decl)
276 << Template->getDeclName();
Douglas Gregorbfea2392009-12-31 08:11:17 +0000277 } else
278 Found.clear();
279 } else {
280 Found.clear();
281 }
282 }
283
John McCallf7a1a742009-11-24 19:00:30 +0000284 FilterAcceptableTemplateNames(Context, Found);
285 if (Found.empty())
286 return;
287
288 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
289 // C++ [basic.lookup.classref]p1:
290 // [...] If the lookup in the class of the object expression finds a
291 // template, the name is also looked up in the context of the entire
292 // postfix-expression and [...]
293 //
294 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
295 LookupOrdinaryName);
296 LookupName(FoundOuter, S);
297 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000298
John McCallf7a1a742009-11-24 19:00:30 +0000299 if (FoundOuter.empty()) {
300 // - if the name is not found, the name found in the class of the
301 // object expression is used, otherwise
302 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
303 // - if the name is found in the context of the entire
304 // postfix-expression and does not name a class template, the name
305 // found in the class of the object expression is used, otherwise
306 } else {
307 // - if the name found is a class template, it must refer to the same
308 // entity as the one found in the class of the object expression,
309 // otherwise the program is ill-formed.
310 if (!Found.isSingleResult() ||
311 Found.getFoundDecl()->getCanonicalDecl()
312 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
313 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000314 diag::ext_nested_name_member_ref_lookup_ambiguous)
315 << Found.getLookupName()
316 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000317 Diag(Found.getRepresentativeDecl()->getLocation(),
318 diag::note_ambig_member_ref_object_type)
319 << ObjectType;
320 Diag(FoundOuter.getFoundDecl()->getLocation(),
321 diag::note_ambig_member_ref_scope);
322
323 // Recover by taking the template that we found in the object
324 // expression's type.
325 }
326 }
327 }
328}
329
John McCall2f841ba2009-12-02 03:53:29 +0000330/// ActOnDependentIdExpression - Handle a dependent id-expression that
331/// was just parsed. This is only possible with an explicit scope
332/// specifier naming a dependent type.
John McCallf7a1a742009-11-24 19:00:30 +0000333Sema::OwningExprResult
334Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
335 DeclarationName Name,
336 SourceLocation NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +0000337 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000338 const TemplateArgumentListInfo *TemplateArgs) {
339 NestedNameSpecifier *Qualifier
340 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000341
342 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000343
John McCall2f841ba2009-12-02 03:53:29 +0000344 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000345 isa<CXXMethodDecl>(DC) &&
346 cast<CXXMethodDecl>(DC)->isInstance()) {
347 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000348
John McCallf7a1a742009-11-24 19:00:30 +0000349 // Since the 'this' expression is synthesized, we don't need to
350 // perform the double-lookup check.
351 NamedDecl *FirstQualifierInScope = 0;
352
John McCallaa81e162009-12-01 22:10:20 +0000353 return Owned(CXXDependentScopeMemberExpr::Create(Context,
354 /*This*/ 0, ThisType,
355 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000356 /*Op*/ SourceLocation(),
357 Qualifier, SS.getRange(),
358 FirstQualifierInScope,
359 Name, NameLoc,
360 TemplateArgs));
361 }
362
363 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
364}
365
366Sema::OwningExprResult
367Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
368 DeclarationName Name,
369 SourceLocation NameLoc,
370 const TemplateArgumentListInfo *TemplateArgs) {
371 return Owned(DependentScopeDeclRefExpr::Create(Context,
372 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
373 SS.getRange(),
374 Name, NameLoc,
375 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000376}
377
Douglas Gregor72c3f312008-12-05 18:15:24 +0000378/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
379/// that the template parameter 'PrevDecl' is being shadowed by a new
380/// declaration at location Loc. Returns true to indicate that this is
381/// an error, and false otherwise.
382bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000383 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000384
385 // Microsoft Visual C++ permits template parameters to be shadowed.
386 if (getLangOptions().Microsoft)
387 return false;
388
389 // C++ [temp.local]p4:
390 // A template-parameter shall not be redeclared within its
391 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000392 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000393 << cast<NamedDecl>(PrevDecl)->getDeclName();
394 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
395 return true;
396}
397
Douglas Gregor2943aed2009-03-03 04:44:36 +0000398/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000399/// the parameter D to reference the templated declaration and return a pointer
400/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000401TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor13d2d6c2009-10-06 21:27:51 +0000402 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000403 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000404 return Temp;
405 }
406 return 0;
407}
408
Douglas Gregor788cd062009-11-11 01:00:40 +0000409static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
410 const ParsedTemplateArgument &Arg) {
411
412 switch (Arg.getKind()) {
413 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000414 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000415 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
416 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000417 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000418 return TemplateArgumentLoc(TemplateArgument(T), DI);
419 }
420
421 case ParsedTemplateArgument::NonType: {
422 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
423 return TemplateArgumentLoc(TemplateArgument(E), E);
424 }
425
426 case ParsedTemplateArgument::Template: {
427 TemplateName Template
428 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
429 return TemplateArgumentLoc(TemplateArgument(Template),
430 Arg.getScopeSpec().getRange(),
431 Arg.getLocation());
432 }
433 }
434
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000435 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000436 return TemplateArgumentLoc();
437}
438
439/// \brief Translates template arguments as provided by the parser
440/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000441void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
442 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000443 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000444 TemplateArgs.addArgument(translateTemplateArgument(*this,
445 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000446}
447
Douglas Gregor72c3f312008-12-05 18:15:24 +0000448/// ActOnTypeParameter - Called when a C++ template type parameter
449/// (e.g., "typename T") has been parsed. Typename specifies whether
450/// the keyword "typename" was used to declare the type parameter
451/// (otherwise, "class" was used), and KeyLoc is the location of the
452/// "class" or "typename" keyword. ParamName is the name of the
453/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump1eb44332009-09-09 15:08:12 +0000454/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000455/// If the type parameter has a default argument, it will be added
456/// later via ActOnTypeParameterDefault.
Mike Stump1eb44332009-09-09 15:08:12 +0000457Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson941df7d2009-06-12 19:58:00 +0000458 SourceLocation EllipsisLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000459 SourceLocation KeyLoc,
460 IdentifierInfo *ParamName,
461 SourceLocation ParamNameLoc,
462 unsigned Depth, unsigned Position) {
Mike Stump1eb44332009-09-09 15:08:12 +0000463 assert(S->isTemplateParamScope() &&
464 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000465 bool Invalid = false;
466
467 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000468 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000469 LookupOrdinaryName,
470 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000471 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000472 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000473 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000474 }
475
Douglas Gregorddc29e12009-02-06 22:42:48 +0000476 SourceLocation Loc = ParamNameLoc;
477 if (!ParamName)
478 Loc = KeyLoc;
479
Douglas Gregor72c3f312008-12-05 18:15:24 +0000480 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000481 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
482 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000483 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000484 if (Invalid)
485 Param->setInvalidDecl();
486
487 if (ParamName) {
488 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000489 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000490 IdResolver.AddDecl(Param);
491 }
492
Chris Lattnerb28317a2009-03-28 19:18:32 +0000493 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000494}
495
Douglas Gregord684b002009-02-10 19:49:53 +0000496/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump1eb44332009-09-09 15:08:12 +0000497/// Default) to the given template type parameter (TypeParam).
498void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregord684b002009-02-10 19:49:53 +0000499 SourceLocation EqualLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000500 SourceLocation DefaultLoc,
Douglas Gregord684b002009-02-10 19:49:53 +0000501 TypeTy *DefaultT) {
Mike Stump1eb44332009-09-09 15:08:12 +0000502 TemplateTypeParmDecl *Parm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000503 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall833ca992009-10-29 08:12:44 +0000504
John McCalla93c9342009-12-07 02:54:59 +0000505 TypeSourceInfo *DefaultTInfo;
506 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall833ca992009-10-29 08:12:44 +0000507
John McCalla93c9342009-12-07 02:54:59 +0000508 assert(DefaultTInfo && "expected source information for type");
Douglas Gregord684b002009-02-10 19:49:53 +0000509
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000510 // C++0x [temp.param]p9:
511 // A default template-argument may be specified for any kind of
Mike Stump1eb44332009-09-09 15:08:12 +0000512 // template-parameter that is not a template parameter pack.
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000513 if (Parm->isParameterPack()) {
514 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlsson9c4c5c82009-06-12 22:30:13 +0000515 return;
516 }
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Douglas Gregord684b002009-02-10 19:49:53 +0000518 // C++ [temp.param]p14:
519 // A template-parameter shall not be used in its own default argument.
520 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Douglas Gregord684b002009-02-10 19:49:53 +0000522 // Check the template argument itself.
John McCalla93c9342009-12-07 02:54:59 +0000523 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000524 Parm->setInvalidDecl();
525 return;
526 }
527
John McCalla93c9342009-12-07 02:54:59 +0000528 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000529}
530
Douglas Gregor2943aed2009-03-03 04:44:36 +0000531/// \brief Check that the type of a non-type template parameter is
532/// well-formed.
533///
534/// \returns the (possibly-promoted) parameter type if valid;
535/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000536QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000537Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000538 // We don't allow variably-modified types as the type of non-type template
539 // parameters.
540 if (T->isVariablyModifiedType()) {
541 Diag(Loc, diag::err_variably_modified_nontype_template_param)
542 << T;
543 return QualType();
544 }
545
Douglas Gregor2943aed2009-03-03 04:44:36 +0000546 // C++ [temp.param]p4:
547 //
548 // A non-type template-parameter shall have one of the following
549 // (optionally cv-qualified) types:
550 //
551 // -- integral or enumeration type,
552 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000553 // -- pointer to object or pointer to function,
554 (T->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000555 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
556 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000557 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000558 T->isReferenceType() ||
559 // -- pointer to member.
560 T->isMemberPointerType() ||
561 // If T is a dependent type, we can't do the check now, so we
562 // assume that it is well-formed.
563 T->isDependentType())
564 return T;
565 // C++ [temp.param]p8:
566 //
567 // A non-type template-parameter of type "array of T" or
568 // "function returning T" is adjusted to be of type "pointer to
569 // T" or "pointer to function returning T", respectively.
570 else if (T->isArrayType())
571 // FIXME: Keep the type prior to promotion?
572 return Context.getArrayDecayedType(T);
573 else if (T->isFunctionType())
574 // FIXME: Keep the type prior to promotion?
575 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000576
Douglas Gregor2943aed2009-03-03 04:44:36 +0000577 Diag(Loc, diag::err_template_nontype_parm_bad_type)
578 << T;
579
580 return QualType();
581}
582
Douglas Gregor72c3f312008-12-05 18:15:24 +0000583/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
584/// template parameter (e.g., "int Size" in "template<int Size>
585/// class Array") has been parsed. S is the current scope and D is
586/// the parsed declarator.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000587Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump1eb44332009-09-09 15:08:12 +0000588 unsigned Depth,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000589 unsigned Position) {
John McCallbf1a0282010-06-04 23:28:52 +0000590 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
591 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000592
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000593 assert(S->isTemplateParamScope() &&
594 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000595 bool Invalid = false;
596
597 IdentifierInfo *ParamName = D.getIdentifier();
598 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000599 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000600 LookupOrdinaryName,
601 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000602 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000603 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000604 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000605 }
606
Douglas Gregor2943aed2009-03-03 04:44:36 +0000607 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorceef30c2009-03-09 16:46:39 +0000608 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000609 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000610 Invalid = true;
611 }
Douglas Gregor5d290d52009-02-10 17:43:50 +0000612
Douglas Gregor72c3f312008-12-05 18:15:24 +0000613 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000614 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
615 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000616 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000617 if (Invalid)
618 Param->setInvalidDecl();
619
620 if (D.getIdentifier()) {
621 // Add the template parameter into the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000622 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72c3f312008-12-05 18:15:24 +0000623 IdResolver.AddDecl(Param);
624 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000625 return DeclPtrTy::make(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000626}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000627
Douglas Gregord684b002009-02-10 19:49:53 +0000628/// \brief Adds a default argument to the given non-type template
629/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000630void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000631 SourceLocation EqualLoc,
632 ExprArg DefaultE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000633 NonTypeTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000634 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregord684b002009-02-10 19:49:53 +0000635 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Douglas Gregord684b002009-02-10 19:49:53 +0000637 // C++ [temp.param]p14:
638 // A template-parameter shall not be used in its own default argument.
639 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Douglas Gregord684b002009-02-10 19:49:53 +0000641 // Check the well-formedness of the default template argument.
Douglas Gregor02cbbd22009-06-11 18:10:32 +0000642 TemplateArgument Converted;
643 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
644 Converted)) {
Douglas Gregord684b002009-02-10 19:49:53 +0000645 TemplateParm->setInvalidDecl();
646 return;
647 }
648
Abramo Bagnarad92f7a22010-06-09 09:26:05 +0000649 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>(), false);
Douglas Gregord684b002009-02-10 19:49:53 +0000650}
651
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000652
653/// ActOnTemplateTemplateParameter - Called when a C++ template template
654/// parameter (e.g. T in template <template <typename> class T> class array)
655/// has been parsed. S is the current scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000656Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
657 SourceLocation TmpLoc,
658 TemplateParamsTy *Params,
659 IdentifierInfo *Name,
660 SourceLocation NameLoc,
661 unsigned Depth,
Mike Stump1eb44332009-09-09 15:08:12 +0000662 unsigned Position) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000663 assert(S->isTemplateParamScope() &&
664 "Template template parameter not in template parameter scope!");
665
666 // Construct the parameter object.
667 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000668 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
669 TmpLoc, Depth, Position, Name,
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000670 (TemplateParameterList*)Params);
671
672 // Make sure the parameter is valid.
673 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
674 // do anything yet. However, if the template parameter list or (eventual)
675 // default value is ever invalidated, that will propagate here.
676 bool Invalid = false;
677 if (Invalid) {
678 Param->setInvalidDecl();
679 }
680
681 // If the tt-param has a name, then link the identifier into the scope
682 // and lookup mechanisms.
683 if (Name) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000684 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000685 IdResolver.AddDecl(Param);
686 }
687
Chris Lattnerb28317a2009-03-28 19:18:32 +0000688 return DeclPtrTy::make(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000689}
690
Douglas Gregord684b002009-02-10 19:49:53 +0000691/// \brief Adds a default argument to the given template template
692/// parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000693void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregord684b002009-02-10 19:49:53 +0000694 SourceLocation EqualLoc,
Douglas Gregor788cd062009-11-11 01:00:40 +0000695 const ParsedTemplateArgument &Default) {
Mike Stump1eb44332009-09-09 15:08:12 +0000696 TemplateTemplateParmDecl *TemplateParm
Chris Lattnerb28317a2009-03-28 19:18:32 +0000697 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor788cd062009-11-11 01:00:40 +0000698
Douglas Gregord684b002009-02-10 19:49:53 +0000699 // C++ [temp.param]p14:
700 // A template-parameter shall not be used in its own default argument.
701 // FIXME: Implement this check! Needs a recursive walk over the types.
702
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000703 // Check only that we have a template template argument. We don't want to
704 // try to check well-formedness now, because our template template parameter
705 // might have dependent types in its template parameters, which we wouldn't
706 // be able to match now.
707 //
708 // If none of the template template parameter's template arguments mention
709 // other template parameters, we could actually perform more checking here.
710 // However, it isn't worth doing.
Douglas Gregor788cd062009-11-11 01:00:40 +0000711 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000712 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
713 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
714 << DefaultArg.getSourceRange();
Douglas Gregord684b002009-02-10 19:49:53 +0000715 return;
716 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000717
Abramo Bagnarad92f7a22010-06-09 09:26:05 +0000718 TemplateParm->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000719}
720
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000721/// ActOnTemplateParameterList - Builds a TemplateParameterList that
722/// contains the template parameters in Params/NumParams.
723Sema::TemplateParamsTy *
724Sema::ActOnTemplateParameterList(unsigned Depth,
725 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000726 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000727 SourceLocation LAngleLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +0000728 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000729 SourceLocation RAngleLoc) {
730 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000731 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000732
Douglas Gregorddc29e12009-02-06 22:42:48 +0000733 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000734 (NamedDecl**)Params, NumParams,
735 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000736}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000737
John McCallb6217662010-03-15 10:12:16 +0000738static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
739 if (SS.isSet())
740 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
741 SS.getRange());
742}
743
Douglas Gregor212e81c2009-03-25 00:13:59 +0000744Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000745Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000746 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000747 IdentifierInfo *Name, SourceLocation NameLoc,
748 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000749 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000750 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000751 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000752 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000753 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000754 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000755
756 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000757 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000758 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000759
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000760 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
761 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000762
763 // There is no such thing as an unnamed class template.
764 if (!Name) {
765 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000766 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000767 }
768
769 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000770 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000771 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000772 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000773 if (SS.isNotEmpty() && !SS.isInvalid()) {
774 SemanticContext = computeDeclContext(SS, true);
775 if (!SemanticContext) {
776 // FIXME: Produce a reasonable diagnostic here
777 return true;
778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
John McCall77bb1aa2010-05-01 00:40:08 +0000780 if (RequireCompleteDeclContext(SS, SemanticContext))
781 return true;
782
John McCalla24dc2e2009-11-17 02:14:36 +0000783 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000784 } else {
785 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000786 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000787 }
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Douglas Gregor57265e32010-04-12 16:00:01 +0000789 if (Previous.isAmbiguous())
790 return true;
791
Douglas Gregorddc29e12009-02-06 22:42:48 +0000792 NamedDecl *PrevDecl = 0;
793 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000794 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000795
Douglas Gregorddc29e12009-02-06 22:42:48 +0000796 // If there is a previous declaration with the same name, check
797 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000798 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000799 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000800
801 // We may have found the injected-class-name of a class template,
802 // class template partial specialization, or class template specialization.
803 // In these cases, grab the template that is being defined or specialized.
804 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
805 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
806 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
807 PrevClassTemplate
808 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
809 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
810 PrevClassTemplate
811 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
812 ->getSpecializedTemplate();
813 }
814 }
815
John McCall65c49462009-12-18 11:25:59 +0000816 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000817 // C++ [namespace.memdef]p3:
818 // [...] When looking for a prior declaration of a class or a function
819 // declared as a friend, and when the name of the friend class or
820 // function is neither a qualified name nor a template-id, scopes outside
821 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000822 if (!SS.isSet()) {
823 DeclContext *OutermostContext = CurContext;
824 while (!OutermostContext->isFileContext())
825 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000826
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000827 if (PrevDecl &&
828 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
829 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
830 SemanticContext = PrevDecl->getDeclContext();
831 } else {
832 // Declarations in outer scopes don't matter. However, the outermost
833 // context we computed is the semantic context for our new
834 // declaration.
835 PrevDecl = PrevClassTemplate = 0;
836 SemanticContext = OutermostContext;
837 }
John McCalle129d442009-12-17 23:21:11 +0000838 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000839
John McCalle129d442009-12-17 23:21:11 +0000840 if (CurContext->isDependentContext()) {
841 // If this is a dependent context, we don't want to link the friend
842 // class template to the template in scope, because that would perform
843 // checking of the template parameter lists that can't be performed
844 // until the outer context is instantiated.
845 PrevDecl = PrevClassTemplate = 0;
846 }
847 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
848 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000849
Douglas Gregorddc29e12009-02-06 22:42:48 +0000850 if (PrevClassTemplate) {
851 // Ensure that the template parameter lists are compatible.
852 if (!TemplateParameterListsAreEqual(TemplateParams,
853 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000854 /*Complain=*/true,
855 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000856 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000857
858 // C++ [temp.class]p4:
859 // In a redeclaration, partial specialization, explicit
860 // specialization or explicit instantiation of a class template,
861 // the class-key shall agree in kind with the original class
862 // template declaration (7.1.5.3).
863 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000864 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000865 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000866 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000867 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000868 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000869 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000870 }
871
Douglas Gregorddc29e12009-02-06 22:42:48 +0000872 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000873 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000874 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000875 Diag(NameLoc, diag::err_redefinition) << Name;
876 Diag(Def->getLocation(), diag::note_previous_definition);
877 // FIXME: Would it make sense to try to "forget" the previous
878 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000879 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000880 }
881 }
882 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
883 // Maybe we will complain about the shadowed template parameter.
884 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
885 // Just pretend that we didn't see the previous declaration.
886 PrevDecl = 0;
887 } else if (PrevDecl) {
888 // C++ [temp]p5:
889 // A class template shall not have the same name as any other
890 // template, class, function, object, enumeration, enumerator,
891 // namespace, or type in the same scope (3.3), except as specified
892 // in (14.5.4).
893 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
894 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000895 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000896 }
897
Douglas Gregord684b002009-02-10 19:49:53 +0000898 // Check the template parameter list of this declaration, possibly
899 // merging in the template parameter list from the previous class
900 // template declaration.
901 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000902 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
903 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000904 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Douglas Gregor57265e32010-04-12 16:00:01 +0000906 if (SS.isSet()) {
907 // If the name of the template was qualified, we must be defining the
908 // template out-of-line.
909 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
910 !(TUK == TUK_Friend && CurContext->isDependentContext()))
911 Diag(NameLoc, diag::err_member_def_does_not_match)
912 << Name << SemanticContext << SS.getRange();
913 }
914
Mike Stump1eb44332009-09-09 15:08:12 +0000915 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000916 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000917 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000918 PrevClassTemplate->getTemplatedDecl() : 0,
919 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000920 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000921
922 ClassTemplateDecl *NewTemplate
923 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
924 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000925 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000926 NewClass->setDescribedClassTemplate(NewTemplate);
927
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000928 // Build the type for the class template declaration now.
John McCall3cb0ebd2010-03-10 03:28:59 +0000929 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
930 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000931 assert(T->isDependentType() && "Class template type is not dependent?");
932 (void)T;
933
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000934 // If we are providing an explicit specialization of a member that is a
935 // class template, make a note of that.
936 if (PrevClassTemplate &&
937 PrevClassTemplate->getInstantiatedFromMemberTemplate())
938 PrevClassTemplate->setMemberSpecialization();
939
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000940 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000941 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000942 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Douglas Gregorddc29e12009-02-06 22:42:48 +0000944 // Set the lexical context of these templates
945 NewClass->setLexicalDeclContext(CurContext);
946 NewTemplate->setLexicalDeclContext(CurContext);
947
John McCall0f434ec2009-07-31 02:45:11 +0000948 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000949 NewClass->startDefinition();
950
951 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000952 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000953
John McCall05b23ea2009-09-14 21:59:20 +0000954 if (TUK != TUK_Friend)
955 PushOnScopeChains(NewTemplate, S);
956 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000957 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000958 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000959 NewClass->setAccess(PrevClassTemplate->getAccess());
960 }
John McCall05b23ea2009-09-14 21:59:20 +0000961
Douglas Gregord85bea22009-09-26 06:47:28 +0000962 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
963 PrevClassTemplate != NULL);
964
John McCall05b23ea2009-09-14 21:59:20 +0000965 // Friend templates are visible in fairly strange ways.
966 if (!CurContext->isDependentContext()) {
967 DeclContext *DC = SemanticContext->getLookupContext();
968 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
969 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
970 PushOnScopeChains(NewTemplate, EnclosingScope,
971 /* AddToContext = */ false);
972 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000973
974 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
975 NewClass->getLocation(),
976 NewTemplate,
977 /*FIXME:*/NewClass->getLocation());
978 Friend->setAccess(AS_public);
979 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000980 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000981
Douglas Gregord684b002009-02-10 19:49:53 +0000982 if (Invalid) {
983 NewTemplate->setInvalidDecl();
984 NewClass->setInvalidDecl();
985 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000986 return DeclPtrTy::make(NewTemplate);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000987}
988
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000989/// \brief Diagnose the presence of a default template argument on a
990/// template parameter, which is ill-formed in certain contexts.
991///
992/// \returns true if the default template argument should be dropped.
993static bool DiagnoseDefaultTemplateArgument(Sema &S,
994 Sema::TemplateParamListContext TPC,
995 SourceLocation ParamLoc,
996 SourceRange DefArgRange) {
997 switch (TPC) {
998 case Sema::TPC_ClassTemplate:
999 return false;
1000
1001 case Sema::TPC_FunctionTemplate:
1002 // C++ [temp.param]p9:
1003 // A default template-argument shall not be specified in a
1004 // function template declaration or a function template
1005 // definition [...]
1006 // (This sentence is not in C++0x, per DR226).
1007 if (!S.getLangOptions().CPlusPlus0x)
1008 S.Diag(ParamLoc,
1009 diag::err_template_parameter_default_in_function_template)
1010 << DefArgRange;
1011 return false;
1012
1013 case Sema::TPC_ClassTemplateMember:
1014 // C++0x [temp.param]p9:
1015 // A default template-argument shall not be specified in the
1016 // template-parameter-lists of the definition of a member of a
1017 // class template that appears outside of the member's class.
1018 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1019 << DefArgRange;
1020 return true;
1021
1022 case Sema::TPC_FriendFunctionTemplate:
1023 // C++ [temp.param]p9:
1024 // A default template-argument shall not be specified in a
1025 // friend template declaration.
1026 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1027 << DefArgRange;
1028 return true;
1029
1030 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1031 // for friend function templates if there is only a single
1032 // declaration (and it is a definition). Strange!
1033 }
1034
1035 return false;
1036}
1037
Douglas Gregord684b002009-02-10 19:49:53 +00001038/// \brief Checks the validity of a template parameter list, possibly
1039/// considering the template parameter list from a previous
1040/// declaration.
1041///
1042/// If an "old" template parameter list is provided, it must be
1043/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1044/// template parameter list.
1045///
1046/// \param NewParams Template parameter list for a new template
1047/// declaration. This template parameter list will be updated with any
1048/// default arguments that are carried through from the previous
1049/// template parameter list.
1050///
1051/// \param OldParams If provided, template parameter list from a
1052/// previous declaration of the same template. Default template
1053/// arguments will be merged from the old template parameter list to
1054/// the new template parameter list.
1055///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001056/// \param TPC Describes the context in which we are checking the given
1057/// template parameter list.
1058///
Douglas Gregord684b002009-02-10 19:49:53 +00001059/// \returns true if an error occurred, false otherwise.
1060bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001061 TemplateParameterList *OldParams,
1062 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001063 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Douglas Gregord684b002009-02-10 19:49:53 +00001065 // C++ [temp.param]p10:
1066 // The set of default template-arguments available for use with a
1067 // template declaration or definition is obtained by merging the
1068 // default arguments from the definition (if in scope) and all
1069 // declarations in scope in the same way default function
1070 // arguments are (8.3.6).
1071 bool SawDefaultArgument = false;
1072 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001073
Anders Carlsson49d25572009-06-12 23:20:15 +00001074 bool SawParameterPack = false;
1075 SourceLocation ParameterPackLoc;
1076
Mike Stump1a35fde2009-02-11 23:03:27 +00001077 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001078 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001079 if (OldParams)
1080 OldParam = OldParams->begin();
1081
1082 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1083 NewParamEnd = NewParams->end();
1084 NewParam != NewParamEnd; ++NewParam) {
1085 // Variables used to diagnose redundant default arguments
1086 bool RedundantDefaultArg = false;
1087 SourceLocation OldDefaultLoc;
1088 SourceLocation NewDefaultLoc;
1089
1090 // Variables used to diagnose missing default arguments
1091 bool MissingDefaultArg = false;
1092
Anders Carlsson49d25572009-06-12 23:20:15 +00001093 // C++0x [temp.param]p11:
1094 // If a template parameter of a class template is a template parameter pack,
1095 // it must be the last template parameter.
1096 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001097 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001098 diag::err_template_param_pack_must_be_last_template_parameter);
1099 Invalid = true;
1100 }
1101
Douglas Gregord684b002009-02-10 19:49:53 +00001102 if (TemplateTypeParmDecl *NewTypeParm
1103 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001104 // Check the presence of a default argument here.
1105 if (NewTypeParm->hasDefaultArgument() &&
1106 DiagnoseDefaultTemplateArgument(*this, TPC,
1107 NewTypeParm->getLocation(),
1108 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001109 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001110 NewTypeParm->removeDefaultArgument();
1111
1112 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001113 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001114 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Anders Carlsson49d25572009-06-12 23:20:15 +00001116 if (NewTypeParm->isParameterPack()) {
1117 assert(!NewTypeParm->hasDefaultArgument() &&
1118 "Parameter packs can't have a default argument!");
1119 SawParameterPack = true;
1120 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001121 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001122 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001123 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1124 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1125 SawDefaultArgument = true;
1126 RedundantDefaultArg = true;
1127 PreviousDefaultArgLoc = NewDefaultLoc;
1128 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1129 // Merge the default argument from the old declaration to the
1130 // new declaration.
1131 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001132 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001133 true);
1134 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1135 } else if (NewTypeParm->hasDefaultArgument()) {
1136 SawDefaultArgument = true;
1137 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1138 } else if (SawDefaultArgument)
1139 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001140 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001141 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001142 // Check the presence of a default argument here.
1143 if (NewNonTypeParm->hasDefaultArgument() &&
1144 DiagnoseDefaultTemplateArgument(*this, TPC,
1145 NewNonTypeParm->getLocation(),
1146 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1147 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001148 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001149 }
1150
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001151 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001152 NonTypeTemplateParmDecl *OldNonTypeParm
1153 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001154 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001155 NewNonTypeParm->hasDefaultArgument()) {
1156 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1157 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1158 SawDefaultArgument = true;
1159 RedundantDefaultArg = true;
1160 PreviousDefaultArgLoc = NewDefaultLoc;
1161 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1162 // Merge the default argument from the old declaration to the
1163 // new declaration.
1164 SawDefaultArgument = true;
1165 // FIXME: We need to create a new kind of "default argument"
1166 // expression that points to a previous template template
1167 // parameter.
1168 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001169 OldNonTypeParm->getDefaultArgument(),
1170 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001171 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1172 } else if (NewNonTypeParm->hasDefaultArgument()) {
1173 SawDefaultArgument = true;
1174 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1175 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001176 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001177 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001178 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001179 TemplateTemplateParmDecl *NewTemplateParm
1180 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001181 if (NewTemplateParm->hasDefaultArgument() &&
1182 DiagnoseDefaultTemplateArgument(*this, TPC,
1183 NewTemplateParm->getLocation(),
1184 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001185 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001186
1187 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001188 TemplateTemplateParmDecl *OldTemplateParm
1189 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001190 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001191 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001192 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1193 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001194 SawDefaultArgument = true;
1195 RedundantDefaultArg = true;
1196 PreviousDefaultArgLoc = NewDefaultLoc;
1197 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1198 // Merge the default argument from the old declaration to the
1199 // new declaration.
1200 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001201 // FIXME: We need to create a new kind of "default argument" expression
1202 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001203 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001204 OldTemplateParm->getDefaultArgument(),
1205 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001206 PreviousDefaultArgLoc
1207 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001208 } else if (NewTemplateParm->hasDefaultArgument()) {
1209 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001210 PreviousDefaultArgLoc
1211 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001212 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001213 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001214 }
1215
1216 if (RedundantDefaultArg) {
1217 // C++ [temp.param]p12:
1218 // A template-parameter shall not be given default arguments
1219 // by two different declarations in the same scope.
1220 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1221 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1222 Invalid = true;
1223 } else if (MissingDefaultArg) {
1224 // C++ [temp.param]p11:
1225 // If a template-parameter has a default template-argument,
1226 // all subsequent template-parameters shall have a default
1227 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001228 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001229 diag::err_template_param_default_arg_missing);
1230 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1231 Invalid = true;
1232 }
1233
1234 // If we have an old template parameter list that we're merging
1235 // in, move on to the next parameter.
1236 if (OldParams)
1237 ++OldParam;
1238 }
1239
1240 return Invalid;
1241}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001242
Mike Stump1eb44332009-09-09 15:08:12 +00001243/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001244/// specifier, returning the template parameter list that applies to the
1245/// name.
1246///
1247/// \param DeclStartLoc the start of the declaration that has a scope
1248/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001249///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001250/// \param SS the scope specifier that will be matched to the given template
1251/// parameter lists. This scope specifier precedes a qualified name that is
1252/// being declared.
1253///
1254/// \param ParamLists the template parameter lists, from the outermost to the
1255/// innermost template parameter lists.
1256///
1257/// \param NumParamLists the number of template parameter lists in ParamLists.
1258///
John McCall77e8b112010-04-13 20:37:33 +00001259/// \param IsFriend Whether to apply the slightly different rules for
1260/// matching template parameters to scope specifiers in friend
1261/// declarations.
1262///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001263/// \param IsExplicitSpecialization will be set true if the entity being
1264/// declared is an explicit specialization, false otherwise.
1265///
Mike Stump1eb44332009-09-09 15:08:12 +00001266/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001267/// name that is preceded by the scope specifier @p SS. This template
1268/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001269/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001270/// template specialization), or may be NULL (if we were's declaring isn't
1271/// itself a template).
1272TemplateParameterList *
1273Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1274 const CXXScopeSpec &SS,
1275 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001276 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001277 bool IsFriend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001278 bool &IsExplicitSpecialization) {
1279 IsExplicitSpecialization = false;
1280
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001281 // Find the template-ids that occur within the nested-name-specifier. These
1282 // template-ids will match up with the template parameter lists.
1283 llvm::SmallVector<const TemplateSpecializationType *, 4>
1284 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001285 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1286 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001287 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1288 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001289 const Type *T = NNS->getAsType();
1290 if (!T) break;
1291
1292 // C++0x [temp.expl.spec]p17:
1293 // A member or a member template may be nested within many
1294 // enclosing class templates. In an explicit specialization for
1295 // such a member, the member declaration shall be preceded by a
1296 // template<> for each enclosing class template that is
1297 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001298 //
1299 // Following the existing practice of GNU and EDG, we allow a typedef of a
1300 // template specialization type.
1301 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1302 T = TT->LookThroughTypedefs().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001303
Mike Stump1eb44332009-09-09 15:08:12 +00001304 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001305 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001306 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1307 if (!Template)
1308 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Ted Kremenek6217b802009-07-29 21:53:49 +00001310 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001311 ClassTemplateSpecializationDecl *SpecDecl
1312 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1313 // If the nested name specifier refers to an explicit specialization,
1314 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001315 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1316 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001317 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001318 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001319 }
Mike Stump1eb44332009-09-09 15:08:12 +00001320
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001321 TemplateIdsInSpecifier.push_back(SpecType);
1322 }
1323 }
Mike Stump1eb44332009-09-09 15:08:12 +00001324
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001325 // Reverse the list of template-ids in the scope specifier, so that we can
1326 // more easily match up the template-ids and the template parameter lists.
1327 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001329 SourceLocation FirstTemplateLoc = DeclStartLoc;
1330 if (NumParamLists)
1331 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001333 // Match the template-ids found in the specifier to the template parameter
1334 // lists.
1335 unsigned Idx = 0;
1336 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1337 Idx != NumTemplateIds; ++Idx) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00001338 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1339 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001340 if (Idx >= NumParamLists) {
1341 // We have a template-id without a corresponding template parameter
1342 // list.
John McCall77e8b112010-04-13 20:37:33 +00001343
1344 // ...which is fine if this is a friend declaration.
1345 if (IsFriend) {
1346 IsExplicitSpecialization = true;
1347 break;
1348 }
1349
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001350 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001351 // FIXME: the location information here isn't great.
1352 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001353 diag::err_template_spec_needs_template_parameters)
Douglas Gregorb88e8882009-07-30 17:40:51 +00001354 << TemplateId
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001355 << SS.getRange();
1356 } else {
1357 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1358 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001359 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001360 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001361 }
1362 return 0;
1363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001365 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001366 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001367 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001368
John McCall31f17ec2010-04-27 00:57:59 +00001369 // Are there cases in (e.g.) friends where this won't match?
1370 if (const InjectedClassNameType *Injected
1371 = TemplateId->getAs<InjectedClassNameType>()) {
1372 CXXRecordDecl *Record = Injected->getDecl();
1373 if (ClassTemplatePartialSpecializationDecl *Partial =
1374 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1375 ExpectedTemplateParams = Partial->getTemplateParameters();
1376 else
1377 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1378 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001379 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001380
John McCall31f17ec2010-04-27 00:57:59 +00001381 if (ExpectedTemplateParams)
1382 TemplateParameterListsAreEqual(ParamLists[Idx],
1383 ExpectedTemplateParams,
1384 true, TPL_TemplateMatch);
1385
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001386 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregorb88e8882009-07-30 17:40:51 +00001387 } else if (ParamLists[Idx]->size() > 0)
Mike Stump1eb44332009-09-09 15:08:12 +00001388 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001389 diag::err_template_param_list_matches_nontemplate)
1390 << TemplateId
1391 << ParamLists[Idx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001392 else
1393 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001394 }
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001396 // If there were at least as many template-ids as there were template
1397 // parameter lists, then there are no template parameter lists remaining for
1398 // the declaration itself.
1399 if (Idx >= NumParamLists)
1400 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001402 // If there were too many template parameter lists, complain about that now.
1403 if (Idx != NumParamLists - 1) {
1404 while (Idx < NumParamLists - 1) {
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001405 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001406 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001407 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1408 : diag::err_template_spec_extra_headers)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001409 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1410 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001411
1412 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1413 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1414 diag::note_explicit_template_spec_does_not_need_header)
1415 << ExplicitSpecializationsInSpecifier.back();
1416 ExplicitSpecializationsInSpecifier.pop_back();
1417 }
1418
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001419 ++Idx;
1420 }
1421 }
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001423 // Return the last template parameter list, which corresponds to the
1424 // entity being declared.
1425 return ParamLists[NumParamLists - 1];
1426}
1427
Douglas Gregor7532dc62009-03-30 22:58:21 +00001428QualType Sema::CheckTemplateIdType(TemplateName Name,
1429 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001430 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001431 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001432 if (!Template) {
1433 // The template name does not resolve to a template, so we just
1434 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001435 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001436 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001437
Douglas Gregor40808ce2009-03-09 23:48:35 +00001438 // Check that the template argument list is well-formed for this
1439 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00001440 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCalld5532b62009-11-23 01:53:49 +00001441 TemplateArgs.size());
1442 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001443 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001444 return QualType();
1445
Mike Stump1eb44332009-09-09 15:08:12 +00001446 assert((Converted.structuredSize() ==
Douglas Gregor7532dc62009-03-30 22:58:21 +00001447 Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001448 "Converted template argument list is too short!");
1449
1450 QualType CanonType;
John McCall31f17ec2010-04-27 00:57:59 +00001451 bool IsCurrentInstantiation = false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00001452
Douglas Gregorcaddba02009-11-12 18:38:13 +00001453 if (Name.isDependent() ||
1454 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001455 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001456 // This class template specialization is a dependent
1457 // type. Therefore, its canonical type is another class template
1458 // specialization type that contains all of the converted
1459 // arguments in canonical form. This ensures that, e.g., A<T> and
1460 // A<T, T> have identical types when A is declared as:
1461 //
1462 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001463 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001464 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlssonfb250522009-06-23 01:26:57 +00001465 Converted.getFlatArguments(),
1466 Converted.flatSize());
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Douglas Gregor1275ae02009-07-28 23:00:59 +00001468 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001469 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001470 // In the future, we need to teach getTemplateSpecializationType to only
1471 // build the canonical type and return that to us.
1472 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001473
1474 // This might work out to be a current instantiation, in which
1475 // case the canonical type needs to be the InjectedClassNameType.
1476 //
1477 // TODO: in theory this could be a simple hashtable lookup; most
1478 // changes to CurContext don't change the set of current
1479 // instantiations.
1480 if (isa<ClassTemplateDecl>(Template)) {
1481 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1482 // If we get out to a namespace, we're done.
1483 if (Ctx->isFileContext()) break;
1484
1485 // If this isn't a record, keep looking.
1486 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1487 if (!Record) continue;
1488
1489 // Look for one of the two cases with InjectedClassNameTypes
1490 // and check whether it's the same template.
1491 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1492 !Record->getDescribedClassTemplate())
1493 continue;
1494
1495 // Fetch the injected class name type and check whether its
1496 // injected type is equal to the type we just built.
1497 QualType ICNT = Context.getTypeDeclType(Record);
1498 QualType Injected = cast<InjectedClassNameType>(ICNT)
1499 ->getInjectedSpecializationType();
1500
1501 if (CanonType != Injected->getCanonicalTypeInternal())
1502 continue;
1503
1504 // If so, the canonical type of this TST is the injected
1505 // class name type of the record we just found.
1506 assert(ICNT.isCanonical());
1507 CanonType = ICNT;
1508 IsCurrentInstantiation = true;
1509 break;
1510 }
1511 }
Mike Stump1eb44332009-09-09 15:08:12 +00001512 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001513 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001514 // Find the class template specialization declaration that
1515 // corresponds to these arguments.
1516 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001517 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00001518 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00001519 Converted.flatSize(),
1520 Context);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001521 void *InsertPos = 0;
1522 ClassTemplateSpecializationDecl *Decl
1523 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1524 if (!Decl) {
1525 // This is the first time we have referenced this class template
1526 // specialization. Create the canonical declaration and add it to
1527 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001528 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001529 ClassTemplate->getTemplatedDecl()->getTagKind(),
1530 ClassTemplate->getDeclContext(),
1531 ClassTemplate->getLocation(),
1532 ClassTemplate,
1533 Converted, 0);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001534 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1535 Decl->setLexicalDeclContext(CurContext);
1536 }
1537
1538 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001539 assert(isa<RecordType>(CanonType) &&
1540 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001541 }
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Douglas Gregor40808ce2009-03-09 23:48:35 +00001543 // Build the fully-sugared type for this class template
1544 // specialization, which refers back to the class template
1545 // specialization we created or found.
John McCall31f17ec2010-04-27 00:57:59 +00001546 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType,
1547 IsCurrentInstantiation);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001548}
1549
Douglas Gregorcc636682009-02-17 23:15:12 +00001550Action::TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001551Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001552 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001553 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001554 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001555 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001556
Douglas Gregor40808ce2009-03-09 23:48:35 +00001557 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001558 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001559 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001560
John McCalld5532b62009-11-23 01:53:49 +00001561 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001562 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001563
1564 if (Result.isNull())
1565 return true;
1566
John McCalla93c9342009-12-07 02:54:59 +00001567 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001568 TemplateSpecializationTypeLoc TL
1569 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1570 TL.setTemplateNameLoc(TemplateLoc);
1571 TL.setLAngleLoc(LAngleLoc);
1572 TL.setRAngleLoc(RAngleLoc);
1573 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1574 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1575
1576 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCall6b2becf2009-09-08 17:47:29 +00001577}
John McCallf1bbbb42009-09-04 01:14:41 +00001578
John McCall6b2becf2009-09-08 17:47:29 +00001579Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1580 TagUseKind TUK,
1581 DeclSpec::TST TagSpec,
1582 SourceLocation TagLoc) {
1583 if (TypeResult.isInvalid())
1584 return Sema::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001585
John McCall833ca992009-10-29 08:12:44 +00001586 // FIXME: preserve source info, ideally without copying the DI.
John McCalla93c9342009-12-07 02:54:59 +00001587 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001588 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001589
John McCall6b2becf2009-09-08 17:47:29 +00001590 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001591 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001592
John McCall6b2becf2009-09-08 17:47:29 +00001593 if (const RecordType *RT = Type->getAs<RecordType>()) {
1594 RecordDecl *D = RT->getDecl();
1595
1596 IdentifierInfo *Id = D->getIdentifier();
1597 assert(Id && "templated class must have an identifier");
1598
1599 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1600 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001601 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001602 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001603 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001604 }
1605 }
1606
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001607 ElaboratedTypeKeyword Keyword
1608 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1609 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001610
1611 return ElabType.getAsOpaquePtr();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001612}
1613
John McCallf7a1a742009-11-24 19:00:30 +00001614Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1615 LookupResult &R,
1616 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001617 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001618 // FIXME: Can we do any checking at this point? I guess we could check the
1619 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001620 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001621 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001622
1623 // These should be filtered out by our callers.
1624 assert(!R.empty() && "empty lookup results when building templateid");
1625 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1626
1627 NestedNameSpecifier *Qualifier = 0;
1628 SourceRange QualifierRange;
1629 if (SS.isSet()) {
1630 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1631 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001632 }
John McCallc373d482010-01-27 01:50:18 +00001633
1634 // We don't want lookup warnings at this point.
1635 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001636
John McCallf7a1a742009-11-24 19:00:30 +00001637 bool Dependent
1638 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1639 &TemplateArgs);
1640 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001641 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001642 Qualifier, QualifierRange,
1643 R.getLookupName(), R.getNameLoc(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001644 RequiresADL, TemplateArgs,
1645 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001646
1647 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001648}
1649
John McCallf7a1a742009-11-24 19:00:30 +00001650// We actually only call this from template instantiation.
1651Sema::OwningExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001652Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001653 DeclarationName Name,
1654 SourceLocation NameLoc,
1655 const TemplateArgumentListInfo &TemplateArgs) {
1656 DeclContext *DC;
1657 if (!(DC = computeDeclContext(SS, false)) ||
1658 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001659 RequireCompleteDeclContext(SS, DC))
John McCallf7a1a742009-11-24 19:00:30 +00001660 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001662 bool MemberOfUnknownSpecialization;
John McCallf7a1a742009-11-24 19:00:30 +00001663 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001664 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1665 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001666
John McCallf7a1a742009-11-24 19:00:30 +00001667 if (R.isAmbiguous())
1668 return ExprError();
1669
1670 if (R.empty()) {
1671 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1672 << Name << SS.getRange();
1673 return ExprError();
1674 }
1675
1676 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1677 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1678 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1679 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1680 return ExprError();
1681 }
1682
1683 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001684}
1685
Douglas Gregorc45c2322009-03-31 00:43:58 +00001686/// \brief Form a dependent template name.
1687///
1688/// This action forms a dependent template name given the template
1689/// name and its (presumably dependent) scope specifier. For
1690/// example, given "MetaFun::template apply", the scope specifier \p
1691/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1692/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump1eb44332009-09-09 15:08:12 +00001693Sema::TemplateTy
Douglas Gregorc45c2322009-03-31 00:43:58 +00001694Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001695 CXXScopeSpec &SS,
Douglas Gregor014e88d2009-11-03 23:16:33 +00001696 UnqualifiedId &Name,
Douglas Gregora481edb2009-11-20 23:39:24 +00001697 TypeTy *ObjectType,
1698 bool EnteringContext) {
Douglas Gregor0707bc52010-01-19 16:01:07 +00001699 DeclContext *LookupCtx = 0;
1700 if (SS.isSet())
1701 LookupCtx = computeDeclContext(SS, EnteringContext);
1702 if (!LookupCtx && ObjectType)
1703 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1704 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001705 // C++0x [temp.names]p5:
1706 // If a name prefixed by the keyword template is not the name of
1707 // a template, the program is ill-formed. [Note: the keyword
1708 // template may not be applied to non-template members of class
1709 // templates. -end note ] [ Note: as is the case with the
1710 // typename prefix, the template prefix is allowed in cases
1711 // where it is not strictly necessary; i.e., when the
1712 // nested-name-specifier or the expression on the left of the ->
1713 // or . is not dependent on a template-parameter, or the use
1714 // does not appear in the scope of a template. -end note]
1715 //
1716 // Note: C++03 was more strict here, because it banned the use of
1717 // the "template" keyword prior to a template-name that was not a
1718 // dependent name. C++ DR468 relaxed this requirement (the
1719 // "template" keyword is now permitted). We follow the C++0x
1720 // rules, even in C++03 mode, retroactively applying the DR.
1721 TemplateTy Template;
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001722 bool MemberOfUnknownSpecialization;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001723 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001724 EnteringContext, Template,
1725 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001726 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1727 isa<CXXRecordDecl>(LookupCtx) &&
1728 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001729 // This is a dependent template.
1730 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001731 Diag(Name.getSourceRange().getBegin(),
1732 diag::err_template_kw_refers_to_non_template)
1733 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001734 << Name.getSourceRange()
1735 << TemplateKWLoc;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001736 return TemplateTy();
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001737 } else {
1738 // We found something; return it.
1739 return Template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001740 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001741 }
1742
Mike Stump1eb44332009-09-09 15:08:12 +00001743 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001744 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001745
1746 switch (Name.getKind()) {
1747 case UnqualifiedId::IK_Identifier:
1748 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1749 Name.Identifier));
1750
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001751 case UnqualifiedId::IK_OperatorFunctionId:
1752 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1753 Name.OperatorFunctionId.Operator));
Sean Hunte6252d12009-11-28 08:58:14 +00001754
1755 case UnqualifiedId::IK_LiteralOperatorId:
1756 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1757
Douglas Gregor014e88d2009-11-03 23:16:33 +00001758 default:
1759 break;
1760 }
1761
1762 Diag(Name.getSourceRange().getBegin(),
1763 diag::err_template_kw_refers_to_non_template)
1764 << GetNameFromUnqualifiedId(Name)
Douglas Gregor0278e122010-05-05 05:58:24 +00001765 << Name.getSourceRange()
1766 << TemplateKWLoc;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001767 return TemplateTy();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001768}
1769
Mike Stump1eb44332009-09-09 15:08:12 +00001770bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001771 const TemplateArgumentLoc &AL,
Anders Carlsson436b1562009-06-13 00:33:33 +00001772 TemplateArgumentListBuilder &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001773 const TemplateArgument &Arg = AL.getArgument();
1774
Anders Carlsson436b1562009-06-13 00:33:33 +00001775 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001776 switch(Arg.getKind()) {
1777 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001778 // C++ [temp.arg.type]p1:
1779 // A template-argument for a template-parameter which is a
1780 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001781 break;
1782 case TemplateArgument::Template: {
1783 // We have a template type parameter but the template argument
1784 // is a template without any arguments.
1785 SourceRange SR = AL.getSourceRange();
1786 TemplateName Name = Arg.getAsTemplate();
1787 Diag(SR.getBegin(), diag::err_template_missing_args)
1788 << Name << SR;
1789 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1790 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001791
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001792 return true;
1793 }
1794 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001795 // We have a template type parameter but the template argument
1796 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001797 SourceRange SR = AL.getSourceRange();
1798 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001799 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001800
Anders Carlsson436b1562009-06-13 00:33:33 +00001801 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001802 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001803 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001804
John McCalla93c9342009-12-07 02:54:59 +00001805 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001806 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Anders Carlsson436b1562009-06-13 00:33:33 +00001808 // Add the converted template type argument.
Anders Carlssonfb250522009-06-23 01:26:57 +00001809 Converted.Append(
John McCall833ca992009-10-29 08:12:44 +00001810 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001811 return false;
1812}
1813
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001814/// \brief Substitute template arguments into the default template argument for
1815/// the given template type parameter.
1816///
1817/// \param SemaRef the semantic analysis object for which we are performing
1818/// the substitution.
1819///
1820/// \param Template the template that we are synthesizing template arguments
1821/// for.
1822///
1823/// \param TemplateLoc the location of the template name that started the
1824/// template-id we are checking.
1825///
1826/// \param RAngleLoc the location of the right angle bracket ('>') that
1827/// terminates the template-id.
1828///
1829/// \param Param the template template parameter whose default we are
1830/// substituting into.
1831///
1832/// \param Converted the list of template arguments provided for template
1833/// parameters that precede \p Param in the template parameter list.
1834///
1835/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001836static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001837SubstDefaultTemplateArgument(Sema &SemaRef,
1838 TemplateDecl *Template,
1839 SourceLocation TemplateLoc,
1840 SourceLocation RAngleLoc,
1841 TemplateTypeParmDecl *Param,
1842 TemplateArgumentListBuilder &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001843 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001844
1845 // If the argument type is dependent, instantiate it now based
1846 // on the previously-computed template arguments.
1847 if (ArgType->getType()->isDependentType()) {
1848 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1849 /*TakeArgs=*/false);
1850
1851 MultiLevelTemplateArgumentList AllTemplateArgs
1852 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1853
1854 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1855 Template, Converted.getFlatArguments(),
1856 Converted.flatSize(),
1857 SourceRange(TemplateLoc, RAngleLoc));
1858
1859 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1860 Param->getDefaultArgumentLoc(),
1861 Param->getDeclName());
1862 }
1863
1864 return ArgType;
1865}
1866
1867/// \brief Substitute template arguments into the default template argument for
1868/// the given non-type template parameter.
1869///
1870/// \param SemaRef the semantic analysis object for which we are performing
1871/// the substitution.
1872///
1873/// \param Template the template that we are synthesizing template arguments
1874/// for.
1875///
1876/// \param TemplateLoc the location of the template name that started the
1877/// template-id we are checking.
1878///
1879/// \param RAngleLoc the location of the right angle bracket ('>') that
1880/// terminates the template-id.
1881///
Douglas Gregor788cd062009-11-11 01:00:40 +00001882/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001883/// substituting into.
1884///
1885/// \param Converted the list of template arguments provided for template
1886/// parameters that precede \p Param in the template parameter list.
1887///
1888/// \returns the substituted template argument, or NULL if an error occurred.
1889static Sema::OwningExprResult
1890SubstDefaultTemplateArgument(Sema &SemaRef,
1891 TemplateDecl *Template,
1892 SourceLocation TemplateLoc,
1893 SourceLocation RAngleLoc,
1894 NonTypeTemplateParmDecl *Param,
1895 TemplateArgumentListBuilder &Converted) {
1896 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1897 /*TakeArgs=*/false);
1898
1899 MultiLevelTemplateArgumentList AllTemplateArgs
1900 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1901
1902 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1903 Template, Converted.getFlatArguments(),
1904 Converted.flatSize(),
1905 SourceRange(TemplateLoc, RAngleLoc));
1906
1907 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1908}
1909
Douglas Gregor788cd062009-11-11 01:00:40 +00001910/// \brief Substitute template arguments into the default template argument for
1911/// the given template template parameter.
1912///
1913/// \param SemaRef the semantic analysis object for which we are performing
1914/// the substitution.
1915///
1916/// \param Template the template that we are synthesizing template arguments
1917/// for.
1918///
1919/// \param TemplateLoc the location of the template name that started the
1920/// template-id we are checking.
1921///
1922/// \param RAngleLoc the location of the right angle bracket ('>') that
1923/// terminates the template-id.
1924///
1925/// \param Param the template template parameter whose default we are
1926/// substituting into.
1927///
1928/// \param Converted the list of template arguments provided for template
1929/// parameters that precede \p Param in the template parameter list.
1930///
1931/// \returns the substituted template argument, or NULL if an error occurred.
1932static TemplateName
1933SubstDefaultTemplateArgument(Sema &SemaRef,
1934 TemplateDecl *Template,
1935 SourceLocation TemplateLoc,
1936 SourceLocation RAngleLoc,
1937 TemplateTemplateParmDecl *Param,
1938 TemplateArgumentListBuilder &Converted) {
1939 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1940 /*TakeArgs=*/false);
1941
1942 MultiLevelTemplateArgumentList AllTemplateArgs
1943 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1944
1945 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1946 Template, Converted.getFlatArguments(),
1947 Converted.flatSize(),
1948 SourceRange(TemplateLoc, RAngleLoc));
1949
1950 return SemaRef.SubstTemplateName(
1951 Param->getDefaultArgument().getArgument().getAsTemplate(),
1952 Param->getDefaultArgument().getTemplateNameLoc(),
1953 AllTemplateArgs);
1954}
1955
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001956/// \brief If the given template parameter has a default template
1957/// argument, substitute into that default template argument and
1958/// return the corresponding template argument.
1959TemplateArgumentLoc
1960Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1961 SourceLocation TemplateLoc,
1962 SourceLocation RAngleLoc,
1963 Decl *Param,
1964 TemplateArgumentListBuilder &Converted) {
1965 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1966 if (!TypeParm->hasDefaultArgument())
1967 return TemplateArgumentLoc();
1968
John McCalla93c9342009-12-07 02:54:59 +00001969 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00001970 TemplateLoc,
1971 RAngleLoc,
1972 TypeParm,
1973 Converted);
1974 if (DI)
1975 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1976
1977 return TemplateArgumentLoc();
1978 }
1979
1980 if (NonTypeTemplateParmDecl *NonTypeParm
1981 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1982 if (!NonTypeParm->hasDefaultArgument())
1983 return TemplateArgumentLoc();
1984
1985 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1986 TemplateLoc,
1987 RAngleLoc,
1988 NonTypeParm,
1989 Converted);
1990 if (Arg.isInvalid())
1991 return TemplateArgumentLoc();
1992
1993 Expr *ArgE = Arg.takeAs<Expr>();
1994 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1995 }
1996
1997 TemplateTemplateParmDecl *TempTempParm
1998 = cast<TemplateTemplateParmDecl>(Param);
1999 if (!TempTempParm->hasDefaultArgument())
2000 return TemplateArgumentLoc();
2001
2002 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2003 TemplateLoc,
2004 RAngleLoc,
2005 TempTempParm,
2006 Converted);
2007 if (TName.isNull())
2008 return TemplateArgumentLoc();
2009
2010 return TemplateArgumentLoc(TemplateArgument(TName),
2011 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2012 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2013}
2014
Douglas Gregore7526412009-11-11 19:31:23 +00002015/// \brief Check that the given template argument corresponds to the given
2016/// template parameter.
2017bool Sema::CheckTemplateArgument(NamedDecl *Param,
2018 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002019 TemplateDecl *Template,
2020 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002021 SourceLocation RAngleLoc,
Douglas Gregor02024a92010-03-28 02:42:43 +00002022 TemplateArgumentListBuilder &Converted,
2023 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002024 // Check template type parameters.
2025 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002026 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002027
Douglas Gregord9e15302009-11-11 19:41:09 +00002028 // Check non-type template parameters.
2029 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002030 // Do substitution on the type of the non-type template parameter
2031 // with the template arguments we've seen thus far.
2032 QualType NTTPType = NTTP->getType();
2033 if (NTTPType->isDependentType()) {
2034 // Do substitution on the type of the non-type template parameter.
2035 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2036 NTTP, Converted.getFlatArguments(),
2037 Converted.flatSize(),
2038 SourceRange(TemplateLoc, RAngleLoc));
2039
2040 TemplateArgumentList TemplateArgs(Context, Converted,
2041 /*TakeArgs=*/false);
2042 NTTPType = SubstType(NTTPType,
2043 MultiLevelTemplateArgumentList(TemplateArgs),
2044 NTTP->getLocation(),
2045 NTTP->getDeclName());
2046 // If that worked, check the non-type template parameter type
2047 // for validity.
2048 if (!NTTPType.isNull())
2049 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2050 NTTP->getLocation());
2051 if (NTTPType.isNull())
2052 return true;
2053 }
2054
2055 switch (Arg.getArgument().getKind()) {
2056 case TemplateArgument::Null:
2057 assert(false && "Should never see a NULL template argument here");
2058 return true;
2059
2060 case TemplateArgument::Expression: {
2061 Expr *E = Arg.getArgument().getAsExpr();
2062 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002063 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002064 return true;
2065
2066 Converted.Append(Result);
2067 break;
2068 }
2069
2070 case TemplateArgument::Declaration:
2071 case TemplateArgument::Integral:
2072 // We've already checked this template argument, so just copy
2073 // it to the list of converted arguments.
2074 Converted.Append(Arg.getArgument());
2075 break;
2076
2077 case TemplateArgument::Template:
2078 // We were given a template template argument. It may not be ill-formed;
2079 // see below.
2080 if (DependentTemplateName *DTN
2081 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2082 // We have a template argument such as \c T::template X, which we
2083 // parsed as a template template argument. However, since we now
2084 // know that we need a non-type template argument, convert this
2085 // template name into an expression.
John McCallf7a1a742009-11-24 19:00:30 +00002086 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2087 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002088 Arg.getTemplateQualifierRange(),
John McCallf7a1a742009-11-24 19:00:30 +00002089 DTN->getIdentifier(),
2090 Arg.getTemplateNameLoc());
Douglas Gregore7526412009-11-11 19:31:23 +00002091
2092 TemplateArgument Result;
2093 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2094 return true;
2095
2096 Converted.Append(Result);
2097 break;
2098 }
2099
2100 // We have a template argument that actually does refer to a class
2101 // template, template alias, or template template parameter, and
2102 // therefore cannot be a non-type template argument.
2103 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2104 << Arg.getSourceRange();
2105
2106 Diag(Param->getLocation(), diag::note_template_param_here);
2107 return true;
2108
2109 case TemplateArgument::Type: {
2110 // We have a non-type template parameter but the template
2111 // argument is a type.
2112
2113 // C++ [temp.arg]p2:
2114 // In a template-argument, an ambiguity between a type-id and
2115 // an expression is resolved to a type-id, regardless of the
2116 // form of the corresponding template-parameter.
2117 //
2118 // We warn specifically about this case, since it can be rather
2119 // confusing for users.
2120 QualType T = Arg.getArgument().getAsType();
2121 SourceRange SR = Arg.getSourceRange();
2122 if (T->isFunctionType())
2123 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2124 else
2125 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2126 Diag(Param->getLocation(), diag::note_template_param_here);
2127 return true;
2128 }
2129
2130 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002131 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002132 break;
2133 }
2134
2135 return false;
2136 }
2137
2138
2139 // Check template template parameters.
2140 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2141
2142 // Substitute into the template parameter list of the template
2143 // template parameter, since previously-supplied template arguments
2144 // may appear within the template template parameter.
2145 {
2146 // Set up a template instantiation context.
2147 LocalInstantiationScope Scope(*this);
2148 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2149 TempParm, Converted.getFlatArguments(),
2150 Converted.flatSize(),
2151 SourceRange(TemplateLoc, RAngleLoc));
2152
2153 TemplateArgumentList TemplateArgs(Context, Converted,
2154 /*TakeArgs=*/false);
2155 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2156 SubstDecl(TempParm, CurContext,
2157 MultiLevelTemplateArgumentList(TemplateArgs)));
2158 if (!TempParm)
2159 return true;
2160
2161 // FIXME: TempParam is leaked.
2162 }
2163
2164 switch (Arg.getArgument().getKind()) {
2165 case TemplateArgument::Null:
2166 assert(false && "Should never see a NULL template argument here");
2167 return true;
2168
2169 case TemplateArgument::Template:
2170 if (CheckTemplateArgument(TempParm, Arg))
2171 return true;
2172
2173 Converted.Append(Arg.getArgument());
2174 break;
2175
2176 case TemplateArgument::Expression:
2177 case TemplateArgument::Type:
2178 // We have a template template parameter but the template
2179 // argument does not refer to a template.
2180 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2181 return true;
2182
2183 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002184 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002185 "Declaration argument with template template parameter");
2186 break;
2187 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002188 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002189 "Integral argument with template template parameter");
2190 break;
2191
2192 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002193 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002194 break;
2195 }
2196
2197 return false;
2198}
2199
Douglas Gregorc15cb382009-02-09 23:23:08 +00002200/// \brief Check that the given template argument list is well-formed
2201/// for specializing the given template.
2202bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2203 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002204 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002205 bool PartialTemplateArgs,
Anders Carlsson1c5976e2009-06-05 03:43:12 +00002206 TemplateArgumentListBuilder &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002207 TemplateParameterList *Params = Template->getTemplateParameters();
2208 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002209 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002210 bool Invalid = false;
2211
John McCalld5532b62009-11-23 01:53:49 +00002212 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2213
Mike Stump1eb44332009-09-09 15:08:12 +00002214 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002215 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002216
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002217 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002218 (NumArgs < Params->getMinRequiredArguments() &&
2219 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002220 // FIXME: point at either the first arg beyond what we can handle,
2221 // or the '>', depending on whether we have too many or too few
2222 // arguments.
2223 SourceRange Range;
2224 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002225 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002226 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2227 << (NumArgs > NumParams)
2228 << (isa<ClassTemplateDecl>(Template)? 0 :
2229 isa<FunctionTemplateDecl>(Template)? 1 :
2230 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2231 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002232 Diag(Template->getLocation(), diag::note_template_decl_here)
2233 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002234 Invalid = true;
2235 }
Mike Stump1eb44332009-09-09 15:08:12 +00002236
2237 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002238 // [...] The type and form of each template-argument specified in
2239 // a template-id shall match the type and form specified for the
2240 // corresponding parameter declared by the template in its
2241 // template-parameter-list.
2242 unsigned ArgIdx = 0;
2243 for (TemplateParameterList::iterator Param = Params->begin(),
2244 ParamEnd = Params->end();
2245 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002246 if (ArgIdx > NumArgs && PartialTemplateArgs)
2247 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002248
Douglas Gregord9e15302009-11-11 19:41:09 +00002249 // If we have a template parameter pack, check every remaining template
2250 // argument against that template parameter pack.
2251 if ((*Param)->isTemplateParameterPack()) {
2252 Converted.BeginPack();
2253 for (; ArgIdx < NumArgs; ++ArgIdx) {
2254 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2255 TemplateLoc, RAngleLoc, Converted)) {
2256 Invalid = true;
2257 break;
2258 }
2259 }
2260 Converted.EndPack();
2261 continue;
2262 }
2263
Douglas Gregorf35f8282009-11-11 21:54:23 +00002264 if (ArgIdx < NumArgs) {
2265 // Check the template argument we were given.
2266 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2267 TemplateLoc, RAngleLoc, Converted))
2268 return true;
2269
2270 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002271 }
Douglas Gregore7526412009-11-11 19:31:23 +00002272
Douglas Gregorf35f8282009-11-11 21:54:23 +00002273 // We have a default template argument that we will use.
2274 TemplateArgumentLoc Arg;
2275
2276 // Retrieve the default template argument from the template
2277 // parameter. For each kind of template parameter, we substitute the
2278 // template arguments provided thus far and any "outer" template arguments
2279 // (when the template parameter was part of a nested template) into
2280 // the default argument.
2281 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2282 if (!TTP->hasDefaultArgument()) {
2283 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2284 break;
2285 }
2286
John McCalla93c9342009-12-07 02:54:59 +00002287 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002288 Template,
2289 TemplateLoc,
2290 RAngleLoc,
2291 TTP,
2292 Converted);
2293 if (!ArgType)
2294 return true;
2295
2296 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2297 ArgType);
2298 } else if (NonTypeTemplateParmDecl *NTTP
2299 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2300 if (!NTTP->hasDefaultArgument()) {
2301 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2302 break;
2303 }
2304
2305 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2306 TemplateLoc,
2307 RAngleLoc,
2308 NTTP,
2309 Converted);
2310 if (E.isInvalid())
2311 return true;
2312
2313 Expr *Ex = E.takeAs<Expr>();
2314 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2315 } else {
2316 TemplateTemplateParmDecl *TempParm
2317 = cast<TemplateTemplateParmDecl>(*Param);
2318
2319 if (!TempParm->hasDefaultArgument()) {
2320 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2321 break;
2322 }
2323
2324 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2325 TemplateLoc,
2326 RAngleLoc,
2327 TempParm,
2328 Converted);
2329 if (Name.isNull())
2330 return true;
2331
2332 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2333 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2334 TempParm->getDefaultArgument().getTemplateNameLoc());
2335 }
2336
2337 // Introduce an instantiation record that describes where we are using
2338 // the default template argument.
2339 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2340 Converted.getFlatArguments(),
2341 Converted.flatSize(),
2342 SourceRange(TemplateLoc, RAngleLoc));
2343
2344 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002345 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002346 RAngleLoc, Converted))
2347 return true;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002348 }
2349
2350 return Invalid;
2351}
2352
2353/// \brief Check a template argument against its corresponding
2354/// template type parameter.
2355///
2356/// This routine implements the semantics of C++ [temp.arg.type]. It
2357/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002358bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002359 TypeSourceInfo *ArgInfo) {
2360 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002361 QualType Arg = ArgInfo->getType();
2362
Douglas Gregorc15cb382009-02-09 23:23:08 +00002363 // C++ [temp.arg.type]p2:
2364 // A local type, a type with no linkage, an unnamed type or a type
2365 // compounded from any of these types shall not be used as a
2366 // template-argument for a template type-parameter.
2367 //
Douglas Gregor0fddb972010-05-22 16:17:30 +00002368 // FIXME: Perform the unnamed type check.
2369 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002370 const TagType *Tag = 0;
John McCall183700f2009-09-21 23:43:11 +00002371 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002372 Tag = EnumT;
Ted Kremenek6217b802009-07-29 21:53:49 +00002373 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregorc15cb382009-02-09 23:23:08 +00002374 Tag = RecordT;
John McCall833ca992009-10-29 08:12:44 +00002375 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnarabd054db2010-05-20 10:00:11 +00002376 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall833ca992009-10-29 08:12:44 +00002377 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2378 << QualType(Tag, 0) << SR;
2379 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor98137532009-03-10 18:33:27 +00002380 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall833ca992009-10-29 08:12:44 +00002381 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002382 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2383 return true;
Douglas Gregor0fddb972010-05-22 16:17:30 +00002384 } else if (Arg->isVariablyModifiedType()) {
2385 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2386 << Arg;
2387 return true;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002388 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002389 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002390 }
2391
2392 return false;
2393}
2394
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002395/// \brief Checks whether the given template argument is the address
2396/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002397static bool
2398CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2399 NonTypeTemplateParmDecl *Param,
2400 QualType ParamType,
2401 Expr *ArgIn,
2402 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002403 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002404 Expr *Arg = ArgIn;
2405 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002406
2407 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002408 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002409 Arg = Cast->getSubExpr();
2410
2411 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002412 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002413 // A template-argument for a non-type, non-template
2414 // template-parameter shall be one of: [...]
2415 //
2416 // -- the address of an object or function with external
2417 // linkage, including function templates and function
2418 // template-ids but excluding non-static class members,
2419 // expressed as & id-expression where the & is optional if
2420 // the name refers to a function or array, or if the
2421 // corresponding template-parameter is a reference; or
2422 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002423
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002424 // Ignore (and complain about) any excess parentheses.
2425 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2426 if (!Invalid) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002427 S.Diag(Arg->getSourceRange().getBegin(),
2428 diag::err_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002429 << Arg->getSourceRange();
2430 Invalid = true;
2431 }
2432
2433 Arg = Parens->getSubExpr();
2434 }
2435
Douglas Gregorb7a09262010-04-01 18:32:35 +00002436 bool AddressTaken = false;
2437 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002438 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002439 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002440 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002441 AddressTaken = true;
2442 AddrOpLoc = UnOp->getOperatorLoc();
2443 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002444 } else
2445 DRE = dyn_cast<DeclRefExpr>(Arg);
2446
Douglas Gregorb7a09262010-04-01 18:32:35 +00002447 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002448 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2449 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002450 S.Diag(Param->getLocation(), diag::note_template_param_here);
2451 return true;
2452 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002453
2454 // Stop checking the precise nature of the argument if it is value dependent,
2455 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002456 if (Arg->isValueDependent()) {
2457 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth038cc392010-01-31 10:01:20 +00002458 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002459 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002460
Douglas Gregorb7a09262010-04-01 18:32:35 +00002461 if (!isa<ValueDecl>(DRE->getDecl())) {
2462 S.Diag(Arg->getSourceRange().getBegin(),
2463 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002464 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002465 S.Diag(Param->getLocation(), diag::note_template_param_here);
2466 return true;
2467 }
2468
2469 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002470
2471 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002472 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2473 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002474 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002475 S.Diag(Param->getLocation(), diag::note_template_param_here);
2476 return true;
2477 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002478
2479 // Cannot refer to non-static member functions
2480 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002481 if (!Method->isStatic()) {
2482 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002483 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002484 S.Diag(Param->getLocation(), diag::note_template_param_here);
2485 return true;
2486 }
Mike Stump1eb44332009-09-09 15:08:12 +00002487
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002488 // Functions must have external linkage.
2489 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002490 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002491 S.Diag(Arg->getSourceRange().getBegin(),
2492 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002493 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002494 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002495 << true;
2496 return true;
2497 }
2498
2499 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002500 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002501
Douglas Gregorb7a09262010-04-01 18:32:35 +00002502 // If the template parameter has pointer type, the function decays.
2503 if (ParamType->isPointerType() && !AddressTaken)
2504 ArgType = S.Context.getPointerType(Func->getType());
2505 else if (AddressTaken && ParamType->isReferenceType()) {
2506 // If we originally had an address-of operator, but the
2507 // parameter has reference type, complain and (if things look
2508 // like they will work) drop the address-of operator.
2509 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2510 ParamType.getNonReferenceType())) {
2511 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2512 << ParamType;
2513 S.Diag(Param->getLocation(), diag::note_template_param_here);
2514 return true;
2515 }
2516
2517 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2518 << ParamType
2519 << FixItHint::CreateRemoval(AddrOpLoc);
2520 S.Diag(Param->getLocation(), diag::note_template_param_here);
2521
2522 ArgType = Func->getType();
2523 }
2524 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002525 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002526 S.Diag(Arg->getSourceRange().getBegin(),
2527 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002528 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002529 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002530 << true;
2531 return true;
2532 }
2533
Douglas Gregorb7a09262010-04-01 18:32:35 +00002534 // A value of reference type is not an object.
2535 if (Var->getType()->isReferenceType()) {
2536 S.Diag(Arg->getSourceRange().getBegin(),
2537 diag::err_template_arg_reference_var)
2538 << Var->getType() << Arg->getSourceRange();
2539 S.Diag(Param->getLocation(), diag::note_template_param_here);
2540 return true;
2541 }
2542
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002543 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002544 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002545
2546 // If the template parameter has pointer type, we must have taken
2547 // the address of this object.
2548 if (ParamType->isReferenceType()) {
2549 if (AddressTaken) {
2550 // If we originally had an address-of operator, but the
2551 // parameter has reference type, complain and (if things look
2552 // like they will work) drop the address-of operator.
2553 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2554 ParamType.getNonReferenceType())) {
2555 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2556 << ParamType;
2557 S.Diag(Param->getLocation(), diag::note_template_param_here);
2558 return true;
2559 }
2560
2561 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2562 << ParamType
2563 << FixItHint::CreateRemoval(AddrOpLoc);
2564 S.Diag(Param->getLocation(), diag::note_template_param_here);
2565
2566 ArgType = Var->getType();
2567 }
2568 } else if (!AddressTaken && ParamType->isPointerType()) {
2569 if (Var->getType()->isArrayType()) {
2570 // Array-to-pointer decay.
2571 ArgType = S.Context.getArrayDecayedType(Var->getType());
2572 } else {
2573 // If the template parameter has pointer type but the address of
2574 // this object was not taken, complain and (possibly) recover by
2575 // taking the address of the entity.
2576 ArgType = S.Context.getPointerType(Var->getType());
2577 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2578 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2579 << ParamType;
2580 S.Diag(Param->getLocation(), diag::note_template_param_here);
2581 return true;
2582 }
2583
2584 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2585 << ParamType
2586 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2587
2588 S.Diag(Param->getLocation(), diag::note_template_param_here);
2589 }
2590 }
2591 } else {
2592 // We found something else, but we don't know specifically what it is.
2593 S.Diag(Arg->getSourceRange().getBegin(),
2594 diag::err_template_arg_not_object_or_func)
2595 << Arg->getSourceRange();
2596 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2597 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002598 }
Mike Stump1eb44332009-09-09 15:08:12 +00002599
Douglas Gregorb7a09262010-04-01 18:32:35 +00002600 if (ParamType->isPointerType() &&
2601 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2602 S.IsQualificationConversion(ArgType, ParamType)) {
2603 // For pointer-to-object types, qualification conversions are
2604 // permitted.
2605 } else {
2606 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2607 if (!ParamRef->getPointeeType()->isFunctionType()) {
2608 // C++ [temp.arg.nontype]p5b3:
2609 // For a non-type template-parameter of type reference to
2610 // object, no conversions apply. The type referred to by the
2611 // reference may be more cv-qualified than the (otherwise
2612 // identical) type of the template- argument. The
2613 // template-parameter is bound directly to the
2614 // template-argument, which shall be an lvalue.
2615
2616 // FIXME: Other qualifiers?
2617 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2618 unsigned ArgQuals = ArgType.getCVRQualifiers();
2619
2620 if ((ParamQuals | ArgQuals) != ParamQuals) {
2621 S.Diag(Arg->getSourceRange().getBegin(),
2622 diag::err_template_arg_ref_bind_ignores_quals)
2623 << ParamType << Arg->getType()
2624 << Arg->getSourceRange();
2625 S.Diag(Param->getLocation(), diag::note_template_param_here);
2626 return true;
2627 }
2628 }
2629 }
2630
2631 // At this point, the template argument refers to an object or
2632 // function with external linkage. We now need to check whether the
2633 // argument and parameter types are compatible.
2634 if (!S.Context.hasSameUnqualifiedType(ArgType,
2635 ParamType.getNonReferenceType())) {
2636 // We can't perform this conversion or binding.
2637 if (ParamType->isReferenceType())
2638 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2639 << ParamType << Arg->getType() << Arg->getSourceRange();
2640 else
2641 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2642 << Arg->getType() << ParamType << Arg->getSourceRange();
2643 S.Diag(Param->getLocation(), diag::note_template_param_here);
2644 return true;
2645 }
2646 }
2647
2648 // Create the template argument.
2649 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00002650 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00002651 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002652}
2653
2654/// \brief Checks whether the given template argument is a pointer to
2655/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002656bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2657 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002658 bool Invalid = false;
2659
2660 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002661 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002662 Arg = Cast->getSubExpr();
2663
2664 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002665 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002666 // A template-argument for a non-type, non-template
2667 // template-parameter shall be one of: [...]
2668 //
2669 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00002670 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002671
2672 // Ignore (and complain about) any excess parentheses.
2673 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2674 if (!Invalid) {
Mike Stump1eb44332009-09-09 15:08:12 +00002675 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002676 diag::err_template_arg_extra_parens)
2677 << Arg->getSourceRange();
2678 Invalid = true;
2679 }
2680
2681 Arg = Parens->getSubExpr();
2682 }
2683
Douglas Gregorcaddba02009-11-12 18:38:13 +00002684 // A pointer-to-member constant written &Class::member.
2685 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00002686 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2687 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2688 if (DRE && !DRE->getQualifier())
2689 DRE = 0;
2690 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00002691 }
2692 // A constant of pointer-to-member type.
2693 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2694 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2695 if (VD->getType()->isMemberPointerType()) {
2696 if (isa<NonTypeTemplateParmDecl>(VD) ||
2697 (isa<VarDecl>(VD) &&
2698 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2699 if (Arg->isTypeDependent() || Arg->isValueDependent())
2700 Converted = TemplateArgument(Arg->Retain());
2701 else
2702 Converted = TemplateArgument(VD->getCanonicalDecl());
2703 return Invalid;
2704 }
2705 }
2706 }
2707
2708 DRE = 0;
2709 }
2710
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002711 if (!DRE)
2712 return Diag(Arg->getSourceRange().getBegin(),
2713 diag::err_template_arg_not_pointer_to_member_form)
2714 << Arg->getSourceRange();
2715
2716 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2717 assert((isa<FieldDecl>(DRE->getDecl()) ||
2718 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2719 "Only non-static member pointers can make it here");
2720
2721 // Okay: this is the address of a non-static member, and therefore
2722 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00002723 if (Arg->isTypeDependent() || Arg->isValueDependent())
2724 Converted = TemplateArgument(Arg->Retain());
2725 else
2726 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002727 return Invalid;
2728 }
2729
2730 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00002731 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002732 diag::err_template_arg_not_pointer_to_member_form)
2733 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002734 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002735 diag::note_template_arg_refers_here);
2736 return true;
2737}
2738
Douglas Gregorc15cb382009-02-09 23:23:08 +00002739/// \brief Check a template argument against its corresponding
2740/// non-type template parameter.
2741///
Douglas Gregor2943aed2009-03-03 04:44:36 +00002742/// This routine implements the semantics of C++ [temp.arg.nontype].
2743/// It returns true if an error occurred, and false otherwise. \p
2744/// InstantiatedParamType is the type of the non-type template
2745/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002746///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002747/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00002748bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00002749 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00002750 TemplateArgument &Converted,
2751 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00002752 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2753
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002754 // If either the parameter has a dependent type or the argument is
2755 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00002756 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2757 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002758 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002759 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00002760 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002761
2762 // C++ [temp.arg.nontype]p5:
2763 // The following conversions are performed on each expression used
2764 // as a non-type template-argument. If a non-type
2765 // template-argument cannot be converted to the type of the
2766 // corresponding template-parameter then the program is
2767 // ill-formed.
2768 //
2769 // -- for a non-type template-parameter of integral or
2770 // enumeration type, integral promotions (4.5) and integral
2771 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002772 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00002773 QualType ArgType = Arg->getType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002774 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002775 // C++ [temp.arg.nontype]p1:
2776 // A template-argument for a non-type, non-template
2777 // template-parameter shall be one of:
2778 //
2779 // -- an integral constant-expression of integral or enumeration
2780 // type; or
2781 // -- the name of a non-type template-parameter; or
2782 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002783 llvm::APSInt Value;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002784 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002785 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002786 diag::err_template_arg_not_integral_or_enumeral)
2787 << ArgType << Arg->getSourceRange();
2788 Diag(Param->getLocation(), diag::note_template_param_here);
2789 return true;
2790 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002791 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002792 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2793 << ArgType << Arg->getSourceRange();
2794 return true;
2795 }
2796
Douglas Gregor02024a92010-03-28 02:42:43 +00002797 // From here on out, all we care about are the unqualified forms
2798 // of the parameter and argument types.
2799 ParamType = ParamType.getUnqualifiedType();
2800 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002801
2802 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00002803 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002804 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00002805 } else if (CTAK == CTAK_Deduced) {
2806 // C++ [temp.deduct.type]p17:
2807 // If, in the declaration of a function template with a non-type
2808 // template-parameter, the non-type template- parameter is used
2809 // in an expression in the function parameter-list and, if the
2810 // corresponding template-argument is deduced, the
2811 // template-argument type shall match the type of the
2812 // template-parameter exactly, except that a template-argument
2813 // deduced from an array bound may be of any integral type.
2814 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2815 << ArgType << ParamType;
2816 Diag(Param->getLocation(), diag::note_template_param_here);
2817 return true;
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002818 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2819 !ParamType->isEnumeralType()) {
2820 // This is an integral promotion or conversion.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002821 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002822 } else {
2823 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002824 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002825 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002826 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002827 Diag(Param->getLocation(), diag::note_template_param_here);
2828 return true;
2829 }
2830
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002831 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00002832 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002833 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002834
2835 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002836 llvm::APSInt OldValue = Value;
2837
2838 // Coerce the template argument's value to the value it will have
2839 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002840 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00002841 if (Value.getBitWidth() != AllowedBits)
2842 Value.extOrTrunc(AllowedBits);
2843 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00002844
2845 // Complain if an unsigned parameter received a negative value.
2846 if (IntegerType->isUnsignedIntegerType()
2847 && (OldValue.isSigned() && OldValue.isNegative())) {
2848 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2849 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2850 << Arg->getSourceRange();
2851 Diag(Param->getLocation(), diag::note_template_param_here);
2852 }
2853
2854 // Complain if we overflowed the template parameter's type.
2855 unsigned RequiredBits;
2856 if (IntegerType->isUnsignedIntegerType())
2857 RequiredBits = OldValue.getActiveBits();
2858 else if (OldValue.isUnsigned())
2859 RequiredBits = OldValue.getActiveBits() + 1;
2860 else
2861 RequiredBits = OldValue.getMinSignedBits();
2862 if (RequiredBits > AllowedBits) {
2863 Diag(Arg->getSourceRange().getBegin(),
2864 diag::warn_template_arg_too_large)
2865 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2866 << Arg->getSourceRange();
2867 Diag(Param->getLocation(), diag::note_template_param_here);
2868 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00002869 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002870
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002871 // Add the value of this argument to the list of converted
2872 // arguments. We use the bitwidth and signedness of the template
2873 // parameter.
2874 if (Arg->isValueDependent()) {
2875 // The argument is value-dependent. Create a new
2876 // TemplateArgument with the converted expression.
2877 Converted = TemplateArgument(Arg);
2878 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002879 }
2880
John McCall833ca992009-10-29 08:12:44 +00002881 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00002882 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00002883 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00002884 return false;
2885 }
Douglas Gregora35284b2009-02-11 00:19:33 +00002886
John McCall6bb80172010-03-30 21:47:33 +00002887 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2888
Douglas Gregorb7a09262010-04-01 18:32:35 +00002889 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2890 // from a template argument of type std::nullptr_t to a non-type
2891 // template parameter of type pointer to object, pointer to
2892 // function, or pointer-to-member, respectively.
2893 if (ArgType->isNullPtrType() &&
2894 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2895 Converted = TemplateArgument((NamedDecl *)0);
2896 return false;
2897 }
2898
Douglas Gregorb86b0572009-02-11 01:18:59 +00002899 // Handle pointer-to-function, reference-to-function, and
2900 // pointer-to-member-function all in (roughly) the same way.
2901 if (// -- For a non-type template-parameter of type pointer to
2902 // function, only the function-to-pointer conversion (4.3) is
2903 // applied. If the template-argument represents a set of
2904 // overloaded functions (or a pointer to such), the matching
2905 // function is selected from the set (13.4).
2906 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002907 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002908 // -- For a non-type template-parameter of type reference to
2909 // function, no conversions apply. If the template-argument
2910 // represents a set of overloaded functions, the matching
2911 // function is selected from the set (13.4).
2912 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002913 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00002914 // -- For a non-type template-parameter of type pointer to
2915 // member function, no conversions apply. If the
2916 // template-argument represents a set of overloaded member
2917 // functions, the matching member function is selected from
2918 // the set (13.4).
2919 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002920 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00002921 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002922
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002923 if (Arg->getType() == Context.OverloadTy) {
2924 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2925 true,
2926 FoundResult)) {
2927 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2928 return true;
2929
2930 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2931 ArgType = Arg->getType();
2932 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002933 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00002934 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002935
Douglas Gregorb7a09262010-04-01 18:32:35 +00002936 if (!ParamType->isMemberPointerType())
2937 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2938 ParamType,
2939 Arg, Converted);
2940
2941 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2942 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2943 Arg->isLvalue(Context) == Expr::LV_Valid);
2944 } else if (!Context.hasSameUnqualifiedType(ArgType,
2945 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00002946 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00002947 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00002948 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00002949 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00002950 Diag(Param->getLocation(), diag::note_template_param_here);
2951 return true;
2952 }
Mike Stump1eb44332009-09-09 15:08:12 +00002953
Douglas Gregorb7a09262010-04-01 18:32:35 +00002954 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00002955 }
2956
Chris Lattnerfe90de72009-02-20 21:37:53 +00002957 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002958 // -- for a non-type template-parameter of type pointer to
2959 // object, qualification conversions (4.4) and the
2960 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002961 // C++0x also allows a value of std::nullptr_t.
Ted Kremenek6217b802009-07-29 21:53:49 +00002962 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002963 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002964
Douglas Gregorb7a09262010-04-01 18:32:35 +00002965 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2966 ParamType,
2967 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002968 }
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Ted Kremenek6217b802009-07-29 21:53:49 +00002970 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00002971 // -- For a non-type template-parameter of type reference to
2972 // object, no conversions apply. The type referred to by the
2973 // reference may be more cv-qualified than the (otherwise
2974 // identical) type of the template-argument. The
2975 // template-parameter is bound directly to the
2976 // template-argument, which must be an lvalue.
Douglas Gregorbad0e652009-03-24 20:32:41 +00002977 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00002978 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00002979
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002980 if (Arg->getType() == Context.OverloadTy) {
2981 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2982 ParamRefType->getPointeeType(),
2983 true,
2984 FoundResult)) {
2985 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2986 return true;
2987
2988 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2989 ArgType = Arg->getType();
2990 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00002991 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00002992 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002993
Douglas Gregorb7a09262010-04-01 18:32:35 +00002994 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2995 ParamType,
2996 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00002997 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00002998
2999 // -- For a non-type template-parameter of type pointer to data
3000 // member, qualification conversions (4.4) are applied.
3001 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3002
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003003 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003004 // Types match exactly: nothing more to do here.
3005 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003006 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
3007 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor658bbb52009-02-11 16:16:59 +00003008 } else {
3009 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003010 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003011 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003012 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003013 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003014 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003015 }
3016
Douglas Gregorcaddba02009-11-12 18:38:13 +00003017 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003018}
3019
3020/// \brief Check a template argument against its corresponding
3021/// template template parameter.
3022///
3023/// This routine implements the semantics of C++ [temp.arg.template].
3024/// It returns true if an error occurred, and false otherwise.
3025bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003026 const TemplateArgumentLoc &Arg) {
3027 TemplateName Name = Arg.getArgument().getAsTemplate();
3028 TemplateDecl *Template = Name.getAsTemplateDecl();
3029 if (!Template) {
3030 // Any dependent template name is fine.
3031 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3032 return false;
3033 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003034
3035 // C++ [temp.arg.template]p1:
3036 // A template-argument for a template template-parameter shall be
3037 // the name of a class template, expressed as id-expression. Only
3038 // primary class templates are considered when matching the
3039 // template template argument with the corresponding parameter;
3040 // partial specializations are not considered even if their
3041 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003042 //
3043 // Note that we also allow template template parameters here, which
3044 // will happen when we are dealing with, e.g., class template
3045 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003046 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003047 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003048 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003049 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003050 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003051 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003052 << Template;
3053 }
3054
3055 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3056 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003057 true,
3058 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003059 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003060}
3061
Douglas Gregor02024a92010-03-28 02:42:43 +00003062/// \brief Given a non-type template argument that refers to a
3063/// declaration and the type of its corresponding non-type template
3064/// parameter, produce an expression that properly refers to that
3065/// declaration.
3066Sema::OwningExprResult
3067Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3068 QualType ParamType,
3069 SourceLocation Loc) {
3070 assert(Arg.getKind() == TemplateArgument::Declaration &&
3071 "Only declaration template arguments permitted here");
3072 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3073
3074 if (VD->getDeclContext()->isRecord() &&
3075 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3076 // If the value is a class member, we might have a pointer-to-member.
3077 // Determine whether the non-type template template parameter is of
3078 // pointer-to-member type. If so, we need to build an appropriate
3079 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3080 // would refer to the member itself.
3081 if (ParamType->isMemberPointerType()) {
3082 QualType ClassType
3083 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3084 NestedNameSpecifier *Qualifier
3085 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3086 CXXScopeSpec SS;
3087 SS.setScopeRep(Qualifier);
3088 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3089 VD->getType().getNonReferenceType(),
3090 Loc,
3091 &SS);
3092 if (RefExpr.isInvalid())
3093 return ExprError();
3094
3095 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorc0c83002010-04-30 21:46:38 +00003096
3097 // We might need to perform a trailing qualification conversion, since
3098 // the element type on the parameter could be more qualified than the
3099 // element type in the expression we constructed.
3100 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3101 ParamType.getUnqualifiedType())) {
3102 Expr *RefE = RefExpr.takeAs<Expr>();
3103 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3104 CastExpr::CK_NoOp);
3105 RefExpr = Owned(RefE);
3106 }
3107
Douglas Gregor02024a92010-03-28 02:42:43 +00003108 assert(!RefExpr.isInvalid() &&
3109 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003110 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003111 return move(RefExpr);
3112 }
3113 }
3114
3115 QualType T = VD->getType().getNonReferenceType();
3116 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003117 // When the non-type template parameter is a pointer, take the
3118 // address of the declaration.
Douglas Gregor02024a92010-03-28 02:42:43 +00003119 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3120 if (RefExpr.isInvalid())
3121 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003122
3123 if (T->isFunctionType() || T->isArrayType()) {
3124 // Decay functions and arrays.
3125 Expr *RefE = (Expr *)RefExpr.get();
3126 DefaultFunctionArrayConversion(RefE);
3127 if (RefE != RefExpr.get()) {
3128 RefExpr.release();
3129 RefExpr = Owned(RefE);
3130 }
3131
3132 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003133 }
3134
Douglas Gregorb7a09262010-04-01 18:32:35 +00003135 // Take the address of everything else
3136 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregor02024a92010-03-28 02:42:43 +00003137 }
3138
3139 // If the non-type template parameter has reference type, qualify the
3140 // resulting declaration reference with the extra qualifiers on the
3141 // type that the reference refers to.
3142 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3143 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3144
3145 return BuildDeclRefExpr(VD, T, Loc);
3146}
3147
3148/// \brief Construct a new expression that refers to the given
3149/// integral template argument with the given source-location
3150/// information.
3151///
3152/// This routine takes care of the mapping from an integral template
3153/// argument (which may have any integral type) to the appropriate
3154/// literal value.
3155Sema::OwningExprResult
3156Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3157 SourceLocation Loc) {
3158 assert(Arg.getKind() == TemplateArgument::Integral &&
3159 "Operation is only value for integral template arguments");
3160 QualType T = Arg.getIntegralType();
3161 if (T->isCharType() || T->isWideCharType())
3162 return Owned(new (Context) CharacterLiteral(
3163 Arg.getAsIntegral()->getZExtValue(),
3164 T->isWideCharType(),
3165 T,
3166 Loc));
3167 if (T->isBooleanType())
3168 return Owned(new (Context) CXXBoolLiteralExpr(
3169 Arg.getAsIntegral()->getBoolValue(),
3170 T,
3171 Loc));
3172
3173 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3174}
3175
3176
Douglas Gregorddc29e12009-02-06 22:42:48 +00003177/// \brief Determine whether the given template parameter lists are
3178/// equivalent.
3179///
Mike Stump1eb44332009-09-09 15:08:12 +00003180/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003181/// source code as part of a new template declaration.
3182///
3183/// \param Old The old template parameter list, typically found via
3184/// name lookup of the template declared with this template parameter
3185/// list.
3186///
3187/// \param Complain If true, this routine will produce a diagnostic if
3188/// the template parameter lists are not equivalent.
3189///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003190/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003191///
3192/// \param TemplateArgLoc If this source location is valid, then we
3193/// are actually checking the template parameter list of a template
3194/// argument (New) against the template parameter list of its
3195/// corresponding template template parameter (Old). We produce
3196/// slightly different diagnostics in this scenario.
3197///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003198/// \returns True if the template parameter lists are equal, false
3199/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003200bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003201Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3202 TemplateParameterList *Old,
3203 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003204 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003205 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003206 if (Old->size() != New->size()) {
3207 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003208 unsigned NextDiag = diag::err_template_param_list_different_arity;
3209 if (TemplateArgLoc.isValid()) {
3210 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3211 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003212 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003213 Diag(New->getTemplateLoc(), NextDiag)
3214 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003215 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003216 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003217 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003218 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003219 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3220 }
3221
3222 return false;
3223 }
3224
3225 for (TemplateParameterList::iterator OldParm = Old->begin(),
3226 OldParmEnd = Old->end(), NewParm = New->begin();
3227 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3228 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003229 if (Complain) {
3230 unsigned NextDiag = diag::err_template_param_different_kind;
3231 if (TemplateArgLoc.isValid()) {
3232 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3233 NextDiag = diag::note_template_param_different_kind;
3234 }
3235 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003236 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003237 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003238 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003239 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003240 return false;
3241 }
3242
Douglas Gregora417b872010-06-04 08:34:32 +00003243 if (TemplateTypeParmDecl *OldTTP
3244 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3245 // Template type parameters are equivalent if either both are template
3246 // type parameter packs or neither are (since we know we're at the same
3247 // index).
3248 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3249 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3250 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3251 // allow one to match a template parameter pack in the template
3252 // parameter list of a template template parameter to one or more
3253 // template parameters in the template parameter list of the
3254 // corresponding template template argument.
3255 if (Complain) {
3256 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3257 if (TemplateArgLoc.isValid()) {
3258 Diag(TemplateArgLoc,
3259 diag::err_template_arg_template_params_mismatch);
3260 NextDiag = diag::note_template_parameter_pack_non_pack;
3261 }
3262 Diag(NewTTP->getLocation(), NextDiag)
3263 << 0 << NewTTP->isParameterPack();
3264 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3265 << 0 << OldTTP->isParameterPack();
3266 }
3267 return false;
3268 }
Mike Stump1eb44332009-09-09 15:08:12 +00003269 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003270 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3271 // The types of non-type template parameters must agree.
3272 NonTypeTemplateParmDecl *NewNTTP
3273 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003274
3275 // If we are matching a template template argument to a template
3276 // template parameter and one of the non-type template parameter types
3277 // is dependent, then we must wait until template instantiation time
3278 // to actually compare the arguments.
3279 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3280 (OldNTTP->getType()->isDependentType() ||
3281 NewNTTP->getType()->isDependentType()))
3282 continue;
3283
Douglas Gregorddc29e12009-02-06 22:42:48 +00003284 if (Context.getCanonicalType(OldNTTP->getType()) !=
3285 Context.getCanonicalType(NewNTTP->getType())) {
3286 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003287 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3288 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003289 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003290 diag::err_template_arg_template_params_mismatch);
3291 NextDiag = diag::note_template_nontype_parm_different_type;
3292 }
3293 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003294 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003295 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003296 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003297 diag::note_template_nontype_parm_prev_declaration)
3298 << OldNTTP->getType();
3299 }
3300 return false;
3301 }
3302 } else {
3303 // The template parameter lists of template template
3304 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003305 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003306 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003307 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003308 = cast<TemplateTemplateParmDecl>(*OldParm);
3309 TemplateTemplateParmDecl *NewTTP
3310 = cast<TemplateTemplateParmDecl>(*NewParm);
3311 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3312 OldTTP->getTemplateParameters(),
3313 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003314 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003315 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003316 return false;
3317 }
3318 }
3319
3320 return true;
3321}
3322
3323/// \brief Check whether a template can be declared within this scope.
3324///
3325/// If the template declaration is valid in this scope, returns
3326/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003327bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003328Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003329 // Find the nearest enclosing declaration scope.
3330 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3331 (S->getFlags() & Scope::TemplateParamScope) != 0)
3332 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003333
Douglas Gregorddc29e12009-02-06 22:42:48 +00003334 // C++ [temp]p2:
3335 // A template-declaration can appear only as a namespace scope or
3336 // class scope declaration.
3337 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003338 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3339 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003340 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003341 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003342
Eli Friedman1503f772009-07-31 01:43:05 +00003343 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003344 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003345
3346 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3347 return false;
3348
Mike Stump1eb44332009-09-09 15:08:12 +00003349 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003350 diag::err_template_outside_namespace_or_class_scope)
3351 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003352}
Douglas Gregorcc636682009-02-17 23:15:12 +00003353
Douglas Gregord5cb8762009-10-07 00:13:32 +00003354/// \brief Determine what kind of template specialization the given declaration
3355/// is.
3356static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3357 if (!D)
3358 return TSK_Undeclared;
3359
Douglas Gregorf6b11852009-10-08 15:14:33 +00003360 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3361 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003362 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3363 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003364 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3365 return Var->getTemplateSpecializationKind();
3366
Douglas Gregord5cb8762009-10-07 00:13:32 +00003367 return TSK_Undeclared;
3368}
3369
Douglas Gregor9302da62009-10-14 23:50:59 +00003370/// \brief Check whether a specialization is well-formed in the current
3371/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003372///
Douglas Gregor9302da62009-10-14 23:50:59 +00003373/// This routine determines whether a template specialization can be declared
3374/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003375///
3376/// \param S the semantic analysis object for which this check is being
3377/// performed.
3378///
3379/// \param Specialized the entity being specialized or instantiated, which
3380/// may be a kind of template (class template, function template, etc.) or
3381/// a member of a class template (member function, static data member,
3382/// member class).
3383///
3384/// \param PrevDecl the previous declaration of this entity, if any.
3385///
3386/// \param Loc the location of the explicit specialization or instantiation of
3387/// this entity.
3388///
3389/// \param IsPartialSpecialization whether this is a partial specialization of
3390/// a class template.
3391///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003392/// \returns true if there was an error that we cannot recover from, false
3393/// otherwise.
3394static bool CheckTemplateSpecializationScope(Sema &S,
3395 NamedDecl *Specialized,
3396 NamedDecl *PrevDecl,
3397 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003398 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003399 // Keep these "kind" numbers in sync with the %select statements in the
3400 // various diagnostics emitted by this routine.
3401 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003402 bool isTemplateSpecialization = false;
3403 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003404 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003405 isTemplateSpecialization = true;
3406 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003407 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003408 isTemplateSpecialization = true;
3409 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003410 EntityKind = 3;
3411 else if (isa<VarDecl>(Specialized))
3412 EntityKind = 4;
3413 else if (isa<RecordDecl>(Specialized))
3414 EntityKind = 5;
3415 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003416 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3417 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003418 return true;
3419 }
3420
Douglas Gregor88b70942009-02-25 22:02:03 +00003421 // C++ [temp.expl.spec]p2:
3422 // An explicit specialization shall be declared in the namespace
3423 // of which the template is a member, or, for member templates, in
3424 // the namespace of which the enclosing class or enclosing class
3425 // template is a member. An explicit specialization of a member
3426 // function, member class or static data member of a class
3427 // template shall be declared in the namespace of which the class
3428 // template is a member. Such a declaration may also be a
3429 // definition. If the declaration is not a definition, the
3430 // specialization may be defined later in the name- space in which
3431 // the explicit specialization was declared, or in a namespace
3432 // that encloses the one in which the explicit specialization was
3433 // declared.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003434 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3435 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003436 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003437 return true;
3438 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003439
Douglas Gregor0a407472009-10-07 17:30:37 +00003440 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3441 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003442 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003443 return true;
3444 }
3445
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003446 // C++ [temp.class.spec]p6:
3447 // A class template partial specialization may be declared or redeclared
3448 // in any namespace scope in which its definition may be defined (14.5.1
3449 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003450 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003451 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003452 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003453 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003454 if ((!PrevDecl ||
3455 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3456 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3457 // There is no prior declaration of this entity, so this
3458 // specialization must be in the same context as the template
3459 // itself.
3460 if (!DC->Equals(SpecializedContext)) {
3461 if (isa<TranslationUnitDecl>(SpecializedContext))
3462 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3463 << EntityKind << Specialized;
3464 else if (isa<NamespaceDecl>(SpecializedContext))
3465 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3466 << EntityKind << Specialized
3467 << cast<NamedDecl>(SpecializedContext);
3468
3469 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3470 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003471 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003472 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003473
3474 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003475 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003476 // Note that HandleDeclarator() performs this check for explicit
3477 // specializations of function templates, static data members, and member
3478 // functions, so we skip the check here for those kinds of entities.
3479 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003480 // Should we refactor that check, so that it occurs later?
3481 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003482 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3483 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003484 if (isa<TranslationUnitDecl>(SpecializedContext))
3485 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3486 << EntityKind << Specialized;
3487 else if (isa<NamespaceDecl>(SpecializedContext))
3488 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3489 << EntityKind << Specialized
3490 << cast<NamedDecl>(SpecializedContext);
3491
Douglas Gregor9302da62009-10-14 23:50:59 +00003492 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003493 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003494
3495 // FIXME: check for specialization-after-instantiation errors and such.
3496
Douglas Gregor88b70942009-02-25 22:02:03 +00003497 return false;
3498}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003499
Douglas Gregore94866f2009-06-12 21:21:02 +00003500/// \brief Check the non-type template arguments of a class template
3501/// partial specialization according to C++ [temp.class.spec]p9.
3502///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003503/// \param TemplateParams the template parameters of the primary class
3504/// template.
3505///
3506/// \param TemplateArg the template arguments of the class template
3507/// partial specialization.
3508///
3509/// \param MirrorsPrimaryTemplate will be set true if the class
3510/// template partial specialization arguments are identical to the
3511/// implicit template arguments of the primary template. This is not
3512/// necessarily an error (C++0x), and it is left to the caller to diagnose
3513/// this condition when it is an error.
3514///
Douglas Gregore94866f2009-06-12 21:21:02 +00003515/// \returns true if there was an error, false otherwise.
3516bool Sema::CheckClassTemplatePartialSpecializationArgs(
3517 TemplateParameterList *TemplateParams,
Anders Carlsson6360be72009-06-13 18:20:51 +00003518 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003519 bool &MirrorsPrimaryTemplate) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003520 // FIXME: the interface to this function will have to change to
3521 // accommodate variadic templates.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003522 MirrorsPrimaryTemplate = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003523
Anders Carlssonfb250522009-06-23 01:26:57 +00003524 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Douglas Gregore94866f2009-06-12 21:21:02 +00003526 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003527 // Determine whether the template argument list of the partial
3528 // specialization is identical to the implicit argument list of
3529 // the primary template. The caller may need to diagnostic this as
3530 // an error per C++ [temp.class.spec]p9b3.
3531 if (MirrorsPrimaryTemplate) {
Mike Stump1eb44332009-09-09 15:08:12 +00003532 if (TemplateTypeParmDecl *TTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003533 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3534 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson6360be72009-06-13 18:20:51 +00003535 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003536 MirrorsPrimaryTemplate = false;
3537 } else if (TemplateTemplateParmDecl *TTP
3538 = dyn_cast<TemplateTemplateParmDecl>(
3539 TemplateParams->getParam(I))) {
Douglas Gregor788cd062009-11-11 01:00:40 +00003540 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump1eb44332009-09-09 15:08:12 +00003541 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor788cd062009-11-11 01:00:40 +00003542 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003543 if (!ArgDecl ||
3544 ArgDecl->getIndex() != TTP->getIndex() ||
3545 ArgDecl->getDepth() != TTP->getDepth())
3546 MirrorsPrimaryTemplate = false;
3547 }
3548 }
3549
Mike Stump1eb44332009-09-09 15:08:12 +00003550 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003551 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003552 if (!Param) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003553 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003554 }
3555
Anders Carlsson6360be72009-06-13 18:20:51 +00003556 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003557 if (!ArgExpr) {
3558 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003559 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003560 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003561
3562 // C++ [temp.class.spec]p8:
3563 // A non-type argument is non-specialized if it is the name of a
3564 // non-type parameter. All other non-type arguments are
3565 // specialized.
3566 //
3567 // Below, we check the two conditions that only apply to
3568 // specialized non-type arguments, so skip any non-specialized
3569 // arguments.
3570 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump1eb44332009-09-09 15:08:12 +00003571 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003572 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003573 if (MirrorsPrimaryTemplate &&
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003574 (Param->getIndex() != NTTP->getIndex() ||
3575 Param->getDepth() != NTTP->getDepth()))
3576 MirrorsPrimaryTemplate = false;
3577
Douglas Gregore94866f2009-06-12 21:21:02 +00003578 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003579 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003580
3581 // C++ [temp.class.spec]p9:
3582 // Within the argument list of a class template partial
3583 // specialization, the following restrictions apply:
3584 // -- A partially specialized non-type argument expression
3585 // shall not involve a template parameter of the partial
3586 // specialization except when the argument expression is a
3587 // simple identifier.
3588 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003589 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003590 diag::err_dependent_non_type_arg_in_partial_spec)
3591 << ArgExpr->getSourceRange();
3592 return true;
3593 }
3594
3595 // -- The type of a template parameter corresponding to a
3596 // specialized non-type argument shall not be dependent on a
3597 // parameter of the specialization.
3598 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003599 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003600 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3601 << Param->getType()
3602 << ArgExpr->getSourceRange();
3603 Diag(Param->getLocation(), diag::note_template_param_here);
3604 return true;
3605 }
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003606
3607 MirrorsPrimaryTemplate = false;
Douglas Gregore94866f2009-06-12 21:21:02 +00003608 }
3609
3610 return false;
3611}
3612
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003613/// \brief Retrieve the previous declaration of the given declaration.
3614static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3615 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3616 return VD->getPreviousDeclaration();
3617 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3618 return FD->getPreviousDeclaration();
3619 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3620 return TD->getPreviousDeclaration();
3621 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3622 return TD->getPreviousDeclaration();
3623 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3624 return FTD->getPreviousDeclaration();
3625 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3626 return CTD->getPreviousDeclaration();
3627 return 0;
3628}
3629
Douglas Gregor212e81c2009-03-25 00:13:59 +00003630Sema::DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003631Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3632 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00003633 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00003634 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00003635 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00003636 SourceLocation TemplateNameLoc,
3637 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00003638 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00003639 SourceLocation RAngleLoc,
3640 AttributeList *Attr,
3641 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003642 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00003643
Douglas Gregorcc636682009-02-17 23:15:12 +00003644 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00003645 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00003646 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00003647 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3648
3649 if (!ClassTemplate) {
3650 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3651 << (Name.getAsTemplateDecl() &&
3652 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3653 return true;
3654 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003655
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003656 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003657 bool isPartialSpecialization = false;
3658
Douglas Gregor88b70942009-02-25 22:02:03 +00003659 // Check the validity of the template headers that introduce this
3660 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003661 // FIXME: We probably shouldn't complain about these headers for
3662 // friend declarations.
Douglas Gregor05396e22009-08-25 17:23:04 +00003663 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00003664 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3665 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003666 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00003667 TUK == TUK_Friend,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003668 isExplicitSpecialization);
Abramo Bagnara9b934882010-06-12 08:15:14 +00003669 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3670 if (TemplateParams)
3671 --NumMatchedTemplateParamLists;
3672
Douglas Gregor05396e22009-08-25 17:23:04 +00003673 if (TemplateParams && TemplateParams->size() > 0) {
3674 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003675
Douglas Gregor05396e22009-08-25 17:23:04 +00003676 // C++ [temp.class.spec]p10:
3677 // The template parameter list of a specialization shall not
3678 // contain default template argument values.
3679 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3680 Decl *Param = TemplateParams->getParam(I);
3681 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3682 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003683 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003684 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00003685 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003686 }
3687 } else if (NonTypeTemplateParmDecl *NTTP
3688 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3689 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003690 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003691 diag::err_default_arg_in_partial_spec)
3692 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003693 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00003694 DefArg->Destroy(Context);
3695 }
3696 } else {
3697 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00003698 if (TTP->hasDefaultArgument()) {
3699 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003700 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00003701 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00003702 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003703 }
3704 }
3705 }
Douglas Gregora735b202009-10-13 14:39:41 +00003706 } else if (TemplateParams) {
3707 if (TUK == TUK_Friend)
3708 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00003709 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00003710 SourceRange(TemplateParams->getTemplateLoc(),
3711 TemplateParams->getRAngleLoc()))
3712 << SourceRange(LAngleLoc, RAngleLoc);
3713 else
3714 isExplicitSpecialization = true;
3715 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00003716 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00003717 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003718 isExplicitSpecialization = true;
3719 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003720
Douglas Gregorcc636682009-02-17 23:15:12 +00003721 // Check that the specialization uses the same tag kind as the
3722 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003723 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3724 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003725 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00003726 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00003727 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00003728 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00003729 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00003730 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00003731 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00003732 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00003733 diag::note_previous_use);
3734 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3735 }
3736
Douglas Gregor40808ce2009-03-09 23:48:35 +00003737 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00003738 TemplateArgumentListInfo TemplateArgs;
3739 TemplateArgs.setLAngleLoc(LAngleLoc);
3740 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00003741 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00003742
Douglas Gregorcc636682009-02-17 23:15:12 +00003743 // Check that the template argument list is well-formed for this
3744 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00003745 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3746 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00003747 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3748 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003749 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003750
Mike Stump1eb44332009-09-09 15:08:12 +00003751 assert((Converted.structuredSize() ==
Douglas Gregorcc636682009-02-17 23:15:12 +00003752 ClassTemplate->getTemplateParameters()->size()) &&
3753 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00003754
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003755 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00003756 // corresponds to these arguments.
3757 llvm::FoldingSetNodeID ID;
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003758 if (isPartialSpecialization) {
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003759 bool MirrorsPrimaryTemplate;
Douglas Gregore94866f2009-06-12 21:21:02 +00003760 if (CheckClassTemplatePartialSpecializationArgs(
3761 ClassTemplate->getTemplateParameters(),
Anders Carlssonfb250522009-06-23 01:26:57 +00003762 Converted, MirrorsPrimaryTemplate))
Douglas Gregore94866f2009-06-12 21:21:02 +00003763 return true;
3764
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003765 if (MirrorsPrimaryTemplate) {
3766 // C++ [temp.class.spec]p9b3:
3767 //
Mike Stump1eb44332009-09-09 15:08:12 +00003768 // -- The argument list of the specialization shall not be identical
3769 // to the implicit argument list of the primary template.
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003770 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall0f434ec2009-07-31 02:45:11 +00003771 << (TUK == TUK_Definition)
Douglas Gregor849b2432010-03-31 17:46:05 +00003772 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall0f434ec2009-07-31 02:45:11 +00003773 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003774 ClassTemplate->getIdentifier(),
3775 TemplateNameLoc,
3776 Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +00003777 TemplateParams,
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003778 AS_none);
3779 }
3780
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003781 // FIXME: Diagnose friend partial specializations
3782
Douglas Gregorde090962010-02-09 00:37:32 +00003783 if (!Name.isDependent() &&
3784 !TemplateSpecializationType::anyDependentTemplateArguments(
3785 TemplateArgs.getArgumentArray(),
3786 TemplateArgs.size())) {
3787 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3788 << ClassTemplate->getDeclName();
3789 isPartialSpecialization = false;
3790 } else {
3791 // FIXME: Template parameter list matters, too
3792 ClassTemplatePartialSpecializationDecl::Profile(ID,
3793 Converted.getFlatArguments(),
3794 Converted.flatSize(),
3795 Context);
3796 }
3797 }
3798
3799 if (!isPartialSpecialization)
Anders Carlsson1c5976e2009-06-05 03:43:12 +00003800 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00003801 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00003802 Converted.flatSize(),
3803 Context);
Douglas Gregorcc636682009-02-17 23:15:12 +00003804 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003805 ClassTemplateSpecializationDecl *PrevDecl = 0;
3806
3807 if (isPartialSpecialization)
3808 PrevDecl
Mike Stump1eb44332009-09-09 15:08:12 +00003809 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003810 InsertPos);
3811 else
3812 PrevDecl
3813 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00003814
3815 ClassTemplateSpecializationDecl *Specialization = 0;
3816
Douglas Gregor88b70942009-02-25 22:02:03 +00003817 // Check whether we can declare a class template specialization in
3818 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003819 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00003820 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00003821 TemplateNameLoc,
3822 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00003823 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003824
Douglas Gregorb88e8882009-07-30 17:40:51 +00003825 // The canonical type
3826 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003827 if (PrevDecl &&
3828 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00003829 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003830 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003831 // arguments was referenced but not declared, or we're only
3832 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00003833 // declaration node as our own, updating its source location to
3834 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003835 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00003836 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00003837 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00003838 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003839 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00003840 // Build the canonical type that describes the converted template
3841 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00003842 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3843 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb88e8882009-07-30 17:40:51 +00003844 Converted.getFlatArguments(),
3845 Converted.flatSize());
3846
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003847 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003848 ClassTemplatePartialSpecializationDecl *PrevPartial
3849 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003850 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3851 : ClassTemplate->getPartialSpecializations().size();
Mike Stump1eb44332009-09-09 15:08:12 +00003852 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00003853 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003854 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00003855 TemplateNameLoc,
3856 TemplateParams,
3857 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003858 Converted,
John McCalld5532b62009-11-23 01:53:49 +00003859 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00003860 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00003861 PrevPartial,
3862 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00003863 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnara9b934882010-06-12 08:15:14 +00003864 if (NumMatchedTemplateParamLists > 0) {
3865 Partial->setTemplateParameterListsInfo(NumMatchedTemplateParamLists,
3866 (TemplateParameterList**) TemplateParameterLists.release());
3867 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003868
3869 if (PrevPartial) {
3870 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3871 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3872 } else {
3873 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3874 }
3875 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00003876
Douglas Gregored9c0f92009-10-29 00:04:11 +00003877 // If we are providing an explicit specialization of a member class
3878 // template specialization, make a note of that.
3879 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3880 PrevPartial->setMemberSpecialization();
3881
Douglas Gregor031a5882009-06-13 00:26:55 +00003882 // Check that all of the template parameters of the class template
3883 // partial specialization are deducible from the template
3884 // arguments. If not, this class template partial specialization
3885 // will never be used.
3886 llvm::SmallVector<bool, 8> DeducibleParams;
3887 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00003888 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00003889 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00003890 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00003891 unsigned NumNonDeducible = 0;
3892 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3893 if (!DeducibleParams[I])
3894 ++NumNonDeducible;
3895
3896 if (NumNonDeducible) {
3897 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3898 << (NumNonDeducible > 1)
3899 << SourceRange(TemplateNameLoc, RAngleLoc);
3900 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3901 if (!DeducibleParams[I]) {
3902 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3903 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00003904 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003905 diag::note_partial_spec_unused_parameter)
3906 << Param->getDeclName();
3907 else
Mike Stump1eb44332009-09-09 15:08:12 +00003908 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00003909 diag::note_partial_spec_unused_parameter)
3910 << std::string("<anonymous>");
3911 }
3912 }
3913 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003914 } else {
3915 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003916 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00003917 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00003918 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00003919 ClassTemplate->getDeclContext(),
3920 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00003921 ClassTemplate,
Anders Carlssonfb250522009-06-23 01:26:57 +00003922 Converted,
Douglas Gregorcc636682009-02-17 23:15:12 +00003923 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00003924 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnara9b934882010-06-12 08:15:14 +00003925 if (NumMatchedTemplateParamLists > 0) {
3926 Specialization->setTemplateParameterListsInfo(
3927 NumMatchedTemplateParamLists,
3928 (TemplateParameterList**) TemplateParameterLists.release());
3929 }
Douglas Gregorcc636682009-02-17 23:15:12 +00003930
3931 if (PrevDecl) {
3932 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3933 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3934 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003935 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregorcc636682009-02-17 23:15:12 +00003936 InsertPos);
3937 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00003938
3939 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003940 }
3941
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003942 // C++ [temp.expl.spec]p6:
3943 // If a template, a member template or the member of a class template is
3944 // explicitly specialized then that specialization shall be declared
3945 // before the first use of that specialization that would cause an implicit
3946 // instantiation to take place, in every translation unit in which such a
3947 // use occurs; no diagnostic is required.
3948 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003949 bool Okay = false;
3950 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3951 // Is there any previous explicit specialization declaration?
3952 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3953 Okay = true;
3954 break;
3955 }
3956 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003957
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003958 if (!Okay) {
3959 SourceRange Range(TemplateNameLoc, RAngleLoc);
3960 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3961 << Context.getTypeDeclType(Specialization) << Range;
3962
3963 Diag(PrevDecl->getPointOfInstantiation(),
3964 diag::note_instantiation_required_here)
3965 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003966 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003967 return true;
3968 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00003969 }
3970
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003971 // If this is not a friend, note that this is an explicit specialization.
3972 if (TUK != TUK_Friend)
3973 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00003974
3975 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00003976 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00003977 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00003978 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00003979 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00003980 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00003981 Diag(Def->getLocation(), diag::note_previous_definition);
3982 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00003983 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00003984 }
3985 }
3986
Douglas Gregorfc705b82009-02-26 22:19:44 +00003987 // Build the fully-sugared type for this class template
3988 // specialization as the user wrote in the specialization
3989 // itself. This means that we'll pretty-print the type retrieved
3990 // from the specialization's declaration the way that the user
3991 // actually wrote the specialization, rather than formatting the
3992 // name based on the "canonical" representation used to store the
3993 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00003994 TypeSourceInfo *WrittenTy
3995 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3996 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00003997 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00003998 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00003999 Specialization->setTemplateKeywordLoc(KWLoc);
4000 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004001 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004002
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004003 // C++ [temp.expl.spec]p9:
4004 // A template explicit specialization is in the scope of the
4005 // namespace in which the template was defined.
4006 //
4007 // We actually implement this paragraph where we set the semantic
4008 // context (in the creation of the ClassTemplateSpecializationDecl),
4009 // but we also maintain the lexical context where the actual
4010 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004011 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004012
Douglas Gregorcc636682009-02-17 23:15:12 +00004013 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004014 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004015 Specialization->startDefinition();
4016
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004017 if (TUK == TUK_Friend) {
4018 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4019 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004020 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004021 /*FIXME:*/KWLoc);
4022 Friend->setAccess(AS_public);
4023 CurContext->addDecl(Friend);
4024 } else {
4025 // Add the specialization into its lexical context, so that it can
4026 // be seen when iterating through the list of declarations in that
4027 // context. However, specializations are not found by name lookup.
4028 CurContext->addDecl(Specialization);
4029 }
Chris Lattnerb28317a2009-03-28 19:18:32 +00004030 return DeclPtrTy::make(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004031}
Douglas Gregord57959a2009-03-27 23:10:48 +00004032
Mike Stump1eb44332009-09-09 15:08:12 +00004033Sema::DeclPtrTy
4034Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004035 MultiTemplateParamsArg TemplateParameterLists,
4036 Declarator &D) {
4037 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4038}
4039
Mike Stump1eb44332009-09-09 15:08:12 +00004040Sema::DeclPtrTy
4041Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004042 MultiTemplateParamsArg TemplateParameterLists,
4043 Declarator &D) {
4044 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4045 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4046 "Not a function declarator!");
4047 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump1eb44332009-09-09 15:08:12 +00004048
Douglas Gregor52591bf2009-06-24 00:54:41 +00004049 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004050 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004051 }
Mike Stump1eb44332009-09-09 15:08:12 +00004052
Douglas Gregor52591bf2009-06-24 00:54:41 +00004053 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004054
4055 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004056 move(TemplateParameterLists),
4057 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004058 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004059 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump1eb44332009-09-09 15:08:12 +00004060 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregore53060f2009-06-25 22:08:12 +00004061 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregorf59a56e2009-07-21 23:53:31 +00004062 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4063 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregore53060f2009-06-25 22:08:12 +00004064 return DeclPtrTy();
Douglas Gregor52591bf2009-06-24 00:54:41 +00004065}
4066
John McCall75042392010-02-11 01:33:53 +00004067/// \brief Strips various properties off an implicit instantiation
4068/// that has just been explicitly specialized.
4069static void StripImplicitInstantiation(NamedDecl *D) {
4070 D->invalidateAttrs();
4071
4072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4073 FD->setInlineSpecified(false);
4074 }
4075}
4076
Douglas Gregor454885e2009-10-15 15:54:05 +00004077/// \brief Diagnose cases where we have an explicit template specialization
4078/// before/after an explicit template instantiation, producing diagnostics
4079/// for those cases where they are required and determining whether the
4080/// new specialization/instantiation will have any effect.
4081///
Douglas Gregor454885e2009-10-15 15:54:05 +00004082/// \param NewLoc the location of the new explicit specialization or
4083/// instantiation.
4084///
4085/// \param NewTSK the kind of the new explicit specialization or instantiation.
4086///
4087/// \param PrevDecl the previous declaration of the entity.
4088///
4089/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4090///
4091/// \param PrevPointOfInstantiation if valid, indicates where the previus
4092/// declaration was instantiated (either implicitly or explicitly).
4093///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004094/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004095/// specialization or instantiation has no effect and should be ignored.
4096///
4097/// \returns true if there was an error that should prevent the introduction of
4098/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004099bool
4100Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4101 TemplateSpecializationKind NewTSK,
4102 NamedDecl *PrevDecl,
4103 TemplateSpecializationKind PrevTSK,
4104 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004105 bool &HasNoEffect) {
4106 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004107
4108 switch (NewTSK) {
4109 case TSK_Undeclared:
4110 case TSK_ImplicitInstantiation:
4111 assert(false && "Don't check implicit instantiations here");
4112 return false;
4113
4114 case TSK_ExplicitSpecialization:
4115 switch (PrevTSK) {
4116 case TSK_Undeclared:
4117 case TSK_ExplicitSpecialization:
4118 // Okay, we're just specializing something that is either already
4119 // explicitly specialized or has merely been mentioned without any
4120 // instantiation.
4121 return false;
4122
4123 case TSK_ImplicitInstantiation:
4124 if (PrevPointOfInstantiation.isInvalid()) {
4125 // The declaration itself has not actually been instantiated, so it is
4126 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004127 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004128 return false;
4129 }
4130 // Fall through
4131
4132 case TSK_ExplicitInstantiationDeclaration:
4133 case TSK_ExplicitInstantiationDefinition:
4134 assert((PrevTSK == TSK_ImplicitInstantiation ||
4135 PrevPointOfInstantiation.isValid()) &&
4136 "Explicit instantiation without point of instantiation?");
4137
4138 // C++ [temp.expl.spec]p6:
4139 // If a template, a member template or the member of a class template
4140 // is explicitly specialized then that specialization shall be declared
4141 // before the first use of that specialization that would cause an
4142 // implicit instantiation to take place, in every translation unit in
4143 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004144 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4145 // Is there any previous explicit specialization declaration?
4146 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4147 return false;
4148 }
4149
Douglas Gregor0d035142009-10-27 18:42:08 +00004150 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004151 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004152 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004153 << (PrevTSK != TSK_ImplicitInstantiation);
4154
4155 return true;
4156 }
4157 break;
4158
4159 case TSK_ExplicitInstantiationDeclaration:
4160 switch (PrevTSK) {
4161 case TSK_ExplicitInstantiationDeclaration:
4162 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004163 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004164 return false;
4165
4166 case TSK_Undeclared:
4167 case TSK_ImplicitInstantiation:
4168 // We're explicitly instantiating something that may have already been
4169 // implicitly instantiated; that's fine.
4170 return false;
4171
4172 case TSK_ExplicitSpecialization:
4173 // C++0x [temp.explicit]p4:
4174 // For a given set of template parameters, if an explicit instantiation
4175 // of a template appears after a declaration of an explicit
4176 // specialization for that template, the explicit instantiation has no
4177 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004178 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004179 return false;
4180
4181 case TSK_ExplicitInstantiationDefinition:
4182 // C++0x [temp.explicit]p10:
4183 // If an entity is the subject of both an explicit instantiation
4184 // declaration and an explicit instantiation definition in the same
4185 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004186 Diag(NewLoc,
4187 diag::err_explicit_instantiation_declaration_after_definition);
4188 Diag(PrevPointOfInstantiation,
4189 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004190 assert(PrevPointOfInstantiation.isValid() &&
4191 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004192 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004193 return false;
4194 }
4195 break;
4196
4197 case TSK_ExplicitInstantiationDefinition:
4198 switch (PrevTSK) {
4199 case TSK_Undeclared:
4200 case TSK_ImplicitInstantiation:
4201 // We're explicitly instantiating something that may have already been
4202 // implicitly instantiated; that's fine.
4203 return false;
4204
4205 case TSK_ExplicitSpecialization:
4206 // C++ DR 259, C++0x [temp.explicit]p4:
4207 // For a given set of template parameters, if an explicit
4208 // instantiation of a template appears after a declaration of
4209 // an explicit specialization for that template, the explicit
4210 // instantiation has no effect.
4211 //
4212 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004213 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004214 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004215 if (!getLangOptions().CPlusPlus0x) {
4216 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004217 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004218 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004219 diag::note_previous_template_specialization);
4220 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004221 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004222 return false;
4223
4224 case TSK_ExplicitInstantiationDeclaration:
4225 // We're explicity instantiating a definition for something for which we
4226 // were previously asked to suppress instantiations. That's fine.
4227 return false;
4228
4229 case TSK_ExplicitInstantiationDefinition:
4230 // C++0x [temp.spec]p5:
4231 // For a given template and a given set of template-arguments,
4232 // - an explicit instantiation definition shall appear at most once
4233 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004234 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004235 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004236 Diag(PrevPointOfInstantiation,
4237 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004238 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004239 return false;
4240 }
4241 break;
4242 }
4243
4244 assert(false && "Missing specialization/instantiation case?");
4245
4246 return false;
4247}
4248
John McCallaf2094e2010-04-08 09:05:18 +00004249/// \brief Perform semantic analysis for the given dependent function
4250/// template specialization. The only possible way to get a dependent
4251/// function template specialization is with a friend declaration,
4252/// like so:
4253///
4254/// template <class T> void foo(T);
4255/// template <class T> class A {
4256/// friend void foo<>(T);
4257/// };
4258///
4259/// There really isn't any useful analysis we can do here, so we
4260/// just store the information.
4261bool
4262Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4263 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4264 LookupResult &Previous) {
4265 // Remove anything from Previous that isn't a function template in
4266 // the correct context.
4267 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4268 LookupResult::Filter F = Previous.makeFilter();
4269 while (F.hasNext()) {
4270 NamedDecl *D = F.next()->getUnderlyingDecl();
4271 if (!isa<FunctionTemplateDecl>(D) ||
4272 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4273 F.erase();
4274 }
4275 F.done();
4276
4277 // Should this be diagnosed here?
4278 if (Previous.empty()) return true;
4279
4280 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4281 ExplicitTemplateArgs);
4282 return false;
4283}
4284
Abramo Bagnarae03db982010-05-20 15:32:11 +00004285/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004286/// specialization.
4287///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004288/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004289/// explicit function template specialization. On successful completion,
4290/// the function declaration \p FD will become a function template
4291/// specialization.
4292///
4293/// \param FD the function declaration, which will be updated to become a
4294/// function template specialization.
4295///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004296/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4297/// if any. Note that this may be valid info even when 0 arguments are
4298/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4299/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004300///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004301/// \param PrevDecl the set of declarations that may be specialized by
4302/// this function specialization.
4303bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004304Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004305 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004306 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004307 // The set of function template specializations that could match this
4308 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004309 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004310
4311 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall68263142009-11-18 22:49:29 +00004312 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4313 I != E; ++I) {
4314 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4315 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004316 // Only consider templates found within the same semantic lookup scope as
4317 // FD.
4318 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4319 continue;
4320
4321 // C++ [temp.expl.spec]p11:
4322 // A trailing template-argument can be left unspecified in the
4323 // template-id naming an explicit function template specialization
4324 // provided it can be deduced from the function argument type.
4325 // Perform template argument deduction to determine whether we may be
4326 // specializing this template.
4327 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004328 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004329 FunctionDecl *Specialization = 0;
4330 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004331 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004332 FD->getType(),
4333 Specialization,
4334 Info)) {
4335 // FIXME: Template argument deduction failed; record why it failed, so
4336 // that we can provide nifty diagnostics.
4337 (void)TDK;
4338 continue;
4339 }
4340
4341 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004342 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004343 }
4344 }
4345
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004346 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004347 UnresolvedSetIterator Result
4348 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4349 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004350 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004351 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004352 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004353 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004354 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004355 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004356 return true;
John McCallc373d482010-01-27 01:50:18 +00004357
4358 // Ignore access information; it doesn't figure into redeclaration checking.
4359 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004360 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004361
4362 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004363 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004364
4365 // If this is a friend declaration, then we're not really declaring
4366 // an explicit specialization.
4367 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004368
Douglas Gregord5cb8762009-10-07 00:13:32 +00004369 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004370 if (!isFriend &&
4371 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004372 Specialization->getPrimaryTemplate(),
4373 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004374 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004375 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004376
4377 // C++ [temp.expl.spec]p6:
4378 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004379 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004380 // before the first use of that specialization that would cause an implicit
4381 // instantiation to take place, in every translation unit in which such a
4382 // use occurs; no diagnostic is required.
4383 FunctionTemplateSpecializationInfo *SpecInfo
4384 = Specialization->getTemplateSpecializationInfo();
4385 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004386
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004387 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004388 if (!isFriend &&
4389 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004390 TSK_ExplicitSpecialization,
4391 Specialization,
4392 SpecInfo->getTemplateSpecializationKind(),
4393 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004394 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004395 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004396
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004397 // Mark the prior declaration as an explicit specialization, so that later
4398 // clients know that this is an explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004399 if (!isFriend)
4400 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004401
4402 // Turn the given function declaration into a function template
4403 // specialization, with the template arguments from the previous
4404 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004405 // Take copies of (semantic and syntactic) template argument lists.
4406 const TemplateArgumentList* TemplArgs = new (Context)
4407 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4408 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4409 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004410 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004411 TemplArgs, /*InsertPos=*/0,
4412 SpecInfo->getTemplateSpecializationKind(),
4413 TemplArgsAsWritten);
4414
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004415 // The "previous declaration" for this function template specialization is
4416 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004417 Previous.clear();
4418 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004419 return false;
4420}
4421
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004422/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004423/// specialization.
4424///
4425/// This routine performs all of the semantic analysis required for an
4426/// explicit member function specialization. On successful completion,
4427/// the function declaration \p FD will become a member function
4428/// specialization.
4429///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004430/// \param Member the member declaration, which will be updated to become a
4431/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004432///
John McCall68263142009-11-18 22:49:29 +00004433/// \param Previous the set of declarations, one of which may be specialized
4434/// by this function specialization; the set will be modified to contain the
4435/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004436bool
John McCall68263142009-11-18 22:49:29 +00004437Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004438 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004439
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004440 // Try to find the member we are instantiating.
4441 NamedDecl *Instantiation = 0;
4442 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004443 MemberSpecializationInfo *MSInfo = 0;
4444
John McCall68263142009-11-18 22:49:29 +00004445 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004446 // Nowhere to look anyway.
4447 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004448 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4449 I != E; ++I) {
4450 NamedDecl *D = (*I)->getUnderlyingDecl();
4451 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004452 if (Context.hasSameType(Function->getType(), Method->getType())) {
4453 Instantiation = Method;
4454 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004455 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004456 break;
4457 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004458 }
4459 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004460 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004461 VarDecl *PrevVar;
4462 if (Previous.isSingleResult() &&
4463 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004464 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004465 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004466 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004467 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004468 }
4469 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004470 CXXRecordDecl *PrevRecord;
4471 if (Previous.isSingleResult() &&
4472 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4473 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004474 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004475 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004476 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004477 }
4478
4479 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004480 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004481 // specializations are always out-of-line, the caller will complain about
4482 // this mismatch later.
4483 return false;
4484 }
John McCall77e8b112010-04-13 20:37:33 +00004485
4486 // If this is a friend, just bail out here before we start turning
4487 // things into explicit specializations.
4488 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4489 // Preserve instantiation information.
4490 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4491 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4492 cast<CXXMethodDecl>(InstantiatedFrom),
4493 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4494 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4495 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4496 cast<CXXRecordDecl>(InstantiatedFrom),
4497 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4498 }
4499
4500 Previous.clear();
4501 Previous.addDecl(Instantiation);
4502 return false;
4503 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004504
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004505 // Make sure that this is a specialization of a member.
4506 if (!InstantiatedFrom) {
4507 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4508 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004509 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4510 return true;
4511 }
4512
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004513 // C++ [temp.expl.spec]p6:
4514 // If a template, a member template or the member of a class template is
4515 // explicitly specialized then that spe- cialization shall be declared
4516 // before the first use of that specialization that would cause an implicit
4517 // instantiation to take place, in every translation unit in which such a
4518 // use occurs; no diagnostic is required.
4519 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004520
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004521 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004522 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4523 TSK_ExplicitSpecialization,
4524 Instantiation,
4525 MSInfo->getTemplateSpecializationKind(),
4526 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004527 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004528 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004529
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004530 // Check the scope of this explicit specialization.
4531 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004532 InstantiatedFrom,
4533 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004534 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004535 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004536
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004537 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004538 // the original declaration to note that it is an explicit specialization
4539 // (if it was previously an implicit instantiation). This latter step
4540 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004541 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004542 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4543 if (InstantiationFunction->getTemplateSpecializationKind() ==
4544 TSK_ImplicitInstantiation) {
4545 InstantiationFunction->setTemplateSpecializationKind(
4546 TSK_ExplicitSpecialization);
4547 InstantiationFunction->setLocation(Member->getLocation());
4548 }
4549
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004550 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4551 cast<CXXMethodDecl>(InstantiatedFrom),
4552 TSK_ExplicitSpecialization);
4553 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004554 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4555 if (InstantiationVar->getTemplateSpecializationKind() ==
4556 TSK_ImplicitInstantiation) {
4557 InstantiationVar->setTemplateSpecializationKind(
4558 TSK_ExplicitSpecialization);
4559 InstantiationVar->setLocation(Member->getLocation());
4560 }
4561
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004562 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4563 cast<VarDecl>(InstantiatedFrom),
4564 TSK_ExplicitSpecialization);
4565 } else {
4566 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004567 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4568 if (InstantiationClass->getTemplateSpecializationKind() ==
4569 TSK_ImplicitInstantiation) {
4570 InstantiationClass->setTemplateSpecializationKind(
4571 TSK_ExplicitSpecialization);
4572 InstantiationClass->setLocation(Member->getLocation());
4573 }
4574
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004575 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004576 cast<CXXRecordDecl>(InstantiatedFrom),
4577 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004578 }
4579
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004580 // Save the caller the trouble of having to figure out which declaration
4581 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004582 Previous.clear();
4583 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004584 return false;
4585}
4586
Douglas Gregor558c0322009-10-14 23:41:34 +00004587/// \brief Check the scope of an explicit instantiation.
4588static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4589 SourceLocation InstLoc,
4590 bool WasQualifiedName) {
4591 DeclContext *ExpectedContext
4592 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4593 DeclContext *CurContext = S.CurContext->getLookupContext();
4594
4595 // C++0x [temp.explicit]p2:
4596 // An explicit instantiation shall appear in an enclosing namespace of its
4597 // template.
4598 //
4599 // This is DR275, which we do not retroactively apply to C++98/03.
4600 if (S.getLangOptions().CPlusPlus0x &&
4601 !CurContext->Encloses(ExpectedContext)) {
4602 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004603 S.Diag(InstLoc,
4604 S.getLangOptions().CPlusPlus0x?
4605 diag::err_explicit_instantiation_out_of_scope
4606 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004607 << D << NS;
4608 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004609 S.Diag(InstLoc,
4610 S.getLangOptions().CPlusPlus0x?
4611 diag::err_explicit_instantiation_must_be_global
4612 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004613 << D;
4614 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4615 return;
4616 }
4617
4618 // C++0x [temp.explicit]p2:
4619 // If the name declared in the explicit instantiation is an unqualified
4620 // name, the explicit instantiation shall appear in the namespace where
4621 // its template is declared or, if that namespace is inline (7.3.1), any
4622 // namespace from its enclosing namespace set.
4623 if (WasQualifiedName)
4624 return;
4625
4626 if (CurContext->Equals(ExpectedContext))
4627 return;
4628
Douglas Gregor2166beb2010-05-11 17:39:34 +00004629 S.Diag(InstLoc,
4630 S.getLangOptions().CPlusPlus0x?
4631 diag::err_explicit_instantiation_unqualified_wrong_namespace
4632 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004633 << D << ExpectedContext;
4634 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4635}
4636
4637/// \brief Determine whether the given scope specifier has a template-id in it.
4638static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4639 if (!SS.isSet())
4640 return false;
4641
4642 // C++0x [temp.explicit]p2:
4643 // If the explicit instantiation is for a member function, a member class
4644 // or a static data member of a class template specialization, the name of
4645 // the class template specialization in the qualified-id for the member
4646 // name shall be a simple-template-id.
4647 //
4648 // C++98 has the same restriction, just worded differently.
4649 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4650 NNS; NNS = NNS->getPrefix())
4651 if (Type *T = NNS->getAsType())
4652 if (isa<TemplateSpecializationType>(T))
4653 return true;
4654
4655 return false;
4656}
4657
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004658// Explicit instantiation of a class template specialization
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004659Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004660Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004661 SourceLocation ExternLoc,
4662 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004663 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004664 SourceLocation KWLoc,
4665 const CXXScopeSpec &SS,
4666 TemplateTy TemplateD,
4667 SourceLocation TemplateNameLoc,
4668 SourceLocation LAngleLoc,
4669 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004670 SourceLocation RAngleLoc,
4671 AttributeList *Attr) {
4672 // Find the class template we're specializing
4673 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004674 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004675 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4676
4677 // Check that the specialization uses the same tag kind as the
4678 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004679 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4680 assert(Kind != TTK_Enum &&
4681 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004682 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004683 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004684 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004685 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004686 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004687 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004688 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004689 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004690 diag::note_previous_use);
4691 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4692 }
4693
Douglas Gregor558c0322009-10-14 23:41:34 +00004694 // C++0x [temp.explicit]p2:
4695 // There are two forms of explicit instantiation: an explicit instantiation
4696 // definition and an explicit instantiation declaration. An explicit
4697 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00004698 TemplateSpecializationKind TSK
4699 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4700 : TSK_ExplicitInstantiationDeclaration;
4701
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004702 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004703 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004704 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004705
4706 // Check that the template argument list is well-formed for this
4707 // template.
Anders Carlssonfb250522009-06-23 01:26:57 +00004708 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4709 TemplateArgs.size());
John McCalld5532b62009-11-23 01:53:49 +00004710 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4711 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004712 return true;
4713
Mike Stump1eb44332009-09-09 15:08:12 +00004714 assert((Converted.structuredSize() ==
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004715 ClassTemplate->getTemplateParameters()->size()) &&
4716 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004718 // Find the class template specialization declaration that
4719 // corresponds to these arguments.
4720 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00004721 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlssonfb250522009-06-23 01:26:57 +00004722 Converted.getFlatArguments(),
Douglas Gregor828e2262009-07-29 16:09:57 +00004723 Converted.flatSize(),
4724 Context);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004725 void *InsertPos = 0;
4726 ClassTemplateSpecializationDecl *PrevDecl
4727 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4728
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004729 TemplateSpecializationKind PrevDecl_TSK
4730 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4731
Douglas Gregord5cb8762009-10-07 00:13:32 +00004732 // C++0x [temp.explicit]p2:
4733 // [...] An explicit instantiation shall appear in an enclosing
4734 // namespace of its template. [...]
4735 //
4736 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004737 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4738 SS.isSet());
Douglas Gregord5cb8762009-10-07 00:13:32 +00004739
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004740 ClassTemplateSpecializationDecl *Specialization = 0;
4741
Douglas Gregord78f5982009-11-25 06:01:46 +00004742 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004743 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004744 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00004745 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004746 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004747 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004748 HasNoEffect))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004749 return DeclPtrTy::make(PrevDecl);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004750
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004751 // Even though HasNoEffect == true means that this explicit instantiation
4752 // has no effect on semantics, we go on to put its syntax in the AST.
4753
4754 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4755 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00004756 // Since the only prior class template specialization with these
4757 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004758 // declaration node as our own, updating the source location
4759 // for the template name to reflect our new declaration.
4760 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00004761 Specialization = PrevDecl;
4762 Specialization->setLocation(TemplateNameLoc);
4763 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00004764 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00004765 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004766 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004767
Douglas Gregor52604ab2009-09-11 21:19:12 +00004768 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004769 // Create a new class template specialization declaration node for
4770 // this explicit specialization.
4771 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004772 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004773 ClassTemplate->getDeclContext(),
4774 TemplateNameLoc,
4775 ClassTemplate,
Douglas Gregor52604ab2009-09-11 21:19:12 +00004776 Converted, PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004777 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004778
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004779 if (!HasNoEffect) {
4780 if (PrevDecl) {
4781 // Remove the previous declaration from the folding set, since we want
4782 // to introduce a new declaration.
4783 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4784 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4785 }
4786 // Insert the new specialization.
4787 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
4788 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004789 }
4790
4791 // Build the fully-sugared type for this explicit instantiation as
4792 // the user wrote in the explicit instantiation itself. This means
4793 // that we'll pretty-print the type retrieved from the
4794 // specialization's declaration the way that the user actually wrote
4795 // the explicit instantiation, rather than formatting the name based
4796 // on the "canonical" representation used to store the template
4797 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004798 TypeSourceInfo *WrittenTy
4799 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4800 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004801 Context.getTypeDeclType(Specialization));
4802 Specialization->setTypeAsWritten(WrittenTy);
4803 TemplateArgsIn.release();
4804
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004805 // Set source locations for keywords.
4806 Specialization->setExternLoc(ExternLoc);
4807 Specialization->setTemplateKeywordLoc(TemplateLoc);
4808
4809 // Add the explicit instantiation into its lexical context. However,
4810 // since explicit instantiations are never found by name lookup, we
4811 // just put it into the declaration context directly.
4812 Specialization->setLexicalDeclContext(CurContext);
4813 CurContext->addDecl(Specialization);
4814
4815 // Syntax is now OK, so return if it has no other effect on semantics.
4816 if (HasNoEffect) {
4817 // Set the template specialization kind.
4818 Specialization->setTemplateSpecializationKind(TSK);
4819 return DeclPtrTy::make(Specialization);
Douglas Gregord78f5982009-11-25 06:01:46 +00004820 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004821
4822 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004823 // A definition of a class template or class member template
4824 // shall be in scope at the point of the explicit instantiation of
4825 // the class template or class member template.
4826 //
4827 // This check comes when we actually try to perform the
4828 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004829 ClassTemplateSpecializationDecl *Def
4830 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004831 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004832 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00004833 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004834 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004835 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004836 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4837 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004838
Douglas Gregor0d035142009-10-27 18:42:08 +00004839 // Instantiate the members of this class template specialization.
4840 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00004841 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004842 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00004843 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4844
4845 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4846 // TSK_ExplicitInstantiationDefinition
4847 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4848 TSK == TSK_ExplicitInstantiationDefinition)
4849 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004850
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004851 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00004852 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004853
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004854 // Set the template specialization kind.
4855 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00004856 return DeclPtrTy::make(Specialization);
4857}
4858
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004859// Explicit instantiation of a member class of a class template.
4860Sema::DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00004861Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00004862 SourceLocation ExternLoc,
4863 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004864 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004865 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004866 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004867 IdentifierInfo *Name,
4868 SourceLocation NameLoc,
4869 AttributeList *Attr) {
4870
Douglas Gregor402abb52009-05-28 23:31:59 +00004871 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00004872 bool IsDependent = false;
John McCall0f434ec2009-07-31 02:45:11 +00004873 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregor7cdbc582009-07-22 23:48:44 +00004874 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCallc4e70192009-09-11 04:59:25 +00004875 MultiTemplateParamsArg(*this, 0, 0),
4876 Owned, IsDependent);
4877 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4878
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004879 if (!TagD)
4880 return true;
4881
4882 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4883 if (Tag->isEnum()) {
4884 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4885 << Context.getTypeDeclType(Tag);
4886 return true;
4887 }
4888
Douglas Gregord0c87372009-05-27 17:30:49 +00004889 if (Tag->isInvalidDecl())
4890 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00004891
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004892 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4893 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4894 if (!Pattern) {
4895 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4896 << Context.getTypeDeclType(Record);
4897 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4898 return true;
4899 }
4900
Douglas Gregor558c0322009-10-14 23:41:34 +00004901 // C++0x [temp.explicit]p2:
4902 // If the explicit instantiation is for a class or member class, the
4903 // elaborated-type-specifier in the declaration shall include a
4904 // simple-template-id.
4905 //
4906 // C++98 has the same restriction, just worded differently.
4907 if (!ScopeSpecifierHasTemplateId(SS))
4908 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4909 << Record << SS.getRange();
4910
4911 // C++0x [temp.explicit]p2:
4912 // There are two forms of explicit instantiation: an explicit instantiation
4913 // definition and an explicit instantiation declaration. An explicit
4914 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00004915 TemplateSpecializationKind TSK
4916 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4917 : TSK_ExplicitInstantiationDeclaration;
4918
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004919 // C++0x [temp.explicit]p2:
4920 // [...] An explicit instantiation shall appear in an enclosing
4921 // namespace of its template. [...]
4922 //
4923 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00004924 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00004925
4926 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00004927 CXXRecordDecl *PrevDecl
4928 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00004929 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00004930 PrevDecl = Record;
4931 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00004932 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004933 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004934 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00004935 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00004936 PrevDecl,
4937 MSInfo->getTemplateSpecializationKind(),
4938 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004939 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00004940 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004941 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00004942 return TagD;
4943 }
4944
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004945 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00004946 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00004947 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004948 // C++ [temp.explicit]p3:
4949 // A definition of a member class of a class template shall be in scope
4950 // at the point of an explicit instantiation of the member class.
4951 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00004952 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004953 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00004954 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4955 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00004956 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4957 << Pattern;
4958 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00004959 } else {
4960 if (InstantiateClass(NameLoc, Record, Def,
4961 getTemplateInstantiationArgs(Record),
4962 TSK))
4963 return true;
4964
Douglas Gregor952b0172010-02-11 01:04:33 +00004965 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00004966 if (!RecordDef)
4967 return true;
4968 }
4969 }
4970
4971 // Instantiate all of the members of the class.
4972 InstantiateClassMembers(NameLoc, RecordDef,
4973 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004974
Douglas Gregor6fb745b2010-05-13 16:44:06 +00004975 if (TSK == TSK_ExplicitInstantiationDefinition)
4976 MarkVTableUsed(NameLoc, RecordDef, true);
4977
Mike Stump390b4cc2009-05-16 07:39:55 +00004978 // FIXME: We don't have any representation for explicit instantiations of
4979 // member classes. Such a representation is not needed for compilation, but it
4980 // should be available for clients that want to see all of the declarations in
4981 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00004982 return TagD;
4983}
4984
Douglas Gregord5a423b2009-09-25 18:43:00 +00004985Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4986 SourceLocation ExternLoc,
4987 SourceLocation TemplateLoc,
4988 Declarator &D) {
4989 // Explicit instantiations always require a name.
4990 DeclarationName Name = GetNameForDeclarator(D);
4991 if (!Name) {
4992 if (!D.isInvalidType())
4993 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4994 diag::err_explicit_instantiation_requires_name)
4995 << D.getDeclSpec().getSourceRange()
4996 << D.getSourceRange();
4997
4998 return true;
4999 }
5000
5001 // The scope passed in may not be a decl scope. Zip up the scope tree until
5002 // we find one that is.
5003 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5004 (S->getFlags() & Scope::TemplateParamScope) != 0)
5005 S = S->getParent();
5006
5007 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005008 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5009 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005010 if (R.isNull())
5011 return true;
5012
5013 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5014 // Cannot explicitly instantiate a typedef.
5015 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5016 << Name;
5017 return true;
5018 }
5019
Douglas Gregor663b5a02009-10-14 20:14:33 +00005020 // C++0x [temp.explicit]p1:
5021 // [...] An explicit instantiation of a function template shall not use the
5022 // inline or constexpr specifiers.
5023 // Presumably, this also applies to member functions of class templates as
5024 // well.
5025 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5026 Diag(D.getDeclSpec().getInlineSpecLoc(),
5027 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005028 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005029
5030 // FIXME: check for constexpr specifier.
5031
Douglas Gregor558c0322009-10-14 23:41:34 +00005032 // C++0x [temp.explicit]p2:
5033 // There are two forms of explicit instantiation: an explicit instantiation
5034 // definition and an explicit instantiation declaration. An explicit
5035 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005036 TemplateSpecializationKind TSK
5037 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5038 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005039
John McCalla24dc2e2009-11-17 02:14:36 +00005040 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
5041 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005042
5043 if (!R->isFunctionType()) {
5044 // C++ [temp.explicit]p1:
5045 // A [...] static data member of a class template can be explicitly
5046 // instantiated from the member definition associated with its class
5047 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005048 if (Previous.isAmbiguous())
5049 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005050
John McCall1bcee0a2009-12-02 08:25:40 +00005051 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005052 if (!Prev || !Prev->isStaticDataMember()) {
5053 // We expect to see a data data member here.
5054 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5055 << Name;
5056 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5057 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005058 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005059 return true;
5060 }
5061
5062 if (!Prev->getInstantiatedFromStaticDataMember()) {
5063 // FIXME: Check for explicit specialization?
5064 Diag(D.getIdentifierLoc(),
5065 diag::err_explicit_instantiation_data_member_not_instantiated)
5066 << Prev;
5067 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5068 // FIXME: Can we provide a note showing where this was declared?
5069 return true;
5070 }
5071
Douglas Gregor558c0322009-10-14 23:41:34 +00005072 // C++0x [temp.explicit]p2:
5073 // If the explicit instantiation is for a member function, a member class
5074 // or a static data member of a class template specialization, the name of
5075 // the class template specialization in the qualified-id for the member
5076 // name shall be a simple-template-id.
5077 //
5078 // C++98 has the same restriction, just worded differently.
5079 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5080 Diag(D.getIdentifierLoc(),
5081 diag::err_explicit_instantiation_without_qualified_id)
5082 << Prev << D.getCXXScopeSpec().getRange();
5083
5084 // Check the scope of this explicit instantiation.
5085 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5086
Douglas Gregor454885e2009-10-15 15:54:05 +00005087 // Verify that it is okay to explicitly instantiate here.
5088 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5089 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005090 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005091 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005092 MSInfo->getTemplateSpecializationKind(),
5093 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005094 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005095 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005096 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005097 return DeclPtrTy();
5098
Douglas Gregord5a423b2009-09-25 18:43:00 +00005099 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005100 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005101 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005102 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5103 /*DefinitionRequired=*/true);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005104
5105 // FIXME: Create an ExplicitInstantiation node?
5106 return DeclPtrTy();
5107 }
5108
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005109 // If the declarator is a template-id, translate the parser's template
5110 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005111 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005112 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005113 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5114 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005115 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5116 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005117 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5118 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005119 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005120 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005121 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005122 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005123 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005124
Douglas Gregord5a423b2009-09-25 18:43:00 +00005125 // C++ [temp.explicit]p1:
5126 // A [...] function [...] can be explicitly instantiated from its template.
5127 // A member function [...] of a class template can be explicitly
5128 // instantiated from the member definition associated with its class
5129 // template.
John McCallc373d482010-01-27 01:50:18 +00005130 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005131 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5132 P != PEnd; ++P) {
5133 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005134 if (!HasExplicitTemplateArgs) {
5135 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5136 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5137 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005138
John McCallc373d482010-01-27 01:50:18 +00005139 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005140 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5141 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005142 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005143 }
5144 }
5145
5146 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5147 if (!FunTmpl)
5148 continue;
5149
John McCall5769d612010-02-08 23:07:23 +00005150 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005151 FunctionDecl *Specialization = 0;
5152 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005153 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005154 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005155 R, Specialization, Info)) {
5156 // FIXME: Keep track of almost-matches?
5157 (void)TDK;
5158 continue;
5159 }
5160
John McCallc373d482010-01-27 01:50:18 +00005161 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005162 }
5163
5164 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005165 UnresolvedSetIterator Result
5166 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005167 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005168 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5169 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5170 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005171
John McCallc373d482010-01-27 01:50:18 +00005172 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005173 return true;
John McCallc373d482010-01-27 01:50:18 +00005174
5175 // Ignore access control bits, we don't need them for redeclaration checking.
5176 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005177
Douglas Gregor0a897e32009-10-15 17:21:20 +00005178 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005179 Diag(D.getIdentifierLoc(),
5180 diag::err_explicit_instantiation_member_function_not_instantiated)
5181 << Specialization
5182 << (Specialization->getTemplateSpecializationKind() ==
5183 TSK_ExplicitSpecialization);
5184 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5185 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005186 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005187
Douglas Gregor0a897e32009-10-15 17:21:20 +00005188 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005189 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5190 PrevDecl = Specialization;
5191
Douglas Gregor0a897e32009-10-15 17:21:20 +00005192 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005193 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005194 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005195 PrevDecl,
5196 PrevDecl->getTemplateSpecializationKind(),
5197 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005198 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005199 return true;
5200
5201 // FIXME: We may still want to build some representation of this
5202 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005203 if (HasNoEffect)
Douglas Gregor0a897e32009-10-15 17:21:20 +00005204 return DeclPtrTy();
5205 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005206
5207 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005208
5209 if (TSK == TSK_ExplicitInstantiationDefinition)
5210 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5211 false, /*DefinitionRequired=*/true);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005212
Douglas Gregor558c0322009-10-14 23:41:34 +00005213 // C++0x [temp.explicit]p2:
5214 // If the explicit instantiation is for a member function, a member class
5215 // or a static data member of a class template specialization, the name of
5216 // the class template specialization in the qualified-id for the member
5217 // name shall be a simple-template-id.
5218 //
5219 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005220 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005221 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005222 D.getCXXScopeSpec().isSet() &&
5223 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5224 Diag(D.getIdentifierLoc(),
5225 diag::err_explicit_instantiation_without_qualified_id)
5226 << Specialization << D.getCXXScopeSpec().getRange();
5227
5228 CheckExplicitInstantiationScope(*this,
5229 FunTmpl? (NamedDecl *)FunTmpl
5230 : Specialization->getInstantiatedFromMemberFunction(),
5231 D.getIdentifierLoc(),
5232 D.getCXXScopeSpec().isSet());
5233
Douglas Gregord5a423b2009-09-25 18:43:00 +00005234 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5235 return DeclPtrTy();
5236}
5237
Douglas Gregord57959a2009-03-27 23:10:48 +00005238Sema::TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005239Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5240 const CXXScopeSpec &SS, IdentifierInfo *Name,
5241 SourceLocation TagLoc, SourceLocation NameLoc) {
5242 // This has to hold, because SS is expected to be defined.
5243 assert(Name && "Expected a name in a dependent tag");
5244
5245 NestedNameSpecifier *NNS
5246 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5247 if (!NNS)
5248 return true;
5249
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005250 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005251
Douglas Gregor48c89f42010-04-24 16:38:41 +00005252 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5253 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005254 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005255 return true;
5256 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005257
5258 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5259 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCallc4e70192009-09-11 04:59:25 +00005260}
5261
5262Sema::TypeResult
Douglas Gregord57959a2009-03-27 23:10:48 +00005263Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5264 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005265 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005266 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5267 if (!NNS)
5268 return true;
5269
Douglas Gregor107de902010-04-24 15:35:55 +00005270 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005271 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005272 if (T.isNull())
5273 return true;
John McCall63b43852010-04-29 23:50:39 +00005274
5275 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5276 if (isa<DependentNameType>(T)) {
5277 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005278 TL.setKeywordLoc(TypenameLoc);
5279 TL.setQualifierRange(SS.getRange());
5280 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005281 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005282 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005283 TL.setKeywordLoc(TypenameLoc);
5284 TL.setQualifierRange(SS.getRange());
5285 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005286 }
5287
5288 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregord57959a2009-03-27 23:10:48 +00005289}
5290
Douglas Gregor17343172009-04-01 00:28:59 +00005291Sema::TypeResult
5292Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5293 SourceLocation TemplateLoc, TypeTy *Ty) {
John McCall4e449832010-05-28 23:32:21 +00005294 TypeSourceInfo *InnerTSI = 0;
5295 QualType T = GetTypeFromParser(Ty, &InnerTSI);
Mike Stump1eb44332009-09-09 15:08:12 +00005296 NestedNameSpecifier *NNS
Douglas Gregor17343172009-04-01 00:28:59 +00005297 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
John McCall4e449832010-05-28 23:32:21 +00005298
5299 assert(isa<TemplateSpecializationType>(T) &&
5300 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005301
Douglas Gregor6946baf2009-09-02 13:05:45 +00005302 if (computeDeclContext(SS, false)) {
5303 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005304 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005305 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005306
5307 // Push the inner type, preserving its source locations if possible.
5308 TypeLocBuilder Builder;
5309 if (InnerTSI)
5310 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5311 else
5312 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5313
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005314 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCall4e449832010-05-28 23:32:21 +00005315 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5316 TL.setKeywordLoc(TypenameLoc);
5317 TL.setQualifierRange(SS.getRange());
5318
5319 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall63b43852010-04-29 23:50:39 +00005320 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor6946baf2009-09-02 13:05:45 +00005321 }
Mike Stump1eb44332009-09-09 15:08:12 +00005322
John McCall33500952010-06-11 00:33:02 +00005323 // TODO: it's really silly that we make a template specialization
5324 // type earlier only to drop it again here.
5325 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5326 DependentTemplateName *DTN =
5327 TST->getTemplateName().getAsDependentTemplateName();
5328 assert(DTN && "dependent template has non-dependent name?");
5329 T = Context.getDependentTemplateSpecializationType(ETK_Typename, NNS,
5330 DTN->getIdentifier(),
5331 TST->getNumArgs(),
5332 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005333 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005334 DependentTemplateSpecializationTypeLoc TL =
5335 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5336 if (InnerTSI) {
5337 TemplateSpecializationTypeLoc TSTL =
5338 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5339 TL.setLAngleLoc(TSTL.getLAngleLoc());
5340 TL.setRAngleLoc(TSTL.getRAngleLoc());
5341 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5342 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5343 } else {
5344 TL.initializeLocal(SourceLocation());
5345 }
John McCall4e449832010-05-28 23:32:21 +00005346 TL.setKeywordLoc(TypenameLoc);
5347 TL.setQualifierRange(SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005348 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor17343172009-04-01 00:28:59 +00005349}
5350
Douglas Gregord57959a2009-03-27 23:10:48 +00005351/// \brief Build the type that describes a C++ typename specifier,
5352/// e.g., "typename T::type".
5353QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005354Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5355 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005356 SourceLocation KeywordLoc, SourceRange NNSRange,
5357 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005358 CXXScopeSpec SS;
5359 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005360 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005361
John McCall77bb1aa2010-05-01 00:40:08 +00005362 DeclContext *Ctx = computeDeclContext(SS);
5363 if (!Ctx) {
5364 // If the nested-name-specifier is dependent and couldn't be
5365 // resolved to a type, build a typename type.
5366 assert(NNS->isDependent());
5367 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005368 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005369
John McCall77bb1aa2010-05-01 00:40:08 +00005370 // If the nested-name-specifier refers to the current instantiation,
5371 // the "typename" keyword itself is superfluous. In C++03, the
5372 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5373 // allows such extraneous "typename" keywords, and we retroactively
5374 // apply this DR to C++03 code. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005375
John McCall77bb1aa2010-05-01 00:40:08 +00005376 if (RequireCompleteDeclContext(SS, Ctx))
5377 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005378
5379 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005380 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005381 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005382 unsigned DiagID = 0;
5383 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005384 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005385 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005386 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005387 break;
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005388
5389 case LookupResult::NotFoundInCurrentInstantiation:
5390 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005391 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005392
5393 case LookupResult::Found:
John McCallf36e02d2009-10-09 21:13:30 +00005394 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005395 // We found a type. Build an ElaboratedType, since the
5396 // typename-specifier was just sugar.
5397 return Context.getElaboratedType(ETK_Typename, NNS,
5398 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005399 }
5400
5401 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005402 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005403 break;
5404
John McCall7ba107a2009-11-18 02:36:19 +00005405 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005406 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005407 return QualType();
5408
Douglas Gregord57959a2009-03-27 23:10:48 +00005409 case LookupResult::FoundOverloaded:
5410 DiagID = diag::err_typename_nested_not_type;
5411 Referenced = *Result.begin();
5412 break;
5413
John McCall6e247262009-10-10 05:48:19 +00005414 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005415 return QualType();
5416 }
5417
5418 // If we get here, it's because name lookup did not find a
5419 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005420 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5421 IILoc);
5422 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005423 if (Referenced)
5424 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5425 << Name;
5426 return QualType();
5427}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005428
5429namespace {
5430 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005431 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005432 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005433 SourceLocation Loc;
5434 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005435
Douglas Gregor4a959d82009-08-06 16:20:37 +00005436 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005437 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5438
Mike Stump1eb44332009-09-09 15:08:12 +00005439 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005440 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005441 DeclarationName Entity)
5442 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005443 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005444
5445 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005446 /// transformed.
5447 ///
5448 /// For the purposes of type reconstruction, a type has already been
5449 /// transformed if it is NULL or if it is not dependent.
5450 bool AlreadyTransformed(QualType T) {
5451 return T.isNull() || !T->isDependentType();
5452 }
Mike Stump1eb44332009-09-09 15:08:12 +00005453
5454 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005455 /// rebuilt.
5456 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005457
Douglas Gregor4a959d82009-08-06 16:20:37 +00005458 /// \brief Returns the name of the entity whose type is being rebuilt.
5459 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005460
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005461 /// \brief Sets the "base" location and entity when that
5462 /// information is known based on another transformation.
5463 void setBase(SourceLocation Loc, DeclarationName Entity) {
5464 this->Loc = Loc;
5465 this->Entity = Entity;
5466 }
5467
Douglas Gregor4a959d82009-08-06 16:20:37 +00005468 /// \brief Transforms an expression by returning the expression itself
5469 /// (an identity function).
5470 ///
5471 /// FIXME: This is completely unsafe; we will need to actually clone the
5472 /// expressions.
5473 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor895162d2010-04-30 18:55:50 +00005474 return getSema().Owned(E->Retain());
Douglas Gregor4a959d82009-08-06 16:20:37 +00005475 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005476 };
5477}
5478
Douglas Gregor4a959d82009-08-06 16:20:37 +00005479/// \brief Rebuilds a type within the context of the current instantiation.
5480///
Mike Stump1eb44332009-09-09 15:08:12 +00005481/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005482/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005483/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005484/// partial specialization thereof). This routine will rebuild that type now
5485/// that we have entered the declarator's scope, which may produce different
5486/// canonical types, e.g.,
5487///
5488/// \code
5489/// template<typename T>
5490/// struct X {
5491/// typedef T* pointer;
5492/// pointer data();
5493/// };
5494///
5495/// template<typename T>
5496/// typename X<T>::pointer X<T>::data() { ... }
5497/// \endcode
5498///
Douglas Gregor4714c122010-03-31 17:34:00 +00005499/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005500/// since we do not know that we can look into X<T> when we parsed the type.
5501/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005502/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005503/// as the canonical type of T*, allowing the return types of the out-of-line
5504/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005505TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5506 SourceLocation Loc,
5507 DeclarationName Name) {
5508 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005509 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005510
Douglas Gregor4a959d82009-08-06 16:20:37 +00005511 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5512 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005513}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005514
John McCall63b43852010-04-29 23:50:39 +00005515bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5516 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005517
5518 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5519 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5520 DeclarationName());
5521 NestedNameSpecifier *Rebuilt =
5522 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005523 if (!Rebuilt) return true;
5524
5525 SS.setScopeRep(Rebuilt);
5526 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005527}
5528
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005529/// \brief Produces a formatted string that describes the binding of
5530/// template parameters to template arguments.
5531std::string
5532Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5533 const TemplateArgumentList &Args) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005534 // FIXME: For variadic templates, we'll need to get the structured list.
5535 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5536 Args.flat_size());
5537}
5538
5539std::string
5540Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5541 const TemplateArgument *Args,
5542 unsigned NumArgs) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005543 std::string Result;
5544
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005545 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005546 return Result;
5547
5548 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005549 if (I >= NumArgs)
5550 break;
5551
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005552 if (I == 0)
5553 Result += "[with ";
5554 else
5555 Result += ", ";
5556
5557 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5558 Result += Id->getName();
5559 } else {
5560 Result += '$';
5561 Result += llvm::utostr(I);
5562 }
5563
5564 Result += " = ";
5565
5566 switch (Args[I].getKind()) {
5567 case TemplateArgument::Null:
5568 Result += "<no value>";
5569 break;
5570
5571 case TemplateArgument::Type: {
5572 std::string TypeStr;
5573 Args[I].getAsType().getAsStringInternal(TypeStr,
5574 Context.PrintingPolicy);
5575 Result += TypeStr;
5576 break;
5577 }
5578
5579 case TemplateArgument::Declaration: {
5580 bool Unnamed = true;
5581 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5582 if (ND->getDeclName()) {
5583 Unnamed = false;
5584 Result += ND->getNameAsString();
5585 }
5586 }
5587
5588 if (Unnamed) {
5589 Result += "<anonymous>";
5590 }
5591 break;
5592 }
5593
Douglas Gregor788cd062009-11-11 01:00:40 +00005594 case TemplateArgument::Template: {
5595 std::string Str;
5596 llvm::raw_string_ostream OS(Str);
5597 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5598 Result += OS.str();
5599 break;
5600 }
5601
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005602 case TemplateArgument::Integral: {
5603 Result += Args[I].getAsIntegral()->toString(10);
5604 break;
5605 }
5606
5607 case TemplateArgument::Expression: {
Douglas Gregor77e2c672010-04-29 04:55:13 +00005608 // FIXME: This is non-optimal, since we're regurgitating the
5609 // expression we were given.
5610 std::string Str;
5611 {
5612 llvm::raw_string_ostream OS(Str);
5613 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5614 Context.PrintingPolicy);
5615 }
5616 Result += Str;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005617 break;
5618 }
5619
5620 case TemplateArgument::Pack:
5621 // FIXME: Format template argument packs
5622 Result += "<template argument pack>";
5623 break;
5624 }
5625 }
5626
5627 Result += ']';
5628 return Result;
5629}