blob: a487825bb37c710576cb6411d7ebbc0f4cca49bc [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
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000014#include "clang/Sema/Scope.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000016#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor4a959d82009-08-06 16:20:37 +000017#include "TreeTransform.h"
Douglas Gregorddc29e12009-02-06 22:42:48 +000018#include "clang/AST/ASTContext.h"
Douglas Gregor898574e2008-12-05 23:32:09 +000019#include "clang/AST/Expr.h"
Douglas Gregorcc45cb32009-02-11 19:52:55 +000020#include "clang/AST/ExprCXX.h"
John McCall92b7f702010-03-11 07:50:04 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000022#include "clang/AST/DeclTemplate.h"
John McCall4e2cbb22010-10-20 05:44:58 +000023#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor5f3aeb62010-10-13 00:27:52 +000024#include "clang/AST/TypeVisitor.h"
John McCall19510852010-08-20 18:27:03 +000025#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/ParsedTemplate.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000027#include "clang/Basic/LangOptions.h"
Douglas Gregord5a423b2009-09-25 18:43:00 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf4ea562009-09-15 16:23:51 +000029#include "llvm/ADT/StringExtras.h"
Douglas Gregor72c3f312008-12-05 18:15:24 +000030using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregor72c3f312008-12-05 18:15:24 +000032
John McCall78b81052010-11-10 02:40:36 +000033// Exported for use by Parser.
34SourceRange
35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
36 unsigned N) {
37 if (!N) return SourceRange();
38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
39}
40
Douglas Gregor2dd078a2009-09-02 22:59:36 +000041/// \brief Determine whether the declaration found is acceptable as the name
42/// of a template and, if so, return that template declaration. Otherwise,
43/// returns NULL.
John McCallad00b772010-06-16 08:42:20 +000044static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45 NamedDecl *Orig) {
46 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump1eb44332009-09-09 15:08:12 +000047
Douglas Gregor2dd078a2009-09-02 22:59:36 +000048 if (isa<TemplateDecl>(D))
John McCallad00b772010-06-16 08:42:20 +000049 return Orig;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Douglas Gregor2dd078a2009-09-02 22:59:36 +000051 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
62 // specialization.
63 if (Record->isInjectedClassName()) {
Douglas Gregor542b5482009-10-14 17:30:58 +000064 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregor2dd078a2009-09-02 22:59:36 +000065 if (Record->getDescribedClassTemplate())
66 return Record->getDescribedClassTemplate();
67
68 if (ClassTemplateSpecializationDecl *Spec
69 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70 return Spec->getSpecializedTemplate();
71 }
Mike Stump1eb44332009-09-09 15:08:12 +000072
Douglas Gregor2dd078a2009-09-02 22:59:36 +000073 return 0;
74 }
Mike Stump1eb44332009-09-09 15:08:12 +000075
Douglas Gregor2dd078a2009-09-02 22:59:36 +000076 return 0;
77}
78
John McCallf7a1a742009-11-24 19:00:30 +000079static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor01e56ae2010-04-12 20:54:26 +000080 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCallf7a1a742009-11-24 19:00:30 +000082 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
John McCallad00b772010-06-16 08:42:20 +000085 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCallf7a1a742009-11-24 19:00:30 +000086 if (!Repl)
87 filter.erase();
Douglas Gregor01e56ae2010-04-12 20:54:26 +000088 else if (Repl != Orig) {
89
90 // C++ [temp.local]p3:
91 // A lookup that finds an injected-class-name (10.2) can result in an
92 // ambiguity in certain cases (for example, if it is found in more than
93 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
95 // is followed by a template-argument-list, the reference refers to the
96 // class template itself and not a specialization thereof, and is not
97 // ambiguous.
98 //
99 // FIXME: Will we eventually have to do the same for alias templates?
100 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
101 if (!ClassTemplates.insert(ClassTmpl)) {
102 filter.erase();
103 continue;
104 }
John McCall8ba66912010-08-13 07:02:08 +0000105
106 // FIXME: we promote access to public here as a workaround to
107 // the fact that LookupResult doesn't let us remember that we
108 // found this template through a particular injected class name,
109 // which means we end up doing nasty things to the invariants.
110 // Pretending that access is public is *much* safer.
111 filter.replace(Repl, AS_public);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000112 }
John McCallf7a1a742009-11-24 19:00:30 +0000113 }
114 filter.done();
115}
116
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000117TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000118 CXXScopeSpec &SS,
Abramo Bagnara7c153532010-08-06 12:11:11 +0000119 bool hasTemplateKeyword,
Douglas Gregor014e88d2009-11-03 23:16:33 +0000120 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +0000121 ParsedType ObjectTypePtr,
Douglas Gregor495c35d2009-08-25 22:51:20 +0000122 bool EnteringContext,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000123 TemplateTy &TemplateResult,
124 bool &MemberOfUnknownSpecialization) {
Douglas Gregorb862b8f2010-01-11 23:29:10 +0000125 assert(getLangOptions().CPlusPlus && "No template names in C!");
126
Douglas Gregor014e88d2009-11-03 23:16:33 +0000127 DeclarationName TName;
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000128 MemberOfUnknownSpecialization = false;
Douglas Gregor014e88d2009-11-03 23:16:33 +0000129
130 switch (Name.getKind()) {
131 case UnqualifiedId::IK_Identifier:
132 TName = DeclarationName(Name.Identifier);
133 break;
134
135 case UnqualifiedId::IK_OperatorFunctionId:
136 TName = Context.DeclarationNames.getCXXOperatorName(
137 Name.OperatorFunctionId.Operator);
138 break;
139
Sean Hunte6252d12009-11-28 08:58:14 +0000140 case UnqualifiedId::IK_LiteralOperatorId:
Sean Hunt3e518bd2009-11-29 07:34:05 +0000141 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
142 break;
Sean Hunte6252d12009-11-28 08:58:14 +0000143
Douglas Gregor014e88d2009-11-03 23:16:33 +0000144 default:
145 return TNK_Non_template;
146 }
Mike Stump1eb44332009-09-09 15:08:12 +0000147
John McCallb3d87482010-08-24 05:47:05 +0000148 QualType ObjectType = ObjectTypePtr.get();
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregorbfea2392009-12-31 08:11:17 +0000150 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
151 LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000152 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
153 MemberOfUnknownSpecialization);
John McCall67d22fb2010-08-28 20:17:00 +0000154 if (R.empty()) return TNK_Non_template;
155 if (R.isAmbiguous()) {
156 // Suppress diagnostics; we'll redo this lookup later.
John McCallb8592062010-08-13 02:23:42 +0000157 R.suppressDiagnostics();
John McCall67d22fb2010-08-28 20:17:00 +0000158
159 // FIXME: we might have ambiguous templates, in which case we
160 // should at least parse them properly!
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000161 return TNK_Non_template;
John McCallb8592062010-08-13 02:23:42 +0000162 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000163
John McCall0bd6feb2009-12-02 08:04:21 +0000164 TemplateName Template;
165 TemplateNameKind TemplateKind;
Mike Stump1eb44332009-09-09 15:08:12 +0000166
John McCall0bd6feb2009-12-02 08:04:21 +0000167 unsigned ResultCount = R.end() - R.begin();
168 if (ResultCount > 1) {
169 // We assume that we'll preserve the qualifier from a function
170 // template name in other ways.
171 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
172 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000173
174 // We'll do this lookup again later.
175 R.suppressDiagnostics();
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000176 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000177 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
178
179 if (SS.isSet() && !SS.isInvalid()) {
180 NestedNameSpecifier *Qualifier
181 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Abramo Bagnara7c153532010-08-06 12:11:11 +0000182 Template = Context.getQualifiedTemplateName(Qualifier,
183 hasTemplateKeyword, TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000184 } else {
185 Template = TemplateName(TD);
186 }
187
John McCallb8592062010-08-13 02:23:42 +0000188 if (isa<FunctionTemplateDecl>(TD)) {
John McCall0bd6feb2009-12-02 08:04:21 +0000189 TemplateKind = TNK_Function_template;
John McCallb8592062010-08-13 02:23:42 +0000190
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
John McCall0bd6feb2009-12-02 08:04:21 +0000194 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
195 TemplateKind = TNK_Type_template;
196 }
Douglas Gregor2dd078a2009-09-02 22:59:36 +0000197 }
Mike Stump1eb44332009-09-09 15:08:12 +0000198
John McCall0bd6feb2009-12-02 08:04:21 +0000199 TemplateResult = TemplateTy::make(Template);
200 return TemplateKind;
John McCallf7a1a742009-11-24 19:00:30 +0000201}
202
Douglas Gregor84d0a192010-01-12 21:28:44 +0000203bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
204 SourceLocation IILoc,
205 Scope *S,
206 const CXXScopeSpec *SS,
207 TemplateTy &SuggestedTemplate,
208 TemplateNameKind &SuggestedKind) {
209 // We can't recover unless there's a dependent scope specifier preceding the
210 // template name.
Douglas Gregord5ab9b02010-05-21 23:43:39 +0000211 // FIXME: Typo correction?
Douglas Gregor84d0a192010-01-12 21:28:44 +0000212 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
213 computeDeclContext(*SS))
214 return false;
215
216 // The code is missing a 'template' keyword prior to the dependent template
217 // name.
218 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
219 Diag(IILoc, diag::err_template_kw_missing)
220 << Qualifier << II.getName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000221 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor84d0a192010-01-12 21:28:44 +0000222 SuggestedTemplate
223 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
224 SuggestedKind = TNK_Dependent_template_name;
225 return true;
226}
227
John McCallf7a1a742009-11-24 19:00:30 +0000228void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000229 Scope *S, CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +0000230 QualType ObjectType,
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000231 bool EnteringContext,
232 bool &MemberOfUnknownSpecialization) {
John McCallf7a1a742009-11-24 19:00:30 +0000233 // Determine where to perform name lookup
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000234 MemberOfUnknownSpecialization = false;
John McCallf7a1a742009-11-24 19:00:30 +0000235 DeclContext *LookupCtx = 0;
236 bool isDependent = false;
237 if (!ObjectType.isNull()) {
238 // This nested-name-specifier occurs in a member access expression, e.g.,
239 // x->B::f, and we are looking into the type of the object.
240 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
241 LookupCtx = computeDeclContext(ObjectType);
242 isDependent = ObjectType->isDependentType();
243 assert((isDependent || !ObjectType->isIncompleteType()) &&
244 "Caller should have completed object type");
245 } else if (SS.isSet()) {
246 // This nested-name-specifier occurs after another nested-name-specifier,
247 // so long into the context associated with the prior nested-name-specifier.
248 LookupCtx = computeDeclContext(SS, EnteringContext);
249 isDependent = isDependentScopeSpecifier(SS);
250
251 // The declaration context must be complete.
John McCall77bb1aa2010-05-01 00:40:08 +0000252 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCallf7a1a742009-11-24 19:00:30 +0000253 return;
254 }
255
256 bool ObjectTypeSearchedInScope = false;
257 if (LookupCtx) {
258 // Perform "qualified" name lookup into the declaration context we
259 // computed, which is either the type of the base of a member access
260 // expression or the declaration context associated with a prior
261 // nested-name-specifier.
262 LookupQualifiedName(Found, LookupCtx);
263
264 if (!ObjectType.isNull() && Found.empty()) {
265 // C++ [basic.lookup.classref]p1:
266 // In a class member access expression (5.2.5), if the . or -> token is
267 // immediately followed by an identifier followed by a <, the
268 // identifier must be looked up to determine whether the < is the
269 // beginning of a template argument list (14.2) or a less-than operator.
270 // The identifier is first looked up in the class of the object
271 // expression. If the identifier is not found, it is then looked up in
272 // the context of the entire postfix-expression and shall name a class
273 // or function template.
John McCallf7a1a742009-11-24 19:00:30 +0000274 if (S) LookupName(Found, S);
275 ObjectTypeSearchedInScope = true;
276 }
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000277 } else if (isDependent && (!S || ObjectType.isNull())) {
Douglas Gregor2e933882010-01-12 17:06:20 +0000278 // We cannot look into a dependent object type or nested nme
279 // specifier.
Douglas Gregor1fd6d442010-05-21 23:18:07 +0000280 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000281 return;
282 } else {
283 // Perform unqualified name lookup in the current scope.
284 LookupName(Found, S);
285 }
286
Douglas Gregor2e933882010-01-12 17:06:20 +0000287 if (Found.empty() && !isDependent) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000288 // If we did not find any names, attempt to correct any typos.
289 DeclarationName Name = Found.getLookupName();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000290 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000291 false, CTC_CXXCasts)) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000292 FilterAcceptableTemplateNames(Context, Found);
John McCallad00b772010-06-16 08:42:20 +0000293 if (!Found.empty()) {
Douglas Gregorbfea2392009-12-31 08:11:17 +0000294 if (LookupCtx)
295 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
296 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +0000297 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000298 Found.getLookupName().getAsString());
299 else
300 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
301 << Name << Found.getLookupName()
Douglas Gregor849b2432010-03-31 17:46:05 +0000302 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorbfea2392009-12-31 08:11:17 +0000303 Found.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000304 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
305 Diag(Template->getLocation(), diag::note_previous_decl)
306 << Template->getDeclName();
John McCallad00b772010-06-16 08:42:20 +0000307 }
Douglas Gregorbfea2392009-12-31 08:11:17 +0000308 } else {
309 Found.clear();
Douglas Gregor12eb5d62010-06-29 19:27:42 +0000310 Found.setLookupName(Name);
Douglas Gregorbfea2392009-12-31 08:11:17 +0000311 }
312 }
313
John McCallf7a1a742009-11-24 19:00:30 +0000314 FilterAcceptableTemplateNames(Context, Found);
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000315 if (Found.empty()) {
316 if (isDependent)
317 MemberOfUnknownSpecialization = true;
John McCallf7a1a742009-11-24 19:00:30 +0000318 return;
Douglas Gregorf9f97a02010-07-16 16:54:17 +0000319 }
John McCallf7a1a742009-11-24 19:00:30 +0000320
321 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
322 // C++ [basic.lookup.classref]p1:
323 // [...] If the lookup in the class of the object expression finds a
324 // template, the name is also looked up in the context of the entire
325 // postfix-expression and [...]
326 //
327 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
328 LookupOrdinaryName);
329 LookupName(FoundOuter, S);
330 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor01e56ae2010-04-12 20:54:26 +0000331
John McCallf7a1a742009-11-24 19:00:30 +0000332 if (FoundOuter.empty()) {
333 // - if the name is not found, the name found in the class of the
334 // object expression is used, otherwise
335 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
336 // - if the name is found in the context of the entire
337 // postfix-expression and does not name a class template, the name
338 // found in the class of the object expression is used, otherwise
John McCallad00b772010-06-16 08:42:20 +0000339 } else if (!Found.isSuppressingDiagnostics()) {
John McCallf7a1a742009-11-24 19:00:30 +0000340 // - if the name found is a class template, it must refer to the same
341 // entity as the one found in the class of the object expression,
342 // otherwise the program is ill-formed.
343 if (!Found.isSingleResult() ||
344 Found.getFoundDecl()->getCanonicalDecl()
345 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
346 Diag(Found.getNameLoc(),
Jeffrey Yasskin21d07e42010-06-05 01:39:57 +0000347 diag::ext_nested_name_member_ref_lookup_ambiguous)
348 << Found.getLookupName()
349 << ObjectType;
John McCallf7a1a742009-11-24 19:00:30 +0000350 Diag(Found.getRepresentativeDecl()->getLocation(),
351 diag::note_ambig_member_ref_object_type)
352 << ObjectType;
353 Diag(FoundOuter.getFoundDecl()->getLocation(),
354 diag::note_ambig_member_ref_scope);
355
356 // Recover by taking the template that we found in the object
357 // expression's type.
358 }
359 }
360 }
361}
362
John McCall2f841ba2009-12-02 03:53:29 +0000363/// ActOnDependentIdExpression - Handle a dependent id-expression that
364/// was just parsed. This is only possible with an explicit scope
365/// specifier naming a dependent type.
John McCall60d7b3a2010-08-24 06:29:42 +0000366ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000367Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000368 const DeclarationNameInfo &NameInfo,
John McCall2f841ba2009-12-02 03:53:29 +0000369 bool isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +0000370 const TemplateArgumentListInfo *TemplateArgs) {
371 NestedNameSpecifier *Qualifier
372 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallea1471e2010-05-20 01:18:31 +0000373
374 DeclContext *DC = getFunctionLevelDeclContext();
John McCallf7a1a742009-11-24 19:00:30 +0000375
John McCall2f841ba2009-12-02 03:53:29 +0000376 if (!isAddressOfOperand &&
John McCallea1471e2010-05-20 01:18:31 +0000377 isa<CXXMethodDecl>(DC) &&
378 cast<CXXMethodDecl>(DC)->isInstance()) {
379 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCall2f841ba2009-12-02 03:53:29 +0000380
John McCallf7a1a742009-11-24 19:00:30 +0000381 // Since the 'this' expression is synthesized, we don't need to
382 // perform the double-lookup check.
383 NamedDecl *FirstQualifierInScope = 0;
384
John McCallaa81e162009-12-01 22:10:20 +0000385 return Owned(CXXDependentScopeMemberExpr::Create(Context,
386 /*This*/ 0, ThisType,
387 /*IsArrow*/ true,
John McCallf7a1a742009-11-24 19:00:30 +0000388 /*Op*/ SourceLocation(),
389 Qualifier, SS.getRange(),
390 FirstQualifierInScope,
Abramo Bagnara25777432010-08-11 22:01:17 +0000391 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000392 TemplateArgs));
393 }
394
Abramo Bagnara25777432010-08-11 22:01:17 +0000395 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
John McCallf7a1a742009-11-24 19:00:30 +0000396}
397
John McCall60d7b3a2010-08-24 06:29:42 +0000398ExprResult
John McCallf7a1a742009-11-24 19:00:30 +0000399Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +0000400 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000401 const TemplateArgumentListInfo *TemplateArgs) {
402 return Owned(DependentScopeDeclRefExpr::Create(Context,
403 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
404 SS.getRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +0000405 NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +0000406 TemplateArgs));
Douglas Gregord6fb7ef2008-12-18 19:37:40 +0000407}
408
Douglas Gregor72c3f312008-12-05 18:15:24 +0000409/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
410/// that the template parameter 'PrevDecl' is being shadowed by a new
411/// declaration at location Loc. Returns true to indicate that this is
412/// an error, and false otherwise.
413bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregorf57172b2008-12-08 18:40:42 +0000414 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000415
416 // Microsoft Visual C++ permits template parameters to be shadowed.
417 if (getLangOptions().Microsoft)
418 return false;
419
420 // C++ [temp.local]p4:
421 // A template-parameter shall not be redeclared within its
422 // scope (including nested scopes).
Mike Stump1eb44332009-09-09 15:08:12 +0000423 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor72c3f312008-12-05 18:15:24 +0000424 << cast<NamedDecl>(PrevDecl)->getDeclName();
425 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
426 return true;
427}
428
Douglas Gregor2943aed2009-03-03 04:44:36 +0000429/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000430/// the parameter D to reference the templated declaration and return a pointer
431/// to the template declaration. Otherwise, do nothing to D and return null.
John McCalld226f652010-08-21 09:40:31 +0000432TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
433 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
434 D = Temp->getTemplatedDecl();
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000435 return Temp;
436 }
437 return 0;
438}
439
Douglas Gregor788cd062009-11-11 01:00:40 +0000440static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
441 const ParsedTemplateArgument &Arg) {
442
443 switch (Arg.getKind()) {
444 case ParsedTemplateArgument::Type: {
John McCalla93c9342009-12-07 02:54:59 +0000445 TypeSourceInfo *DI;
Douglas Gregor788cd062009-11-11 01:00:40 +0000446 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
447 if (!DI)
John McCalla93c9342009-12-07 02:54:59 +0000448 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor788cd062009-11-11 01:00:40 +0000449 return TemplateArgumentLoc(TemplateArgument(T), DI);
450 }
451
452 case ParsedTemplateArgument::NonType: {
453 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
454 return TemplateArgumentLoc(TemplateArgument(E), E);
455 }
456
457 case ParsedTemplateArgument::Template: {
John McCall2b5289b2010-08-23 07:28:44 +0000458 TemplateName Template = Arg.getAsTemplate().get();
Douglas Gregor788cd062009-11-11 01:00:40 +0000459 return TemplateArgumentLoc(TemplateArgument(Template),
460 Arg.getScopeSpec().getRange(),
461 Arg.getLocation());
462 }
463 }
464
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +0000465 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000466 return TemplateArgumentLoc();
467}
468
469/// \brief Translates template arguments as provided by the parser
470/// into template arguments used by semantic analysis.
John McCalld5532b62009-11-23 01:53:49 +0000471void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
472 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor788cd062009-11-11 01:00:40 +0000473 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCalld5532b62009-11-23 01:53:49 +0000474 TemplateArgs.addArgument(translateTemplateArgument(*this,
475 TemplateArgsIn[I]));
Douglas Gregor788cd062009-11-11 01:00:40 +0000476}
477
Douglas Gregor72c3f312008-12-05 18:15:24 +0000478/// ActOnTypeParameter - Called when a C++ template type parameter
479/// (e.g., "typename T") has been parsed. Typename specifies whether
480/// the keyword "typename" was used to declare the type parameter
481/// (otherwise, "class" was used), and KeyLoc is the location of the
482/// "class" or "typename" keyword. ParamName is the name of the
483/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregorefed5c82010-06-16 15:23:05 +0000484/// ParamName is the location of the parameter name (if any).
Douglas Gregor72c3f312008-12-05 18:15:24 +0000485/// If the type parameter has a default argument, it will be added
486/// later via ActOnTypeParameterDefault.
John McCalld226f652010-08-21 09:40:31 +0000487Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
488 SourceLocation EllipsisLoc,
489 SourceLocation KeyLoc,
490 IdentifierInfo *ParamName,
491 SourceLocation ParamNameLoc,
492 unsigned Depth, unsigned Position,
493 SourceLocation EqualLoc,
John McCallb3d87482010-08-24 05:47:05 +0000494 ParsedType DefaultArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000495 assert(S->isTemplateParamScope() &&
496 "Template type parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000497 bool Invalid = false;
498
499 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000500 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000501 LookupOrdinaryName,
502 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000503 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000504 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000505 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000506 }
507
Douglas Gregorddc29e12009-02-06 22:42:48 +0000508 SourceLocation Loc = ParamNameLoc;
509 if (!ParamName)
510 Loc = KeyLoc;
511
Douglas Gregor72c3f312008-12-05 18:15:24 +0000512 TemplateTypeParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000513 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
514 Loc, Depth, Position, ParamName, Typename,
Anders Carlsson6d845ae2009-06-12 22:23:22 +0000515 Ellipsis);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000516 if (Invalid)
517 Param->setInvalidDecl();
518
519 if (ParamName) {
520 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000521 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000522 IdResolver.AddDecl(Param);
523 }
524
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000525 // Handle the default argument, if provided.
526 if (DefaultArg) {
527 TypeSourceInfo *DefaultTInfo;
528 GetTypeFromParser(DefaultArg, &DefaultTInfo);
529
530 assert(DefaultTInfo && "expected source information for type");
531
532 // C++0x [temp.param]p9:
533 // A default template-argument may be specified for any kind of
534 // template-parameter that is not a template parameter pack.
535 if (Ellipsis) {
536 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
John McCalld226f652010-08-21 09:40:31 +0000537 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000538 }
Douglas Gregor6f526752010-12-16 08:48:57 +0000539
540 // Check for unexpanded parameter packs.
541 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
542 UPPC_DefaultArgument))
543 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000544
545 // Check the template argument itself.
546 if (CheckTemplateArgument(Param, DefaultTInfo)) {
547 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000548 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000549 }
550
551 Param->setDefaultArgument(DefaultTInfo, false);
552 }
553
John McCalld226f652010-08-21 09:40:31 +0000554 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000555}
556
Douglas Gregor2943aed2009-03-03 04:44:36 +0000557/// \brief Check that the type of a non-type template parameter is
558/// well-formed.
559///
560/// \returns the (possibly-promoted) parameter type if valid;
561/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump1eb44332009-09-09 15:08:12 +0000562QualType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000563Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora481ec42010-05-23 19:57:01 +0000564 // We don't allow variably-modified types as the type of non-type template
565 // parameters.
566 if (T->isVariablyModifiedType()) {
567 Diag(Loc, diag::err_variably_modified_nontype_template_param)
568 << T;
569 return QualType();
570 }
571
Douglas Gregor2943aed2009-03-03 04:44:36 +0000572 // C++ [temp.param]p4:
573 //
574 // A non-type template-parameter shall have one of the following
575 // (optionally cv-qualified) types:
576 //
577 // -- integral or enumeration type,
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000578 if (T->isIntegralOrEnumerationType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000579 // -- pointer to object or pointer to function,
Eli Friedman13578692010-08-05 02:49:48 +0000580 T->isPointerType() ||
Mike Stump1eb44332009-09-09 15:08:12 +0000581 // -- reference to object or reference to function,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000582 T->isReferenceType() ||
583 // -- pointer to member.
584 T->isMemberPointerType() ||
585 // If T is a dependent type, we can't do the check now, so we
586 // assume that it is well-formed.
587 T->isDependentType())
588 return T;
589 // C++ [temp.param]p8:
590 //
591 // A non-type template-parameter of type "array of T" or
592 // "function returning T" is adjusted to be of type "pointer to
593 // T" or "pointer to function returning T", respectively.
594 else if (T->isArrayType())
595 // FIXME: Keep the type prior to promotion?
596 return Context.getArrayDecayedType(T);
597 else if (T->isFunctionType())
598 // FIXME: Keep the type prior to promotion?
599 return Context.getPointerType(T);
Douglas Gregor0fddb972010-05-22 16:17:30 +0000600
Douglas Gregor2943aed2009-03-03 04:44:36 +0000601 Diag(Loc, diag::err_template_nontype_parm_bad_type)
602 << T;
603
604 return QualType();
605}
606
John McCalld226f652010-08-21 09:40:31 +0000607Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
608 unsigned Depth,
609 unsigned Position,
610 SourceLocation EqualLoc,
John McCall9ae2f072010-08-23 23:25:46 +0000611 Expr *Default) {
John McCallbf1a0282010-06-04 23:28:52 +0000612 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
613 QualType T = TInfo->getType();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000614
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000615 assert(S->isTemplateParamScope() &&
616 "Non-type template parameter not in template parameter scope!");
Douglas Gregor72c3f312008-12-05 18:15:24 +0000617 bool Invalid = false;
618
619 IdentifierInfo *ParamName = D.getIdentifier();
620 if (ParamName) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000621 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorc0b39642010-04-15 23:40:53 +0000622 LookupOrdinaryName,
623 ForRedeclaration);
Douglas Gregorf57172b2008-12-08 18:40:42 +0000624 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor72c3f312008-12-05 18:15:24 +0000625 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000626 PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000627 }
628
Douglas Gregor4d2abba2010-12-16 15:36:43 +0000629 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
630 if (T.isNull()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000631 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorceef30c2009-03-09 16:46:39 +0000632 Invalid = true;
633 }
Douglas Gregor781def02010-12-16 08:56:23 +0000634
Douglas Gregor10738d32010-12-23 23:51:58 +0000635 bool IsParameterPack = D.hasEllipsis();
Douglas Gregor72c3f312008-12-05 18:15:24 +0000636 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000637 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
638 D.getIdentifierLoc(),
Douglas Gregor10738d32010-12-23 23:51:58 +0000639 Depth, Position, ParamName, T,
640 IsParameterPack, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000641 if (Invalid)
642 Param->setInvalidDecl();
643
644 if (D.getIdentifier()) {
645 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000646 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000647 IdResolver.AddDecl(Param);
648 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000649
650 // Check the well-formedness of the default template argument, if provided.
Douglas Gregor10738d32010-12-23 23:51:58 +0000651 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000652 // Check for unexpanded parameter packs.
653 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
654 return Param;
655
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000656 TemplateArgument Converted;
657 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
658 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000659 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000660 }
661
John McCall9ae2f072010-08-23 23:25:46 +0000662 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000663 }
664
John McCalld226f652010-08-21 09:40:31 +0000665 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000666}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000667
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000668/// ActOnTemplateTemplateParameter - Called when a C++ template template
669/// parameter (e.g. T in template <template <typename> class T> class array)
670/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000671Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
672 SourceLocation TmpLoc,
673 TemplateParamsTy *Params,
674 IdentifierInfo *Name,
675 SourceLocation NameLoc,
676 unsigned Depth,
677 unsigned Position,
678 SourceLocation EqualLoc,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000679 const ParsedTemplateArgument &Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000680 assert(S->isTemplateParamScope() &&
681 "Template template parameter not in template parameter scope!");
682
683 // Construct the parameter object.
684 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000685 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000686 NameLoc.isInvalid()? TmpLoc : NameLoc,
687 Depth, Position, Name,
Douglas Gregor369ea272010-10-21 17:26:49 +0000688 Params);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000689
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000690 // If the template template parameter has a name, then link the identifier
691 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000692 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000693 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000694 IdResolver.AddDecl(Param);
695 }
696
Douglas Gregor6f526752010-12-16 08:48:57 +0000697 if (Params->size() == 0) {
698 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
699 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
700 Param->setInvalidDecl();
701 }
702
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000703 if (!Default.isInvalid()) {
704 // Check only that we have a template template argument. We don't want to
705 // try to check well-formedness now, because our template template parameter
706 // might have dependent types in its template parameters, which we wouldn't
707 // be able to match now.
708 //
709 // If none of the template template parameter's template arguments mention
710 // other template parameters, we could actually perform more checking here.
711 // However, it isn't worth doing.
712 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
713 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
714 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
715 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000716 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000717 }
718
Douglas Gregor6f526752010-12-16 08:48:57 +0000719 // Check for unexpanded parameter packs.
720 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
721 DefaultArg.getArgument().getAsTemplate(),
722 UPPC_DefaultArgument))
723 return Param;
724
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000725 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000726 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000727
John McCalld226f652010-08-21 09:40:31 +0000728 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000729}
730
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000731/// ActOnTemplateParameterList - Builds a TemplateParameterList that
732/// contains the template parameters in Params/NumParams.
733Sema::TemplateParamsTy *
734Sema::ActOnTemplateParameterList(unsigned Depth,
735 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000736 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000737 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000738 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000739 SourceLocation RAngleLoc) {
740 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000741 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000742
Douglas Gregorddc29e12009-02-06 22:42:48 +0000743 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000744 (NamedDecl**)Params, NumParams,
745 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000746}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000747
John McCallb6217662010-03-15 10:12:16 +0000748static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
749 if (SS.isSet())
750 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
751 SS.getRange());
752}
753
John McCallf312b1e2010-08-26 23:41:50 +0000754DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000755Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000756 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000757 IdentifierInfo *Name, SourceLocation NameLoc,
758 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000759 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000760 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000761 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000762 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000763 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000764 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000765
766 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000767 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000768 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000769
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000770 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
771 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000772
773 // There is no such thing as an unnamed class template.
774 if (!Name) {
775 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000776 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000777 }
778
779 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000780 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000781 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000782 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000783 if (SS.isNotEmpty() && !SS.isInvalid()) {
784 SemanticContext = computeDeclContext(SS, true);
785 if (!SemanticContext) {
786 // FIXME: Produce a reasonable diagnostic here
787 return true;
788 }
Mike Stump1eb44332009-09-09 15:08:12 +0000789
John McCall77bb1aa2010-05-01 00:40:08 +0000790 if (RequireCompleteDeclContext(SS, SemanticContext))
791 return true;
792
John McCalla24dc2e2009-11-17 02:14:36 +0000793 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000794 } else {
795 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000796 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000797 }
Mike Stump1eb44332009-09-09 15:08:12 +0000798
Douglas Gregor57265e32010-04-12 16:00:01 +0000799 if (Previous.isAmbiguous())
800 return true;
801
Douglas Gregorddc29e12009-02-06 22:42:48 +0000802 NamedDecl *PrevDecl = 0;
803 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000804 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000805
Douglas Gregorddc29e12009-02-06 22:42:48 +0000806 // If there is a previous declaration with the same name, check
807 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000808 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000809 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000810
811 // We may have found the injected-class-name of a class template,
812 // class template partial specialization, or class template specialization.
813 // In these cases, grab the template that is being defined or specialized.
814 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
815 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
816 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
817 PrevClassTemplate
818 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
819 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
820 PrevClassTemplate
821 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
822 ->getSpecializedTemplate();
823 }
824 }
825
John McCall65c49462009-12-18 11:25:59 +0000826 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000827 // C++ [namespace.memdef]p3:
828 // [...] When looking for a prior declaration of a class or a function
829 // declared as a friend, and when the name of the friend class or
830 // function is neither a qualified name nor a template-id, scopes outside
831 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000832 if (!SS.isSet()) {
833 DeclContext *OutermostContext = CurContext;
834 while (!OutermostContext->isFileContext())
835 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000836
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000837 if (PrevDecl &&
838 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
839 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
840 SemanticContext = PrevDecl->getDeclContext();
841 } else {
842 // Declarations in outer scopes don't matter. However, the outermost
843 // context we computed is the semantic context for our new
844 // declaration.
845 PrevDecl = PrevClassTemplate = 0;
846 SemanticContext = OutermostContext;
847 }
John McCalle129d442009-12-17 23:21:11 +0000848 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000849
John McCalle129d442009-12-17 23:21:11 +0000850 if (CurContext->isDependentContext()) {
851 // If this is a dependent context, we don't want to link the friend
852 // class template to the template in scope, because that would perform
853 // checking of the template parameter lists that can't be performed
854 // until the outer context is instantiated.
855 PrevDecl = PrevClassTemplate = 0;
856 }
857 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
858 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000859
Douglas Gregorddc29e12009-02-06 22:42:48 +0000860 if (PrevClassTemplate) {
861 // Ensure that the template parameter lists are compatible.
862 if (!TemplateParameterListsAreEqual(TemplateParams,
863 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000864 /*Complain=*/true,
865 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000866 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000867
868 // C++ [temp.class]p4:
869 // In a redeclaration, partial specialization, explicit
870 // specialization or explicit instantiation of a class template,
871 // the class-key shall agree in kind with the original class
872 // template declaration (7.1.5.3).
873 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000874 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000875 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000876 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000877 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000878 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000879 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000880 }
881
Douglas Gregorddc29e12009-02-06 22:42:48 +0000882 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000883 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000884 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000885 Diag(NameLoc, diag::err_redefinition) << Name;
886 Diag(Def->getLocation(), diag::note_previous_definition);
887 // FIXME: Would it make sense to try to "forget" the previous
888 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000889 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000890 }
891 }
892 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
893 // Maybe we will complain about the shadowed template parameter.
894 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
895 // Just pretend that we didn't see the previous declaration.
896 PrevDecl = 0;
897 } else if (PrevDecl) {
898 // C++ [temp]p5:
899 // A class template shall not have the same name as any other
900 // template, class, function, object, enumeration, enumerator,
901 // namespace, or type in the same scope (3.3), except as specified
902 // in (14.5.4).
903 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
904 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000905 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000906 }
907
Douglas Gregord684b002009-02-10 19:49:53 +0000908 // Check the template parameter list of this declaration, possibly
909 // merging in the template parameter list from the previous class
910 // template declaration.
911 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000912 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
913 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000914 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregor57265e32010-04-12 16:00:01 +0000916 if (SS.isSet()) {
917 // If the name of the template was qualified, we must be defining the
918 // template out-of-line.
919 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
920 !(TUK == TUK_Friend && CurContext->isDependentContext()))
921 Diag(NameLoc, diag::err_member_def_does_not_match)
922 << Name << SemanticContext << SS.getRange();
923 }
924
Mike Stump1eb44332009-09-09 15:08:12 +0000925 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000926 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000927 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000928 PrevClassTemplate->getTemplatedDecl() : 0,
929 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000930 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000931
932 ClassTemplateDecl *NewTemplate
933 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
934 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000935 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000936 NewClass->setDescribedClassTemplate(NewTemplate);
937
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000938 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000939 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000940 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000941 assert(T->isDependentType() && "Class template type is not dependent?");
942 (void)T;
943
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000944 // If we are providing an explicit specialization of a member that is a
945 // class template, make a note of that.
946 if (PrevClassTemplate &&
947 PrevClassTemplate->getInstantiatedFromMemberTemplate())
948 PrevClassTemplate->setMemberSpecialization();
949
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000950 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000951 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000952 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Douglas Gregorddc29e12009-02-06 22:42:48 +0000954 // Set the lexical context of these templates
955 NewClass->setLexicalDeclContext(CurContext);
956 NewTemplate->setLexicalDeclContext(CurContext);
957
John McCall0f434ec2009-07-31 02:45:11 +0000958 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000959 NewClass->startDefinition();
960
961 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000962 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000963
John McCall05b23ea2009-09-14 21:59:20 +0000964 if (TUK != TUK_Friend)
965 PushOnScopeChains(NewTemplate, S);
966 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000967 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000968 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000969 NewClass->setAccess(PrevClassTemplate->getAccess());
970 }
John McCall05b23ea2009-09-14 21:59:20 +0000971
Douglas Gregord85bea22009-09-26 06:47:28 +0000972 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
973 PrevClassTemplate != NULL);
974
John McCall05b23ea2009-09-14 21:59:20 +0000975 // Friend templates are visible in fairly strange ways.
976 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000977 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +0000978 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
979 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
980 PushOnScopeChains(NewTemplate, EnclosingScope,
981 /* AddToContext = */ false);
982 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000983
984 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
985 NewClass->getLocation(),
986 NewTemplate,
987 /*FIXME:*/NewClass->getLocation());
988 Friend->setAccess(AS_public);
989 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000990 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000991
Douglas Gregord684b002009-02-10 19:49:53 +0000992 if (Invalid) {
993 NewTemplate->setInvalidDecl();
994 NewClass->setInvalidDecl();
995 }
John McCalld226f652010-08-21 09:40:31 +0000996 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000997}
998
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000999/// \brief Diagnose the presence of a default template argument on a
1000/// template parameter, which is ill-formed in certain contexts.
1001///
1002/// \returns true if the default template argument should be dropped.
1003static bool DiagnoseDefaultTemplateArgument(Sema &S,
1004 Sema::TemplateParamListContext TPC,
1005 SourceLocation ParamLoc,
1006 SourceRange DefArgRange) {
1007 switch (TPC) {
1008 case Sema::TPC_ClassTemplate:
1009 return false;
1010
1011 case Sema::TPC_FunctionTemplate:
1012 // C++ [temp.param]p9:
1013 // A default template-argument shall not be specified in a
1014 // function template declaration or a function template
1015 // definition [...]
1016 // (This sentence is not in C++0x, per DR226).
1017 if (!S.getLangOptions().CPlusPlus0x)
1018 S.Diag(ParamLoc,
1019 diag::err_template_parameter_default_in_function_template)
1020 << DefArgRange;
1021 return false;
1022
1023 case Sema::TPC_ClassTemplateMember:
1024 // C++0x [temp.param]p9:
1025 // A default template-argument shall not be specified in the
1026 // template-parameter-lists of the definition of a member of a
1027 // class template that appears outside of the member's class.
1028 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1029 << DefArgRange;
1030 return true;
1031
1032 case Sema::TPC_FriendFunctionTemplate:
1033 // C++ [temp.param]p9:
1034 // A default template-argument shall not be specified in a
1035 // friend template declaration.
1036 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1037 << DefArgRange;
1038 return true;
1039
1040 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1041 // for friend function templates if there is only a single
1042 // declaration (and it is a definition). Strange!
1043 }
1044
1045 return false;
1046}
1047
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001048/// \brief Check for unexpanded parameter packs within the template parameters
1049/// of a template template parameter, recursively.
1050bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){
1051 TemplateParameterList *Params = TTP->getTemplateParameters();
1052 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1053 NamedDecl *P = Params->getParam(I);
1054 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1055 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1056 NTTP->getTypeSourceInfo(),
1057 Sema::UPPC_NonTypeTemplateParameterType))
1058 return true;
1059
1060 continue;
1061 }
1062
1063 if (TemplateTemplateParmDecl *InnerTTP
1064 = dyn_cast<TemplateTemplateParmDecl>(P))
1065 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1066 return true;
1067 }
1068
1069 return false;
1070}
1071
Douglas Gregord684b002009-02-10 19:49:53 +00001072/// \brief Checks the validity of a template parameter list, possibly
1073/// considering the template parameter list from a previous
1074/// declaration.
1075///
1076/// If an "old" template parameter list is provided, it must be
1077/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1078/// template parameter list.
1079///
1080/// \param NewParams Template parameter list for a new template
1081/// declaration. This template parameter list will be updated with any
1082/// default arguments that are carried through from the previous
1083/// template parameter list.
1084///
1085/// \param OldParams If provided, template parameter list from a
1086/// previous declaration of the same template. Default template
1087/// arguments will be merged from the old template parameter list to
1088/// the new template parameter list.
1089///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001090/// \param TPC Describes the context in which we are checking the given
1091/// template parameter list.
1092///
Douglas Gregord684b002009-02-10 19:49:53 +00001093/// \returns true if an error occurred, false otherwise.
1094bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001095 TemplateParameterList *OldParams,
1096 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001097 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001098
Douglas Gregord684b002009-02-10 19:49:53 +00001099 // C++ [temp.param]p10:
1100 // The set of default template-arguments available for use with a
1101 // template declaration or definition is obtained by merging the
1102 // default arguments from the definition (if in scope) and all
1103 // declarations in scope in the same way default function
1104 // arguments are (8.3.6).
1105 bool SawDefaultArgument = false;
1106 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001107
Anders Carlsson49d25572009-06-12 23:20:15 +00001108 bool SawParameterPack = false;
1109 SourceLocation ParameterPackLoc;
1110
Mike Stump1a35fde2009-02-11 23:03:27 +00001111 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001112 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001113 if (OldParams)
1114 OldParam = OldParams->begin();
1115
1116 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1117 NewParamEnd = NewParams->end();
1118 NewParam != NewParamEnd; ++NewParam) {
1119 // Variables used to diagnose redundant default arguments
1120 bool RedundantDefaultArg = false;
1121 SourceLocation OldDefaultLoc;
1122 SourceLocation NewDefaultLoc;
1123
1124 // Variables used to diagnose missing default arguments
1125 bool MissingDefaultArg = false;
1126
Anders Carlsson49d25572009-06-12 23:20:15 +00001127 // C++0x [temp.param]p11:
1128 // If a template parameter of a class template is a template parameter pack,
1129 // it must be the last template parameter.
1130 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001131 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001132 diag::err_template_param_pack_must_be_last_template_parameter);
1133 Invalid = true;
1134 }
1135
Douglas Gregord684b002009-02-10 19:49:53 +00001136 if (TemplateTypeParmDecl *NewTypeParm
1137 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001138 // Check the presence of a default argument here.
1139 if (NewTypeParm->hasDefaultArgument() &&
1140 DiagnoseDefaultTemplateArgument(*this, TPC,
1141 NewTypeParm->getLocation(),
1142 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001143 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001144 NewTypeParm->removeDefaultArgument();
1145
1146 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001147 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001148 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Anders Carlsson49d25572009-06-12 23:20:15 +00001150 if (NewTypeParm->isParameterPack()) {
1151 assert(!NewTypeParm->hasDefaultArgument() &&
1152 "Parameter packs can't have a default argument!");
1153 SawParameterPack = true;
1154 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001155 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001156 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001157 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1158 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1159 SawDefaultArgument = true;
1160 RedundantDefaultArg = true;
1161 PreviousDefaultArgLoc = NewDefaultLoc;
1162 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1163 // Merge the default argument from the old declaration to the
1164 // new declaration.
1165 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001166 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001167 true);
1168 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1169 } else if (NewTypeParm->hasDefaultArgument()) {
1170 SawDefaultArgument = true;
1171 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1172 } else if (SawDefaultArgument)
1173 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001174 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001175 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001176 // Check for unexpanded parameter packs.
1177 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1178 NewNonTypeParm->getTypeSourceInfo(),
1179 UPPC_NonTypeTemplateParameterType)) {
1180 Invalid = true;
1181 continue;
1182 }
1183
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001184 // Check the presence of a default argument here.
1185 if (NewNonTypeParm->hasDefaultArgument() &&
1186 DiagnoseDefaultTemplateArgument(*this, TPC,
1187 NewNonTypeParm->getLocation(),
1188 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001189 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001190 }
1191
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001192 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001193 NonTypeTemplateParmDecl *OldNonTypeParm
1194 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001195 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001196 NewNonTypeParm->hasDefaultArgument()) {
1197 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1198 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1199 SawDefaultArgument = true;
1200 RedundantDefaultArg = true;
1201 PreviousDefaultArgLoc = NewDefaultLoc;
1202 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1203 // Merge the default argument from the old declaration to the
1204 // new declaration.
1205 SawDefaultArgument = true;
1206 // FIXME: We need to create a new kind of "default argument"
1207 // expression that points to a previous template template
1208 // parameter.
1209 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001210 OldNonTypeParm->getDefaultArgument(),
1211 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001212 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1213 } else if (NewNonTypeParm->hasDefaultArgument()) {
1214 SawDefaultArgument = true;
1215 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1216 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001217 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001218 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001219 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001220 TemplateTemplateParmDecl *NewTemplateParm
1221 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001222
1223 // Check for unexpanded parameter packs, recursively.
1224 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1225 Invalid = true;
1226 continue;
1227 }
1228
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001229 if (NewTemplateParm->hasDefaultArgument() &&
1230 DiagnoseDefaultTemplateArgument(*this, TPC,
1231 NewTemplateParm->getLocation(),
1232 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001233 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001234
1235 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001236 TemplateTemplateParmDecl *OldTemplateParm
1237 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001238 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001239 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001240 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1241 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001242 SawDefaultArgument = true;
1243 RedundantDefaultArg = true;
1244 PreviousDefaultArgLoc = NewDefaultLoc;
1245 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1246 // Merge the default argument from the old declaration to the
1247 // new declaration.
1248 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001249 // FIXME: We need to create a new kind of "default argument" expression
1250 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001251 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001252 OldTemplateParm->getDefaultArgument(),
1253 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001254 PreviousDefaultArgLoc
1255 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001256 } else if (NewTemplateParm->hasDefaultArgument()) {
1257 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001258 PreviousDefaultArgLoc
1259 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001260 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001261 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001262 }
1263
1264 if (RedundantDefaultArg) {
1265 // C++ [temp.param]p12:
1266 // A template-parameter shall not be given default arguments
1267 // by two different declarations in the same scope.
1268 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1269 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1270 Invalid = true;
1271 } else if (MissingDefaultArg) {
1272 // C++ [temp.param]p11:
1273 // If a template-parameter has a default template-argument,
1274 // all subsequent template-parameters shall have a default
1275 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001276 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001277 diag::err_template_param_default_arg_missing);
1278 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1279 Invalid = true;
1280 }
1281
1282 // If we have an old template parameter list that we're merging
1283 // in, move on to the next parameter.
1284 if (OldParams)
1285 ++OldParam;
1286 }
1287
1288 return Invalid;
1289}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001290
John McCall4e2cbb22010-10-20 05:44:58 +00001291namespace {
1292
1293/// A class which looks for a use of a certain level of template
1294/// parameter.
1295struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1296 typedef RecursiveASTVisitor<DependencyChecker> super;
1297
1298 unsigned Depth;
1299 bool Match;
1300
1301 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1302 NamedDecl *ND = Params->getParam(0);
1303 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1304 Depth = PD->getDepth();
1305 } else if (NonTypeTemplateParmDecl *PD =
1306 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1307 Depth = PD->getDepth();
1308 } else {
1309 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1310 }
1311 }
1312
1313 bool Matches(unsigned ParmDepth) {
1314 if (ParmDepth >= Depth) {
1315 Match = true;
1316 return true;
1317 }
1318 return false;
1319 }
1320
1321 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1322 return !Matches(T->getDepth());
1323 }
1324
1325 bool TraverseTemplateName(TemplateName N) {
1326 if (TemplateTemplateParmDecl *PD =
1327 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1328 if (Matches(PD->getDepth())) return false;
1329 return super::TraverseTemplateName(N);
1330 }
1331
1332 bool VisitDeclRefExpr(DeclRefExpr *E) {
1333 if (NonTypeTemplateParmDecl *PD =
1334 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1335 if (PD->getDepth() == Depth) {
1336 Match = true;
1337 return false;
1338 }
1339 }
1340 return super::VisitDeclRefExpr(E);
1341 }
1342};
1343}
1344
1345/// Determines whether a template-id depends on the given parameter
1346/// list.
1347static bool
1348DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1349 TemplateParameterList *Params) {
1350 DependencyChecker Checker(Params);
1351 Checker.TraverseType(QualType(TemplateId, 0));
1352 return Checker.Match;
1353}
1354
Mike Stump1eb44332009-09-09 15:08:12 +00001355/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001356/// specifier, returning the template parameter list that applies to the
1357/// name.
1358///
1359/// \param DeclStartLoc the start of the declaration that has a scope
1360/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001361///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001362/// \param SS the scope specifier that will be matched to the given template
1363/// parameter lists. This scope specifier precedes a qualified name that is
1364/// being declared.
1365///
1366/// \param ParamLists the template parameter lists, from the outermost to the
1367/// innermost template parameter lists.
1368///
1369/// \param NumParamLists the number of template parameter lists in ParamLists.
1370///
John McCall77e8b112010-04-13 20:37:33 +00001371/// \param IsFriend Whether to apply the slightly different rules for
1372/// matching template parameters to scope specifiers in friend
1373/// declarations.
1374///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001375/// \param IsExplicitSpecialization will be set true if the entity being
1376/// declared is an explicit specialization, false otherwise.
1377///
Mike Stump1eb44332009-09-09 15:08:12 +00001378/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001379/// name that is preceded by the scope specifier @p SS. This template
1380/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001381/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001382/// template specialization), or may be NULL (if we were's declaring isn't
1383/// itself a template).
1384TemplateParameterList *
1385Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1386 const CXXScopeSpec &SS,
1387 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001388 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001389 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001390 bool &IsExplicitSpecialization,
1391 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001392 IsExplicitSpecialization = false;
1393
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001394 // Find the template-ids that occur within the nested-name-specifier. These
1395 // template-ids will match up with the template parameter lists.
1396 llvm::SmallVector<const TemplateSpecializationType *, 4>
1397 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001398 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1399 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001400 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1401 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001402 const Type *T = NNS->getAsType();
1403 if (!T) break;
1404
1405 // C++0x [temp.expl.spec]p17:
1406 // A member or a member template may be nested within many
1407 // enclosing class templates. In an explicit specialization for
1408 // such a member, the member declaration shall be preceded by a
1409 // template<> for each enclosing class template that is
1410 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001411 //
1412 // Following the existing practice of GNU and EDG, we allow a typedef of a
1413 // template specialization type.
John McCall49f4e1c2010-12-10 11:01:00 +00001414 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1415 T = TT->getDecl()->getUnderlyingType().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001416
Mike Stump1eb44332009-09-09 15:08:12 +00001417 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001418 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001419 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1420 if (!Template)
1421 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Ted Kremenek6217b802009-07-29 21:53:49 +00001423 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001424 ClassTemplateSpecializationDecl *SpecDecl
1425 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1426 // If the nested name specifier refers to an explicit specialization,
1427 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001428 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1429 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001430 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001431 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001432 }
Mike Stump1eb44332009-09-09 15:08:12 +00001433
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001434 TemplateIdsInSpecifier.push_back(SpecType);
1435 }
1436 }
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001438 // Reverse the list of template-ids in the scope specifier, so that we can
1439 // more easily match up the template-ids and the template parameter lists.
1440 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001442 SourceLocation FirstTemplateLoc = DeclStartLoc;
1443 if (NumParamLists)
1444 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001446 // Match the template-ids found in the specifier to the template parameter
1447 // lists.
John McCall4e2cbb22010-10-20 05:44:58 +00001448 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001449 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCall4e2cbb22010-10-20 05:44:58 +00001450 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1451 const TemplateSpecializationType *TemplateId
1452 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregorb88e8882009-07-30 17:40:51 +00001453 bool DependentTemplateId = TemplateId->isDependentType();
John McCall4e2cbb22010-10-20 05:44:58 +00001454
1455 // In friend declarations we can have template-ids which don't
1456 // depend on the corresponding template parameter lists. But
1457 // assume that empty parameter lists are supposed to match this
1458 // template-id.
1459 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1460 if (!DependentTemplateId ||
1461 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1462 continue;
1463 }
1464
1465 if (ParamIdx >= NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001466 // We have a template-id without a corresponding template parameter
1467 // list.
John McCall77e8b112010-04-13 20:37:33 +00001468
1469 // ...which is fine if this is a friend declaration.
1470 if (IsFriend) {
1471 IsExplicitSpecialization = true;
1472 break;
1473 }
1474
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001475 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001476 // FIXME: the location information here isn't great.
1477 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001478 diag::err_template_spec_needs_template_parameters)
John McCall4e2cbb22010-10-20 05:44:58 +00001479 << QualType(TemplateId, 0)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001480 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001481 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001482 } else {
1483 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1484 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001485 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001486 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001487 }
1488 return 0;
1489 }
Mike Stump1eb44332009-09-09 15:08:12 +00001490
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001491 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001492 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001493 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001494
John McCall31f17ec2010-04-27 00:57:59 +00001495 // Are there cases in (e.g.) friends where this won't match?
1496 if (const InjectedClassNameType *Injected
1497 = TemplateId->getAs<InjectedClassNameType>()) {
1498 CXXRecordDecl *Record = Injected->getDecl();
1499 if (ClassTemplatePartialSpecializationDecl *Partial =
1500 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1501 ExpectedTemplateParams = Partial->getTemplateParameters();
1502 else
1503 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1504 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001505 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001506
John McCall31f17ec2010-04-27 00:57:59 +00001507 if (ExpectedTemplateParams)
John McCall4e2cbb22010-10-20 05:44:58 +00001508 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall31f17ec2010-04-27 00:57:59 +00001509 ExpectedTemplateParams,
1510 true, TPL_TemplateMatch);
1511
John McCall4e2cbb22010-10-20 05:44:58 +00001512 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1513 TPC_ClassTemplateMember);
1514 } else if (ParamLists[ParamIdx]->size() > 0)
1515 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001516 diag::err_template_param_list_matches_nontemplate)
1517 << TemplateId
John McCall4e2cbb22010-10-20 05:44:58 +00001518 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001519 else
1520 IsExplicitSpecialization = true;
John McCall4e2cbb22010-10-20 05:44:58 +00001521
1522 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001523 }
Mike Stump1eb44332009-09-09 15:08:12 +00001524
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001525 // If there were at least as many template-ids as there were template
1526 // parameter lists, then there are no template parameter lists remaining for
1527 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001528 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001529 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001531 // If there were too many template parameter lists, complain about that now.
John McCall4e2cbb22010-10-20 05:44:58 +00001532 if (ParamIdx != NumParamLists - 1) {
1533 while (ParamIdx < NumParamLists - 1) {
1534 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1535 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001536 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1537 : diag::err_template_spec_extra_headers)
John McCall4e2cbb22010-10-20 05:44:58 +00001538 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1539 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001540
1541 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1542 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1543 diag::note_explicit_template_spec_does_not_need_header)
1544 << ExplicitSpecializationsInSpecifier.back();
1545 ExplicitSpecializationsInSpecifier.pop_back();
1546 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001547
1548 // We have a template parameter list with no corresponding scope, which
1549 // means that the resulting template declaration can't be instantiated
1550 // properly (we'll end up with dependent nodes when we shouldn't).
1551 if (!isExplicitSpecHeader)
1552 Invalid = true;
1553
John McCall4e2cbb22010-10-20 05:44:58 +00001554 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001555 }
1556 }
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001558 // Return the last template parameter list, which corresponds to the
1559 // entity being declared.
1560 return ParamLists[NumParamLists - 1];
1561}
1562
Douglas Gregor7532dc62009-03-30 22:58:21 +00001563QualType Sema::CheckTemplateIdType(TemplateName Name,
1564 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001565 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001566 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001567 if (!Template) {
1568 // The template name does not resolve to a template, so we just
1569 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001570 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001571 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001572
Douglas Gregor40808ce2009-03-09 23:48:35 +00001573 // Check that the template argument list is well-formed for this
1574 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001575 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001576 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001577 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001578 return QualType();
1579
Douglas Gregor910f8002010-11-07 23:05:16 +00001580 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001581 "Converted template argument list is too short!");
1582
1583 QualType CanonType;
1584
Douglas Gregorcaddba02009-11-12 18:38:13 +00001585 if (Name.isDependent() ||
1586 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001587 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001588 // This class template specialization is a dependent
1589 // type. Therefore, its canonical type is another class template
1590 // specialization type that contains all of the converted
1591 // arguments in canonical form. This ensures that, e.g., A<T> and
1592 // A<T, T> have identical types when A is declared as:
1593 //
1594 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001595 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001596 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001597 Converted.data(),
1598 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Douglas Gregor1275ae02009-07-28 23:00:59 +00001600 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001601 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001602 // In the future, we need to teach getTemplateSpecializationType to only
1603 // build the canonical type and return that to us.
1604 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001605
1606 // This might work out to be a current instantiation, in which
1607 // case the canonical type needs to be the InjectedClassNameType.
1608 //
1609 // TODO: in theory this could be a simple hashtable lookup; most
1610 // changes to CurContext don't change the set of current
1611 // instantiations.
1612 if (isa<ClassTemplateDecl>(Template)) {
1613 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1614 // If we get out to a namespace, we're done.
1615 if (Ctx->isFileContext()) break;
1616
1617 // If this isn't a record, keep looking.
1618 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1619 if (!Record) continue;
1620
1621 // Look for one of the two cases with InjectedClassNameTypes
1622 // and check whether it's the same template.
1623 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1624 !Record->getDescribedClassTemplate())
1625 continue;
1626
1627 // Fetch the injected class name type and check whether its
1628 // injected type is equal to the type we just built.
1629 QualType ICNT = Context.getTypeDeclType(Record);
1630 QualType Injected = cast<InjectedClassNameType>(ICNT)
1631 ->getInjectedSpecializationType();
1632
1633 if (CanonType != Injected->getCanonicalTypeInternal())
1634 continue;
1635
1636 // If so, the canonical type of this TST is the injected
1637 // class name type of the record we just found.
1638 assert(ICNT.isCanonical());
1639 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001640 break;
1641 }
1642 }
Mike Stump1eb44332009-09-09 15:08:12 +00001643 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001644 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001645 // Find the class template specialization declaration that
1646 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001647 void *InsertPos = 0;
1648 ClassTemplateSpecializationDecl *Decl
Douglas Gregor910f8002010-11-07 23:05:16 +00001649 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1650 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001651 if (!Decl) {
1652 // This is the first time we have referenced this class template
1653 // specialization. Create the canonical declaration and add it to
1654 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001655 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001656 ClassTemplate->getTemplatedDecl()->getTagKind(),
1657 ClassTemplate->getDeclContext(),
1658 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00001659 ClassTemplate,
1660 Converted.data(),
1661 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001662 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001663 Decl->setLexicalDeclContext(CurContext);
1664 }
1665
1666 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001667 assert(isa<RecordType>(CanonType) &&
1668 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001669 }
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Douglas Gregor40808ce2009-03-09 23:48:35 +00001671 // Build the fully-sugared type for this class template
1672 // specialization, which refers back to the class template
1673 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001674 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001675}
1676
John McCallf312b1e2010-08-26 23:41:50 +00001677TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001678Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001679 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001680 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001681 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001682 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001683
Douglas Gregor40808ce2009-03-09 23:48:35 +00001684 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001685 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001686 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001687
John McCalld5532b62009-11-23 01:53:49 +00001688 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001689 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001690
1691 if (Result.isNull())
1692 return true;
1693
John McCalla93c9342009-12-07 02:54:59 +00001694 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001695 TemplateSpecializationTypeLoc TL
1696 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1697 TL.setTemplateNameLoc(TemplateLoc);
1698 TL.setLAngleLoc(LAngleLoc);
1699 TL.setRAngleLoc(RAngleLoc);
1700 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1701 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1702
John McCallb3d87482010-08-24 05:47:05 +00001703 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001704}
John McCallf1bbbb42009-09-04 01:14:41 +00001705
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001706TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1707 TypeResult TypeResult,
John McCallf312b1e2010-08-26 23:41:50 +00001708 TagUseKind TUK,
1709 TypeSpecifierType TagSpec,
1710 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001711 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001712 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001713
John McCalla93c9342009-12-07 02:54:59 +00001714 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001715 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001716
John McCall6b2becf2009-09-08 17:47:29 +00001717 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001718 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001719
John McCall6b2becf2009-09-08 17:47:29 +00001720 if (const RecordType *RT = Type->getAs<RecordType>()) {
1721 RecordDecl *D = RT->getDecl();
1722
1723 IdentifierInfo *Id = D->getIdentifier();
1724 assert(Id && "templated class must have an identifier");
1725
1726 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1727 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001728 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001729 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001730 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001731 }
1732 }
1733
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001734 ElaboratedTypeKeyword Keyword
1735 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1736 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001737
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001738 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1739 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1740 TL.setKeywordLoc(TagLoc);
1741 TL.setQualifierRange(SS.getRange());
1742 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1743 return CreateParsedType(ElabType, ElabDI);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001744}
1745
John McCall60d7b3a2010-08-24 06:29:42 +00001746ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001747 LookupResult &R,
1748 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001749 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001750 // FIXME: Can we do any checking at this point? I guess we could check the
1751 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001752 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001753 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001754
1755 // These should be filtered out by our callers.
1756 assert(!R.empty() && "empty lookup results when building templateid");
1757 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1758
1759 NestedNameSpecifier *Qualifier = 0;
1760 SourceRange QualifierRange;
1761 if (SS.isSet()) {
1762 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1763 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001764 }
John McCallc373d482010-01-27 01:50:18 +00001765
1766 // We don't want lookup warnings at this point.
1767 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001768
John McCallf7a1a742009-11-24 19:00:30 +00001769 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001770 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001771 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001772 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001773 RequiresADL, TemplateArgs,
1774 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001775
1776 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001777}
1778
John McCallf7a1a742009-11-24 19:00:30 +00001779// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001780ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001781Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001782 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001783 const TemplateArgumentListInfo &TemplateArgs) {
1784 DeclContext *DC;
1785 if (!(DC = computeDeclContext(SS, false)) ||
1786 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001787 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001788 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001790 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001791 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001792 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1793 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001794
John McCallf7a1a742009-11-24 19:00:30 +00001795 if (R.isAmbiguous())
1796 return ExprError();
1797
1798 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001799 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1800 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001801 return ExprError();
1802 }
1803
1804 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001805 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1806 << (NestedNameSpecifier*) SS.getScopeRep()
1807 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001808 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1809 return ExprError();
1810 }
1811
1812 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001813}
1814
Douglas Gregorc45c2322009-03-31 00:43:58 +00001815/// \brief Form a dependent template name.
1816///
1817/// This action forms a dependent template name given the template
1818/// name and its (presumably dependent) scope specifier. For
1819/// example, given "MetaFun::template apply", the scope specifier \p
1820/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1821/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001822TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1823 SourceLocation TemplateKWLoc,
1824 CXXScopeSpec &SS,
1825 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001826 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001827 bool EnteringContext,
1828 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001829 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1830 !getLangOptions().CPlusPlus0x)
1831 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1832 << FixItHint::CreateRemoval(TemplateKWLoc);
1833
Douglas Gregor0707bc52010-01-19 16:01:07 +00001834 DeclContext *LookupCtx = 0;
1835 if (SS.isSet())
1836 LookupCtx = computeDeclContext(SS, EnteringContext);
1837 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001838 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001839 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001840 // C++0x [temp.names]p5:
1841 // If a name prefixed by the keyword template is not the name of
1842 // a template, the program is ill-formed. [Note: the keyword
1843 // template may not be applied to non-template members of class
1844 // templates. -end note ] [ Note: as is the case with the
1845 // typename prefix, the template prefix is allowed in cases
1846 // where it is not strictly necessary; i.e., when the
1847 // nested-name-specifier or the expression on the left of the ->
1848 // or . is not dependent on a template-parameter, or the use
1849 // does not appear in the scope of a template. -end note]
1850 //
1851 // Note: C++03 was more strict here, because it banned the use of
1852 // the "template" keyword prior to a template-name that was not a
1853 // dependent name. C++ DR468 relaxed this requirement (the
1854 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001855 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001856 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001857 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1858 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001859 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001860 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1861 isa<CXXRecordDecl>(LookupCtx) &&
1862 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001863 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001864 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001865 Diag(Name.getSourceRange().getBegin(),
1866 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001867 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001868 << Name.getSourceRange()
1869 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001870 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001871 } else {
1872 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001873 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001874 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001875 }
1876
Mike Stump1eb44332009-09-09 15:08:12 +00001877 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001878 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001879
1880 switch (Name.getKind()) {
1881 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001882 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1883 Name.Identifier));
1884 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001885
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001886 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001887 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001888 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001889 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001890
1891 case UnqualifiedId::IK_LiteralOperatorId:
1892 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1893
Douglas Gregor014e88d2009-11-03 23:16:33 +00001894 default:
1895 break;
1896 }
1897
1898 Diag(Name.getSourceRange().getBegin(),
1899 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001900 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001901 << Name.getSourceRange()
1902 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001903 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001904}
1905
Mike Stump1eb44332009-09-09 15:08:12 +00001906bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001907 const TemplateArgumentLoc &AL,
Douglas Gregor910f8002010-11-07 23:05:16 +00001908 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001909 const TemplateArgument &Arg = AL.getArgument();
1910
Anders Carlsson436b1562009-06-13 00:33:33 +00001911 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001912 switch(Arg.getKind()) {
1913 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001914 // C++ [temp.arg.type]p1:
1915 // A template-argument for a template-parameter which is a
1916 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001917 break;
1918 case TemplateArgument::Template: {
1919 // We have a template type parameter but the template argument
1920 // is a template without any arguments.
1921 SourceRange SR = AL.getSourceRange();
1922 TemplateName Name = Arg.getAsTemplate();
1923 Diag(SR.getBegin(), diag::err_template_missing_args)
1924 << Name << SR;
1925 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1926 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001927
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001928 return true;
1929 }
1930 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001931 // We have a template type parameter but the template argument
1932 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001933 SourceRange SR = AL.getSourceRange();
1934 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001935 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001936
Anders Carlsson436b1562009-06-13 00:33:33 +00001937 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001938 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001939 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001940
John McCalla93c9342009-12-07 02:54:59 +00001941 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001942 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Anders Carlsson436b1562009-06-13 00:33:33 +00001944 // Add the converted template type argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001945 Converted.push_back(
John McCall833ca992009-10-29 08:12:44 +00001946 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001947 return false;
1948}
1949
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001950/// \brief Substitute template arguments into the default template argument for
1951/// the given template type parameter.
1952///
1953/// \param SemaRef the semantic analysis object for which we are performing
1954/// the substitution.
1955///
1956/// \param Template the template that we are synthesizing template arguments
1957/// for.
1958///
1959/// \param TemplateLoc the location of the template name that started the
1960/// template-id we are checking.
1961///
1962/// \param RAngleLoc the location of the right angle bracket ('>') that
1963/// terminates the template-id.
1964///
1965/// \param Param the template template parameter whose default we are
1966/// substituting into.
1967///
1968/// \param Converted the list of template arguments provided for template
1969/// parameters that precede \p Param in the template parameter list.
1970///
1971/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001972static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001973SubstDefaultTemplateArgument(Sema &SemaRef,
1974 TemplateDecl *Template,
1975 SourceLocation TemplateLoc,
1976 SourceLocation RAngleLoc,
1977 TemplateTypeParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00001978 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001979 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001980
1981 // If the argument type is dependent, instantiate it now based
1982 // on the previously-computed template arguments.
1983 if (ArgType->getType()->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001984 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1985 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001986
1987 MultiLevelTemplateArgumentList AllTemplateArgs
1988 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1989
1990 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00001991 Template, Converted.data(),
1992 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001993 SourceRange(TemplateLoc, RAngleLoc));
1994
1995 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1996 Param->getDefaultArgumentLoc(),
1997 Param->getDeclName());
1998 }
1999
2000 return ArgType;
2001}
2002
2003/// \brief Substitute template arguments into the default template argument for
2004/// the given non-type template parameter.
2005///
2006/// \param SemaRef the semantic analysis object for which we are performing
2007/// the substitution.
2008///
2009/// \param Template the template that we are synthesizing template arguments
2010/// for.
2011///
2012/// \param TemplateLoc the location of the template name that started the
2013/// template-id we are checking.
2014///
2015/// \param RAngleLoc the location of the right angle bracket ('>') that
2016/// terminates the template-id.
2017///
Douglas Gregor788cd062009-11-11 01:00:40 +00002018/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002019/// substituting into.
2020///
2021/// \param Converted the list of template arguments provided for template
2022/// parameters that precede \p Param in the template parameter list.
2023///
2024/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002025static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002026SubstDefaultTemplateArgument(Sema &SemaRef,
2027 TemplateDecl *Template,
2028 SourceLocation TemplateLoc,
2029 SourceLocation RAngleLoc,
2030 NonTypeTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002031 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2032 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2033 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002034
2035 MultiLevelTemplateArgumentList AllTemplateArgs
2036 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2037
2038 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002039 Template, Converted.data(),
2040 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002041 SourceRange(TemplateLoc, RAngleLoc));
2042
2043 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2044}
2045
Douglas Gregor788cd062009-11-11 01:00:40 +00002046/// \brief Substitute template arguments into the default template argument for
2047/// the given template template parameter.
2048///
2049/// \param SemaRef the semantic analysis object for which we are performing
2050/// the substitution.
2051///
2052/// \param Template the template that we are synthesizing template arguments
2053/// for.
2054///
2055/// \param TemplateLoc the location of the template name that started the
2056/// template-id we are checking.
2057///
2058/// \param RAngleLoc the location of the right angle bracket ('>') that
2059/// terminates the template-id.
2060///
2061/// \param Param the template template parameter whose default we are
2062/// substituting into.
2063///
2064/// \param Converted the list of template arguments provided for template
2065/// parameters that precede \p Param in the template parameter list.
2066///
2067/// \returns the substituted template argument, or NULL if an error occurred.
2068static TemplateName
2069SubstDefaultTemplateArgument(Sema &SemaRef,
2070 TemplateDecl *Template,
2071 SourceLocation TemplateLoc,
2072 SourceLocation RAngleLoc,
2073 TemplateTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002074 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2075 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2076 Converted.data(), Converted.size());
Douglas Gregor788cd062009-11-11 01:00:40 +00002077
2078 MultiLevelTemplateArgumentList AllTemplateArgs
2079 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2080
2081 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002082 Template, Converted.data(),
2083 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002084 SourceRange(TemplateLoc, RAngleLoc));
2085
2086 return SemaRef.SubstTemplateName(
2087 Param->getDefaultArgument().getArgument().getAsTemplate(),
2088 Param->getDefaultArgument().getTemplateNameLoc(),
2089 AllTemplateArgs);
2090}
2091
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002092/// \brief If the given template parameter has a default template
2093/// argument, substitute into that default template argument and
2094/// return the corresponding template argument.
2095TemplateArgumentLoc
2096Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2097 SourceLocation TemplateLoc,
2098 SourceLocation RAngleLoc,
2099 Decl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002100 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2101 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002102 if (!TypeParm->hasDefaultArgument())
2103 return TemplateArgumentLoc();
2104
John McCalla93c9342009-12-07 02:54:59 +00002105 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002106 TemplateLoc,
2107 RAngleLoc,
2108 TypeParm,
2109 Converted);
2110 if (DI)
2111 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2112
2113 return TemplateArgumentLoc();
2114 }
2115
2116 if (NonTypeTemplateParmDecl *NonTypeParm
2117 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2118 if (!NonTypeParm->hasDefaultArgument())
2119 return TemplateArgumentLoc();
2120
John McCall60d7b3a2010-08-24 06:29:42 +00002121 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002122 TemplateLoc,
2123 RAngleLoc,
2124 NonTypeParm,
2125 Converted);
2126 if (Arg.isInvalid())
2127 return TemplateArgumentLoc();
2128
2129 Expr *ArgE = Arg.takeAs<Expr>();
2130 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2131 }
2132
2133 TemplateTemplateParmDecl *TempTempParm
2134 = cast<TemplateTemplateParmDecl>(Param);
2135 if (!TempTempParm->hasDefaultArgument())
2136 return TemplateArgumentLoc();
2137
2138 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2139 TemplateLoc,
2140 RAngleLoc,
2141 TempTempParm,
2142 Converted);
2143 if (TName.isNull())
2144 return TemplateArgumentLoc();
2145
2146 return TemplateArgumentLoc(TemplateArgument(TName),
2147 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2148 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2149}
2150
Douglas Gregore7526412009-11-11 19:31:23 +00002151/// \brief Check that the given template argument corresponds to the given
2152/// template parameter.
2153bool Sema::CheckTemplateArgument(NamedDecl *Param,
2154 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002155 TemplateDecl *Template,
2156 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002157 SourceLocation RAngleLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002158 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002159 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002160 // Check template type parameters.
2161 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002162 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002163
Douglas Gregord9e15302009-11-11 19:41:09 +00002164 // Check non-type template parameters.
2165 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002166 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002167 // with the template arguments we've seen thus far. But if the
2168 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002169 QualType NTTPType = NTTP->getType();
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002170 if (NTTPType->isDependentType() &&
2171 !isa<TemplateTemplateParmDecl>(Template) &&
2172 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002173 // Do substitution on the type of the non-type template parameter.
2174 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002175 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002176 SourceRange(TemplateLoc, RAngleLoc));
2177
Douglas Gregor910f8002010-11-07 23:05:16 +00002178 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2179 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002180 NTTPType = SubstType(NTTPType,
2181 MultiLevelTemplateArgumentList(TemplateArgs),
2182 NTTP->getLocation(),
2183 NTTP->getDeclName());
2184 // If that worked, check the non-type template parameter type
2185 // for validity.
2186 if (!NTTPType.isNull())
2187 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2188 NTTP->getLocation());
2189 if (NTTPType.isNull())
2190 return true;
2191 }
2192
2193 switch (Arg.getArgument().getKind()) {
2194 case TemplateArgument::Null:
2195 assert(false && "Should never see a NULL template argument here");
2196 return true;
2197
2198 case TemplateArgument::Expression: {
2199 Expr *E = Arg.getArgument().getAsExpr();
2200 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002201 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002202 return true;
2203
Douglas Gregor910f8002010-11-07 23:05:16 +00002204 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002205 break;
2206 }
2207
2208 case TemplateArgument::Declaration:
2209 case TemplateArgument::Integral:
2210 // We've already checked this template argument, so just copy
2211 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002212 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002213 break;
2214
2215 case TemplateArgument::Template:
2216 // We were given a template template argument. It may not be ill-formed;
2217 // see below.
2218 if (DependentTemplateName *DTN
2219 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2220 // We have a template argument such as \c T::template X, which we
2221 // parsed as a template template argument. However, since we now
2222 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002223 // template name into an expression.
2224
2225 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2226 Arg.getTemplateNameLoc());
2227
John McCallf7a1a742009-11-24 19:00:30 +00002228 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2229 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002230 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002231 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002232
2233 TemplateArgument Result;
2234 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2235 return true;
2236
Douglas Gregor910f8002010-11-07 23:05:16 +00002237 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002238 break;
2239 }
2240
2241 // We have a template argument that actually does refer to a class
2242 // template, template alias, or template template parameter, and
2243 // therefore cannot be a non-type template argument.
2244 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2245 << Arg.getSourceRange();
2246
2247 Diag(Param->getLocation(), diag::note_template_param_here);
2248 return true;
2249
2250 case TemplateArgument::Type: {
2251 // We have a non-type template parameter but the template
2252 // argument is a type.
2253
2254 // C++ [temp.arg]p2:
2255 // In a template-argument, an ambiguity between a type-id and
2256 // an expression is resolved to a type-id, regardless of the
2257 // form of the corresponding template-parameter.
2258 //
2259 // We warn specifically about this case, since it can be rather
2260 // confusing for users.
2261 QualType T = Arg.getArgument().getAsType();
2262 SourceRange SR = Arg.getSourceRange();
2263 if (T->isFunctionType())
2264 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2265 else
2266 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2267 Diag(Param->getLocation(), diag::note_template_param_here);
2268 return true;
2269 }
2270
2271 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002272 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002273 break;
2274 }
2275
2276 return false;
2277 }
2278
2279
2280 // Check template template parameters.
2281 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2282
2283 // Substitute into the template parameter list of the template
2284 // template parameter, since previously-supplied template arguments
2285 // may appear within the template template parameter.
2286 {
2287 // Set up a template instantiation context.
2288 LocalInstantiationScope Scope(*this);
2289 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002290 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002291 SourceRange(TemplateLoc, RAngleLoc));
2292
Douglas Gregor910f8002010-11-07 23:05:16 +00002293 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2294 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002295 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2296 SubstDecl(TempParm, CurContext,
2297 MultiLevelTemplateArgumentList(TemplateArgs)));
2298 if (!TempParm)
2299 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002300 }
2301
2302 switch (Arg.getArgument().getKind()) {
2303 case TemplateArgument::Null:
2304 assert(false && "Should never see a NULL template argument here");
2305 return true;
2306
2307 case TemplateArgument::Template:
2308 if (CheckTemplateArgument(TempParm, Arg))
2309 return true;
2310
Douglas Gregor910f8002010-11-07 23:05:16 +00002311 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002312 break;
2313
2314 case TemplateArgument::Expression:
2315 case TemplateArgument::Type:
2316 // We have a template template parameter but the template
2317 // argument does not refer to a template.
2318 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2319 return true;
2320
2321 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002322 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002323 "Declaration argument with template template parameter");
2324 break;
2325 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002326 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002327 "Integral argument with template template parameter");
2328 break;
2329
2330 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002331 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002332 break;
2333 }
2334
2335 return false;
2336}
2337
Douglas Gregorc15cb382009-02-09 23:23:08 +00002338/// \brief Check that the given template argument list is well-formed
2339/// for specializing the given template.
2340bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2341 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002342 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002343 bool PartialTemplateArgs,
Douglas Gregor910f8002010-11-07 23:05:16 +00002344 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002345 TemplateParameterList *Params = Template->getTemplateParameters();
2346 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002347 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002348 bool Invalid = false;
2349
John McCalld5532b62009-11-23 01:53:49 +00002350 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2351
Mike Stump1eb44332009-09-09 15:08:12 +00002352 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002353 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002354
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002355 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002356 (NumArgs < Params->getMinRequiredArguments() &&
2357 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002358 // FIXME: point at either the first arg beyond what we can handle,
2359 // or the '>', depending on whether we have too many or too few
2360 // arguments.
2361 SourceRange Range;
2362 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002363 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002364 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2365 << (NumArgs > NumParams)
2366 << (isa<ClassTemplateDecl>(Template)? 0 :
2367 isa<FunctionTemplateDecl>(Template)? 1 :
2368 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2369 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002370 Diag(Template->getLocation(), diag::note_template_decl_here)
2371 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002372 Invalid = true;
2373 }
Mike Stump1eb44332009-09-09 15:08:12 +00002374
2375 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002376 // [...] The type and form of each template-argument specified in
2377 // a template-id shall match the type and form specified for the
2378 // corresponding parameter declared by the template in its
2379 // template-parameter-list.
Douglas Gregor14be16b2010-12-20 16:57:52 +00002380 llvm::SmallVector<TemplateArgument, 2> ArgumentPack;
2381 TemplateParameterList::iterator Param = Params->begin(),
2382 ParamEnd = Params->end();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002383 unsigned ArgIdx = 0;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002384 while (Param != ParamEnd) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002385 if (ArgIdx > NumArgs && PartialTemplateArgs)
2386 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002387
Douglas Gregorf35f8282009-11-11 21:54:23 +00002388 if (ArgIdx < NumArgs) {
2389 // Check the template argument we were given.
2390 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2391 TemplateLoc, RAngleLoc, Converted))
2392 return true;
2393
Douglas Gregor14be16b2010-12-20 16:57:52 +00002394 if ((*Param)->isTemplateParameterPack()) {
2395 // The template parameter was a template parameter pack, so take the
2396 // deduced argument and place it on the argument pack. Note that we
2397 // stay on the same template parameter so that we can deduce more
2398 // arguments.
2399 ArgumentPack.push_back(Converted.back());
2400 Converted.pop_back();
2401 } else {
2402 // Move to the next template parameter.
2403 ++Param;
2404 }
2405 ++ArgIdx;
Douglas Gregorf35f8282009-11-11 21:54:23 +00002406 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002407 }
Douglas Gregore7526412009-11-11 19:31:23 +00002408
Douglas Gregor14be16b2010-12-20 16:57:52 +00002409 // If we have a template parameter pack with no more corresponding
2410 // arguments, just break out now and we'll fill in the argument pack below.
2411 if ((*Param)->isTemplateParameterPack())
2412 break;
2413
Douglas Gregorf35f8282009-11-11 21:54:23 +00002414 // We have a default template argument that we will use.
2415 TemplateArgumentLoc Arg;
2416
2417 // Retrieve the default template argument from the template
2418 // parameter. For each kind of template parameter, we substitute the
2419 // template arguments provided thus far and any "outer" template arguments
2420 // (when the template parameter was part of a nested template) into
2421 // the default argument.
2422 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2423 if (!TTP->hasDefaultArgument()) {
2424 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2425 break;
2426 }
2427
John McCalla93c9342009-12-07 02:54:59 +00002428 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002429 Template,
2430 TemplateLoc,
2431 RAngleLoc,
2432 TTP,
2433 Converted);
2434 if (!ArgType)
2435 return true;
2436
2437 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2438 ArgType);
2439 } else if (NonTypeTemplateParmDecl *NTTP
2440 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2441 if (!NTTP->hasDefaultArgument()) {
2442 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2443 break;
2444 }
2445
John McCall60d7b3a2010-08-24 06:29:42 +00002446 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002447 TemplateLoc,
2448 RAngleLoc,
2449 NTTP,
2450 Converted);
2451 if (E.isInvalid())
2452 return true;
2453
2454 Expr *Ex = E.takeAs<Expr>();
2455 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2456 } else {
2457 TemplateTemplateParmDecl *TempParm
2458 = cast<TemplateTemplateParmDecl>(*Param);
2459
2460 if (!TempParm->hasDefaultArgument()) {
2461 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2462 break;
2463 }
2464
2465 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2466 TemplateLoc,
2467 RAngleLoc,
2468 TempParm,
2469 Converted);
2470 if (Name.isNull())
2471 return true;
2472
2473 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2474 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2475 TempParm->getDefaultArgument().getTemplateNameLoc());
2476 }
2477
2478 // Introduce an instantiation record that describes where we are using
2479 // the default template argument.
2480 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002481 Converted.data(), Converted.size(),
Douglas Gregorf35f8282009-11-11 21:54:23 +00002482 SourceRange(TemplateLoc, RAngleLoc));
2483
2484 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002485 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002486 RAngleLoc, Converted))
2487 return true;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002488
2489 // Move to the next template parameter and argument.
2490 ++Param;
2491 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002492 }
Douglas Gregor14be16b2010-12-20 16:57:52 +00002493
2494 // Form argument packs for each of the parameter packs remaining.
2495 while (Param != ParamEnd) {
2496 if ((*Param)->isTemplateParameterPack()) {
2497 // The parameter pack takes the contents of the current argument pack,
2498 // which we built up earlier.
2499 if (ArgumentPack.empty()) {
2500 Converted.push_back(TemplateArgument(0, 0));
2501 } else {
2502 TemplateArgument *PackedArgs
2503 = new (Context) TemplateArgument [ArgumentPack.size()];
2504 std::copy(ArgumentPack.begin(), ArgumentPack.end(), PackedArgs);
2505 Converted.push_back(TemplateArgument(PackedArgs, ArgumentPack.size()));
2506 ArgumentPack.clear();
2507 }
2508 }
2509
2510 ++Param;
2511 }
2512
Douglas Gregorc15cb382009-02-09 23:23:08 +00002513 return Invalid;
2514}
2515
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002516namespace {
2517 class UnnamedLocalNoLinkageFinder
2518 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2519 {
2520 Sema &S;
2521 SourceRange SR;
2522
2523 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2524
2525 public:
2526 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2527
2528 bool Visit(QualType T) {
2529 return inherited::Visit(T.getTypePtr());
2530 }
2531
2532#define TYPE(Class, Parent) \
2533 bool Visit##Class##Type(const Class##Type *);
2534#define ABSTRACT_TYPE(Class, Parent) \
2535 bool Visit##Class##Type(const Class##Type *) { return false; }
2536#define NON_CANONICAL_TYPE(Class, Parent) \
2537 bool Visit##Class##Type(const Class##Type *) { return false; }
2538#include "clang/AST/TypeNodes.def"
2539
2540 bool VisitTagDecl(const TagDecl *Tag);
2541 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2542 };
2543}
2544
2545bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2546 return false;
2547}
2548
2549bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2550 return Visit(T->getElementType());
2551}
2552
2553bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2554 return Visit(T->getPointeeType());
2555}
2556
2557bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2558 const BlockPointerType* T) {
2559 return Visit(T->getPointeeType());
2560}
2561
2562bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2563 const LValueReferenceType* T) {
2564 return Visit(T->getPointeeType());
2565}
2566
2567bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2568 const RValueReferenceType* T) {
2569 return Visit(T->getPointeeType());
2570}
2571
2572bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2573 const MemberPointerType* T) {
2574 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2575}
2576
2577bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2578 const ConstantArrayType* T) {
2579 return Visit(T->getElementType());
2580}
2581
2582bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2583 const IncompleteArrayType* T) {
2584 return Visit(T->getElementType());
2585}
2586
2587bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2588 const VariableArrayType* T) {
2589 return Visit(T->getElementType());
2590}
2591
2592bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2593 const DependentSizedArrayType* T) {
2594 return Visit(T->getElementType());
2595}
2596
2597bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2598 const DependentSizedExtVectorType* T) {
2599 return Visit(T->getElementType());
2600}
2601
2602bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2603 return Visit(T->getElementType());
2604}
2605
2606bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2607 return Visit(T->getElementType());
2608}
2609
2610bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2611 const FunctionProtoType* T) {
2612 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2613 AEnd = T->arg_type_end();
2614 A != AEnd; ++A) {
2615 if (Visit(*A))
2616 return true;
2617 }
2618
2619 return Visit(T->getResultType());
2620}
2621
2622bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2623 const FunctionNoProtoType* T) {
2624 return Visit(T->getResultType());
2625}
2626
2627bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2628 const UnresolvedUsingType*) {
2629 return false;
2630}
2631
2632bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2633 return false;
2634}
2635
2636bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2637 return Visit(T->getUnderlyingType());
2638}
2639
2640bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2641 return false;
2642}
2643
2644bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2645 return VisitTagDecl(T->getDecl());
2646}
2647
2648bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2649 return VisitTagDecl(T->getDecl());
2650}
2651
2652bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2653 const TemplateTypeParmType*) {
2654 return false;
2655}
2656
2657bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2658 const TemplateSpecializationType*) {
2659 return false;
2660}
2661
2662bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2663 const InjectedClassNameType* T) {
2664 return VisitTagDecl(T->getDecl());
2665}
2666
2667bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2668 const DependentNameType* T) {
2669 return VisitNestedNameSpecifier(T->getQualifier());
2670}
2671
2672bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2673 const DependentTemplateSpecializationType* T) {
2674 return VisitNestedNameSpecifier(T->getQualifier());
2675}
2676
Douglas Gregor7536dd52010-12-20 02:24:11 +00002677bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
2678 const PackExpansionType* T) {
2679 return Visit(T->getPattern());
2680}
2681
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002682bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2683 return false;
2684}
2685
2686bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2687 const ObjCInterfaceType *) {
2688 return false;
2689}
2690
2691bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2692 const ObjCObjectPointerType *) {
2693 return false;
2694}
2695
2696bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2697 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2698 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2699 << S.Context.getTypeDeclType(Tag) << SR;
2700 return true;
2701 }
2702
2703 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2704 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2705 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2706 return true;
2707 }
2708
2709 return false;
2710}
2711
2712bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2713 NestedNameSpecifier *NNS) {
2714 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2715 return true;
2716
2717 switch (NNS->getKind()) {
2718 case NestedNameSpecifier::Identifier:
2719 case NestedNameSpecifier::Namespace:
2720 case NestedNameSpecifier::Global:
2721 return false;
2722
2723 case NestedNameSpecifier::TypeSpec:
2724 case NestedNameSpecifier::TypeSpecWithTemplate:
2725 return Visit(QualType(NNS->getAsType(), 0));
2726 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00002727 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002728}
2729
2730
Douglas Gregorc15cb382009-02-09 23:23:08 +00002731/// \brief Check a template argument against its corresponding
2732/// template type parameter.
2733///
2734/// This routine implements the semantics of C++ [temp.arg.type]. It
2735/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002736bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002737 TypeSourceInfo *ArgInfo) {
2738 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002739 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00002740 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002741
2742 if (Arg->isVariablyModifiedType()) {
2743 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002744 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002745 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002746 }
2747
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002748 // C++03 [temp.arg.type]p2:
2749 // A local type, a type with no linkage, an unnamed type or a type
2750 // compounded from any of these types shall not be used as a
2751 // template-argument for a template type-parameter.
2752 //
2753 // C++0x allows these, and even in C++03 we allow them as an extension with
2754 // a warning.
Douglas Gregordb4d4bb2010-10-13 18:05:20 +00002755 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002756 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2757 (void)Finder.Visit(Context.getCanonicalType(Arg));
2758 }
2759
Douglas Gregorc15cb382009-02-09 23:23:08 +00002760 return false;
2761}
2762
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002763/// \brief Checks whether the given template argument is the address
2764/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002765static bool
2766CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2767 NonTypeTemplateParmDecl *Param,
2768 QualType ParamType,
2769 Expr *ArgIn,
2770 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002771 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002772 Expr *Arg = ArgIn;
2773 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002774
2775 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002776 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002777 Arg = Cast->getSubExpr();
2778
2779 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002780 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002781 // A template-argument for a non-type, non-template
2782 // template-parameter shall be one of: [...]
2783 //
2784 // -- the address of an object or function with external
2785 // linkage, including function templates and function
2786 // template-ids but excluding non-static class members,
2787 // expressed as & id-expression where the & is optional if
2788 // the name refers to a function or array, or if the
2789 // corresponding template-parameter is a reference; or
2790 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002792 // In C++98/03 mode, give an extension warning on any extra parentheses.
2793 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2794 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002795 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002796 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002797 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002798 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002799 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002800 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002801 }
2802
2803 Arg = Parens->getSubExpr();
2804 }
2805
Douglas Gregorb7a09262010-04-01 18:32:35 +00002806 bool AddressTaken = false;
2807 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002808 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002809 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002810 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002811 AddressTaken = true;
2812 AddrOpLoc = UnOp->getOperatorLoc();
2813 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002814 } else
2815 DRE = dyn_cast<DeclRefExpr>(Arg);
2816
Douglas Gregorb7a09262010-04-01 18:32:35 +00002817 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002818 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2819 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002820 S.Diag(Param->getLocation(), diag::note_template_param_here);
2821 return true;
2822 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002823
2824 // Stop checking the precise nature of the argument if it is value dependent,
2825 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002826 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00002827 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00002828 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002829 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002830
Douglas Gregorb7a09262010-04-01 18:32:35 +00002831 if (!isa<ValueDecl>(DRE->getDecl())) {
2832 S.Diag(Arg->getSourceRange().getBegin(),
2833 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002834 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002835 S.Diag(Param->getLocation(), diag::note_template_param_here);
2836 return true;
2837 }
2838
2839 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002840
2841 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002842 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2843 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002844 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002845 S.Diag(Param->getLocation(), diag::note_template_param_here);
2846 return true;
2847 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002848
2849 // Cannot refer to non-static member functions
2850 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002851 if (!Method->isStatic()) {
2852 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002853 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002854 S.Diag(Param->getLocation(), diag::note_template_param_here);
2855 return true;
2856 }
Mike Stump1eb44332009-09-09 15:08:12 +00002857
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002858 // Functions must have external linkage.
2859 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002860 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002861 S.Diag(Arg->getSourceRange().getBegin(),
2862 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002863 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002864 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002865 << true;
2866 return true;
2867 }
2868
2869 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002870 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002871
Douglas Gregorb7a09262010-04-01 18:32:35 +00002872 // If the template parameter has pointer type, the function decays.
2873 if (ParamType->isPointerType() && !AddressTaken)
2874 ArgType = S.Context.getPointerType(Func->getType());
2875 else if (AddressTaken && ParamType->isReferenceType()) {
2876 // If we originally had an address-of operator, but the
2877 // parameter has reference type, complain and (if things look
2878 // like they will work) drop the address-of operator.
2879 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2880 ParamType.getNonReferenceType())) {
2881 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2882 << ParamType;
2883 S.Diag(Param->getLocation(), diag::note_template_param_here);
2884 return true;
2885 }
2886
2887 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2888 << ParamType
2889 << FixItHint::CreateRemoval(AddrOpLoc);
2890 S.Diag(Param->getLocation(), diag::note_template_param_here);
2891
2892 ArgType = Func->getType();
2893 }
2894 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002895 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002896 S.Diag(Arg->getSourceRange().getBegin(),
2897 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002898 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002899 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002900 << true;
2901 return true;
2902 }
2903
Douglas Gregorb7a09262010-04-01 18:32:35 +00002904 // A value of reference type is not an object.
2905 if (Var->getType()->isReferenceType()) {
2906 S.Diag(Arg->getSourceRange().getBegin(),
2907 diag::err_template_arg_reference_var)
2908 << Var->getType() << Arg->getSourceRange();
2909 S.Diag(Param->getLocation(), diag::note_template_param_here);
2910 return true;
2911 }
2912
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002913 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002914 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002915
2916 // If the template parameter has pointer type, we must have taken
2917 // the address of this object.
2918 if (ParamType->isReferenceType()) {
2919 if (AddressTaken) {
2920 // If we originally had an address-of operator, but the
2921 // parameter has reference type, complain and (if things look
2922 // like they will work) drop the address-of operator.
2923 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2924 ParamType.getNonReferenceType())) {
2925 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2926 << ParamType;
2927 S.Diag(Param->getLocation(), diag::note_template_param_here);
2928 return true;
2929 }
2930
2931 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2932 << ParamType
2933 << FixItHint::CreateRemoval(AddrOpLoc);
2934 S.Diag(Param->getLocation(), diag::note_template_param_here);
2935
2936 ArgType = Var->getType();
2937 }
2938 } else if (!AddressTaken && ParamType->isPointerType()) {
2939 if (Var->getType()->isArrayType()) {
2940 // Array-to-pointer decay.
2941 ArgType = S.Context.getArrayDecayedType(Var->getType());
2942 } else {
2943 // If the template parameter has pointer type but the address of
2944 // this object was not taken, complain and (possibly) recover by
2945 // taking the address of the entity.
2946 ArgType = S.Context.getPointerType(Var->getType());
2947 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2948 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2949 << ParamType;
2950 S.Diag(Param->getLocation(), diag::note_template_param_here);
2951 return true;
2952 }
2953
2954 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2955 << ParamType
2956 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2957
2958 S.Diag(Param->getLocation(), diag::note_template_param_here);
2959 }
2960 }
2961 } else {
2962 // We found something else, but we don't know specifically what it is.
2963 S.Diag(Arg->getSourceRange().getBegin(),
2964 diag::err_template_arg_not_object_or_func)
2965 << Arg->getSourceRange();
2966 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2967 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002968 }
Mike Stump1eb44332009-09-09 15:08:12 +00002969
Douglas Gregorb7a09262010-04-01 18:32:35 +00002970 if (ParamType->isPointerType() &&
2971 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2972 S.IsQualificationConversion(ArgType, ParamType)) {
2973 // For pointer-to-object types, qualification conversions are
2974 // permitted.
2975 } else {
2976 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2977 if (!ParamRef->getPointeeType()->isFunctionType()) {
2978 // C++ [temp.arg.nontype]p5b3:
2979 // For a non-type template-parameter of type reference to
2980 // object, no conversions apply. The type referred to by the
2981 // reference may be more cv-qualified than the (otherwise
2982 // identical) type of the template- argument. The
2983 // template-parameter is bound directly to the
2984 // template-argument, which shall be an lvalue.
2985
2986 // FIXME: Other qualifiers?
2987 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2988 unsigned ArgQuals = ArgType.getCVRQualifiers();
2989
2990 if ((ParamQuals | ArgQuals) != ParamQuals) {
2991 S.Diag(Arg->getSourceRange().getBegin(),
2992 diag::err_template_arg_ref_bind_ignores_quals)
2993 << ParamType << Arg->getType()
2994 << Arg->getSourceRange();
2995 S.Diag(Param->getLocation(), diag::note_template_param_here);
2996 return true;
2997 }
2998 }
2999 }
3000
3001 // At this point, the template argument refers to an object or
3002 // function with external linkage. We now need to check whether the
3003 // argument and parameter types are compatible.
3004 if (!S.Context.hasSameUnqualifiedType(ArgType,
3005 ParamType.getNonReferenceType())) {
3006 // We can't perform this conversion or binding.
3007 if (ParamType->isReferenceType())
3008 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3009 << ParamType << Arg->getType() << Arg->getSourceRange();
3010 else
3011 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3012 << Arg->getType() << ParamType << Arg->getSourceRange();
3013 S.Diag(Param->getLocation(), diag::note_template_param_here);
3014 return true;
3015 }
3016 }
3017
3018 // Create the template argument.
3019 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00003020 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003021 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003022}
3023
3024/// \brief Checks whether the given template argument is a pointer to
3025/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003026bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
3027 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003028 bool Invalid = false;
3029
3030 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003031 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003032 Arg = Cast->getSubExpr();
3033
3034 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003035 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003036 // A template-argument for a non-type, non-template
3037 // template-parameter shall be one of: [...]
3038 //
3039 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003040 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003041
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003042 // In C++98/03 mode, give an extension warning on any extra parentheses.
3043 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3044 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003045 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003046 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00003047 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003048 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003049 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003050 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003051 }
3052
3053 Arg = Parens->getSubExpr();
3054 }
3055
Douglas Gregorcaddba02009-11-12 18:38:13 +00003056 // A pointer-to-member constant written &Class::member.
3057 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003058 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003059 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3060 if (DRE && !DRE->getQualifier())
3061 DRE = 0;
3062 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003063 }
3064 // A constant of pointer-to-member type.
3065 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3066 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3067 if (VD->getType()->isMemberPointerType()) {
3068 if (isa<NonTypeTemplateParmDecl>(VD) ||
3069 (isa<VarDecl>(VD) &&
3070 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3071 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003072 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003073 else
3074 Converted = TemplateArgument(VD->getCanonicalDecl());
3075 return Invalid;
3076 }
3077 }
3078 }
3079
3080 DRE = 0;
3081 }
3082
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003083 if (!DRE)
3084 return Diag(Arg->getSourceRange().getBegin(),
3085 diag::err_template_arg_not_pointer_to_member_form)
3086 << Arg->getSourceRange();
3087
3088 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3089 assert((isa<FieldDecl>(DRE->getDecl()) ||
3090 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3091 "Only non-static member pointers can make it here");
3092
3093 // Okay: this is the address of a non-static member, and therefore
3094 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003095 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003096 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003097 else
3098 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003099 return Invalid;
3100 }
3101
3102 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003103 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003104 diag::err_template_arg_not_pointer_to_member_form)
3105 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003106 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003107 diag::note_template_arg_refers_here);
3108 return true;
3109}
3110
Douglas Gregorc15cb382009-02-09 23:23:08 +00003111/// \brief Check a template argument against its corresponding
3112/// non-type template parameter.
3113///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003114/// This routine implements the semantics of C++ [temp.arg.nontype].
3115/// It returns true if an error occurred, and false otherwise. \p
3116/// InstantiatedParamType is the type of the non-type template
3117/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003118///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003119/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00003120bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00003121 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00003122 TemplateArgument &Converted,
3123 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003124 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3125
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003126 // If either the parameter has a dependent type or the argument is
3127 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003128 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3129 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003130 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003131 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00003132 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003133
3134 // C++ [temp.arg.nontype]p5:
3135 // The following conversions are performed on each expression used
3136 // as a non-type template-argument. If a non-type
3137 // template-argument cannot be converted to the type of the
3138 // corresponding template-parameter then the program is
3139 // ill-formed.
3140 //
3141 // -- for a non-type template-parameter of integral or
3142 // enumeration type, integral promotions (4.5) and integral
3143 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003144 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003145 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003146 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003147 // C++ [temp.arg.nontype]p1:
3148 // A template-argument for a non-type, non-template
3149 // template-parameter shall be one of:
3150 //
3151 // -- an integral constant-expression of integral or enumeration
3152 // type; or
3153 // -- the name of a non-type template-parameter; or
3154 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003155 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003156 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003157 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003158 diag::err_template_arg_not_integral_or_enumeral)
3159 << ArgType << Arg->getSourceRange();
3160 Diag(Param->getLocation(), diag::note_template_param_here);
3161 return true;
3162 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003163 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003164 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3165 << ArgType << Arg->getSourceRange();
3166 return true;
3167 }
3168
Douglas Gregor02024a92010-03-28 02:42:43 +00003169 // From here on out, all we care about are the unqualified forms
3170 // of the parameter and argument types.
3171 ParamType = ParamType.getUnqualifiedType();
3172 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003173
3174 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003175 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003176 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003177 } else if (CTAK == CTAK_Deduced) {
3178 // C++ [temp.deduct.type]p17:
3179 // If, in the declaration of a function template with a non-type
3180 // template-parameter, the non-type template- parameter is used
3181 // in an expression in the function parameter-list and, if the
3182 // corresponding template-argument is deduced, the
3183 // template-argument type shall match the type of the
3184 // template-parameter exactly, except that a template-argument
3185 // deduced from an array bound may be of any integral type.
3186 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3187 << ArgType << ParamType;
3188 Diag(Param->getLocation(), diag::note_template_param_here);
John McCalldaa8e4e2010-11-15 09:13:47 +00003189 return true;
3190 } else if (ParamType->isBooleanType()) {
3191 // This is an integral-to-boolean conversion.
3192 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003193 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3194 !ParamType->isEnumeralType()) {
3195 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00003196 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003197 } else {
3198 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003199 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003200 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003201 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003202 Diag(Param->getLocation(), diag::note_template_param_here);
3203 return true;
3204 }
3205
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003206 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003207 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003208 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003209
3210 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003211 llvm::APSInt OldValue = Value;
3212
3213 // Coerce the template argument's value to the value it will have
3214 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003215 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003216 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003217 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003218 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003219
3220 // Complain if an unsigned parameter received a negative value.
3221 if (IntegerType->isUnsignedIntegerType()
3222 && (OldValue.isSigned() && OldValue.isNegative())) {
3223 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3224 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3225 << Arg->getSourceRange();
3226 Diag(Param->getLocation(), diag::note_template_param_here);
3227 }
3228
3229 // Complain if we overflowed the template parameter's type.
3230 unsigned RequiredBits;
3231 if (IntegerType->isUnsignedIntegerType())
3232 RequiredBits = OldValue.getActiveBits();
3233 else if (OldValue.isUnsigned())
3234 RequiredBits = OldValue.getActiveBits() + 1;
3235 else
3236 RequiredBits = OldValue.getMinSignedBits();
3237 if (RequiredBits > AllowedBits) {
3238 Diag(Arg->getSourceRange().getBegin(),
3239 diag::warn_template_arg_too_large)
3240 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3241 << Arg->getSourceRange();
3242 Diag(Param->getLocation(), diag::note_template_param_here);
3243 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003244 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003245
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003246 // Add the value of this argument to the list of converted
3247 // arguments. We use the bitwidth and signedness of the template
3248 // parameter.
3249 if (Arg->isValueDependent()) {
3250 // The argument is value-dependent. Create a new
3251 // TemplateArgument with the converted expression.
3252 Converted = TemplateArgument(Arg);
3253 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003254 }
3255
John McCall833ca992009-10-29 08:12:44 +00003256 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00003257 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003258 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003259 return false;
3260 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003261
John McCall6bb80172010-03-30 21:47:33 +00003262 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3263
Douglas Gregorb7a09262010-04-01 18:32:35 +00003264 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3265 // from a template argument of type std::nullptr_t to a non-type
3266 // template parameter of type pointer to object, pointer to
3267 // function, or pointer-to-member, respectively.
3268 if (ArgType->isNullPtrType() &&
3269 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3270 Converted = TemplateArgument((NamedDecl *)0);
3271 return false;
3272 }
3273
Douglas Gregorb86b0572009-02-11 01:18:59 +00003274 // Handle pointer-to-function, reference-to-function, and
3275 // pointer-to-member-function all in (roughly) the same way.
3276 if (// -- For a non-type template-parameter of type pointer to
3277 // function, only the function-to-pointer conversion (4.3) is
3278 // applied. If the template-argument represents a set of
3279 // overloaded functions (or a pointer to such), the matching
3280 // function is selected from the set (13.4).
3281 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003282 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003283 // -- For a non-type template-parameter of type reference to
3284 // function, no conversions apply. If the template-argument
3285 // represents a set of overloaded functions, the matching
3286 // function is selected from the set (13.4).
3287 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003288 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003289 // -- For a non-type template-parameter of type pointer to
3290 // member function, no conversions apply. If the
3291 // template-argument represents a set of overloaded member
3292 // functions, the matching member function is selected from
3293 // the set (13.4).
3294 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003295 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003296 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003297
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003298 if (Arg->getType() == Context.OverloadTy) {
3299 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3300 true,
3301 FoundResult)) {
3302 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3303 return true;
3304
3305 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3306 ArgType = Arg->getType();
3307 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003308 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00003309 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003310
Douglas Gregorb7a09262010-04-01 18:32:35 +00003311 if (!ParamType->isMemberPointerType())
3312 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3313 ParamType,
3314 Arg, Converted);
3315
3316 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00003317 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00003318 } else if (!Context.hasSameUnqualifiedType(ArgType,
3319 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003320 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003321 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003322 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003323 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003324 Diag(Param->getLocation(), diag::note_template_param_here);
3325 return true;
3326 }
Mike Stump1eb44332009-09-09 15:08:12 +00003327
Douglas Gregorb7a09262010-04-01 18:32:35 +00003328 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00003329 }
3330
Chris Lattnerfe90de72009-02-20 21:37:53 +00003331 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003332 // -- for a non-type template-parameter of type pointer to
3333 // object, qualification conversions (4.4) and the
3334 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003335 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003336 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003337 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003338
Douglas Gregorb7a09262010-04-01 18:32:35 +00003339 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3340 ParamType,
3341 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003342 }
Mike Stump1eb44332009-09-09 15:08:12 +00003343
Ted Kremenek6217b802009-07-29 21:53:49 +00003344 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003345 // -- For a non-type template-parameter of type reference to
3346 // object, no conversions apply. The type referred to by the
3347 // reference may be more cv-qualified than the (otherwise
3348 // identical) type of the template-argument. The
3349 // template-parameter is bound directly to the
3350 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003351 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003352 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003353
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003354 if (Arg->getType() == Context.OverloadTy) {
3355 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3356 ParamRefType->getPointeeType(),
3357 true,
3358 FoundResult)) {
3359 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3360 return true;
3361
3362 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3363 ArgType = Arg->getType();
3364 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00003365 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00003366 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003367
Douglas Gregorb7a09262010-04-01 18:32:35 +00003368 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3369 ParamType,
3370 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003371 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003372
3373 // -- For a non-type template-parameter of type pointer to data
3374 // member, qualification conversions (4.4) are applied.
3375 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3376
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003377 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003378 // Types match exactly: nothing more to do here.
3379 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00003380 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00003381 } else {
3382 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003383 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003384 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003385 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003386 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003387 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003388 }
3389
Douglas Gregorcaddba02009-11-12 18:38:13 +00003390 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003391}
3392
3393/// \brief Check a template argument against its corresponding
3394/// template template parameter.
3395///
3396/// This routine implements the semantics of C++ [temp.arg.template].
3397/// It returns true if an error occurred, and false otherwise.
3398bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003399 const TemplateArgumentLoc &Arg) {
3400 TemplateName Name = Arg.getArgument().getAsTemplate();
3401 TemplateDecl *Template = Name.getAsTemplateDecl();
3402 if (!Template) {
3403 // Any dependent template name is fine.
3404 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3405 return false;
3406 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003407
3408 // C++ [temp.arg.template]p1:
3409 // A template-argument for a template template-parameter shall be
3410 // the name of a class template, expressed as id-expression. Only
3411 // primary class templates are considered when matching the
3412 // template template argument with the corresponding parameter;
3413 // partial specializations are not considered even if their
3414 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003415 //
3416 // Note that we also allow template template parameters here, which
3417 // will happen when we are dealing with, e.g., class template
3418 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003419 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003420 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003421 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003422 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003423 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003424 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003425 << Template;
3426 }
3427
3428 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3429 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003430 true,
3431 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003432 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003433}
3434
Douglas Gregor02024a92010-03-28 02:42:43 +00003435/// \brief Given a non-type template argument that refers to a
3436/// declaration and the type of its corresponding non-type template
3437/// parameter, produce an expression that properly refers to that
3438/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003439ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003440Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3441 QualType ParamType,
3442 SourceLocation Loc) {
3443 assert(Arg.getKind() == TemplateArgument::Declaration &&
3444 "Only declaration template arguments permitted here");
3445 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3446
3447 if (VD->getDeclContext()->isRecord() &&
3448 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3449 // If the value is a class member, we might have a pointer-to-member.
3450 // Determine whether the non-type template template parameter is of
3451 // pointer-to-member type. If so, we need to build an appropriate
3452 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3453 // would refer to the member itself.
3454 if (ParamType->isMemberPointerType()) {
3455 QualType ClassType
3456 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3457 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003458 = NestedNameSpecifier::Create(Context, 0, false,
3459 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003460 CXXScopeSpec SS;
3461 SS.setScopeRep(Qualifier);
John McCalldfa1edb2010-11-23 20:48:44 +00003462
3463 // The actual value-ness of this is unimportant, but for
3464 // internal consistency's sake, references to instance methods
3465 // are r-values.
3466 ExprValueKind VK = VK_LValue;
3467 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3468 VK = VK_RValue;
3469
John McCall60d7b3a2010-08-24 06:29:42 +00003470 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00003471 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00003472 VK,
John McCallf89e55a2010-11-18 06:31:45 +00003473 Loc,
3474 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00003475 if (RefExpr.isInvalid())
3476 return ExprError();
3477
John McCall2de56d12010-08-25 11:45:40 +00003478 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003479
3480 // We might need to perform a trailing qualification conversion, since
3481 // the element type on the parameter could be more qualified than the
3482 // element type in the expression we constructed.
3483 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3484 ParamType.getUnqualifiedType())) {
3485 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003486 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003487 RefExpr = Owned(RefE);
3488 }
3489
Douglas Gregor02024a92010-03-28 02:42:43 +00003490 assert(!RefExpr.isInvalid() &&
3491 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003492 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003493 return move(RefExpr);
3494 }
3495 }
3496
3497 QualType T = VD->getType().getNonReferenceType();
3498 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003499 // When the non-type template parameter is a pointer, take the
3500 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00003501 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003502 if (RefExpr.isInvalid())
3503 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003504
3505 if (T->isFunctionType() || T->isArrayType()) {
3506 // Decay functions and arrays.
3507 Expr *RefE = (Expr *)RefExpr.get();
3508 DefaultFunctionArrayConversion(RefE);
3509 if (RefE != RefExpr.get()) {
3510 RefExpr.release();
3511 RefExpr = Owned(RefE);
3512 }
3513
3514 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003515 }
3516
Douglas Gregorb7a09262010-04-01 18:32:35 +00003517 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003518 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003519 }
3520
John McCallf89e55a2010-11-18 06:31:45 +00003521 ExprValueKind VK = VK_RValue;
3522
Douglas Gregor02024a92010-03-28 02:42:43 +00003523 // If the non-type template parameter has reference type, qualify the
3524 // resulting declaration reference with the extra qualifiers on the
3525 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00003526 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3527 VK = VK_LValue;
3528 T = Context.getQualifiedType(T,
3529 TargetRef->getPointeeType().getQualifiers());
3530 }
Douglas Gregor02024a92010-03-28 02:42:43 +00003531
John McCallf89e55a2010-11-18 06:31:45 +00003532 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003533}
3534
3535/// \brief Construct a new expression that refers to the given
3536/// integral template argument with the given source-location
3537/// information.
3538///
3539/// This routine takes care of the mapping from an integral template
3540/// argument (which may have any integral type) to the appropriate
3541/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003542ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003543Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3544 SourceLocation Loc) {
3545 assert(Arg.getKind() == TemplateArgument::Integral &&
3546 "Operation is only value for integral template arguments");
3547 QualType T = Arg.getIntegralType();
3548 if (T->isCharType() || T->isWideCharType())
3549 return Owned(new (Context) CharacterLiteral(
3550 Arg.getAsIntegral()->getZExtValue(),
3551 T->isWideCharType(),
3552 T,
3553 Loc));
3554 if (T->isBooleanType())
3555 return Owned(new (Context) CXXBoolLiteralExpr(
3556 Arg.getAsIntegral()->getBoolValue(),
3557 T,
3558 Loc));
3559
Peter Collingbournefb7b3632010-12-15 15:06:14 +00003560 QualType BT;
3561 if (const EnumType *ET = T->getAs<EnumType>())
3562 BT = ET->getDecl()->getPromotionType();
3563 else
3564 BT = T;
3565
3566 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3567 ImpCastExprToType(E, T, CK_IntegralCast);
3568
3569 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00003570}
3571
3572
Douglas Gregorddc29e12009-02-06 22:42:48 +00003573/// \brief Determine whether the given template parameter lists are
3574/// equivalent.
3575///
Mike Stump1eb44332009-09-09 15:08:12 +00003576/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003577/// source code as part of a new template declaration.
3578///
3579/// \param Old The old template parameter list, typically found via
3580/// name lookup of the template declared with this template parameter
3581/// list.
3582///
3583/// \param Complain If true, this routine will produce a diagnostic if
3584/// the template parameter lists are not equivalent.
3585///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003586/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003587///
3588/// \param TemplateArgLoc If this source location is valid, then we
3589/// are actually checking the template parameter list of a template
3590/// argument (New) against the template parameter list of its
3591/// corresponding template template parameter (Old). We produce
3592/// slightly different diagnostics in this scenario.
3593///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003594/// \returns True if the template parameter lists are equal, false
3595/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003596bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003597Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3598 TemplateParameterList *Old,
3599 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003600 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003601 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003602 if (Old->size() != New->size()) {
3603 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003604 unsigned NextDiag = diag::err_template_param_list_different_arity;
3605 if (TemplateArgLoc.isValid()) {
3606 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3607 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003608 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003609 Diag(New->getTemplateLoc(), NextDiag)
3610 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003611 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003612 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003613 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003614 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003615 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3616 }
3617
3618 return false;
3619 }
3620
3621 for (TemplateParameterList::iterator OldParm = Old->begin(),
3622 OldParmEnd = Old->end(), NewParm = New->begin();
3623 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3624 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003625 if (Complain) {
3626 unsigned NextDiag = diag::err_template_param_different_kind;
3627 if (TemplateArgLoc.isValid()) {
3628 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3629 NextDiag = diag::note_template_param_different_kind;
3630 }
3631 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003632 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003633 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003634 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003635 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003636 return false;
3637 }
3638
Douglas Gregora417b872010-06-04 08:34:32 +00003639 if (TemplateTypeParmDecl *OldTTP
3640 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3641 // Template type parameters are equivalent if either both are template
3642 // type parameter packs or neither are (since we know we're at the same
3643 // index).
3644 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3645 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3646 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3647 // allow one to match a template parameter pack in the template
3648 // parameter list of a template template parameter to one or more
3649 // template parameters in the template parameter list of the
3650 // corresponding template template argument.
3651 if (Complain) {
3652 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3653 if (TemplateArgLoc.isValid()) {
3654 Diag(TemplateArgLoc,
3655 diag::err_template_arg_template_params_mismatch);
3656 NextDiag = diag::note_template_parameter_pack_non_pack;
3657 }
3658 Diag(NewTTP->getLocation(), NextDiag)
3659 << 0 << NewTTP->isParameterPack();
3660 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3661 << 0 << OldTTP->isParameterPack();
3662 }
3663 return false;
3664 }
Mike Stump1eb44332009-09-09 15:08:12 +00003665 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003666 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3667 // The types of non-type template parameters must agree.
3668 NonTypeTemplateParmDecl *NewNTTP
3669 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003670
3671 // If we are matching a template template argument to a template
3672 // template parameter and one of the non-type template parameter types
3673 // is dependent, then we must wait until template instantiation time
3674 // to actually compare the arguments.
3675 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3676 (OldNTTP->getType()->isDependentType() ||
3677 NewNTTP->getType()->isDependentType()))
3678 continue;
3679
Douglas Gregorddc29e12009-02-06 22:42:48 +00003680 if (Context.getCanonicalType(OldNTTP->getType()) !=
3681 Context.getCanonicalType(NewNTTP->getType())) {
3682 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003683 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3684 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003685 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003686 diag::err_template_arg_template_params_mismatch);
3687 NextDiag = diag::note_template_nontype_parm_different_type;
3688 }
3689 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003690 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003691 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003692 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003693 diag::note_template_nontype_parm_prev_declaration)
3694 << OldNTTP->getType();
3695 }
3696 return false;
3697 }
3698 } else {
3699 // The template parameter lists of template template
3700 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003701 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003702 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003703 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003704 = cast<TemplateTemplateParmDecl>(*OldParm);
3705 TemplateTemplateParmDecl *NewTTP
3706 = cast<TemplateTemplateParmDecl>(*NewParm);
3707 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3708 OldTTP->getTemplateParameters(),
3709 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003710 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003711 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003712 return false;
3713 }
3714 }
3715
3716 return true;
3717}
3718
3719/// \brief Check whether a template can be declared within this scope.
3720///
3721/// If the template declaration is valid in this scope, returns
3722/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003723bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003724Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003725 // Find the nearest enclosing declaration scope.
3726 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3727 (S->getFlags() & Scope::TemplateParamScope) != 0)
3728 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003729
Douglas Gregorddc29e12009-02-06 22:42:48 +00003730 // C++ [temp]p2:
3731 // A template-declaration can appear only as a namespace scope or
3732 // class scope declaration.
3733 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003734 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3735 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003736 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003737 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003738
Eli Friedman1503f772009-07-31 01:43:05 +00003739 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003740 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003741
3742 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3743 return false;
3744
Mike Stump1eb44332009-09-09 15:08:12 +00003745 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003746 diag::err_template_outside_namespace_or_class_scope)
3747 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003748}
Douglas Gregorcc636682009-02-17 23:15:12 +00003749
Douglas Gregord5cb8762009-10-07 00:13:32 +00003750/// \brief Determine what kind of template specialization the given declaration
3751/// is.
3752static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3753 if (!D)
3754 return TSK_Undeclared;
3755
Douglas Gregorf6b11852009-10-08 15:14:33 +00003756 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3757 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003758 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3759 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003760 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3761 return Var->getTemplateSpecializationKind();
3762
Douglas Gregord5cb8762009-10-07 00:13:32 +00003763 return TSK_Undeclared;
3764}
3765
Douglas Gregor9302da62009-10-14 23:50:59 +00003766/// \brief Check whether a specialization is well-formed in the current
3767/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003768///
Douglas Gregor9302da62009-10-14 23:50:59 +00003769/// This routine determines whether a template specialization can be declared
3770/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003771///
3772/// \param S the semantic analysis object for which this check is being
3773/// performed.
3774///
3775/// \param Specialized the entity being specialized or instantiated, which
3776/// may be a kind of template (class template, function template, etc.) or
3777/// a member of a class template (member function, static data member,
3778/// member class).
3779///
3780/// \param PrevDecl the previous declaration of this entity, if any.
3781///
3782/// \param Loc the location of the explicit specialization or instantiation of
3783/// this entity.
3784///
3785/// \param IsPartialSpecialization whether this is a partial specialization of
3786/// a class template.
3787///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003788/// \returns true if there was an error that we cannot recover from, false
3789/// otherwise.
3790static bool CheckTemplateSpecializationScope(Sema &S,
3791 NamedDecl *Specialized,
3792 NamedDecl *PrevDecl,
3793 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003794 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003795 // Keep these "kind" numbers in sync with the %select statements in the
3796 // various diagnostics emitted by this routine.
3797 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003798 bool isTemplateSpecialization = false;
3799 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003800 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003801 isTemplateSpecialization = true;
3802 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003803 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003804 isTemplateSpecialization = true;
3805 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003806 EntityKind = 3;
3807 else if (isa<VarDecl>(Specialized))
3808 EntityKind = 4;
3809 else if (isa<RecordDecl>(Specialized))
3810 EntityKind = 5;
3811 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003812 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3813 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003814 return true;
3815 }
3816
Douglas Gregor88b70942009-02-25 22:02:03 +00003817 // C++ [temp.expl.spec]p2:
3818 // An explicit specialization shall be declared in the namespace
3819 // of which the template is a member, or, for member templates, in
3820 // the namespace of which the enclosing class or enclosing class
3821 // template is a member. An explicit specialization of a member
3822 // function, member class or static data member of a class
3823 // template shall be declared in the namespace of which the class
3824 // template is a member. Such a declaration may also be a
3825 // definition. If the declaration is not a definition, the
3826 // specialization may be defined later in the name- space in which
3827 // the explicit specialization was declared, or in a namespace
3828 // that encloses the one in which the explicit specialization was
3829 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003830 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003831 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003832 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003833 return true;
3834 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003835
Douglas Gregor0a407472009-10-07 17:30:37 +00003836 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3837 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003838 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003839 return true;
3840 }
3841
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003842 // C++ [temp.class.spec]p6:
3843 // A class template partial specialization may be declared or redeclared
3844 // in any namespace scope in which its definition may be defined (14.5.1
3845 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003846 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003847 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003848 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003849 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003850 if ((!PrevDecl ||
3851 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3852 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00003853 // C++ [temp.exp.spec]p2:
3854 // An explicit specialization shall be declared in the namespace of which
3855 // the template is a member, or, for member templates, in the namespace
3856 // of which the enclosing class or enclosing class template is a member.
3857 // An explicit specialization of a member function, member class or
3858 // static data member of a class template shall be declared in the
3859 // namespace of which the class template is a member.
3860 //
3861 // C++0x [temp.expl.spec]p2:
3862 // An explicit specialization shall be declared in a namespace enclosing
3863 // the specialized template.
3864 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3865 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00003866 bool IsCPlusPlus0xExtension
3867 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003868 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003869 S.Diag(Loc, IsCPlusPlus0xExtension
3870 ? diag::ext_template_spec_decl_out_of_scope_global
3871 : diag::err_template_spec_decl_out_of_scope_global)
3872 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00003873 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003874 S.Diag(Loc, IsCPlusPlus0xExtension
3875 ? diag::ext_template_spec_decl_out_of_scope
3876 : diag::err_template_spec_decl_out_of_scope)
3877 << EntityKind << Specialized
3878 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003879
3880 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3881 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003882 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003883 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003884
3885 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003886 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003887 // Note that HandleDeclarator() performs this check for explicit
3888 // specializations of function templates, static data members, and member
3889 // functions, so we skip the check here for those kinds of entities.
3890 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003891 // Should we refactor that check, so that it occurs later?
3892 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003893 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3894 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003895 if (isa<TranslationUnitDecl>(SpecializedContext))
3896 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3897 << EntityKind << Specialized;
3898 else if (isa<NamespaceDecl>(SpecializedContext))
3899 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3900 << EntityKind << Specialized
3901 << cast<NamedDecl>(SpecializedContext);
3902
Douglas Gregor9302da62009-10-14 23:50:59 +00003903 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003904 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003905
3906 // FIXME: check for specialization-after-instantiation errors and such.
3907
Douglas Gregor88b70942009-02-25 22:02:03 +00003908 return false;
3909}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003910
Douglas Gregore94866f2009-06-12 21:21:02 +00003911/// \brief Check the non-type template arguments of a class template
3912/// partial specialization according to C++ [temp.class.spec]p9.
3913///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003914/// \param TemplateParams the template parameters of the primary class
3915/// template.
3916///
3917/// \param TemplateArg the template arguments of the class template
3918/// partial specialization.
3919///
Douglas Gregore94866f2009-06-12 21:21:02 +00003920/// \returns true if there was an error, false otherwise.
3921bool Sema::CheckClassTemplatePartialSpecializationArgs(
3922 TemplateParameterList *TemplateParams,
Douglas Gregorb9c66312010-12-23 17:13:55 +00003923 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor910f8002010-11-07 23:05:16 +00003924 const TemplateArgument *ArgList = TemplateArgs.data();
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Douglas Gregore94866f2009-06-12 21:21:02 +00003926 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00003927 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003928 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregorb9c66312010-12-23 17:13:55 +00003929 if (!Param)
Douglas Gregore94866f2009-06-12 21:21:02 +00003930 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003931
Anders Carlsson6360be72009-06-13 18:20:51 +00003932 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003933 if (!ArgExpr) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003934 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003935 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003936
Douglas Gregorb9c66312010-12-23 17:13:55 +00003937 // FIXME: Variadic templates. Unwrap argument packs.
3938
Douglas Gregore94866f2009-06-12 21:21:02 +00003939 // C++ [temp.class.spec]p8:
3940 // A non-type argument is non-specialized if it is the name of a
3941 // non-type parameter. All other non-type arguments are
3942 // specialized.
3943 //
3944 // Below, we check the two conditions that only apply to
3945 // specialized non-type arguments, so skip any non-specialized
3946 // arguments.
3947 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorb9c66312010-12-23 17:13:55 +00003948 if (llvm::isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00003949 continue;
Douglas Gregorb9c66312010-12-23 17:13:55 +00003950
Douglas Gregore94866f2009-06-12 21:21:02 +00003951 // C++ [temp.class.spec]p9:
3952 // Within the argument list of a class template partial
3953 // specialization, the following restrictions apply:
3954 // -- A partially specialized non-type argument expression
3955 // shall not involve a template parameter of the partial
3956 // specialization except when the argument expression is a
3957 // simple identifier.
3958 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003959 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003960 diag::err_dependent_non_type_arg_in_partial_spec)
3961 << ArgExpr->getSourceRange();
3962 return true;
3963 }
3964
3965 // -- The type of a template parameter corresponding to a
3966 // specialized non-type argument shall not be dependent on a
3967 // parameter of the specialization.
3968 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003969 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003970 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3971 << Param->getType()
3972 << ArgExpr->getSourceRange();
3973 Diag(Param->getLocation(), diag::note_template_param_here);
3974 return true;
3975 }
3976 }
3977
3978 return false;
3979}
3980
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003981/// \brief Retrieve the previous declaration of the given declaration.
3982static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3983 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3984 return VD->getPreviousDeclaration();
3985 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3986 return FD->getPreviousDeclaration();
3987 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3988 return TD->getPreviousDeclaration();
3989 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3990 return TD->getPreviousDeclaration();
3991 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3992 return FTD->getPreviousDeclaration();
3993 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3994 return CTD->getPreviousDeclaration();
3995 return 0;
3996}
3997
John McCalld226f652010-08-21 09:40:31 +00003998DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00003999Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4000 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004001 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004002 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004003 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004004 SourceLocation TemplateNameLoc,
4005 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004006 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004007 SourceLocation RAngleLoc,
4008 AttributeList *Attr,
4009 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004010 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004011
Douglas Gregorcc636682009-02-17 23:15:12 +00004012 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004013 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004014 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004015 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4016
4017 if (!ClassTemplate) {
4018 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4019 << (Name.getAsTemplateDecl() &&
4020 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4021 return true;
4022 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004023
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004024 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004025 bool isPartialSpecialization = false;
4026
Douglas Gregor88b70942009-02-25 22:02:03 +00004027 // Check the validity of the template headers that introduce this
4028 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004029 // FIXME: We probably shouldn't complain about these headers for
4030 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004031 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004032 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00004033 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4034 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004035 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004036 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004037 isExplicitSpecialization,
4038 Invalid);
4039 if (Invalid)
4040 return true;
4041
Abramo Bagnara9b934882010-06-12 08:15:14 +00004042 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4043 if (TemplateParams)
4044 --NumMatchedTemplateParamLists;
4045
Douglas Gregor05396e22009-08-25 17:23:04 +00004046 if (TemplateParams && TemplateParams->size() > 0) {
4047 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004048
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00004049 if (TUK == TUK_Friend) {
4050 Diag(KWLoc, diag::err_partial_specialization_friend)
4051 << SourceRange(LAngleLoc, RAngleLoc);
4052 return true;
4053 }
4054
Douglas Gregor05396e22009-08-25 17:23:04 +00004055 // C++ [temp.class.spec]p10:
4056 // The template parameter list of a specialization shall not
4057 // contain default template argument values.
4058 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4059 Decl *Param = TemplateParams->getParam(I);
4060 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4061 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004062 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004063 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004064 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004065 }
4066 } else if (NonTypeTemplateParmDecl *NTTP
4067 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4068 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004069 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004070 diag::err_default_arg_in_partial_spec)
4071 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004072 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004073 }
4074 } else {
4075 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004076 if (TTP->hasDefaultArgument()) {
4077 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004078 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004079 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004080 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004081 }
4082 }
4083 }
Douglas Gregora735b202009-10-13 14:39:41 +00004084 } else if (TemplateParams) {
4085 if (TUK == TUK_Friend)
4086 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004087 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004088 SourceRange(TemplateParams->getTemplateLoc(),
4089 TemplateParams->getRAngleLoc()))
4090 << SourceRange(LAngleLoc, RAngleLoc);
4091 else
4092 isExplicitSpecialization = true;
4093 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004094 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004095 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004096 isExplicitSpecialization = true;
4097 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004098
Douglas Gregorcc636682009-02-17 23:15:12 +00004099 // Check that the specialization uses the same tag kind as the
4100 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004101 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4102 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004103 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004104 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004105 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004106 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004107 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004108 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004109 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004110 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004111 diag::note_previous_use);
4112 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4113 }
4114
Douglas Gregor40808ce2009-03-09 23:48:35 +00004115 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004116 TemplateArgumentListInfo TemplateArgs;
4117 TemplateArgs.setLAngleLoc(LAngleLoc);
4118 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004119 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004120
Douglas Gregorcc636682009-02-17 23:15:12 +00004121 // Check that the template argument list is well-formed for this
4122 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00004123 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004124 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4125 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004126 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004127
Douglas Gregor910f8002010-11-07 23:05:16 +00004128 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004129 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004130
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004131 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004132 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004133 if (isPartialSpecialization) {
Douglas Gregore94866f2009-06-12 21:21:02 +00004134 if (CheckClassTemplatePartialSpecializationArgs(
4135 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00004136 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00004137 return true;
4138
Douglas Gregorde090962010-02-09 00:37:32 +00004139 if (!Name.isDependent() &&
4140 !TemplateSpecializationType::anyDependentTemplateArguments(
4141 TemplateArgs.getArgumentArray(),
4142 TemplateArgs.size())) {
4143 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4144 << ClassTemplate->getDeclName();
4145 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004146 }
4147 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004148
Douglas Gregorcc636682009-02-17 23:15:12 +00004149 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004150 ClassTemplateSpecializationDecl *PrevDecl = 0;
4151
4152 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004153 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004154 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004155 = ClassTemplate->findPartialSpecialization(Converted.data(),
4156 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004157 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004158 else
4159 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004160 = ClassTemplate->findSpecialization(Converted.data(),
4161 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004162
4163 ClassTemplateSpecializationDecl *Specialization = 0;
4164
Douglas Gregor88b70942009-02-25 22:02:03 +00004165 // Check whether we can declare a class template specialization in
4166 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004167 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00004168 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00004169 TemplateNameLoc,
4170 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004171 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004172
Douglas Gregorb88e8882009-07-30 17:40:51 +00004173 // The canonical type
4174 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004175 if (PrevDecl &&
4176 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004177 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004178 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004179 // arguments was referenced but not declared, or we're only
4180 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00004181 // declaration node as our own, updating its source location to
4182 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004183 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004184 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00004185 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004186 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004187 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004188 // Build the canonical type that describes the converted template
4189 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004190 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4191 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00004192 Converted.data(),
4193 Converted.size());
4194
4195 if (Context.hasSameType(CanonType,
4196 ClassTemplate->getInjectedClassNameSpecialization())) {
4197 // C++ [temp.class.spec]p9b3:
4198 //
4199 // -- The argument list of the specialization shall not be identical
4200 // to the implicit argument list of the primary template.
4201 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4202 << (TUK == TUK_Definition)
4203 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4204 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4205 ClassTemplate->getIdentifier(),
4206 TemplateNameLoc,
4207 Attr,
4208 TemplateParams,
4209 AS_none);
4210 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00004211
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004212 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004213 ClassTemplatePartialSpecializationDecl *PrevPartial
4214 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004215 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004216 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00004217 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00004218 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004219 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00004220 TemplateNameLoc,
4221 TemplateParams,
4222 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004223 Converted.data(),
4224 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00004225 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00004226 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004227 PrevPartial,
4228 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00004229 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004230 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004231 Partial->setTemplateParameterListsInfo(Context,
4232 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004233 (TemplateParameterList**) TemplateParameterLists.release());
4234 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004235
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004236 if (!PrevPartial)
4237 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004238 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00004239
Douglas Gregored9c0f92009-10-29 00:04:11 +00004240 // If we are providing an explicit specialization of a member class
4241 // template specialization, make a note of that.
4242 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4243 PrevPartial->setMemberSpecialization();
4244
Douglas Gregor031a5882009-06-13 00:26:55 +00004245 // Check that all of the template parameters of the class template
4246 // partial specialization are deducible from the template
4247 // arguments. If not, this class template partial specialization
4248 // will never be used.
4249 llvm::SmallVector<bool, 8> DeducibleParams;
4250 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00004251 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004252 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00004253 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00004254 unsigned NumNonDeducible = 0;
4255 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4256 if (!DeducibleParams[I])
4257 ++NumNonDeducible;
4258
4259 if (NumNonDeducible) {
4260 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4261 << (NumNonDeducible > 1)
4262 << SourceRange(TemplateNameLoc, RAngleLoc);
4263 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4264 if (!DeducibleParams[I]) {
4265 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4266 if (Param->getDeclName())
Mike Stump1eb44332009-09-09 15:08:12 +00004267 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004268 diag::note_partial_spec_unused_parameter)
4269 << Param->getDeclName();
4270 else
Mike Stump1eb44332009-09-09 15:08:12 +00004271 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004272 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00004273 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00004274 }
4275 }
4276 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004277 } else {
4278 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004279 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004280 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004281 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00004282 ClassTemplate->getDeclContext(),
4283 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004284 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004285 Converted.data(),
4286 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004287 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004288 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004289 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004290 Specialization->setTemplateParameterListsInfo(Context,
4291 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004292 (TemplateParameterList**) TemplateParameterLists.release());
4293 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004294
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004295 if (!PrevDecl)
4296 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00004297
4298 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004299 }
4300
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004301 // C++ [temp.expl.spec]p6:
4302 // If a template, a member template or the member of a class template is
4303 // explicitly specialized then that specialization shall be declared
4304 // before the first use of that specialization that would cause an implicit
4305 // instantiation to take place, in every translation unit in which such a
4306 // use occurs; no diagnostic is required.
4307 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004308 bool Okay = false;
4309 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4310 // Is there any previous explicit specialization declaration?
4311 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4312 Okay = true;
4313 break;
4314 }
4315 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004316
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004317 if (!Okay) {
4318 SourceRange Range(TemplateNameLoc, RAngleLoc);
4319 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4320 << Context.getTypeDeclType(Specialization) << Range;
4321
4322 Diag(PrevDecl->getPointOfInstantiation(),
4323 diag::note_instantiation_required_here)
4324 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004325 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004326 return true;
4327 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004328 }
4329
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004330 // If this is not a friend, note that this is an explicit specialization.
4331 if (TUK != TUK_Friend)
4332 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004333
4334 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004335 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00004336 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004337 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004338 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004339 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00004340 Diag(Def->getLocation(), diag::note_previous_definition);
4341 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00004342 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004343 }
4344 }
4345
John McCall7f1b9872010-12-18 03:30:47 +00004346 if (Attr)
4347 ProcessDeclAttributeList(S, Specialization, Attr);
4348
Douglas Gregorfc705b82009-02-26 22:19:44 +00004349 // Build the fully-sugared type for this class template
4350 // specialization as the user wrote in the specialization
4351 // itself. This means that we'll pretty-print the type retrieved
4352 // from the specialization's declaration the way that the user
4353 // actually wrote the specialization, rather than formatting the
4354 // name based on the "canonical" representation used to store the
4355 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004356 TypeSourceInfo *WrittenTy
4357 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4358 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004359 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004360 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00004361 if (TemplateParams)
4362 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004363 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004364 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004365
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004366 // C++ [temp.expl.spec]p9:
4367 // A template explicit specialization is in the scope of the
4368 // namespace in which the template was defined.
4369 //
4370 // We actually implement this paragraph where we set the semantic
4371 // context (in the creation of the ClassTemplateSpecializationDecl),
4372 // but we also maintain the lexical context where the actual
4373 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004374 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004375
Douglas Gregorcc636682009-02-17 23:15:12 +00004376 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004377 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004378 Specialization->startDefinition();
4379
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004380 if (TUK == TUK_Friend) {
4381 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4382 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004383 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004384 /*FIXME:*/KWLoc);
4385 Friend->setAccess(AS_public);
4386 CurContext->addDecl(Friend);
4387 } else {
4388 // Add the specialization into its lexical context, so that it can
4389 // be seen when iterating through the list of declarations in that
4390 // context. However, specializations are not found by name lookup.
4391 CurContext->addDecl(Specialization);
4392 }
John McCalld226f652010-08-21 09:40:31 +00004393 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004394}
Douglas Gregord57959a2009-03-27 23:10:48 +00004395
John McCalld226f652010-08-21 09:40:31 +00004396Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004397 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004398 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004399 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4400}
4401
John McCalld226f652010-08-21 09:40:31 +00004402Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004403 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004404 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004405 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004406 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00004407
Douglas Gregor52591bf2009-06-24 00:54:41 +00004408 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004409 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004410 }
Mike Stump1eb44332009-09-09 15:08:12 +00004411
Douglas Gregor52591bf2009-06-24 00:54:41 +00004412 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004413
John McCalld226f652010-08-21 09:40:31 +00004414 Decl *DP = HandleDeclarator(ParentScope, D,
4415 move(TemplateParameterLists),
4416 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004417 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004418 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004419 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004420 FunctionTemplate->getTemplatedDecl());
4421 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4422 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4423 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004424}
4425
John McCall75042392010-02-11 01:33:53 +00004426/// \brief Strips various properties off an implicit instantiation
4427/// that has just been explicitly specialized.
4428static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004429 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004430
4431 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4432 FD->setInlineSpecified(false);
4433 }
4434}
4435
Douglas Gregor454885e2009-10-15 15:54:05 +00004436/// \brief Diagnose cases where we have an explicit template specialization
4437/// before/after an explicit template instantiation, producing diagnostics
4438/// for those cases where they are required and determining whether the
4439/// new specialization/instantiation will have any effect.
4440///
Douglas Gregor454885e2009-10-15 15:54:05 +00004441/// \param NewLoc the location of the new explicit specialization or
4442/// instantiation.
4443///
4444/// \param NewTSK the kind of the new explicit specialization or instantiation.
4445///
4446/// \param PrevDecl the previous declaration of the entity.
4447///
4448/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4449///
4450/// \param PrevPointOfInstantiation if valid, indicates where the previus
4451/// declaration was instantiated (either implicitly or explicitly).
4452///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004453/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004454/// specialization or instantiation has no effect and should be ignored.
4455///
4456/// \returns true if there was an error that should prevent the introduction of
4457/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004458bool
4459Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4460 TemplateSpecializationKind NewTSK,
4461 NamedDecl *PrevDecl,
4462 TemplateSpecializationKind PrevTSK,
4463 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004464 bool &HasNoEffect) {
4465 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004466
4467 switch (NewTSK) {
4468 case TSK_Undeclared:
4469 case TSK_ImplicitInstantiation:
4470 assert(false && "Don't check implicit instantiations here");
4471 return false;
4472
4473 case TSK_ExplicitSpecialization:
4474 switch (PrevTSK) {
4475 case TSK_Undeclared:
4476 case TSK_ExplicitSpecialization:
4477 // Okay, we're just specializing something that is either already
4478 // explicitly specialized or has merely been mentioned without any
4479 // instantiation.
4480 return false;
4481
4482 case TSK_ImplicitInstantiation:
4483 if (PrevPointOfInstantiation.isInvalid()) {
4484 // The declaration itself has not actually been instantiated, so it is
4485 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004486 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004487 return false;
4488 }
4489 // Fall through
4490
4491 case TSK_ExplicitInstantiationDeclaration:
4492 case TSK_ExplicitInstantiationDefinition:
4493 assert((PrevTSK == TSK_ImplicitInstantiation ||
4494 PrevPointOfInstantiation.isValid()) &&
4495 "Explicit instantiation without point of instantiation?");
4496
4497 // C++ [temp.expl.spec]p6:
4498 // If a template, a member template or the member of a class template
4499 // is explicitly specialized then that specialization shall be declared
4500 // before the first use of that specialization that would cause an
4501 // implicit instantiation to take place, in every translation unit in
4502 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004503 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4504 // Is there any previous explicit specialization declaration?
4505 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4506 return false;
4507 }
4508
Douglas Gregor0d035142009-10-27 18:42:08 +00004509 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004510 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004511 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004512 << (PrevTSK != TSK_ImplicitInstantiation);
4513
4514 return true;
4515 }
4516 break;
4517
4518 case TSK_ExplicitInstantiationDeclaration:
4519 switch (PrevTSK) {
4520 case TSK_ExplicitInstantiationDeclaration:
4521 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004522 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004523 return false;
4524
4525 case TSK_Undeclared:
4526 case TSK_ImplicitInstantiation:
4527 // We're explicitly instantiating something that may have already been
4528 // implicitly instantiated; that's fine.
4529 return false;
4530
4531 case TSK_ExplicitSpecialization:
4532 // C++0x [temp.explicit]p4:
4533 // For a given set of template parameters, if an explicit instantiation
4534 // of a template appears after a declaration of an explicit
4535 // specialization for that template, the explicit instantiation has no
4536 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004537 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004538 return false;
4539
4540 case TSK_ExplicitInstantiationDefinition:
4541 // C++0x [temp.explicit]p10:
4542 // If an entity is the subject of both an explicit instantiation
4543 // declaration and an explicit instantiation definition in the same
4544 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004545 Diag(NewLoc,
4546 diag::err_explicit_instantiation_declaration_after_definition);
4547 Diag(PrevPointOfInstantiation,
4548 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004549 assert(PrevPointOfInstantiation.isValid() &&
4550 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004551 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004552 return false;
4553 }
4554 break;
4555
4556 case TSK_ExplicitInstantiationDefinition:
4557 switch (PrevTSK) {
4558 case TSK_Undeclared:
4559 case TSK_ImplicitInstantiation:
4560 // We're explicitly instantiating something that may have already been
4561 // implicitly instantiated; that's fine.
4562 return false;
4563
4564 case TSK_ExplicitSpecialization:
4565 // C++ DR 259, C++0x [temp.explicit]p4:
4566 // For a given set of template parameters, if an explicit
4567 // instantiation of a template appears after a declaration of
4568 // an explicit specialization for that template, the explicit
4569 // instantiation has no effect.
4570 //
4571 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004572 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004573 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004574 if (!getLangOptions().CPlusPlus0x) {
4575 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004576 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004577 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004578 diag::note_previous_template_specialization);
4579 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004580 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004581 return false;
4582
4583 case TSK_ExplicitInstantiationDeclaration:
4584 // We're explicity instantiating a definition for something for which we
4585 // were previously asked to suppress instantiations. That's fine.
4586 return false;
4587
4588 case TSK_ExplicitInstantiationDefinition:
4589 // C++0x [temp.spec]p5:
4590 // For a given template and a given set of template-arguments,
4591 // - an explicit instantiation definition shall appear at most once
4592 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004593 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004594 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004595 Diag(PrevPointOfInstantiation,
4596 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004597 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004598 return false;
4599 }
4600 break;
4601 }
4602
4603 assert(false && "Missing specialization/instantiation case?");
4604
4605 return false;
4606}
4607
John McCallaf2094e2010-04-08 09:05:18 +00004608/// \brief Perform semantic analysis for the given dependent function
4609/// template specialization. The only possible way to get a dependent
4610/// function template specialization is with a friend declaration,
4611/// like so:
4612///
4613/// template <class T> void foo(T);
4614/// template <class T> class A {
4615/// friend void foo<>(T);
4616/// };
4617///
4618/// There really isn't any useful analysis we can do here, so we
4619/// just store the information.
4620bool
4621Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4622 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4623 LookupResult &Previous) {
4624 // Remove anything from Previous that isn't a function template in
4625 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004626 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004627 LookupResult::Filter F = Previous.makeFilter();
4628 while (F.hasNext()) {
4629 NamedDecl *D = F.next()->getUnderlyingDecl();
4630 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004631 !FDLookupContext->InEnclosingNamespaceSetOf(
4632 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004633 F.erase();
4634 }
4635 F.done();
4636
4637 // Should this be diagnosed here?
4638 if (Previous.empty()) return true;
4639
4640 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4641 ExplicitTemplateArgs);
4642 return false;
4643}
4644
Abramo Bagnarae03db982010-05-20 15:32:11 +00004645/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004646/// specialization.
4647///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004648/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004649/// explicit function template specialization. On successful completion,
4650/// the function declaration \p FD will become a function template
4651/// specialization.
4652///
4653/// \param FD the function declaration, which will be updated to become a
4654/// function template specialization.
4655///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004656/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4657/// if any. Note that this may be valid info even when 0 arguments are
4658/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4659/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004660///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004661/// \param PrevDecl the set of declarations that may be specialized by
4662/// this function specialization.
4663bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004664Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004665 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004666 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004667 // The set of function template specializations that could match this
4668 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004669 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004670
Sebastian Redl7a126a42010-08-31 00:36:30 +00004671 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004672 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4673 I != E; ++I) {
4674 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4675 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004676 // Only consider templates found within the same semantic lookup scope as
4677 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004678 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4679 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004680 continue;
4681
4682 // C++ [temp.expl.spec]p11:
4683 // A trailing template-argument can be left unspecified in the
4684 // template-id naming an explicit function template specialization
4685 // provided it can be deduced from the function argument type.
4686 // Perform template argument deduction to determine whether we may be
4687 // specializing this template.
4688 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004689 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004690 FunctionDecl *Specialization = 0;
4691 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004692 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004693 FD->getType(),
4694 Specialization,
4695 Info)) {
4696 // FIXME: Template argument deduction failed; record why it failed, so
4697 // that we can provide nifty diagnostics.
4698 (void)TDK;
4699 continue;
4700 }
4701
4702 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004703 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004704 }
4705 }
4706
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004707 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004708 UnresolvedSetIterator Result
4709 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4710 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004711 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004712 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004713 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004714 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004715 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004716 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004717 return true;
John McCallc373d482010-01-27 01:50:18 +00004718
4719 // Ignore access information; it doesn't figure into redeclaration checking.
4720 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004721 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004722
4723 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004724 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004725
4726 // If this is a friend declaration, then we're not really declaring
4727 // an explicit specialization.
4728 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004729
Douglas Gregord5cb8762009-10-07 00:13:32 +00004730 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004731 if (!isFriend &&
4732 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004733 Specialization->getPrimaryTemplate(),
4734 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004735 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004736 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004737
4738 // C++ [temp.expl.spec]p6:
4739 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004740 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004741 // before the first use of that specialization that would cause an implicit
4742 // instantiation to take place, in every translation unit in which such a
4743 // use occurs; no diagnostic is required.
4744 FunctionTemplateSpecializationInfo *SpecInfo
4745 = Specialization->getTemplateSpecializationInfo();
4746 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004747
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004748 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004749 if (!isFriend &&
4750 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004751 TSK_ExplicitSpecialization,
4752 Specialization,
4753 SpecInfo->getTemplateSpecializationKind(),
4754 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004755 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004756 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004757
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004758 // Mark the prior declaration as an explicit specialization, so that later
4759 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004760 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004761 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004762 MarkUnusedFileScopedDecl(Specialization);
4763 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004764
4765 // Turn the given function declaration into a function template
4766 // specialization, with the template arguments from the previous
4767 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004768 // Take copies of (semantic and syntactic) template argument lists.
4769 const TemplateArgumentList* TemplArgs = new (Context)
4770 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4771 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4772 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004773 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004774 TemplArgs, /*InsertPos=*/0,
4775 SpecInfo->getTemplateSpecializationKind(),
4776 TemplArgsAsWritten);
4777
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004778 // The "previous declaration" for this function template specialization is
4779 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004780 Previous.clear();
4781 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004782 return false;
4783}
4784
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004785/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004786/// specialization.
4787///
4788/// This routine performs all of the semantic analysis required for an
4789/// explicit member function specialization. On successful completion,
4790/// the function declaration \p FD will become a member function
4791/// specialization.
4792///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004793/// \param Member the member declaration, which will be updated to become a
4794/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004795///
John McCall68263142009-11-18 22:49:29 +00004796/// \param Previous the set of declarations, one of which may be specialized
4797/// by this function specialization; the set will be modified to contain the
4798/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004799bool
John McCall68263142009-11-18 22:49:29 +00004800Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004801 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004802
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004803 // Try to find the member we are instantiating.
4804 NamedDecl *Instantiation = 0;
4805 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004806 MemberSpecializationInfo *MSInfo = 0;
4807
John McCall68263142009-11-18 22:49:29 +00004808 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004809 // Nowhere to look anyway.
4810 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004811 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4812 I != E; ++I) {
4813 NamedDecl *D = (*I)->getUnderlyingDecl();
4814 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004815 if (Context.hasSameType(Function->getType(), Method->getType())) {
4816 Instantiation = Method;
4817 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004818 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004819 break;
4820 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004821 }
4822 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004823 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004824 VarDecl *PrevVar;
4825 if (Previous.isSingleResult() &&
4826 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004827 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004828 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004829 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004830 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004831 }
4832 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004833 CXXRecordDecl *PrevRecord;
4834 if (Previous.isSingleResult() &&
4835 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4836 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004837 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004838 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004839 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004840 }
4841
4842 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004843 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004844 // specializations are always out-of-line, the caller will complain about
4845 // this mismatch later.
4846 return false;
4847 }
John McCall77e8b112010-04-13 20:37:33 +00004848
4849 // If this is a friend, just bail out here before we start turning
4850 // things into explicit specializations.
4851 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4852 // Preserve instantiation information.
4853 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4854 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4855 cast<CXXMethodDecl>(InstantiatedFrom),
4856 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4857 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4858 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4859 cast<CXXRecordDecl>(InstantiatedFrom),
4860 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4861 }
4862
4863 Previous.clear();
4864 Previous.addDecl(Instantiation);
4865 return false;
4866 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004867
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004868 // Make sure that this is a specialization of a member.
4869 if (!InstantiatedFrom) {
4870 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4871 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004872 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4873 return true;
4874 }
4875
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004876 // C++ [temp.expl.spec]p6:
4877 // If a template, a member template or the member of a class template is
4878 // explicitly specialized then that spe- cialization shall be declared
4879 // before the first use of that specialization that would cause an implicit
4880 // instantiation to take place, in every translation unit in which such a
4881 // use occurs; no diagnostic is required.
4882 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004883
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004884 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004885 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4886 TSK_ExplicitSpecialization,
4887 Instantiation,
4888 MSInfo->getTemplateSpecializationKind(),
4889 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004890 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004891 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004892
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004893 // Check the scope of this explicit specialization.
4894 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004895 InstantiatedFrom,
4896 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004897 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004898 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004899
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004900 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004901 // the original declaration to note that it is an explicit specialization
4902 // (if it was previously an implicit instantiation). This latter step
4903 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004904 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004905 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4906 if (InstantiationFunction->getTemplateSpecializationKind() ==
4907 TSK_ImplicitInstantiation) {
4908 InstantiationFunction->setTemplateSpecializationKind(
4909 TSK_ExplicitSpecialization);
4910 InstantiationFunction->setLocation(Member->getLocation());
4911 }
4912
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004913 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4914 cast<CXXMethodDecl>(InstantiatedFrom),
4915 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004916 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004917 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004918 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4919 if (InstantiationVar->getTemplateSpecializationKind() ==
4920 TSK_ImplicitInstantiation) {
4921 InstantiationVar->setTemplateSpecializationKind(
4922 TSK_ExplicitSpecialization);
4923 InstantiationVar->setLocation(Member->getLocation());
4924 }
4925
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004926 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4927 cast<VarDecl>(InstantiatedFrom),
4928 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004929 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004930 } else {
4931 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004932 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4933 if (InstantiationClass->getTemplateSpecializationKind() ==
4934 TSK_ImplicitInstantiation) {
4935 InstantiationClass->setTemplateSpecializationKind(
4936 TSK_ExplicitSpecialization);
4937 InstantiationClass->setLocation(Member->getLocation());
4938 }
4939
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004940 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004941 cast<CXXRecordDecl>(InstantiatedFrom),
4942 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004943 }
4944
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004945 // Save the caller the trouble of having to figure out which declaration
4946 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004947 Previous.clear();
4948 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004949 return false;
4950}
4951
Douglas Gregor558c0322009-10-14 23:41:34 +00004952/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00004953///
4954/// \returns true if a serious error occurs, false otherwise.
4955static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00004956 SourceLocation InstLoc,
4957 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00004958 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4959 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00004960
Douglas Gregor669eed82010-07-13 00:10:04 +00004961 if (CurContext->isRecord()) {
4962 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4963 << D;
4964 return true;
4965 }
4966
Douglas Gregor558c0322009-10-14 23:41:34 +00004967 // C++0x [temp.explicit]p2:
4968 // An explicit instantiation shall appear in an enclosing namespace of its
4969 // template.
4970 //
4971 // This is DR275, which we do not retroactively apply to C++98/03.
4972 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004973 !CurContext->Encloses(OrigContext)) {
4974 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004975 S.Diag(InstLoc,
4976 S.getLangOptions().CPlusPlus0x?
4977 diag::err_explicit_instantiation_out_of_scope
4978 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004979 << D << NS;
4980 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004981 S.Diag(InstLoc,
4982 S.getLangOptions().CPlusPlus0x?
4983 diag::err_explicit_instantiation_must_be_global
4984 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004985 << D;
4986 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004987 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004988 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00004989
Douglas Gregor558c0322009-10-14 23:41:34 +00004990 // C++0x [temp.explicit]p2:
4991 // If the name declared in the explicit instantiation is an unqualified
4992 // name, the explicit instantiation shall appear in the namespace where
4993 // its template is declared or, if that namespace is inline (7.3.1), any
4994 // namespace from its enclosing namespace set.
4995 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00004996 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00004997
4998 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00004999 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005000
Douglas Gregor2166beb2010-05-11 17:39:34 +00005001 S.Diag(InstLoc,
5002 S.getLangOptions().CPlusPlus0x?
5003 diag::err_explicit_instantiation_unqualified_wrong_namespace
5004 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl7a126a42010-08-31 00:36:30 +00005005 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00005006 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005007 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005008}
5009
5010/// \brief Determine whether the given scope specifier has a template-id in it.
5011static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5012 if (!SS.isSet())
5013 return false;
5014
5015 // C++0x [temp.explicit]p2:
5016 // If the explicit instantiation is for a member function, a member class
5017 // or a static data member of a class template specialization, the name of
5018 // the class template specialization in the qualified-id for the member
5019 // name shall be a simple-template-id.
5020 //
5021 // C++98 has the same restriction, just worded differently.
5022 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5023 NNS; NNS = NNS->getPrefix())
5024 if (Type *T = NNS->getAsType())
5025 if (isa<TemplateSpecializationType>(T))
5026 return true;
5027
5028 return false;
5029}
5030
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005031// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00005032DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005033Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005034 SourceLocation ExternLoc,
5035 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005036 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005037 SourceLocation KWLoc,
5038 const CXXScopeSpec &SS,
5039 TemplateTy TemplateD,
5040 SourceLocation TemplateNameLoc,
5041 SourceLocation LAngleLoc,
5042 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005043 SourceLocation RAngleLoc,
5044 AttributeList *Attr) {
5045 // Find the class template we're specializing
5046 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005047 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005048 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5049
5050 // Check that the specialization uses the same tag kind as the
5051 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005052 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5053 assert(Kind != TTK_Enum &&
5054 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005055 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00005056 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005057 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005058 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005059 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005060 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005061 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005062 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005063 diag::note_previous_use);
5064 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5065 }
5066
Douglas Gregor558c0322009-10-14 23:41:34 +00005067 // C++0x [temp.explicit]p2:
5068 // There are two forms of explicit instantiation: an explicit instantiation
5069 // definition and an explicit instantiation declaration. An explicit
5070 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005071 TemplateSpecializationKind TSK
5072 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5073 : TSK_ExplicitInstantiationDeclaration;
5074
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005075 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005076 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005077 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005078
5079 // Check that the template argument list is well-formed for this
5080 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00005081 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005082 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5083 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005084 return true;
5085
Douglas Gregor910f8002010-11-07 23:05:16 +00005086 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005087 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005088
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005089 // Find the class template specialization declaration that
5090 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005091 void *InsertPos = 0;
5092 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005093 = ClassTemplate->findSpecialization(Converted.data(),
5094 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005095
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005096 TemplateSpecializationKind PrevDecl_TSK
5097 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5098
Douglas Gregord5cb8762009-10-07 00:13:32 +00005099 // C++0x [temp.explicit]p2:
5100 // [...] An explicit instantiation shall appear in an enclosing
5101 // namespace of its template. [...]
5102 //
5103 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005104 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5105 SS.isSet()))
5106 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00005107
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005108 ClassTemplateSpecializationDecl *Specialization = 0;
5109
Douglas Gregord78f5982009-11-25 06:01:46 +00005110 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005111 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005112 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005113 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005114 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005115 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005116 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005117 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005118
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005119 // Even though HasNoEffect == true means that this explicit instantiation
5120 // has no effect on semantics, we go on to put its syntax in the AST.
5121
5122 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5123 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005124 // Since the only prior class template specialization with these
5125 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005126 // declaration node as our own, updating the source location
5127 // for the template name to reflect our new declaration.
5128 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005129 Specialization = PrevDecl;
5130 Specialization->setLocation(TemplateNameLoc);
5131 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00005132 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00005133 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005134 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005135
Douglas Gregor52604ab2009-09-11 21:19:12 +00005136 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005137 // Create a new class template specialization declaration node for
5138 // this explicit specialization.
5139 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005140 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005141 ClassTemplate->getDeclContext(),
5142 TemplateNameLoc,
5143 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005144 Converted.data(),
5145 Converted.size(),
5146 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005147 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005148
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005149 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005150 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005151 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005152 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005153 }
5154
5155 // Build the fully-sugared type for this explicit instantiation as
5156 // the user wrote in the explicit instantiation itself. This means
5157 // that we'll pretty-print the type retrieved from the
5158 // specialization's declaration the way that the user actually wrote
5159 // the explicit instantiation, rather than formatting the name based
5160 // on the "canonical" representation used to store the template
5161 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005162 TypeSourceInfo *WrittenTy
5163 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5164 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005165 Context.getTypeDeclType(Specialization));
5166 Specialization->setTypeAsWritten(WrittenTy);
5167 TemplateArgsIn.release();
5168
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005169 // Set source locations for keywords.
5170 Specialization->setExternLoc(ExternLoc);
5171 Specialization->setTemplateKeywordLoc(TemplateLoc);
5172
5173 // Add the explicit instantiation into its lexical context. However,
5174 // since explicit instantiations are never found by name lookup, we
5175 // just put it into the declaration context directly.
5176 Specialization->setLexicalDeclContext(CurContext);
5177 CurContext->addDecl(Specialization);
5178
5179 // Syntax is now OK, so return if it has no other effect on semantics.
5180 if (HasNoEffect) {
5181 // Set the template specialization kind.
5182 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005183 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005184 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005185
5186 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005187 // A definition of a class template or class member template
5188 // shall be in scope at the point of the explicit instantiation of
5189 // the class template or class member template.
5190 //
5191 // This check comes when we actually try to perform the
5192 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005193 ClassTemplateSpecializationDecl *Def
5194 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005195 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005196 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005197 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005198 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005199 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005200 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5201 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005202
Douglas Gregor0d035142009-10-27 18:42:08 +00005203 // Instantiate the members of this class template specialization.
5204 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005205 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005206 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005207 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5208
5209 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5210 // TSK_ExplicitInstantiationDefinition
5211 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5212 TSK == TSK_ExplicitInstantiationDefinition)
5213 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005214
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005215 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005216 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005217
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005218 // Set the template specialization kind.
5219 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005220 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005221}
5222
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005223// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00005224DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005225Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005226 SourceLocation ExternLoc,
5227 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005228 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005229 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005230 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005231 IdentifierInfo *Name,
5232 SourceLocation NameLoc,
5233 AttributeList *Attr) {
5234
Douglas Gregor402abb52009-05-28 23:31:59 +00005235 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00005236 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00005237 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00005238 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5239 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00005240 Owned, IsDependent, false, false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005241 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00005242 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5243
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005244 if (!TagD)
5245 return true;
5246
John McCalld226f652010-08-21 09:40:31 +00005247 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005248 if (Tag->isEnum()) {
5249 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5250 << Context.getTypeDeclType(Tag);
5251 return true;
5252 }
5253
Douglas Gregord0c87372009-05-27 17:30:49 +00005254 if (Tag->isInvalidDecl())
5255 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00005256
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005257 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5258 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5259 if (!Pattern) {
5260 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5261 << Context.getTypeDeclType(Record);
5262 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5263 return true;
5264 }
5265
Douglas Gregor558c0322009-10-14 23:41:34 +00005266 // C++0x [temp.explicit]p2:
5267 // If the explicit instantiation is for a class or member class, the
5268 // elaborated-type-specifier in the declaration shall include a
5269 // simple-template-id.
5270 //
5271 // C++98 has the same restriction, just worded differently.
5272 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00005273 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005274 << Record << SS.getRange();
5275
5276 // C++0x [temp.explicit]p2:
5277 // There are two forms of explicit instantiation: an explicit instantiation
5278 // definition and an explicit instantiation declaration. An explicit
5279 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00005280 TemplateSpecializationKind TSK
5281 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5282 : TSK_ExplicitInstantiationDeclaration;
5283
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005284 // C++0x [temp.explicit]p2:
5285 // [...] An explicit instantiation shall appear in an enclosing
5286 // namespace of its template. [...]
5287 //
5288 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00005289 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00005290
5291 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00005292 CXXRecordDecl *PrevDecl
5293 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00005294 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00005295 PrevDecl = Record;
5296 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00005297 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005298 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005299 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00005300 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00005301 PrevDecl,
5302 MSInfo->getTemplateSpecializationKind(),
5303 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005304 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005305 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005306 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005307 return TagD;
5308 }
5309
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005310 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00005311 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005312 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005313 // C++ [temp.explicit]p3:
5314 // A definition of a member class of a class template shall be in scope
5315 // at the point of an explicit instantiation of the member class.
5316 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00005317 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005318 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005319 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5320 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005321 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5322 << Pattern;
5323 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00005324 } else {
5325 if (InstantiateClass(NameLoc, Record, Def,
5326 getTemplateInstantiationArgs(Record),
5327 TSK))
5328 return true;
5329
Douglas Gregor952b0172010-02-11 01:04:33 +00005330 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00005331 if (!RecordDef)
5332 return true;
5333 }
5334 }
5335
5336 // Instantiate all of the members of the class.
5337 InstantiateClassMembers(NameLoc, RecordDef,
5338 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005339
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005340 if (TSK == TSK_ExplicitInstantiationDefinition)
5341 MarkVTableUsed(NameLoc, RecordDef, true);
5342
Mike Stump390b4cc2009-05-16 07:39:55 +00005343 // FIXME: We don't have any representation for explicit instantiations of
5344 // member classes. Such a representation is not needed for compilation, but it
5345 // should be available for clients that want to see all of the declarations in
5346 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005347 return TagD;
5348}
5349
John McCallf312b1e2010-08-26 23:41:50 +00005350DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5351 SourceLocation ExternLoc,
5352 SourceLocation TemplateLoc,
5353 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005354 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00005355 // TODO: check if/when DNInfo should replace Name.
5356 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5357 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005358 if (!Name) {
5359 if (!D.isInvalidType())
5360 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5361 diag::err_explicit_instantiation_requires_name)
5362 << D.getDeclSpec().getSourceRange()
5363 << D.getSourceRange();
5364
5365 return true;
5366 }
5367
5368 // The scope passed in may not be a decl scope. Zip up the scope tree until
5369 // we find one that is.
5370 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5371 (S->getFlags() & Scope::TemplateParamScope) != 0)
5372 S = S->getParent();
5373
5374 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005375 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5376 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005377 if (R.isNull())
5378 return true;
5379
5380 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5381 // Cannot explicitly instantiate a typedef.
5382 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5383 << Name;
5384 return true;
5385 }
5386
Douglas Gregor663b5a02009-10-14 20:14:33 +00005387 // C++0x [temp.explicit]p1:
5388 // [...] An explicit instantiation of a function template shall not use the
5389 // inline or constexpr specifiers.
5390 // Presumably, this also applies to member functions of class templates as
5391 // well.
5392 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5393 Diag(D.getDeclSpec().getInlineSpecLoc(),
5394 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005395 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005396
5397 // FIXME: check for constexpr specifier.
5398
Douglas Gregor558c0322009-10-14 23:41:34 +00005399 // C++0x [temp.explicit]p2:
5400 // There are two forms of explicit instantiation: an explicit instantiation
5401 // definition and an explicit instantiation declaration. An explicit
5402 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005403 TemplateSpecializationKind TSK
5404 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5405 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005406
Abramo Bagnara25777432010-08-11 22:01:17 +00005407 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005408 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005409
5410 if (!R->isFunctionType()) {
5411 // C++ [temp.explicit]p1:
5412 // A [...] static data member of a class template can be explicitly
5413 // instantiated from the member definition associated with its class
5414 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005415 if (Previous.isAmbiguous())
5416 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005417
John McCall1bcee0a2009-12-02 08:25:40 +00005418 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005419 if (!Prev || !Prev->isStaticDataMember()) {
5420 // We expect to see a data data member here.
5421 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5422 << Name;
5423 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5424 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005425 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005426 return true;
5427 }
5428
5429 if (!Prev->getInstantiatedFromStaticDataMember()) {
5430 // FIXME: Check for explicit specialization?
5431 Diag(D.getIdentifierLoc(),
5432 diag::err_explicit_instantiation_data_member_not_instantiated)
5433 << Prev;
5434 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5435 // FIXME: Can we provide a note showing where this was declared?
5436 return true;
5437 }
5438
Douglas Gregor558c0322009-10-14 23:41:34 +00005439 // C++0x [temp.explicit]p2:
5440 // If the explicit instantiation is for a member function, a member class
5441 // or a static data member of a class template specialization, the name of
5442 // the class template specialization in the qualified-id for the member
5443 // name shall be a simple-template-id.
5444 //
5445 // C++98 has the same restriction, just worded differently.
5446 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5447 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005448 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005449 << Prev << D.getCXXScopeSpec().getRange();
5450
5451 // Check the scope of this explicit instantiation.
5452 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5453
Douglas Gregor454885e2009-10-15 15:54:05 +00005454 // Verify that it is okay to explicitly instantiate here.
5455 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5456 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005457 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005458 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005459 MSInfo->getTemplateSpecializationKind(),
5460 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005461 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005462 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005463 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005464 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005465
Douglas Gregord5a423b2009-09-25 18:43:00 +00005466 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005467 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005468 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005469 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005470
5471 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005472 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005473 }
5474
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005475 // If the declarator is a template-id, translate the parser's template
5476 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005477 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005478 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005479 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5480 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005481 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5482 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005483 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5484 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005485 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005486 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005487 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005488 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005489 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005490
Douglas Gregord5a423b2009-09-25 18:43:00 +00005491 // C++ [temp.explicit]p1:
5492 // A [...] function [...] can be explicitly instantiated from its template.
5493 // A member function [...] of a class template can be explicitly
5494 // instantiated from the member definition associated with its class
5495 // template.
John McCallc373d482010-01-27 01:50:18 +00005496 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005497 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5498 P != PEnd; ++P) {
5499 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005500 if (!HasExplicitTemplateArgs) {
5501 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5502 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5503 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005504
John McCallc373d482010-01-27 01:50:18 +00005505 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005506 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5507 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005508 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005509 }
5510 }
5511
5512 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5513 if (!FunTmpl)
5514 continue;
5515
John McCall5769d612010-02-08 23:07:23 +00005516 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005517 FunctionDecl *Specialization = 0;
5518 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005519 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005520 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005521 R, Specialization, Info)) {
5522 // FIXME: Keep track of almost-matches?
5523 (void)TDK;
5524 continue;
5525 }
5526
John McCallc373d482010-01-27 01:50:18 +00005527 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005528 }
5529
5530 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005531 UnresolvedSetIterator Result
5532 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005533 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005534 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5535 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5536 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005537
John McCallc373d482010-01-27 01:50:18 +00005538 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005539 return true;
John McCallc373d482010-01-27 01:50:18 +00005540
5541 // Ignore access control bits, we don't need them for redeclaration checking.
5542 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005543
Douglas Gregor0a897e32009-10-15 17:21:20 +00005544 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005545 Diag(D.getIdentifierLoc(),
5546 diag::err_explicit_instantiation_member_function_not_instantiated)
5547 << Specialization
5548 << (Specialization->getTemplateSpecializationKind() ==
5549 TSK_ExplicitSpecialization);
5550 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5551 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005552 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005553
Douglas Gregor0a897e32009-10-15 17:21:20 +00005554 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005555 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5556 PrevDecl = Specialization;
5557
Douglas Gregor0a897e32009-10-15 17:21:20 +00005558 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005559 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005560 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005561 PrevDecl,
5562 PrevDecl->getTemplateSpecializationKind(),
5563 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005564 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005565 return true;
5566
5567 // FIXME: We may still want to build some representation of this
5568 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005569 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005570 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005571 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005572
5573 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005574
5575 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005576 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005577
Douglas Gregor558c0322009-10-14 23:41:34 +00005578 // C++0x [temp.explicit]p2:
5579 // If the explicit instantiation is for a member function, a member class
5580 // or a static data member of a class template specialization, the name of
5581 // the class template specialization in the qualified-id for the member
5582 // name shall be a simple-template-id.
5583 //
5584 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005585 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005586 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005587 D.getCXXScopeSpec().isSet() &&
5588 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5589 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005590 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005591 << Specialization << D.getCXXScopeSpec().getRange();
5592
5593 CheckExplicitInstantiationScope(*this,
5594 FunTmpl? (NamedDecl *)FunTmpl
5595 : Specialization->getInstantiatedFromMemberFunction(),
5596 D.getIdentifierLoc(),
5597 D.getCXXScopeSpec().isSet());
5598
Douglas Gregord5a423b2009-09-25 18:43:00 +00005599 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005600 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005601}
5602
John McCallf312b1e2010-08-26 23:41:50 +00005603TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005604Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5605 const CXXScopeSpec &SS, IdentifierInfo *Name,
5606 SourceLocation TagLoc, SourceLocation NameLoc) {
5607 // This has to hold, because SS is expected to be defined.
5608 assert(Name && "Expected a name in a dependent tag");
5609
5610 NestedNameSpecifier *NNS
5611 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5612 if (!NNS)
5613 return true;
5614
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005615 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005616
Douglas Gregor48c89f42010-04-24 16:38:41 +00005617 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5618 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005619 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005620 return true;
5621 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005622
5623 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005624 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005625}
5626
John McCallf312b1e2010-08-26 23:41:50 +00005627TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005628Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5629 const CXXScopeSpec &SS, const IdentifierInfo &II,
5630 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005631 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005632 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5633 if (!NNS)
5634 return true;
5635
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005636 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5637 !getLangOptions().CPlusPlus0x)
5638 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5639 << FixItHint::CreateRemoval(TypenameLoc);
5640
Douglas Gregor107de902010-04-24 15:35:55 +00005641 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005642 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005643 if (T.isNull())
5644 return true;
John McCall63b43852010-04-29 23:50:39 +00005645
5646 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5647 if (isa<DependentNameType>(T)) {
5648 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005649 TL.setKeywordLoc(TypenameLoc);
5650 TL.setQualifierRange(SS.getRange());
5651 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005652 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005653 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005654 TL.setKeywordLoc(TypenameLoc);
5655 TL.setQualifierRange(SS.getRange());
5656 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005657 }
5658
John McCallb3d87482010-08-24 05:47:05 +00005659 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005660}
5661
John McCallf312b1e2010-08-26 23:41:50 +00005662TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005663Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5664 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005665 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005666 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5667 !getLangOptions().CPlusPlus0x)
5668 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5669 << FixItHint::CreateRemoval(TypenameLoc);
5670
John McCall4e449832010-05-28 23:32:21 +00005671 TypeSourceInfo *InnerTSI = 0;
5672 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005673
5674 assert(isa<TemplateSpecializationType>(T) &&
5675 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005676
Douglas Gregor6946baf2009-09-02 13:05:45 +00005677 if (computeDeclContext(SS, false)) {
5678 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005679 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005680 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005681
5682 // Push the inner type, preserving its source locations if possible.
5683 TypeLocBuilder Builder;
5684 if (InnerTSI)
5685 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5686 else
5687 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5688
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005689 /* Note: NNS already embedded in template specialization type T. */
5690 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005691 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5692 TL.setKeywordLoc(TypenameLoc);
5693 TL.setQualifierRange(SS.getRange());
5694
5695 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005696 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005697 }
Mike Stump1eb44332009-09-09 15:08:12 +00005698
John McCall33500952010-06-11 00:33:02 +00005699 // TODO: it's really silly that we make a template specialization
5700 // type earlier only to drop it again here.
5701 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5702 DependentTemplateName *DTN =
5703 TST->getTemplateName().getAsDependentTemplateName();
5704 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005705 assert(DTN->getQualifier()
5706 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5707 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5708 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005709 DTN->getIdentifier(),
5710 TST->getNumArgs(),
5711 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005712 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005713 DependentTemplateSpecializationTypeLoc TL =
5714 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5715 if (InnerTSI) {
5716 TemplateSpecializationTypeLoc TSTL =
5717 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5718 TL.setLAngleLoc(TSTL.getLAngleLoc());
5719 TL.setRAngleLoc(TSTL.getRAngleLoc());
5720 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5721 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5722 } else {
5723 TL.initializeLocal(SourceLocation());
5724 }
John McCall4e449832010-05-28 23:32:21 +00005725 TL.setKeywordLoc(TypenameLoc);
5726 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005727 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005728}
5729
Douglas Gregord57959a2009-03-27 23:10:48 +00005730/// \brief Build the type that describes a C++ typename specifier,
5731/// e.g., "typename T::type".
5732QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005733Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5734 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005735 SourceLocation KeywordLoc, SourceRange NNSRange,
5736 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005737 CXXScopeSpec SS;
5738 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005739 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005740
John McCall77bb1aa2010-05-01 00:40:08 +00005741 DeclContext *Ctx = computeDeclContext(SS);
5742 if (!Ctx) {
5743 // If the nested-name-specifier is dependent and couldn't be
5744 // resolved to a type, build a typename type.
5745 assert(NNS->isDependent());
5746 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005747 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005748
John McCall77bb1aa2010-05-01 00:40:08 +00005749 // If the nested-name-specifier refers to the current instantiation,
5750 // the "typename" keyword itself is superfluous. In C++03, the
5751 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5752 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005753 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005754
John McCall77bb1aa2010-05-01 00:40:08 +00005755 if (RequireCompleteDeclContext(SS, Ctx))
5756 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005757
5758 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005759 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005760 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005761 unsigned DiagID = 0;
5762 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005763 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005764 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005765 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005766 break;
Douglas Gregord9545042010-12-09 00:06:27 +00005767
5768 case LookupResult::FoundUnresolvedValue: {
5769 // We found a using declaration that is a value. Most likely, the using
5770 // declaration itself is meant to have the 'typename' keyword.
5771 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5772 IILoc);
5773 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5774 << Name << Ctx << FullRange;
5775 if (UnresolvedUsingValueDecl *Using
5776 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5777 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5778 Diag(Loc, diag::note_using_value_decl_missing_typename)
5779 << FixItHint::CreateInsertion(Loc, "typename ");
5780 }
5781 }
5782 // Fall through to create a dependent typename type, from which we can recover
5783 // better.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005784
5785 case LookupResult::NotFoundInCurrentInstantiation:
5786 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005787 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005788
5789 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005790 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005791 // We found a type. Build an ElaboratedType, since the
5792 // typename-specifier was just sugar.
5793 return Context.getElaboratedType(ETK_Typename, NNS,
5794 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005795 }
5796
5797 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005798 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005799 break;
5800
Douglas Gregord9545042010-12-09 00:06:27 +00005801
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005802 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005803 return QualType();
5804
Douglas Gregord57959a2009-03-27 23:10:48 +00005805 case LookupResult::FoundOverloaded:
5806 DiagID = diag::err_typename_nested_not_type;
5807 Referenced = *Result.begin();
5808 break;
5809
John McCall6e247262009-10-10 05:48:19 +00005810 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005811 return QualType();
5812 }
5813
5814 // If we get here, it's because name lookup did not find a
5815 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005816 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5817 IILoc);
5818 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005819 if (Referenced)
5820 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5821 << Name;
5822 return QualType();
5823}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005824
5825namespace {
5826 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005827 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005828 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005829 SourceLocation Loc;
5830 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005831
Douglas Gregor4a959d82009-08-06 16:20:37 +00005832 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005833 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5834
Mike Stump1eb44332009-09-09 15:08:12 +00005835 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005836 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005837 DeclarationName Entity)
5838 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005839 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005840
5841 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005842 /// transformed.
5843 ///
5844 /// For the purposes of type reconstruction, a type has already been
5845 /// transformed if it is NULL or if it is not dependent.
5846 bool AlreadyTransformed(QualType T) {
5847 return T.isNull() || !T->isDependentType();
5848 }
Mike Stump1eb44332009-09-09 15:08:12 +00005849
5850 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005851 /// rebuilt.
5852 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005853
Douglas Gregor4a959d82009-08-06 16:20:37 +00005854 /// \brief Returns the name of the entity whose type is being rebuilt.
5855 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005856
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005857 /// \brief Sets the "base" location and entity when that
5858 /// information is known based on another transformation.
5859 void setBase(SourceLocation Loc, DeclarationName Entity) {
5860 this->Loc = Loc;
5861 this->Entity = Entity;
5862 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005863 };
5864}
5865
Douglas Gregor4a959d82009-08-06 16:20:37 +00005866/// \brief Rebuilds a type within the context of the current instantiation.
5867///
Mike Stump1eb44332009-09-09 15:08:12 +00005868/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005869/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005870/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005871/// partial specialization thereof). This routine will rebuild that type now
5872/// that we have entered the declarator's scope, which may produce different
5873/// canonical types, e.g.,
5874///
5875/// \code
5876/// template<typename T>
5877/// struct X {
5878/// typedef T* pointer;
5879/// pointer data();
5880/// };
5881///
5882/// template<typename T>
5883/// typename X<T>::pointer X<T>::data() { ... }
5884/// \endcode
5885///
Douglas Gregor4714c122010-03-31 17:34:00 +00005886/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005887/// since we do not know that we can look into X<T> when we parsed the type.
5888/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005889/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005890/// as the canonical type of T*, allowing the return types of the out-of-line
5891/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005892TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5893 SourceLocation Loc,
5894 DeclarationName Name) {
5895 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005896 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005897
Douglas Gregor4a959d82009-08-06 16:20:37 +00005898 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5899 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005900}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005901
John McCall60d7b3a2010-08-24 06:29:42 +00005902ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00005903 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5904 DeclarationName());
5905 return Rebuilder.TransformExpr(E);
5906}
5907
John McCall63b43852010-04-29 23:50:39 +00005908bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5909 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005910
5911 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5912 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5913 DeclarationName());
5914 NestedNameSpecifier *Rebuilt =
5915 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005916 if (!Rebuilt) return true;
5917
5918 SS.setScopeRep(Rebuilt);
5919 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005920}
5921
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005922/// \brief Produces a formatted string that describes the binding of
5923/// template parameters to template arguments.
5924std::string
5925Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5926 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00005927 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005928}
5929
5930std::string
5931Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5932 const TemplateArgument *Args,
5933 unsigned NumArgs) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00005934 llvm::SmallString<128> Str;
5935 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005936
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005937 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00005938 return std::string();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005939
5940 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005941 if (I >= NumArgs)
5942 break;
5943
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005944 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00005945 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005946 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00005947 Out << ", ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005948
5949 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00005950 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005951 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00005952 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005953 }
5954
Douglas Gregor87dd6972010-12-20 16:52:59 +00005955 Out << " = ";
5956 Args[I].print(Context.PrintingPolicy, Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005957 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00005958
5959 Out << ']';
5960 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005961}
Douglas Gregord0937222010-12-13 22:49:22 +00005962