blob: 7357e9449069477e1e565d0c137a066ae3698c11 [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 Gregora8bc8c92010-12-23 22:44:42 +0000635 if (D.hasEllipsis()) {
636 // FIXME: Variadic templates.
637 Diag(D.getEllipsisLoc(), diag::err_non_type_parameter_pack_unsupported);
638 Invalid = true;
639 }
640
Douglas Gregor72c3f312008-12-05 18:15:24 +0000641 NonTypeTemplateParmDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +0000642 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
643 D.getIdentifierLoc(),
John McCalla93c9342009-12-07 02:54:59 +0000644 Depth, Position, ParamName, T, TInfo);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000645 if (Invalid)
646 Param->setInvalidDecl();
647
648 if (D.getIdentifier()) {
649 // Add the template parameter into the current scope.
John McCalld226f652010-08-21 09:40:31 +0000650 S->AddDecl(Param);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000651 IdResolver.AddDecl(Param);
652 }
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000653
654 // Check the well-formedness of the default template argument, if provided.
John McCall9ae2f072010-08-23 23:25:46 +0000655 if (Default) {
Douglas Gregor6f526752010-12-16 08:48:57 +0000656 // Check for unexpanded parameter packs.
657 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
658 return Param;
659
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000660 TemplateArgument Converted;
661 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
662 Param->setInvalidDecl();
John McCalld226f652010-08-21 09:40:31 +0000663 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000664 }
665
John McCall9ae2f072010-08-23 23:25:46 +0000666 Param->setDefaultArgument(Default, false);
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000667 }
668
John McCalld226f652010-08-21 09:40:31 +0000669 return Param;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000670}
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000671
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000672/// ActOnTemplateTemplateParameter - Called when a C++ template template
673/// parameter (e.g. T in template <template <typename> class T> class array)
674/// has been parsed. S is the current scope.
John McCalld226f652010-08-21 09:40:31 +0000675Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
676 SourceLocation TmpLoc,
677 TemplateParamsTy *Params,
678 IdentifierInfo *Name,
679 SourceLocation NameLoc,
680 unsigned Depth,
681 unsigned Position,
682 SourceLocation EqualLoc,
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000683 const ParsedTemplateArgument &Default) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000684 assert(S->isTemplateParamScope() &&
685 "Template template parameter not in template parameter scope!");
686
687 // Construct the parameter object.
688 TemplateTemplateParmDecl *Param =
John McCall7a9813c2010-01-22 00:28:27 +0000689 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000690 NameLoc.isInvalid()? TmpLoc : NameLoc,
691 Depth, Position, Name,
Douglas Gregor369ea272010-10-21 17:26:49 +0000692 Params);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000693
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000694 // If the template template parameter has a name, then link the identifier
695 // into the scope and lookup mechanisms.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000696 if (Name) {
John McCalld226f652010-08-21 09:40:31 +0000697 S->AddDecl(Param);
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000698 IdResolver.AddDecl(Param);
699 }
700
Douglas Gregor6f526752010-12-16 08:48:57 +0000701 if (Params->size() == 0) {
702 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
703 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
704 Param->setInvalidDecl();
705 }
706
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000707 if (!Default.isInvalid()) {
708 // Check only that we have a template template argument. We don't want to
709 // try to check well-formedness now, because our template template parameter
710 // might have dependent types in its template parameters, which we wouldn't
711 // be able to match now.
712 //
713 // If none of the template template parameter's template arguments mention
714 // other template parameters, we could actually perform more checking here.
715 // However, it isn't worth doing.
716 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
717 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
718 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
719 << DefaultArg.getSourceRange();
John McCalld226f652010-08-21 09:40:31 +0000720 return Param;
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000721 }
722
Douglas Gregor6f526752010-12-16 08:48:57 +0000723 // Check for unexpanded parameter packs.
724 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
725 DefaultArg.getArgument().getAsTemplate(),
726 UPPC_DefaultArgument))
727 return Param;
728
Douglas Gregorbb3310a2010-07-01 00:00:45 +0000729 Param->setDefaultArgument(DefaultArg, false);
Douglas Gregord684b002009-02-10 19:49:53 +0000730 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000731
John McCalld226f652010-08-21 09:40:31 +0000732 return Param;
Douglas Gregord684b002009-02-10 19:49:53 +0000733}
734
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000735/// ActOnTemplateParameterList - Builds a TemplateParameterList that
736/// contains the template parameters in Params/NumParams.
737Sema::TemplateParamsTy *
738Sema::ActOnTemplateParameterList(unsigned Depth,
739 SourceLocation ExportLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000740 SourceLocation TemplateLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000741 SourceLocation LAngleLoc,
John McCalld226f652010-08-21 09:40:31 +0000742 Decl **Params, unsigned NumParams,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000743 SourceLocation RAngleLoc) {
744 if (ExportLoc.isValid())
Douglas Gregor51ffb0c2009-11-25 18:55:14 +0000745 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000746
Douglas Gregorddc29e12009-02-06 22:42:48 +0000747 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbf4ea562009-09-15 16:23:51 +0000748 (NamedDecl**)Params, NumParams,
749 RAngleLoc);
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +0000750}
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000751
John McCallb6217662010-03-15 10:12:16 +0000752static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
753 if (SS.isSet())
754 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
755 SS.getRange());
756}
757
John McCallf312b1e2010-08-26 23:41:50 +0000758DeclResult
John McCall0f434ec2009-07-31 02:45:11 +0000759Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +0000760 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorddc29e12009-02-06 22:42:48 +0000761 IdentifierInfo *Name, SourceLocation NameLoc,
762 AttributeList *Attr,
Douglas Gregor05396e22009-08-25 17:23:04 +0000763 TemplateParameterList *TemplateParams,
Anders Carlsson5aeccdb2009-03-26 00:52:18 +0000764 AccessSpecifier AS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000765 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor05396e22009-08-25 17:23:04 +0000766 "No template parameters");
John McCall0f434ec2009-07-31 02:45:11 +0000767 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregord684b002009-02-10 19:49:53 +0000768 bool Invalid = false;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000769
770 // Check that we can declare a template here.
Douglas Gregor05396e22009-08-25 17:23:04 +0000771 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000772 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000773
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000774 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
775 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorddc29e12009-02-06 22:42:48 +0000776
777 // There is no such thing as an unnamed class template.
778 if (!Name) {
779 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000780 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000781 }
782
783 // Find any previous declaration with this name.
Douglas Gregor05396e22009-08-25 17:23:04 +0000784 DeclContext *SemanticContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000785 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall7d384dd2009-11-18 07:57:50 +0000786 ForRedeclaration);
Douglas Gregor05396e22009-08-25 17:23:04 +0000787 if (SS.isNotEmpty() && !SS.isInvalid()) {
788 SemanticContext = computeDeclContext(SS, true);
789 if (!SemanticContext) {
790 // FIXME: Produce a reasonable diagnostic here
791 return true;
792 }
Mike Stump1eb44332009-09-09 15:08:12 +0000793
John McCall77bb1aa2010-05-01 00:40:08 +0000794 if (RequireCompleteDeclContext(SS, SemanticContext))
795 return true;
796
John McCalla24dc2e2009-11-17 02:14:36 +0000797 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor05396e22009-08-25 17:23:04 +0000798 } else {
799 SemanticContext = CurContext;
John McCalla24dc2e2009-11-17 02:14:36 +0000800 LookupName(Previous, S);
Douglas Gregor05396e22009-08-25 17:23:04 +0000801 }
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Douglas Gregor57265e32010-04-12 16:00:01 +0000803 if (Previous.isAmbiguous())
804 return true;
805
Douglas Gregorddc29e12009-02-06 22:42:48 +0000806 NamedDecl *PrevDecl = 0;
807 if (Previous.begin() != Previous.end())
Douglas Gregor57265e32010-04-12 16:00:01 +0000808 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000809
Douglas Gregorddc29e12009-02-06 22:42:48 +0000810 // If there is a previous declaration with the same name, check
811 // whether this is a valid redeclaration.
Mike Stump1eb44332009-09-09 15:08:12 +0000812 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorddc29e12009-02-06 22:42:48 +0000813 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregord7e5bdb2009-10-09 21:11:42 +0000814
815 // We may have found the injected-class-name of a class template,
816 // class template partial specialization, or class template specialization.
817 // In these cases, grab the template that is being defined or specialized.
818 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
819 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
820 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
821 PrevClassTemplate
822 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
823 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
824 PrevClassTemplate
825 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
826 ->getSpecializedTemplate();
827 }
828 }
829
John McCall65c49462009-12-18 11:25:59 +0000830 if (TUK == TUK_Friend) {
John McCalle129d442009-12-17 23:21:11 +0000831 // C++ [namespace.memdef]p3:
832 // [...] When looking for a prior declaration of a class or a function
833 // declared as a friend, and when the name of the friend class or
834 // function is neither a qualified name nor a template-id, scopes outside
835 // the innermost enclosing namespace scope are not considered.
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000836 if (!SS.isSet()) {
837 DeclContext *OutermostContext = CurContext;
838 while (!OutermostContext->isFileContext())
839 OutermostContext = OutermostContext->getLookupParent();
John McCall65c49462009-12-18 11:25:59 +0000840
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000841 if (PrevDecl &&
842 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
843 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
844 SemanticContext = PrevDecl->getDeclContext();
845 } else {
846 // Declarations in outer scopes don't matter. However, the outermost
847 // context we computed is the semantic context for our new
848 // declaration.
849 PrevDecl = PrevClassTemplate = 0;
850 SemanticContext = OutermostContext;
851 }
John McCalle129d442009-12-17 23:21:11 +0000852 }
Douglas Gregorc1c9df72010-04-18 17:37:40 +0000853
John McCalle129d442009-12-17 23:21:11 +0000854 if (CurContext->isDependentContext()) {
855 // If this is a dependent context, we don't want to link the friend
856 // class template to the template in scope, because that would perform
857 // checking of the template parameter lists that can't be performed
858 // until the outer context is instantiated.
859 PrevDecl = PrevClassTemplate = 0;
860 }
861 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
862 PrevDecl = PrevClassTemplate = 0;
Douglas Gregor57265e32010-04-12 16:00:01 +0000863
Douglas Gregorddc29e12009-02-06 22:42:48 +0000864 if (PrevClassTemplate) {
865 // Ensure that the template parameter lists are compatible.
866 if (!TemplateParameterListsAreEqual(TemplateParams,
867 PrevClassTemplate->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +0000868 /*Complain=*/true,
869 TPL_TemplateMatch))
Douglas Gregor212e81c2009-03-25 00:13:59 +0000870 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000871
872 // C++ [temp.class]p4:
873 // In a redeclaration, partial specialization, explicit
874 // specialization or explicit instantiation of a class template,
875 // the class-key shall agree in kind with the original class
876 // template declaration (7.1.5.3).
877 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregor501c5ce2009-05-14 16:41:31 +0000878 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000879 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +0000880 << Name
Douglas Gregor849b2432010-03-31 17:46:05 +0000881 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorddc29e12009-02-06 22:42:48 +0000882 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregora3a83512009-04-01 23:51:29 +0000883 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorddc29e12009-02-06 22:42:48 +0000884 }
885
Douglas Gregorddc29e12009-02-06 22:42:48 +0000886 // Check for redefinition of this class template.
John McCall0f434ec2009-07-31 02:45:11 +0000887 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +0000888 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorddc29e12009-02-06 22:42:48 +0000889 Diag(NameLoc, diag::err_redefinition) << Name;
890 Diag(Def->getLocation(), diag::note_previous_definition);
891 // FIXME: Would it make sense to try to "forget" the previous
892 // definition, as part of error recovery?
Douglas Gregor212e81c2009-03-25 00:13:59 +0000893 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000894 }
895 }
896 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
897 // Maybe we will complain about the shadowed template parameter.
898 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
899 // Just pretend that we didn't see the previous declaration.
900 PrevDecl = 0;
901 } else if (PrevDecl) {
902 // C++ [temp]p5:
903 // A class template shall not have the same name as any other
904 // template, class, function, object, enumeration, enumerator,
905 // namespace, or type in the same scope (3.3), except as specified
906 // in (14.5.4).
907 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
908 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor212e81c2009-03-25 00:13:59 +0000909 return true;
Douglas Gregorddc29e12009-02-06 22:42:48 +0000910 }
911
Douglas Gregord684b002009-02-10 19:49:53 +0000912 // Check the template parameter list of this declaration, possibly
913 // merging in the template parameter list from the previous class
914 // template declaration.
915 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +0000916 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
917 TPC_ClassTemplate))
Douglas Gregord684b002009-02-10 19:49:53 +0000918 Invalid = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Douglas Gregor57265e32010-04-12 16:00:01 +0000920 if (SS.isSet()) {
921 // If the name of the template was qualified, we must be defining the
922 // template out-of-line.
923 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
924 !(TUK == TUK_Friend && CurContext->isDependentContext()))
925 Diag(NameLoc, diag::err_member_def_does_not_match)
926 << Name << SemanticContext << SS.getRange();
927 }
928
Mike Stump1eb44332009-09-09 15:08:12 +0000929 CXXRecordDecl *NewClass =
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000930 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump1eb44332009-09-09 15:08:12 +0000931 PrevClassTemplate?
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000932 PrevClassTemplate->getTemplatedDecl() : 0,
933 /*DelayTypeCreation=*/true);
John McCallb6217662010-03-15 10:12:16 +0000934 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000935
936 ClassTemplateDecl *NewTemplate
937 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
938 DeclarationName(Name), TemplateParams,
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000939 NewClass, PrevClassTemplate);
Douglas Gregorbefc20e2009-03-26 00:10:35 +0000940 NewClass->setDescribedClassTemplate(NewTemplate);
941
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000942 // Build the type for the class template declaration now.
Douglas Gregor24bae922010-07-08 18:37:38 +0000943 QualType T = NewTemplate->getInjectedClassNameSpecialization();
John McCall3cb0ebd2010-03-10 03:28:59 +0000944 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregoraafc0cc2009-05-15 19:11:46 +0000945 assert(T->isDependentType() && "Class template type is not dependent?");
946 (void)T;
947
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000948 // If we are providing an explicit specialization of a member that is a
949 // class template, make a note of that.
950 if (PrevClassTemplate &&
951 PrevClassTemplate->getInstantiatedFromMemberTemplate())
952 PrevClassTemplate->setMemberSpecialization();
953
Anders Carlsson4cbe82c2009-03-26 01:24:28 +0000954 // Set the access specifier.
Douglas Gregord85bea22009-09-26 06:47:28 +0000955 if (!Invalid && TUK != TUK_Friend)
John McCall05b23ea2009-09-14 21:59:20 +0000956 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregorddc29e12009-02-06 22:42:48 +0000958 // Set the lexical context of these templates
959 NewClass->setLexicalDeclContext(CurContext);
960 NewTemplate->setLexicalDeclContext(CurContext);
961
John McCall0f434ec2009-07-31 02:45:11 +0000962 if (TUK == TUK_Definition)
Douglas Gregorddc29e12009-02-06 22:42:48 +0000963 NewClass->startDefinition();
964
965 if (Attr)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000966 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorddc29e12009-02-06 22:42:48 +0000967
John McCall05b23ea2009-09-14 21:59:20 +0000968 if (TUK != TUK_Friend)
969 PushOnScopeChains(NewTemplate, S);
970 else {
Douglas Gregord85bea22009-09-26 06:47:28 +0000971 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall05b23ea2009-09-14 21:59:20 +0000972 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregord85bea22009-09-26 06:47:28 +0000973 NewClass->setAccess(PrevClassTemplate->getAccess());
974 }
John McCall05b23ea2009-09-14 21:59:20 +0000975
Douglas Gregord85bea22009-09-26 06:47:28 +0000976 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
977 PrevClassTemplate != NULL);
978
John McCall05b23ea2009-09-14 21:59:20 +0000979 // Friend templates are visible in fairly strange ways.
980 if (!CurContext->isDependentContext()) {
Sebastian Redl7a126a42010-08-31 00:36:30 +0000981 DeclContext *DC = SemanticContext->getRedeclContext();
John McCall05b23ea2009-09-14 21:59:20 +0000982 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
983 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
984 PushOnScopeChains(NewTemplate, EnclosingScope,
985 /* AddToContext = */ false);
986 }
Douglas Gregord85bea22009-09-26 06:47:28 +0000987
988 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
989 NewClass->getLocation(),
990 NewTemplate,
991 /*FIXME:*/NewClass->getLocation());
992 Friend->setAccess(AS_public);
993 CurContext->addDecl(Friend);
John McCall05b23ea2009-09-14 21:59:20 +0000994 }
Douglas Gregorddc29e12009-02-06 22:42:48 +0000995
Douglas Gregord684b002009-02-10 19:49:53 +0000996 if (Invalid) {
997 NewTemplate->setInvalidDecl();
998 NewClass->setInvalidDecl();
999 }
John McCalld226f652010-08-21 09:40:31 +00001000 return NewTemplate;
Douglas Gregorddc29e12009-02-06 22:42:48 +00001001}
1002
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001003/// \brief Diagnose the presence of a default template argument on a
1004/// template parameter, which is ill-formed in certain contexts.
1005///
1006/// \returns true if the default template argument should be dropped.
1007static bool DiagnoseDefaultTemplateArgument(Sema &S,
1008 Sema::TemplateParamListContext TPC,
1009 SourceLocation ParamLoc,
1010 SourceRange DefArgRange) {
1011 switch (TPC) {
1012 case Sema::TPC_ClassTemplate:
1013 return false;
1014
1015 case Sema::TPC_FunctionTemplate:
1016 // C++ [temp.param]p9:
1017 // A default template-argument shall not be specified in a
1018 // function template declaration or a function template
1019 // definition [...]
1020 // (This sentence is not in C++0x, per DR226).
1021 if (!S.getLangOptions().CPlusPlus0x)
1022 S.Diag(ParamLoc,
1023 diag::err_template_parameter_default_in_function_template)
1024 << DefArgRange;
1025 return false;
1026
1027 case Sema::TPC_ClassTemplateMember:
1028 // C++0x [temp.param]p9:
1029 // A default template-argument shall not be specified in the
1030 // template-parameter-lists of the definition of a member of a
1031 // class template that appears outside of the member's class.
1032 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1033 << DefArgRange;
1034 return true;
1035
1036 case Sema::TPC_FriendFunctionTemplate:
1037 // C++ [temp.param]p9:
1038 // A default template-argument shall not be specified in a
1039 // friend template declaration.
1040 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1041 << DefArgRange;
1042 return true;
1043
1044 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1045 // for friend function templates if there is only a single
1046 // declaration (and it is a definition). Strange!
1047 }
1048
1049 return false;
1050}
1051
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001052/// \brief Check for unexpanded parameter packs within the template parameters
1053/// of a template template parameter, recursively.
1054bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){
1055 TemplateParameterList *Params = TTP->getTemplateParameters();
1056 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1057 NamedDecl *P = Params->getParam(I);
1058 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1059 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1060 NTTP->getTypeSourceInfo(),
1061 Sema::UPPC_NonTypeTemplateParameterType))
1062 return true;
1063
1064 continue;
1065 }
1066
1067 if (TemplateTemplateParmDecl *InnerTTP
1068 = dyn_cast<TemplateTemplateParmDecl>(P))
1069 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1070 return true;
1071 }
1072
1073 return false;
1074}
1075
Douglas Gregord684b002009-02-10 19:49:53 +00001076/// \brief Checks the validity of a template parameter list, possibly
1077/// considering the template parameter list from a previous
1078/// declaration.
1079///
1080/// If an "old" template parameter list is provided, it must be
1081/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1082/// template parameter list.
1083///
1084/// \param NewParams Template parameter list for a new template
1085/// declaration. This template parameter list will be updated with any
1086/// default arguments that are carried through from the previous
1087/// template parameter list.
1088///
1089/// \param OldParams If provided, template parameter list from a
1090/// previous declaration of the same template. Default template
1091/// arguments will be merged from the old template parameter list to
1092/// the new template parameter list.
1093///
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001094/// \param TPC Describes the context in which we are checking the given
1095/// template parameter list.
1096///
Douglas Gregord684b002009-02-10 19:49:53 +00001097/// \returns true if an error occurred, false otherwise.
1098bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001099 TemplateParameterList *OldParams,
1100 TemplateParamListContext TPC) {
Douglas Gregord684b002009-02-10 19:49:53 +00001101 bool Invalid = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Douglas Gregord684b002009-02-10 19:49:53 +00001103 // C++ [temp.param]p10:
1104 // The set of default template-arguments available for use with a
1105 // template declaration or definition is obtained by merging the
1106 // default arguments from the definition (if in scope) and all
1107 // declarations in scope in the same way default function
1108 // arguments are (8.3.6).
1109 bool SawDefaultArgument = false;
1110 SourceLocation PreviousDefaultArgLoc;
Douglas Gregorc15cb382009-02-09 23:23:08 +00001111
Anders Carlsson49d25572009-06-12 23:20:15 +00001112 bool SawParameterPack = false;
1113 SourceLocation ParameterPackLoc;
1114
Mike Stump1a35fde2009-02-11 23:03:27 +00001115 // Dummy initialization to avoid warnings.
Douglas Gregor1bc69132009-02-11 20:46:19 +00001116 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregord684b002009-02-10 19:49:53 +00001117 if (OldParams)
1118 OldParam = OldParams->begin();
1119
1120 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1121 NewParamEnd = NewParams->end();
1122 NewParam != NewParamEnd; ++NewParam) {
1123 // Variables used to diagnose redundant default arguments
1124 bool RedundantDefaultArg = false;
1125 SourceLocation OldDefaultLoc;
1126 SourceLocation NewDefaultLoc;
1127
1128 // Variables used to diagnose missing default arguments
1129 bool MissingDefaultArg = false;
1130
Anders Carlsson49d25572009-06-12 23:20:15 +00001131 // C++0x [temp.param]p11:
1132 // If a template parameter of a class template is a template parameter pack,
1133 // it must be the last template parameter.
1134 if (SawParameterPack) {
Mike Stump1eb44332009-09-09 15:08:12 +00001135 Diag(ParameterPackLoc,
Anders Carlsson49d25572009-06-12 23:20:15 +00001136 diag::err_template_param_pack_must_be_last_template_parameter);
1137 Invalid = true;
1138 }
1139
Douglas Gregord684b002009-02-10 19:49:53 +00001140 if (TemplateTypeParmDecl *NewTypeParm
1141 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001142 // Check the presence of a default argument here.
1143 if (NewTypeParm->hasDefaultArgument() &&
1144 DiagnoseDefaultTemplateArgument(*this, TPC,
1145 NewTypeParm->getLocation(),
1146 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnarabd054db2010-05-20 10:00:11 +00001147 .getSourceRange()))
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001148 NewTypeParm->removeDefaultArgument();
1149
1150 // Merge default arguments for template type parameters.
Mike Stump1eb44332009-09-09 15:08:12 +00001151 TemplateTypeParmDecl *OldTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001152 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Anders Carlsson49d25572009-06-12 23:20:15 +00001154 if (NewTypeParm->isParameterPack()) {
1155 assert(!NewTypeParm->hasDefaultArgument() &&
1156 "Parameter packs can't have a default argument!");
1157 SawParameterPack = true;
1158 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump1eb44332009-09-09 15:08:12 +00001159 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall833ca992009-10-29 08:12:44 +00001160 NewTypeParm->hasDefaultArgument()) {
Douglas Gregord684b002009-02-10 19:49:53 +00001161 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1162 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1163 SawDefaultArgument = true;
1164 RedundantDefaultArg = true;
1165 PreviousDefaultArgLoc = NewDefaultLoc;
1166 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1167 // Merge the default argument from the old declaration to the
1168 // new declaration.
1169 SawDefaultArgument = true;
John McCall833ca992009-10-29 08:12:44 +00001170 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregord684b002009-02-10 19:49:53 +00001171 true);
1172 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1173 } else if (NewTypeParm->hasDefaultArgument()) {
1174 SawDefaultArgument = true;
1175 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1176 } else if (SawDefaultArgument)
1177 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001178 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregord684b002009-02-10 19:49:53 +00001179 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001180 // Check for unexpanded parameter packs.
1181 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1182 NewNonTypeParm->getTypeSourceInfo(),
1183 UPPC_NonTypeTemplateParameterType)) {
1184 Invalid = true;
1185 continue;
1186 }
1187
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001188 // Check the presence of a default argument here.
1189 if (NewNonTypeParm->hasDefaultArgument() &&
1190 DiagnoseDefaultTemplateArgument(*this, TPC,
1191 NewNonTypeParm->getLocation(),
1192 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001193 NewNonTypeParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001194 }
1195
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001196 // Merge default arguments for non-type template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001197 NonTypeTemplateParmDecl *OldNonTypeParm
1198 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001199 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001200 NewNonTypeParm->hasDefaultArgument()) {
1201 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1202 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1203 SawDefaultArgument = true;
1204 RedundantDefaultArg = true;
1205 PreviousDefaultArgLoc = NewDefaultLoc;
1206 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1207 // Merge the default argument from the old declaration to the
1208 // new declaration.
1209 SawDefaultArgument = true;
1210 // FIXME: We need to create a new kind of "default argument"
1211 // expression that points to a previous template template
1212 // parameter.
1213 NewNonTypeParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001214 OldNonTypeParm->getDefaultArgument(),
1215 /*Inherited=*/ true);
Douglas Gregord684b002009-02-10 19:49:53 +00001216 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1217 } else if (NewNonTypeParm->hasDefaultArgument()) {
1218 SawDefaultArgument = true;
1219 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1220 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001221 MissingDefaultArg = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001222 } else {
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001223 // Check the presence of a default argument here.
Douglas Gregord684b002009-02-10 19:49:53 +00001224 TemplateTemplateParmDecl *NewTemplateParm
1225 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregor4d2abba2010-12-16 15:36:43 +00001226
1227 // Check for unexpanded parameter packs, recursively.
1228 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1229 Invalid = true;
1230 continue;
1231 }
1232
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001233 if (NewTemplateParm->hasDefaultArgument() &&
1234 DiagnoseDefaultTemplateArgument(*this, TPC,
1235 NewTemplateParm->getLocation(),
1236 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001237 NewTemplateParm->removeDefaultArgument();
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001238
1239 // Merge default arguments for template template parameters
Douglas Gregord684b002009-02-10 19:49:53 +00001240 TemplateTemplateParmDecl *OldTemplateParm
1241 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001242 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregord684b002009-02-10 19:49:53 +00001243 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor788cd062009-11-11 01:00:40 +00001244 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1245 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001246 SawDefaultArgument = true;
1247 RedundantDefaultArg = true;
1248 PreviousDefaultArgLoc = NewDefaultLoc;
1249 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1250 // Merge the default argument from the old declaration to the
1251 // new declaration.
1252 SawDefaultArgument = true;
Mike Stump390b4cc2009-05-16 07:39:55 +00001253 // FIXME: We need to create a new kind of "default argument" expression
1254 // that points to a previous template template parameter.
Douglas Gregord684b002009-02-10 19:49:53 +00001255 NewTemplateParm->setDefaultArgument(
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001256 OldTemplateParm->getDefaultArgument(),
1257 /*Inherited=*/ true);
Douglas Gregor788cd062009-11-11 01:00:40 +00001258 PreviousDefaultArgLoc
1259 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001260 } else if (NewTemplateParm->hasDefaultArgument()) {
1261 SawDefaultArgument = true;
Douglas Gregor788cd062009-11-11 01:00:40 +00001262 PreviousDefaultArgLoc
1263 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregord684b002009-02-10 19:49:53 +00001264 } else if (SawDefaultArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001265 MissingDefaultArg = true;
Douglas Gregord684b002009-02-10 19:49:53 +00001266 }
1267
1268 if (RedundantDefaultArg) {
1269 // C++ [temp.param]p12:
1270 // A template-parameter shall not be given default arguments
1271 // by two different declarations in the same scope.
1272 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1273 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1274 Invalid = true;
1275 } else if (MissingDefaultArg) {
1276 // C++ [temp.param]p11:
1277 // If a template-parameter has a default template-argument,
1278 // all subsequent template-parameters shall have a default
1279 // template-argument supplied.
Mike Stump1eb44332009-09-09 15:08:12 +00001280 Diag((*NewParam)->getLocation(),
Douglas Gregord684b002009-02-10 19:49:53 +00001281 diag::err_template_param_default_arg_missing);
1282 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1283 Invalid = true;
1284 }
1285
1286 // If we have an old template parameter list that we're merging
1287 // in, move on to the next parameter.
1288 if (OldParams)
1289 ++OldParam;
1290 }
1291
1292 return Invalid;
1293}
Douglas Gregorc15cb382009-02-09 23:23:08 +00001294
John McCall4e2cbb22010-10-20 05:44:58 +00001295namespace {
1296
1297/// A class which looks for a use of a certain level of template
1298/// parameter.
1299struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1300 typedef RecursiveASTVisitor<DependencyChecker> super;
1301
1302 unsigned Depth;
1303 bool Match;
1304
1305 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1306 NamedDecl *ND = Params->getParam(0);
1307 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1308 Depth = PD->getDepth();
1309 } else if (NonTypeTemplateParmDecl *PD =
1310 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1311 Depth = PD->getDepth();
1312 } else {
1313 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1314 }
1315 }
1316
1317 bool Matches(unsigned ParmDepth) {
1318 if (ParmDepth >= Depth) {
1319 Match = true;
1320 return true;
1321 }
1322 return false;
1323 }
1324
1325 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1326 return !Matches(T->getDepth());
1327 }
1328
1329 bool TraverseTemplateName(TemplateName N) {
1330 if (TemplateTemplateParmDecl *PD =
1331 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1332 if (Matches(PD->getDepth())) return false;
1333 return super::TraverseTemplateName(N);
1334 }
1335
1336 bool VisitDeclRefExpr(DeclRefExpr *E) {
1337 if (NonTypeTemplateParmDecl *PD =
1338 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1339 if (PD->getDepth() == Depth) {
1340 Match = true;
1341 return false;
1342 }
1343 }
1344 return super::VisitDeclRefExpr(E);
1345 }
1346};
1347}
1348
1349/// Determines whether a template-id depends on the given parameter
1350/// list.
1351static bool
1352DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1353 TemplateParameterList *Params) {
1354 DependencyChecker Checker(Params);
1355 Checker.TraverseType(QualType(TemplateId, 0));
1356 return Checker.Match;
1357}
1358
Mike Stump1eb44332009-09-09 15:08:12 +00001359/// \brief Match the given template parameter lists to the given scope
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001360/// specifier, returning the template parameter list that applies to the
1361/// name.
1362///
1363/// \param DeclStartLoc the start of the declaration that has a scope
1364/// specifier or a template parameter list.
Mike Stump1eb44332009-09-09 15:08:12 +00001365///
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001366/// \param SS the scope specifier that will be matched to the given template
1367/// parameter lists. This scope specifier precedes a qualified name that is
1368/// being declared.
1369///
1370/// \param ParamLists the template parameter lists, from the outermost to the
1371/// innermost template parameter lists.
1372///
1373/// \param NumParamLists the number of template parameter lists in ParamLists.
1374///
John McCall77e8b112010-04-13 20:37:33 +00001375/// \param IsFriend Whether to apply the slightly different rules for
1376/// matching template parameters to scope specifiers in friend
1377/// declarations.
1378///
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001379/// \param IsExplicitSpecialization will be set true if the entity being
1380/// declared is an explicit specialization, false otherwise.
1381///
Mike Stump1eb44332009-09-09 15:08:12 +00001382/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001383/// name that is preceded by the scope specifier @p SS. This template
1384/// parameter list may be have template parameters (if we're declaring a
Mike Stump1eb44332009-09-09 15:08:12 +00001385/// template) or may have no template parameters (if we're declaring a
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001386/// template specialization), or may be NULL (if we were's declaring isn't
1387/// itself a template).
1388TemplateParameterList *
1389Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1390 const CXXScopeSpec &SS,
1391 TemplateParameterList **ParamLists,
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001392 unsigned NumParamLists,
John McCall77e8b112010-04-13 20:37:33 +00001393 bool IsFriend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001394 bool &IsExplicitSpecialization,
1395 bool &Invalid) {
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001396 IsExplicitSpecialization = false;
1397
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001398 // Find the template-ids that occur within the nested-name-specifier. These
1399 // template-ids will match up with the template parameter lists.
1400 llvm::SmallVector<const TemplateSpecializationType *, 4>
1401 TemplateIdsInSpecifier;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001402 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1403 ExplicitSpecializationsInSpecifier;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001404 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1405 NNS; NNS = NNS->getPrefix()) {
John McCall4b2b02b2009-12-15 02:19:47 +00001406 const Type *T = NNS->getAsType();
1407 if (!T) break;
1408
1409 // C++0x [temp.expl.spec]p17:
1410 // A member or a member template may be nested within many
1411 // enclosing class templates. In an explicit specialization for
1412 // such a member, the member declaration shall be preceded by a
1413 // template<> for each enclosing class template that is
1414 // explicitly specialized.
Douglas Gregorfe331062010-02-13 05:23:25 +00001415 //
1416 // Following the existing practice of GNU and EDG, we allow a typedef of a
1417 // template specialization type.
John McCall49f4e1c2010-12-10 11:01:00 +00001418 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1419 T = TT->getDecl()->getUnderlyingType().getTypePtr();
John McCall4b2b02b2009-12-15 02:19:47 +00001420
Mike Stump1eb44332009-09-09 15:08:12 +00001421 if (const TemplateSpecializationType *SpecType
Douglas Gregorfe331062010-02-13 05:23:25 +00001422 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001423 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1424 if (!Template)
1425 continue; // FIXME: should this be an error? probably...
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Ted Kremenek6217b802009-07-29 21:53:49 +00001427 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001428 ClassTemplateSpecializationDecl *SpecDecl
1429 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1430 // If the nested name specifier refers to an explicit specialization,
1431 // we don't need a template<> header.
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001432 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1433 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001434 continue;
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001435 }
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001436 }
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001438 TemplateIdsInSpecifier.push_back(SpecType);
1439 }
1440 }
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001442 // Reverse the list of template-ids in the scope specifier, so that we can
1443 // more easily match up the template-ids and the template parameter lists.
1444 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001446 SourceLocation FirstTemplateLoc = DeclStartLoc;
1447 if (NumParamLists)
1448 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001450 // Match the template-ids found in the specifier to the template parameter
1451 // lists.
John McCall4e2cbb22010-10-20 05:44:58 +00001452 unsigned ParamIdx = 0, TemplateIdx = 0;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001453 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
John McCall4e2cbb22010-10-20 05:44:58 +00001454 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1455 const TemplateSpecializationType *TemplateId
1456 = TemplateIdsInSpecifier[TemplateIdx];
Douglas Gregorb88e8882009-07-30 17:40:51 +00001457 bool DependentTemplateId = TemplateId->isDependentType();
John McCall4e2cbb22010-10-20 05:44:58 +00001458
1459 // In friend declarations we can have template-ids which don't
1460 // depend on the corresponding template parameter lists. But
1461 // assume that empty parameter lists are supposed to match this
1462 // template-id.
1463 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1464 if (!DependentTemplateId ||
1465 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1466 continue;
1467 }
1468
1469 if (ParamIdx >= NumParamLists) {
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001470 // We have a template-id without a corresponding template parameter
1471 // list.
John McCall77e8b112010-04-13 20:37:33 +00001472
1473 // ...which is fine if this is a friend declaration.
1474 if (IsFriend) {
1475 IsExplicitSpecialization = true;
1476 break;
1477 }
1478
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001479 if (DependentTemplateId) {
Mike Stump1eb44332009-09-09 15:08:12 +00001480 // FIXME: the location information here isn't great.
1481 Diag(SS.getRange().getBegin(),
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001482 diag::err_template_spec_needs_template_parameters)
John McCall4e2cbb22010-10-20 05:44:58 +00001483 << QualType(TemplateId, 0)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001484 << SS.getRange();
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001485 Invalid = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001486 } else {
1487 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1488 << SS.getRange()
Douglas Gregor849b2432010-03-31 17:46:05 +00001489 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001490 IsExplicitSpecialization = true;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001491 }
1492 return 0;
1493 }
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001495 // Check the template parameter list against its corresponding template-id.
Douglas Gregorb88e8882009-07-30 17:40:51 +00001496 if (DependentTemplateId) {
John McCall31f17ec2010-04-27 00:57:59 +00001497 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00001498
John McCall31f17ec2010-04-27 00:57:59 +00001499 // Are there cases in (e.g.) friends where this won't match?
1500 if (const InjectedClassNameType *Injected
1501 = TemplateId->getAs<InjectedClassNameType>()) {
1502 CXXRecordDecl *Record = Injected->getDecl();
1503 if (ClassTemplatePartialSpecializationDecl *Partial =
1504 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1505 ExpectedTemplateParams = Partial->getTemplateParameters();
1506 else
1507 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1508 ->getTemplateParameters();
Mike Stump1eb44332009-09-09 15:08:12 +00001509 }
Douglas Gregor5b6d70e2009-11-25 17:50:39 +00001510
John McCall31f17ec2010-04-27 00:57:59 +00001511 if (ExpectedTemplateParams)
John McCall4e2cbb22010-10-20 05:44:58 +00001512 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
John McCall31f17ec2010-04-27 00:57:59 +00001513 ExpectedTemplateParams,
1514 true, TPL_TemplateMatch);
1515
John McCall4e2cbb22010-10-20 05:44:58 +00001516 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1517 TPC_ClassTemplateMember);
1518 } else if (ParamLists[ParamIdx]->size() > 0)
1519 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregorb88e8882009-07-30 17:40:51 +00001520 diag::err_template_param_list_matches_nontemplate)
1521 << TemplateId
John McCall4e2cbb22010-10-20 05:44:58 +00001522 << ParamLists[ParamIdx]->getSourceRange();
Douglas Gregor1fef4e62009-10-07 22:35:40 +00001523 else
1524 IsExplicitSpecialization = true;
John McCall4e2cbb22010-10-20 05:44:58 +00001525
1526 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001527 }
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001529 // If there were at least as many template-ids as there were template
1530 // parameter lists, then there are no template parameter lists remaining for
1531 // the declaration itself.
John McCall4e2cbb22010-10-20 05:44:58 +00001532 if (ParamIdx >= NumParamLists)
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001533 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001535 // If there were too many template parameter lists, complain about that now.
John McCall4e2cbb22010-10-20 05:44:58 +00001536 if (ParamIdx != NumParamLists - 1) {
1537 while (ParamIdx < NumParamLists - 1) {
1538 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1539 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001540 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1541 : diag::err_template_spec_extra_headers)
John McCall4e2cbb22010-10-20 05:44:58 +00001542 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1543 ParamLists[ParamIdx]->getRAngleLoc());
Douglas Gregor3ebd7532009-11-23 12:11:45 +00001544
1545 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1546 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1547 diag::note_explicit_template_spec_does_not_need_header)
1548 << ExplicitSpecializationsInSpecifier.back();
1549 ExplicitSpecializationsInSpecifier.pop_back();
1550 }
Douglas Gregor0167f3c2010-07-14 23:14:12 +00001551
1552 // We have a template parameter list with no corresponding scope, which
1553 // means that the resulting template declaration can't be instantiated
1554 // properly (we'll end up with dependent nodes when we shouldn't).
1555 if (!isExplicitSpecHeader)
1556 Invalid = true;
1557
John McCall4e2cbb22010-10-20 05:44:58 +00001558 ++ParamIdx;
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001559 }
1560 }
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Douglas Gregorf59a56e2009-07-21 23:53:31 +00001562 // Return the last template parameter list, which corresponds to the
1563 // entity being declared.
1564 return ParamLists[NumParamLists - 1];
1565}
1566
Douglas Gregor7532dc62009-03-30 22:58:21 +00001567QualType Sema::CheckTemplateIdType(TemplateName Name,
1568 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00001569 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001570 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorc45c2322009-03-31 00:43:58 +00001571 if (!Template) {
1572 // The template name does not resolve to a template, so we just
1573 // build a dependent template-id type.
John McCalld5532b62009-11-23 01:53:49 +00001574 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorc45c2322009-03-31 00:43:58 +00001575 }
Douglas Gregor7532dc62009-03-30 22:58:21 +00001576
Douglas Gregor40808ce2009-03-09 23:48:35 +00001577 // Check that the template argument list is well-formed for this
1578 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001579 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00001580 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00001581 false, Converted))
Douglas Gregor40808ce2009-03-09 23:48:35 +00001582 return QualType();
1583
Douglas Gregor910f8002010-11-07 23:05:16 +00001584 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
Douglas Gregor40808ce2009-03-09 23:48:35 +00001585 "Converted template argument list is too short!");
1586
1587 QualType CanonType;
1588
Douglas Gregorcaddba02009-11-12 18:38:13 +00001589 if (Name.isDependent() ||
1590 TemplateSpecializationType::anyDependentTemplateArguments(
John McCalld5532b62009-11-23 01:53:49 +00001591 TemplateArgs)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001592 // This class template specialization is a dependent
1593 // type. Therefore, its canonical type is another class template
1594 // specialization type that contains all of the converted
1595 // arguments in canonical form. This ensures that, e.g., A<T> and
1596 // A<T, T> have identical types when A is declared as:
1597 //
1598 // template<typename T, typename U = T> struct A;
Douglas Gregor25a3ef72009-05-07 06:41:52 +00001599 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00001600 CanonType = Context.getTemplateSpecializationType(CanonName,
Douglas Gregor910f8002010-11-07 23:05:16 +00001601 Converted.data(),
1602 Converted.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Douglas Gregor1275ae02009-07-28 23:00:59 +00001604 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall833ca992009-10-29 08:12:44 +00001605 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregor1275ae02009-07-28 23:00:59 +00001606 // In the future, we need to teach getTemplateSpecializationType to only
1607 // build the canonical type and return that to us.
1608 CanonType = Context.getCanonicalType(CanonType);
John McCall31f17ec2010-04-27 00:57:59 +00001609
1610 // This might work out to be a current instantiation, in which
1611 // case the canonical type needs to be the InjectedClassNameType.
1612 //
1613 // TODO: in theory this could be a simple hashtable lookup; most
1614 // changes to CurContext don't change the set of current
1615 // instantiations.
1616 if (isa<ClassTemplateDecl>(Template)) {
1617 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1618 // If we get out to a namespace, we're done.
1619 if (Ctx->isFileContext()) break;
1620
1621 // If this isn't a record, keep looking.
1622 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1623 if (!Record) continue;
1624
1625 // Look for one of the two cases with InjectedClassNameTypes
1626 // and check whether it's the same template.
1627 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1628 !Record->getDescribedClassTemplate())
1629 continue;
1630
1631 // Fetch the injected class name type and check whether its
1632 // injected type is equal to the type we just built.
1633 QualType ICNT = Context.getTypeDeclType(Record);
1634 QualType Injected = cast<InjectedClassNameType>(ICNT)
1635 ->getInjectedSpecializationType();
1636
1637 if (CanonType != Injected->getCanonicalTypeInternal())
1638 continue;
1639
1640 // If so, the canonical type of this TST is the injected
1641 // class name type of the record we just found.
1642 assert(ICNT.isCanonical());
1643 CanonType = ICNT;
John McCall31f17ec2010-04-27 00:57:59 +00001644 break;
1645 }
1646 }
Mike Stump1eb44332009-09-09 15:08:12 +00001647 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregor7532dc62009-03-30 22:58:21 +00001648 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00001649 // Find the class template specialization declaration that
1650 // corresponds to these arguments.
Douglas Gregor40808ce2009-03-09 23:48:35 +00001651 void *InsertPos = 0;
1652 ClassTemplateSpecializationDecl *Decl
Douglas Gregor910f8002010-11-07 23:05:16 +00001653 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1654 InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001655 if (!Decl) {
1656 // This is the first time we have referenced this class template
1657 // specialization. Create the canonical declaration and add it to
1658 // the set of specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00001659 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00001660 ClassTemplate->getTemplatedDecl()->getTagKind(),
1661 ClassTemplate->getDeclContext(),
1662 ClassTemplate->getLocation(),
Douglas Gregor910f8002010-11-07 23:05:16 +00001663 ClassTemplate,
1664 Converted.data(),
1665 Converted.size(), 0);
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001666 ClassTemplate->AddSpecialization(Decl, InsertPos);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001667 Decl->setLexicalDeclContext(CurContext);
1668 }
1669
1670 CanonType = Context.getTypeDeclType(Decl);
John McCall3cb0ebd2010-03-10 03:28:59 +00001671 assert(isa<RecordType>(CanonType) &&
1672 "type of non-dependent specialization is not a RecordType");
Douglas Gregor40808ce2009-03-09 23:48:35 +00001673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Douglas Gregor40808ce2009-03-09 23:48:35 +00001675 // Build the fully-sugared type for this class template
1676 // specialization, which refers back to the class template
1677 // specialization we created or found.
John McCall71d74bc2010-06-13 09:25:03 +00001678 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001679}
1680
John McCallf312b1e2010-08-26 23:41:50 +00001681TypeResult
Douglas Gregor7532dc62009-03-30 22:58:21 +00001682Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001683 SourceLocation LAngleLoc,
Douglas Gregor7532dc62009-03-30 22:58:21 +00001684 ASTTemplateArgsPtr TemplateArgsIn,
John McCall6b2becf2009-09-08 17:47:29 +00001685 SourceLocation RAngleLoc) {
Douglas Gregor7532dc62009-03-30 22:58:21 +00001686 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor55f6b142009-02-09 18:46:07 +00001687
Douglas Gregor40808ce2009-03-09 23:48:35 +00001688 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00001689 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00001690 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001691
John McCalld5532b62009-11-23 01:53:49 +00001692 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00001693 TemplateArgsIn.release();
Douglas Gregor31a19b62009-04-01 21:51:26 +00001694
1695 if (Result.isNull())
1696 return true;
1697
John McCalla93c9342009-12-07 02:54:59 +00001698 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall833ca992009-10-29 08:12:44 +00001699 TemplateSpecializationTypeLoc TL
1700 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1701 TL.setTemplateNameLoc(TemplateLoc);
1702 TL.setLAngleLoc(LAngleLoc);
1703 TL.setRAngleLoc(RAngleLoc);
1704 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1705 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1706
John McCallb3d87482010-08-24 05:47:05 +00001707 return CreateParsedType(Result, DI);
John McCall6b2becf2009-09-08 17:47:29 +00001708}
John McCallf1bbbb42009-09-04 01:14:41 +00001709
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001710TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1711 TypeResult TypeResult,
John McCallf312b1e2010-08-26 23:41:50 +00001712 TagUseKind TUK,
1713 TypeSpecifierType TagSpec,
1714 SourceLocation TagLoc) {
John McCall6b2becf2009-09-08 17:47:29 +00001715 if (TypeResult.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00001716 return ::TypeResult();
John McCallf1bbbb42009-09-04 01:14:41 +00001717
John McCalla93c9342009-12-07 02:54:59 +00001718 TypeSourceInfo *DI;
John McCall833ca992009-10-29 08:12:44 +00001719 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCallf1bbbb42009-09-04 01:14:41 +00001720
John McCall6b2becf2009-09-08 17:47:29 +00001721 // Verify the tag specifier.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001722 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump1eb44332009-09-09 15:08:12 +00001723
John McCall6b2becf2009-09-08 17:47:29 +00001724 if (const RecordType *RT = Type->getAs<RecordType>()) {
1725 RecordDecl *D = RT->getDecl();
1726
1727 IdentifierInfo *Id = D->getIdentifier();
1728 assert(Id && "templated class must have an identifier");
1729
1730 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1731 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCallc4e70192009-09-11 04:59:25 +00001732 << Type
Douglas Gregor849b2432010-03-31 17:46:05 +00001733 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCallc4e70192009-09-11 04:59:25 +00001734 Diag(D->getLocation(), diag::note_previous_use);
John McCallf1bbbb42009-09-04 01:14:41 +00001735 }
1736 }
1737
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001738 ElaboratedTypeKeyword Keyword
1739 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1740 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCall6b2becf2009-09-08 17:47:29 +00001741
Craig Silverstein45ab4b52010-11-18 08:32:02 +00001742 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1743 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1744 TL.setKeywordLoc(TagLoc);
1745 TL.setQualifierRange(SS.getRange());
1746 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1747 return CreateParsedType(ElabType, ElabDI);
Douglas Gregor55f6b142009-02-09 18:46:07 +00001748}
1749
John McCall60d7b3a2010-08-24 06:29:42 +00001750ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
John McCallf7a1a742009-11-24 19:00:30 +00001751 LookupResult &R,
1752 bool RequiresADL,
John McCalld5532b62009-11-23 01:53:49 +00001753 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001754 // FIXME: Can we do any checking at this point? I guess we could check the
1755 // template arguments that we have against the template name, if the template
Mike Stump1eb44332009-09-09 15:08:12 +00001756 // name refers to a single template. That's not a terribly common case,
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001757 // though.
John McCallf7a1a742009-11-24 19:00:30 +00001758
1759 // These should be filtered out by our callers.
1760 assert(!R.empty() && "empty lookup results when building templateid");
1761 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1762
1763 NestedNameSpecifier *Qualifier = 0;
1764 SourceRange QualifierRange;
1765 if (SS.isSet()) {
1766 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1767 QualifierRange = SS.getRange();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001768 }
John McCallc373d482010-01-27 01:50:18 +00001769
1770 // We don't want lookup warnings at this point.
1771 R.suppressDiagnostics();
Douglas Gregora9e29aa2009-10-22 07:19:14 +00001772
John McCallf7a1a742009-11-24 19:00:30 +00001773 UnresolvedLookupExpr *ULE
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00001774 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001775 Qualifier, QualifierRange,
Abramo Bagnara25777432010-08-11 22:01:17 +00001776 R.getLookupNameInfo(),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00001777 RequiresADL, TemplateArgs,
1778 R.begin(), R.end());
John McCallf7a1a742009-11-24 19:00:30 +00001779
1780 return Owned(ULE);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001781}
1782
John McCallf7a1a742009-11-24 19:00:30 +00001783// We actually only call this from template instantiation.
John McCall60d7b3a2010-08-24 06:29:42 +00001784ExprResult
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00001785Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
Abramo Bagnara25777432010-08-11 22:01:17 +00001786 const DeclarationNameInfo &NameInfo,
John McCallf7a1a742009-11-24 19:00:30 +00001787 const TemplateArgumentListInfo &TemplateArgs) {
1788 DeclContext *DC;
1789 if (!(DC = computeDeclContext(SS, false)) ||
1790 DC->isDependentContext() ||
John McCall77bb1aa2010-05-01 00:40:08 +00001791 RequireCompleteDeclContext(SS, DC))
Abramo Bagnara25777432010-08-11 22:01:17 +00001792 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001793
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001794 bool MemberOfUnknownSpecialization;
Abramo Bagnara25777432010-08-11 22:01:17 +00001795 LookupResult R(*this, NameInfo, LookupOrdinaryName);
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001796 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1797 MemberOfUnknownSpecialization);
Mike Stump1eb44332009-09-09 15:08:12 +00001798
John McCallf7a1a742009-11-24 19:00:30 +00001799 if (R.isAmbiguous())
1800 return ExprError();
1801
1802 if (R.empty()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001803 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1804 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001805 return ExprError();
1806 }
1807
1808 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
Abramo Bagnara25777432010-08-11 22:01:17 +00001809 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1810 << (NestedNameSpecifier*) SS.getScopeRep()
1811 << NameInfo.getName() << SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001812 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1813 return ExprError();
1814 }
1815
1816 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00001817}
1818
Douglas Gregorc45c2322009-03-31 00:43:58 +00001819/// \brief Form a dependent template name.
1820///
1821/// This action forms a dependent template name given the template
1822/// name and its (presumably dependent) scope specifier. For
1823/// example, given "MetaFun::template apply", the scope specifier \p
1824/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1825/// of the "template" keyword, and "apply" is the \p Name.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001826TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1827 SourceLocation TemplateKWLoc,
1828 CXXScopeSpec &SS,
1829 UnqualifiedId &Name,
John McCallb3d87482010-08-24 05:47:05 +00001830 ParsedType ObjectType,
Douglas Gregord6ab2322010-06-16 23:00:59 +00001831 bool EnteringContext,
1832 TemplateTy &Result) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00001833 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1834 !getLangOptions().CPlusPlus0x)
1835 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1836 << FixItHint::CreateRemoval(TemplateKWLoc);
1837
Douglas Gregor0707bc52010-01-19 16:01:07 +00001838 DeclContext *LookupCtx = 0;
1839 if (SS.isSet())
1840 LookupCtx = computeDeclContext(SS, EnteringContext);
1841 if (!LookupCtx && ObjectType)
John McCallb3d87482010-08-24 05:47:05 +00001842 LookupCtx = computeDeclContext(ObjectType.get());
Douglas Gregor0707bc52010-01-19 16:01:07 +00001843 if (LookupCtx) {
Douglas Gregorc45c2322009-03-31 00:43:58 +00001844 // C++0x [temp.names]p5:
1845 // If a name prefixed by the keyword template is not the name of
1846 // a template, the program is ill-formed. [Note: the keyword
1847 // template may not be applied to non-template members of class
1848 // templates. -end note ] [ Note: as is the case with the
1849 // typename prefix, the template prefix is allowed in cases
1850 // where it is not strictly necessary; i.e., when the
1851 // nested-name-specifier or the expression on the left of the ->
1852 // or . is not dependent on a template-parameter, or the use
1853 // does not appear in the scope of a template. -end note]
1854 //
1855 // Note: C++03 was more strict here, because it banned the use of
1856 // the "template" keyword prior to a template-name that was not a
1857 // dependent name. C++ DR468 relaxed this requirement (the
1858 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregor732281d2010-06-14 22:07:54 +00001859 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001860 bool MemberOfUnknownSpecialization;
Abramo Bagnara7c153532010-08-06 12:11:11 +00001861 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1862 ObjectType, EnteringContext, Result,
Douglas Gregor1fd6d442010-05-21 23:18:07 +00001863 MemberOfUnknownSpecialization);
Douglas Gregor0707bc52010-01-19 16:01:07 +00001864 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1865 isa<CXXRecordDecl>(LookupCtx) &&
1866 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord6ab2322010-06-16 23:00:59 +00001867 // This is a dependent template. Handle it below.
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001868 } else if (TNK == TNK_Non_template) {
Douglas Gregor014e88d2009-11-03 23:16:33 +00001869 Diag(Name.getSourceRange().getBegin(),
1870 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001871 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001872 << Name.getSourceRange()
1873 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001874 return TNK_Non_template;
Douglas Gregor9edad9b2010-01-14 17:47:39 +00001875 } else {
1876 // We found something; return it.
Douglas Gregord6ab2322010-06-16 23:00:59 +00001877 return TNK;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001878 }
Douglas Gregorc45c2322009-03-31 00:43:58 +00001879 }
1880
Mike Stump1eb44332009-09-09 15:08:12 +00001881 NestedNameSpecifier *Qualifier
Douglas Gregor2dd078a2009-09-02 22:59:36 +00001882 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor014e88d2009-11-03 23:16:33 +00001883
1884 switch (Name.getKind()) {
1885 case UnqualifiedId::IK_Identifier:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001886 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1887 Name.Identifier));
1888 return TNK_Dependent_template_name;
Douglas Gregor014e88d2009-11-03 23:16:33 +00001889
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001890 case UnqualifiedId::IK_OperatorFunctionId:
Douglas Gregord6ab2322010-06-16 23:00:59 +00001891 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
Douglas Gregorca1bdd72009-11-04 00:56:37 +00001892 Name.OperatorFunctionId.Operator));
Douglas Gregord6ab2322010-06-16 23:00:59 +00001893 return TNK_Dependent_template_name;
Sean Hunte6252d12009-11-28 08:58:14 +00001894
1895 case UnqualifiedId::IK_LiteralOperatorId:
1896 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1897
Douglas Gregor014e88d2009-11-03 23:16:33 +00001898 default:
1899 break;
1900 }
1901
1902 Diag(Name.getSourceRange().getBegin(),
1903 diag::err_template_kw_refers_to_non_template)
Abramo Bagnara25777432010-08-11 22:01:17 +00001904 << GetNameFromUnqualifiedId(Name).getName()
Douglas Gregor0278e122010-05-05 05:58:24 +00001905 << Name.getSourceRange()
1906 << TemplateKWLoc;
Douglas Gregord6ab2322010-06-16 23:00:59 +00001907 return TNK_Non_template;
Douglas Gregorc45c2322009-03-31 00:43:58 +00001908}
1909
Mike Stump1eb44332009-09-09 15:08:12 +00001910bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall833ca992009-10-29 08:12:44 +00001911 const TemplateArgumentLoc &AL,
Douglas Gregor910f8002010-11-07 23:05:16 +00001912 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCall833ca992009-10-29 08:12:44 +00001913 const TemplateArgument &Arg = AL.getArgument();
1914
Anders Carlsson436b1562009-06-13 00:33:33 +00001915 // Check template type parameter.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001916 switch(Arg.getKind()) {
1917 case TemplateArgument::Type:
Anders Carlsson436b1562009-06-13 00:33:33 +00001918 // C++ [temp.arg.type]p1:
1919 // A template-argument for a template-parameter which is a
1920 // type shall be a type-id.
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001921 break;
1922 case TemplateArgument::Template: {
1923 // We have a template type parameter but the template argument
1924 // is a template without any arguments.
1925 SourceRange SR = AL.getSourceRange();
1926 TemplateName Name = Arg.getAsTemplate();
1927 Diag(SR.getBegin(), diag::err_template_missing_args)
1928 << Name << SR;
1929 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1930 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlsson436b1562009-06-13 00:33:33 +00001931
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001932 return true;
1933 }
1934 default: {
Anders Carlsson436b1562009-06-13 00:33:33 +00001935 // We have a template type parameter but the template argument
1936 // is not a type.
John McCall828bff22009-10-29 18:45:58 +00001937 SourceRange SR = AL.getSourceRange();
1938 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlsson436b1562009-06-13 00:33:33 +00001939 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00001940
Anders Carlsson436b1562009-06-13 00:33:33 +00001941 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001942 }
Jeffrey Yasskindb88d8a2010-04-08 00:03:06 +00001943 }
Anders Carlsson436b1562009-06-13 00:33:33 +00001944
John McCalla93c9342009-12-07 02:54:59 +00001945 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlsson436b1562009-06-13 00:33:33 +00001946 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001947
Anders Carlsson436b1562009-06-13 00:33:33 +00001948 // Add the converted template type argument.
Douglas Gregor910f8002010-11-07 23:05:16 +00001949 Converted.push_back(
John McCall833ca992009-10-29 08:12:44 +00001950 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlsson436b1562009-06-13 00:33:33 +00001951 return false;
1952}
1953
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001954/// \brief Substitute template arguments into the default template argument for
1955/// the given template type parameter.
1956///
1957/// \param SemaRef the semantic analysis object for which we are performing
1958/// the substitution.
1959///
1960/// \param Template the template that we are synthesizing template arguments
1961/// for.
1962///
1963/// \param TemplateLoc the location of the template name that started the
1964/// template-id we are checking.
1965///
1966/// \param RAngleLoc the location of the right angle bracket ('>') that
1967/// terminates the template-id.
1968///
1969/// \param Param the template template parameter whose default we are
1970/// substituting into.
1971///
1972/// \param Converted the list of template arguments provided for template
1973/// parameters that precede \p Param in the template parameter list.
1974///
1975/// \returns the substituted template argument, or NULL if an error occurred.
John McCalla93c9342009-12-07 02:54:59 +00001976static TypeSourceInfo *
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001977SubstDefaultTemplateArgument(Sema &SemaRef,
1978 TemplateDecl *Template,
1979 SourceLocation TemplateLoc,
1980 SourceLocation RAngleLoc,
1981 TemplateTypeParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00001982 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
John McCalla93c9342009-12-07 02:54:59 +00001983 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001984
1985 // If the argument type is dependent, instantiate it now based
1986 // on the previously-computed template arguments.
1987 if (ArgType->getType()->isDependentType()) {
Douglas Gregor910f8002010-11-07 23:05:16 +00001988 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1989 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001990
1991 MultiLevelTemplateArgumentList AllTemplateArgs
1992 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1993
1994 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00001995 Template, Converted.data(),
1996 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001997 SourceRange(TemplateLoc, RAngleLoc));
1998
1999 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2000 Param->getDefaultArgumentLoc(),
2001 Param->getDeclName());
2002 }
2003
2004 return ArgType;
2005}
2006
2007/// \brief Substitute template arguments into the default template argument for
2008/// the given non-type template parameter.
2009///
2010/// \param SemaRef the semantic analysis object for which we are performing
2011/// the substitution.
2012///
2013/// \param Template the template that we are synthesizing template arguments
2014/// for.
2015///
2016/// \param TemplateLoc the location of the template name that started the
2017/// template-id we are checking.
2018///
2019/// \param RAngleLoc the location of the right angle bracket ('>') that
2020/// terminates the template-id.
2021///
Douglas Gregor788cd062009-11-11 01:00:40 +00002022/// \param Param the non-type template parameter whose default we are
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002023/// substituting into.
2024///
2025/// \param Converted the list of template arguments provided for template
2026/// parameters that precede \p Param in the template parameter list.
2027///
2028/// \returns the substituted template argument, or NULL if an error occurred.
John McCall60d7b3a2010-08-24 06:29:42 +00002029static ExprResult
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002030SubstDefaultTemplateArgument(Sema &SemaRef,
2031 TemplateDecl *Template,
2032 SourceLocation TemplateLoc,
2033 SourceLocation RAngleLoc,
2034 NonTypeTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002035 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2036 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2037 Converted.data(), Converted.size());
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002038
2039 MultiLevelTemplateArgumentList AllTemplateArgs
2040 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2041
2042 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002043 Template, Converted.data(),
2044 Converted.size(),
Douglas Gregor0f8716b2009-11-09 19:17:50 +00002045 SourceRange(TemplateLoc, RAngleLoc));
2046
2047 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2048}
2049
Douglas Gregor788cd062009-11-11 01:00:40 +00002050/// \brief Substitute template arguments into the default template argument for
2051/// the given template template parameter.
2052///
2053/// \param SemaRef the semantic analysis object for which we are performing
2054/// the substitution.
2055///
2056/// \param Template the template that we are synthesizing template arguments
2057/// for.
2058///
2059/// \param TemplateLoc the location of the template name that started the
2060/// template-id we are checking.
2061///
2062/// \param RAngleLoc the location of the right angle bracket ('>') that
2063/// terminates the template-id.
2064///
2065/// \param Param the template template parameter whose default we are
2066/// substituting into.
2067///
2068/// \param Converted the list of template arguments provided for template
2069/// parameters that precede \p Param in the template parameter list.
2070///
2071/// \returns the substituted template argument, or NULL if an error occurred.
2072static TemplateName
2073SubstDefaultTemplateArgument(Sema &SemaRef,
2074 TemplateDecl *Template,
2075 SourceLocation TemplateLoc,
2076 SourceLocation RAngleLoc,
2077 TemplateTemplateParmDecl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002078 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2079 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2080 Converted.data(), Converted.size());
Douglas Gregor788cd062009-11-11 01:00:40 +00002081
2082 MultiLevelTemplateArgumentList AllTemplateArgs
2083 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2084
2085 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002086 Template, Converted.data(),
2087 Converted.size(),
Douglas Gregor788cd062009-11-11 01:00:40 +00002088 SourceRange(TemplateLoc, RAngleLoc));
2089
2090 return SemaRef.SubstTemplateName(
2091 Param->getDefaultArgument().getArgument().getAsTemplate(),
2092 Param->getDefaultArgument().getTemplateNameLoc(),
2093 AllTemplateArgs);
2094}
2095
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002096/// \brief If the given template parameter has a default template
2097/// argument, substitute into that default template argument and
2098/// return the corresponding template argument.
2099TemplateArgumentLoc
2100Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2101 SourceLocation TemplateLoc,
2102 SourceLocation RAngleLoc,
2103 Decl *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002104 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2105 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002106 if (!TypeParm->hasDefaultArgument())
2107 return TemplateArgumentLoc();
2108
John McCalla93c9342009-12-07 02:54:59 +00002109 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002110 TemplateLoc,
2111 RAngleLoc,
2112 TypeParm,
2113 Converted);
2114 if (DI)
2115 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2116
2117 return TemplateArgumentLoc();
2118 }
2119
2120 if (NonTypeTemplateParmDecl *NonTypeParm
2121 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2122 if (!NonTypeParm->hasDefaultArgument())
2123 return TemplateArgumentLoc();
2124
John McCall60d7b3a2010-08-24 06:29:42 +00002125 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor51ffb0c2009-11-25 18:55:14 +00002126 TemplateLoc,
2127 RAngleLoc,
2128 NonTypeParm,
2129 Converted);
2130 if (Arg.isInvalid())
2131 return TemplateArgumentLoc();
2132
2133 Expr *ArgE = Arg.takeAs<Expr>();
2134 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2135 }
2136
2137 TemplateTemplateParmDecl *TempTempParm
2138 = cast<TemplateTemplateParmDecl>(Param);
2139 if (!TempTempParm->hasDefaultArgument())
2140 return TemplateArgumentLoc();
2141
2142 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2143 TemplateLoc,
2144 RAngleLoc,
2145 TempTempParm,
2146 Converted);
2147 if (TName.isNull())
2148 return TemplateArgumentLoc();
2149
2150 return TemplateArgumentLoc(TemplateArgument(TName),
2151 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2152 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2153}
2154
Douglas Gregore7526412009-11-11 19:31:23 +00002155/// \brief Check that the given template argument corresponds to the given
2156/// template parameter.
2157bool Sema::CheckTemplateArgument(NamedDecl *Param,
2158 const TemplateArgumentLoc &Arg,
Douglas Gregore7526412009-11-11 19:31:23 +00002159 TemplateDecl *Template,
2160 SourceLocation TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002161 SourceLocation RAngleLoc,
Douglas Gregor910f8002010-11-07 23:05:16 +00002162 llvm::SmallVectorImpl<TemplateArgument> &Converted,
Douglas Gregor02024a92010-03-28 02:42:43 +00002163 CheckTemplateArgumentKind CTAK) {
Douglas Gregord9e15302009-11-11 19:41:09 +00002164 // Check template type parameters.
2165 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregore7526412009-11-11 19:31:23 +00002166 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregore7526412009-11-11 19:31:23 +00002167
Douglas Gregord9e15302009-11-11 19:41:09 +00002168 // Check non-type template parameters.
2169 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregore7526412009-11-11 19:31:23 +00002170 // Do substitution on the type of the non-type template parameter
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002171 // with the template arguments we've seen thus far. But if the
2172 // template has a dependent context then we cannot substitute yet.
Douglas Gregore7526412009-11-11 19:31:23 +00002173 QualType NTTPType = NTTP->getType();
Peter Collingbourne9f6f6a12010-12-10 17:08:53 +00002174 if (NTTPType->isDependentType() &&
2175 !isa<TemplateTemplateParmDecl>(Template) &&
2176 !Template->getDeclContext()->isDependentContext()) {
Douglas Gregore7526412009-11-11 19:31:23 +00002177 // Do substitution on the type of the non-type template parameter.
2178 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002179 NTTP, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002180 SourceRange(TemplateLoc, RAngleLoc));
2181
Douglas Gregor910f8002010-11-07 23:05:16 +00002182 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2183 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002184 NTTPType = SubstType(NTTPType,
2185 MultiLevelTemplateArgumentList(TemplateArgs),
2186 NTTP->getLocation(),
2187 NTTP->getDeclName());
2188 // If that worked, check the non-type template parameter type
2189 // for validity.
2190 if (!NTTPType.isNull())
2191 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2192 NTTP->getLocation());
2193 if (NTTPType.isNull())
2194 return true;
2195 }
2196
2197 switch (Arg.getArgument().getKind()) {
2198 case TemplateArgument::Null:
2199 assert(false && "Should never see a NULL template argument here");
2200 return true;
2201
2202 case TemplateArgument::Expression: {
2203 Expr *E = Arg.getArgument().getAsExpr();
2204 TemplateArgument Result;
Douglas Gregor02024a92010-03-28 02:42:43 +00002205 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregore7526412009-11-11 19:31:23 +00002206 return true;
2207
Douglas Gregor910f8002010-11-07 23:05:16 +00002208 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002209 break;
2210 }
2211
2212 case TemplateArgument::Declaration:
2213 case TemplateArgument::Integral:
2214 // We've already checked this template argument, so just copy
2215 // it to the list of converted arguments.
Douglas Gregor910f8002010-11-07 23:05:16 +00002216 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002217 break;
2218
2219 case TemplateArgument::Template:
2220 // We were given a template template argument. It may not be ill-formed;
2221 // see below.
2222 if (DependentTemplateName *DTN
2223 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2224 // We have a template argument such as \c T::template X, which we
2225 // parsed as a template template argument. However, since we now
2226 // know that we need a non-type template argument, convert this
Abramo Bagnara25777432010-08-11 22:01:17 +00002227 // template name into an expression.
2228
2229 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2230 Arg.getTemplateNameLoc());
2231
John McCallf7a1a742009-11-24 19:00:30 +00002232 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2233 DTN->getQualifier(),
Douglas Gregore7526412009-11-11 19:31:23 +00002234 Arg.getTemplateQualifierRange(),
Abramo Bagnara25777432010-08-11 22:01:17 +00002235 NameInfo);
Douglas Gregore7526412009-11-11 19:31:23 +00002236
2237 TemplateArgument Result;
2238 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2239 return true;
2240
Douglas Gregor910f8002010-11-07 23:05:16 +00002241 Converted.push_back(Result);
Douglas Gregore7526412009-11-11 19:31:23 +00002242 break;
2243 }
2244
2245 // We have a template argument that actually does refer to a class
2246 // template, template alias, or template template parameter, and
2247 // therefore cannot be a non-type template argument.
2248 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2249 << Arg.getSourceRange();
2250
2251 Diag(Param->getLocation(), diag::note_template_param_here);
2252 return true;
2253
2254 case TemplateArgument::Type: {
2255 // We have a non-type template parameter but the template
2256 // argument is a type.
2257
2258 // C++ [temp.arg]p2:
2259 // In a template-argument, an ambiguity between a type-id and
2260 // an expression is resolved to a type-id, regardless of the
2261 // form of the corresponding template-parameter.
2262 //
2263 // We warn specifically about this case, since it can be rather
2264 // confusing for users.
2265 QualType T = Arg.getArgument().getAsType();
2266 SourceRange SR = Arg.getSourceRange();
2267 if (T->isFunctionType())
2268 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2269 else
2270 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2271 Diag(Param->getLocation(), diag::note_template_param_here);
2272 return true;
2273 }
2274
2275 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002276 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002277 break;
2278 }
2279
2280 return false;
2281 }
2282
2283
2284 // Check template template parameters.
2285 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2286
2287 // Substitute into the template parameter list of the template
2288 // template parameter, since previously-supplied template arguments
2289 // may appear within the template template parameter.
2290 {
2291 // Set up a template instantiation context.
2292 LocalInstantiationScope Scope(*this);
2293 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
Douglas Gregor910f8002010-11-07 23:05:16 +00002294 TempParm, Converted.data(), Converted.size(),
Douglas Gregore7526412009-11-11 19:31:23 +00002295 SourceRange(TemplateLoc, RAngleLoc));
2296
Douglas Gregor910f8002010-11-07 23:05:16 +00002297 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2298 Converted.data(), Converted.size());
Douglas Gregore7526412009-11-11 19:31:23 +00002299 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2300 SubstDecl(TempParm, CurContext,
2301 MultiLevelTemplateArgumentList(TemplateArgs)));
2302 if (!TempParm)
2303 return true;
Douglas Gregore7526412009-11-11 19:31:23 +00002304 }
2305
2306 switch (Arg.getArgument().getKind()) {
2307 case TemplateArgument::Null:
2308 assert(false && "Should never see a NULL template argument here");
2309 return true;
2310
2311 case TemplateArgument::Template:
2312 if (CheckTemplateArgument(TempParm, Arg))
2313 return true;
2314
Douglas Gregor910f8002010-11-07 23:05:16 +00002315 Converted.push_back(Arg.getArgument());
Douglas Gregore7526412009-11-11 19:31:23 +00002316 break;
2317
2318 case TemplateArgument::Expression:
2319 case TemplateArgument::Type:
2320 // We have a template template parameter but the template
2321 // argument does not refer to a template.
2322 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2323 return true;
2324
2325 case TemplateArgument::Declaration:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002326 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002327 "Declaration argument with template template parameter");
2328 break;
2329 case TemplateArgument::Integral:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002330 llvm_unreachable(
Douglas Gregore7526412009-11-11 19:31:23 +00002331 "Integral argument with template template parameter");
2332 break;
2333
2334 case TemplateArgument::Pack:
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00002335 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregore7526412009-11-11 19:31:23 +00002336 break;
2337 }
2338
2339 return false;
2340}
2341
Douglas Gregorc15cb382009-02-09 23:23:08 +00002342/// \brief Check that the given template argument list is well-formed
2343/// for specializing the given template.
2344bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2345 SourceLocation TemplateLoc,
John McCalld5532b62009-11-23 01:53:49 +00002346 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregor16134c62009-07-01 00:28:38 +00002347 bool PartialTemplateArgs,
Douglas Gregor910f8002010-11-07 23:05:16 +00002348 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002349 TemplateParameterList *Params = Template->getTemplateParameters();
2350 unsigned NumParams = Params->size();
John McCalld5532b62009-11-23 01:53:49 +00002351 unsigned NumArgs = TemplateArgs.size();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002352 bool Invalid = false;
2353
John McCalld5532b62009-11-23 01:53:49 +00002354 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2355
Mike Stump1eb44332009-09-09 15:08:12 +00002356 bool HasParameterPack =
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002357 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump1eb44332009-09-09 15:08:12 +00002358
Anders Carlsson0ceffb52009-06-13 02:08:00 +00002359 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregor16134c62009-07-01 00:28:38 +00002360 (NumArgs < Params->getMinRequiredArguments() &&
2361 !PartialTemplateArgs)) {
Douglas Gregorc15cb382009-02-09 23:23:08 +00002362 // FIXME: point at either the first arg beyond what we can handle,
2363 // or the '>', depending on whether we have too many or too few
2364 // arguments.
2365 SourceRange Range;
2366 if (NumArgs > NumParams)
Douglas Gregor40808ce2009-03-09 23:48:35 +00002367 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregorc15cb382009-02-09 23:23:08 +00002368 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2369 << (NumArgs > NumParams)
2370 << (isa<ClassTemplateDecl>(Template)? 0 :
2371 isa<FunctionTemplateDecl>(Template)? 1 :
2372 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2373 << Template << Range;
Douglas Gregor62cb18d2009-02-11 18:16:40 +00002374 Diag(Template->getLocation(), diag::note_template_decl_here)
2375 << Params->getSourceRange();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002376 Invalid = true;
2377 }
Mike Stump1eb44332009-09-09 15:08:12 +00002378
2379 // C++ [temp.arg]p1:
Douglas Gregorc15cb382009-02-09 23:23:08 +00002380 // [...] The type and form of each template-argument specified in
2381 // a template-id shall match the type and form specified for the
2382 // corresponding parameter declared by the template in its
2383 // template-parameter-list.
Douglas Gregor14be16b2010-12-20 16:57:52 +00002384 llvm::SmallVector<TemplateArgument, 2> ArgumentPack;
2385 TemplateParameterList::iterator Param = Params->begin(),
2386 ParamEnd = Params->end();
Douglas Gregorc15cb382009-02-09 23:23:08 +00002387 unsigned ArgIdx = 0;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002388 while (Param != ParamEnd) {
Douglas Gregor16134c62009-07-01 00:28:38 +00002389 if (ArgIdx > NumArgs && PartialTemplateArgs)
2390 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002391
Douglas Gregorf35f8282009-11-11 21:54:23 +00002392 if (ArgIdx < NumArgs) {
2393 // Check the template argument we were given.
2394 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2395 TemplateLoc, RAngleLoc, Converted))
2396 return true;
2397
Douglas Gregor14be16b2010-12-20 16:57:52 +00002398 if ((*Param)->isTemplateParameterPack()) {
2399 // The template parameter was a template parameter pack, so take the
2400 // deduced argument and place it on the argument pack. Note that we
2401 // stay on the same template parameter so that we can deduce more
2402 // arguments.
2403 ArgumentPack.push_back(Converted.back());
2404 Converted.pop_back();
2405 } else {
2406 // Move to the next template parameter.
2407 ++Param;
2408 }
2409 ++ArgIdx;
Douglas Gregorf35f8282009-11-11 21:54:23 +00002410 continue;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002411 }
Douglas Gregore7526412009-11-11 19:31:23 +00002412
Douglas Gregor14be16b2010-12-20 16:57:52 +00002413 // If we have a template parameter pack with no more corresponding
2414 // arguments, just break out now and we'll fill in the argument pack below.
2415 if ((*Param)->isTemplateParameterPack())
2416 break;
2417
Douglas Gregorf35f8282009-11-11 21:54:23 +00002418 // We have a default template argument that we will use.
2419 TemplateArgumentLoc Arg;
2420
2421 // Retrieve the default template argument from the template
2422 // parameter. For each kind of template parameter, we substitute the
2423 // template arguments provided thus far and any "outer" template arguments
2424 // (when the template parameter was part of a nested template) into
2425 // the default argument.
2426 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2427 if (!TTP->hasDefaultArgument()) {
2428 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2429 break;
2430 }
2431
John McCalla93c9342009-12-07 02:54:59 +00002432 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002433 Template,
2434 TemplateLoc,
2435 RAngleLoc,
2436 TTP,
2437 Converted);
2438 if (!ArgType)
2439 return true;
2440
2441 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2442 ArgType);
2443 } else if (NonTypeTemplateParmDecl *NTTP
2444 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2445 if (!NTTP->hasDefaultArgument()) {
2446 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2447 break;
2448 }
2449
John McCall60d7b3a2010-08-24 06:29:42 +00002450 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregorf35f8282009-11-11 21:54:23 +00002451 TemplateLoc,
2452 RAngleLoc,
2453 NTTP,
2454 Converted);
2455 if (E.isInvalid())
2456 return true;
2457
2458 Expr *Ex = E.takeAs<Expr>();
2459 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2460 } else {
2461 TemplateTemplateParmDecl *TempParm
2462 = cast<TemplateTemplateParmDecl>(*Param);
2463
2464 if (!TempParm->hasDefaultArgument()) {
2465 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2466 break;
2467 }
2468
2469 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2470 TemplateLoc,
2471 RAngleLoc,
2472 TempParm,
2473 Converted);
2474 if (Name.isNull())
2475 return true;
2476
2477 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2478 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2479 TempParm->getDefaultArgument().getTemplateNameLoc());
2480 }
2481
2482 // Introduce an instantiation record that describes where we are using
2483 // the default template argument.
2484 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
Douglas Gregor910f8002010-11-07 23:05:16 +00002485 Converted.data(), Converted.size(),
Douglas Gregorf35f8282009-11-11 21:54:23 +00002486 SourceRange(TemplateLoc, RAngleLoc));
2487
2488 // Check the default template argument.
Douglas Gregord9e15302009-11-11 19:41:09 +00002489 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregore7526412009-11-11 19:31:23 +00002490 RAngleLoc, Converted))
2491 return true;
Douglas Gregor14be16b2010-12-20 16:57:52 +00002492
2493 // Move to the next template parameter and argument.
2494 ++Param;
2495 ++ArgIdx;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002496 }
Douglas Gregor14be16b2010-12-20 16:57:52 +00002497
2498 // Form argument packs for each of the parameter packs remaining.
2499 while (Param != ParamEnd) {
2500 if ((*Param)->isTemplateParameterPack()) {
2501 // The parameter pack takes the contents of the current argument pack,
2502 // which we built up earlier.
2503 if (ArgumentPack.empty()) {
2504 Converted.push_back(TemplateArgument(0, 0));
2505 } else {
2506 TemplateArgument *PackedArgs
2507 = new (Context) TemplateArgument [ArgumentPack.size()];
2508 std::copy(ArgumentPack.begin(), ArgumentPack.end(), PackedArgs);
2509 Converted.push_back(TemplateArgument(PackedArgs, ArgumentPack.size()));
2510 ArgumentPack.clear();
2511 }
2512 }
2513
2514 ++Param;
2515 }
2516
Douglas Gregorc15cb382009-02-09 23:23:08 +00002517 return Invalid;
2518}
2519
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002520namespace {
2521 class UnnamedLocalNoLinkageFinder
2522 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2523 {
2524 Sema &S;
2525 SourceRange SR;
2526
2527 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2528
2529 public:
2530 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2531
2532 bool Visit(QualType T) {
2533 return inherited::Visit(T.getTypePtr());
2534 }
2535
2536#define TYPE(Class, Parent) \
2537 bool Visit##Class##Type(const Class##Type *);
2538#define ABSTRACT_TYPE(Class, Parent) \
2539 bool Visit##Class##Type(const Class##Type *) { return false; }
2540#define NON_CANONICAL_TYPE(Class, Parent) \
2541 bool Visit##Class##Type(const Class##Type *) { return false; }
2542#include "clang/AST/TypeNodes.def"
2543
2544 bool VisitTagDecl(const TagDecl *Tag);
2545 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2546 };
2547}
2548
2549bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2550 return false;
2551}
2552
2553bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2554 return Visit(T->getElementType());
2555}
2556
2557bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2558 return Visit(T->getPointeeType());
2559}
2560
2561bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2562 const BlockPointerType* T) {
2563 return Visit(T->getPointeeType());
2564}
2565
2566bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2567 const LValueReferenceType* T) {
2568 return Visit(T->getPointeeType());
2569}
2570
2571bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2572 const RValueReferenceType* T) {
2573 return Visit(T->getPointeeType());
2574}
2575
2576bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2577 const MemberPointerType* T) {
2578 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2579}
2580
2581bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2582 const ConstantArrayType* T) {
2583 return Visit(T->getElementType());
2584}
2585
2586bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2587 const IncompleteArrayType* T) {
2588 return Visit(T->getElementType());
2589}
2590
2591bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2592 const VariableArrayType* T) {
2593 return Visit(T->getElementType());
2594}
2595
2596bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2597 const DependentSizedArrayType* T) {
2598 return Visit(T->getElementType());
2599}
2600
2601bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2602 const DependentSizedExtVectorType* T) {
2603 return Visit(T->getElementType());
2604}
2605
2606bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2607 return Visit(T->getElementType());
2608}
2609
2610bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2611 return Visit(T->getElementType());
2612}
2613
2614bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2615 const FunctionProtoType* T) {
2616 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2617 AEnd = T->arg_type_end();
2618 A != AEnd; ++A) {
2619 if (Visit(*A))
2620 return true;
2621 }
2622
2623 return Visit(T->getResultType());
2624}
2625
2626bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2627 const FunctionNoProtoType* T) {
2628 return Visit(T->getResultType());
2629}
2630
2631bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2632 const UnresolvedUsingType*) {
2633 return false;
2634}
2635
2636bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2637 return false;
2638}
2639
2640bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2641 return Visit(T->getUnderlyingType());
2642}
2643
2644bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2645 return false;
2646}
2647
2648bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2649 return VisitTagDecl(T->getDecl());
2650}
2651
2652bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2653 return VisitTagDecl(T->getDecl());
2654}
2655
2656bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2657 const TemplateTypeParmType*) {
2658 return false;
2659}
2660
2661bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2662 const TemplateSpecializationType*) {
2663 return false;
2664}
2665
2666bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2667 const InjectedClassNameType* T) {
2668 return VisitTagDecl(T->getDecl());
2669}
2670
2671bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2672 const DependentNameType* T) {
2673 return VisitNestedNameSpecifier(T->getQualifier());
2674}
2675
2676bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2677 const DependentTemplateSpecializationType* T) {
2678 return VisitNestedNameSpecifier(T->getQualifier());
2679}
2680
Douglas Gregor7536dd52010-12-20 02:24:11 +00002681bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
2682 const PackExpansionType* T) {
2683 return Visit(T->getPattern());
2684}
2685
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002686bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2687 return false;
2688}
2689
2690bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2691 const ObjCInterfaceType *) {
2692 return false;
2693}
2694
2695bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2696 const ObjCObjectPointerType *) {
2697 return false;
2698}
2699
2700bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2701 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2702 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2703 << S.Context.getTypeDeclType(Tag) << SR;
2704 return true;
2705 }
2706
2707 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2708 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2709 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2710 return true;
2711 }
2712
2713 return false;
2714}
2715
2716bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2717 NestedNameSpecifier *NNS) {
2718 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2719 return true;
2720
2721 switch (NNS->getKind()) {
2722 case NestedNameSpecifier::Identifier:
2723 case NestedNameSpecifier::Namespace:
2724 case NestedNameSpecifier::Global:
2725 return false;
2726
2727 case NestedNameSpecifier::TypeSpec:
2728 case NestedNameSpecifier::TypeSpecWithTemplate:
2729 return Visit(QualType(NNS->getAsType(), 0));
2730 }
Fariborz Jahanian7b1ec6c2010-10-13 16:19:16 +00002731 return false;
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002732}
2733
2734
Douglas Gregorc15cb382009-02-09 23:23:08 +00002735/// \brief Check a template argument against its corresponding
2736/// template type parameter.
2737///
2738/// This routine implements the semantics of C++ [temp.arg.type]. It
2739/// returns true if an error occurred, and false otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002740bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCalla93c9342009-12-07 02:54:59 +00002741 TypeSourceInfo *ArgInfo) {
2742 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall833ca992009-10-29 08:12:44 +00002743 QualType Arg = ArgInfo->getType();
Douglas Gregor0fddb972010-05-22 16:17:30 +00002744 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Chandler Carruth17fb8552010-09-03 21:12:34 +00002745
2746 if (Arg->isVariablyModifiedType()) {
2747 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
Douglas Gregor4b52e252009-12-21 23:17:24 +00002748 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00002749 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregorc15cb382009-02-09 23:23:08 +00002750 }
2751
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002752 // C++03 [temp.arg.type]p2:
2753 // A local type, a type with no linkage, an unnamed type or a type
2754 // compounded from any of these types shall not be used as a
2755 // template-argument for a template type-parameter.
2756 //
2757 // C++0x allows these, and even in C++03 we allow them as an extension with
2758 // a warning.
Douglas Gregordb4d4bb2010-10-13 18:05:20 +00002759 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00002760 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2761 (void)Finder.Visit(Context.getCanonicalType(Arg));
2762 }
2763
Douglas Gregorc15cb382009-02-09 23:23:08 +00002764 return false;
2765}
2766
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002767/// \brief Checks whether the given template argument is the address
2768/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002769static bool
2770CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2771 NonTypeTemplateParmDecl *Param,
2772 QualType ParamType,
2773 Expr *ArgIn,
2774 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002775 bool Invalid = false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002776 Expr *Arg = ArgIn;
2777 QualType ArgType = Arg->getType();
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002778
2779 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00002780 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002781 Arg = Cast->getSubExpr();
2782
2783 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00002784 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002785 // A template-argument for a non-type, non-template
2786 // template-parameter shall be one of: [...]
2787 //
2788 // -- the address of an object or function with external
2789 // linkage, including function templates and function
2790 // template-ids but excluding non-static class members,
2791 // expressed as & id-expression where the & is optional if
2792 // the name refers to a function or array, or if the
2793 // corresponding template-parameter is a reference; or
2794 DeclRefExpr *DRE = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002795
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002796 // In C++98/03 mode, give an extension warning on any extra parentheses.
2797 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2798 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002799 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002800 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002801 S.Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002802 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002803 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00002804 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002805 }
2806
2807 Arg = Parens->getSubExpr();
2808 }
2809
Douglas Gregorb7a09262010-04-01 18:32:35 +00002810 bool AddressTaken = false;
2811 SourceLocation AddrOpLoc;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002812 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00002813 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002814 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb7a09262010-04-01 18:32:35 +00002815 AddressTaken = true;
2816 AddrOpLoc = UnOp->getOperatorLoc();
2817 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002818 } else
2819 DRE = dyn_cast<DeclRefExpr>(Arg);
2820
Douglas Gregorb7a09262010-04-01 18:32:35 +00002821 if (!DRE) {
Douglas Gregor1a8cf732010-04-14 23:11:21 +00002822 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2823 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002824 S.Diag(Param->getLocation(), diag::note_template_param_here);
2825 return true;
2826 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002827
2828 // Stop checking the precise nature of the argument if it is value dependent,
2829 // it should be checked when instantiated.
Douglas Gregorb7a09262010-04-01 18:32:35 +00002830 if (Arg->isValueDependent()) {
John McCall3fa5cae2010-10-26 07:05:15 +00002831 Converted = TemplateArgument(ArgIn);
Chandler Carruth038cc392010-01-31 10:01:20 +00002832 return false;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002833 }
Chandler Carruth038cc392010-01-31 10:01:20 +00002834
Douglas Gregorb7a09262010-04-01 18:32:35 +00002835 if (!isa<ValueDecl>(DRE->getDecl())) {
2836 S.Diag(Arg->getSourceRange().getBegin(),
2837 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002838 << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002839 S.Diag(Param->getLocation(), diag::note_template_param_here);
2840 return true;
2841 }
2842
2843 NamedDecl *Entity = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002844
2845 // Cannot refer to non-static data members
Douglas Gregorb7a09262010-04-01 18:32:35 +00002846 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2847 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002848 << Field << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002849 S.Diag(Param->getLocation(), diag::note_template_param_here);
2850 return true;
2851 }
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002852
2853 // Cannot refer to non-static member functions
2854 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb7a09262010-04-01 18:32:35 +00002855 if (!Method->isStatic()) {
2856 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002857 << Method << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002858 S.Diag(Param->getLocation(), diag::note_template_param_here);
2859 return true;
2860 }
Mike Stump1eb44332009-09-09 15:08:12 +00002861
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002862 // Functions must have external linkage.
2863 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002864 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002865 S.Diag(Arg->getSourceRange().getBegin(),
2866 diag::err_template_arg_function_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002867 << Func << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002868 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002869 << true;
2870 return true;
2871 }
2872
2873 // Okay: we've named a function with external linkage.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002874 Entity = Func;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002875
Douglas Gregorb7a09262010-04-01 18:32:35 +00002876 // If the template parameter has pointer type, the function decays.
2877 if (ParamType->isPointerType() && !AddressTaken)
2878 ArgType = S.Context.getPointerType(Func->getType());
2879 else if (AddressTaken && ParamType->isReferenceType()) {
2880 // If we originally had an address-of operator, but the
2881 // parameter has reference type, complain and (if things look
2882 // like they will work) drop the address-of operator.
2883 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2884 ParamType.getNonReferenceType())) {
2885 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2886 << ParamType;
2887 S.Diag(Param->getLocation(), diag::note_template_param_here);
2888 return true;
2889 }
2890
2891 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2892 << ParamType
2893 << FixItHint::CreateRemoval(AddrOpLoc);
2894 S.Diag(Param->getLocation(), diag::note_template_param_here);
2895
2896 ArgType = Func->getType();
2897 }
2898 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor0b6bc8b2010-02-03 09:33:45 +00002899 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00002900 S.Diag(Arg->getSourceRange().getBegin(),
2901 diag::err_template_arg_object_not_extern)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002902 << Var << Arg->getSourceRange();
Douglas Gregorb7a09262010-04-01 18:32:35 +00002903 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002904 << true;
2905 return true;
2906 }
2907
Douglas Gregorb7a09262010-04-01 18:32:35 +00002908 // A value of reference type is not an object.
2909 if (Var->getType()->isReferenceType()) {
2910 S.Diag(Arg->getSourceRange().getBegin(),
2911 diag::err_template_arg_reference_var)
2912 << Var->getType() << Arg->getSourceRange();
2913 S.Diag(Param->getLocation(), diag::note_template_param_here);
2914 return true;
2915 }
2916
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002917 // Okay: we've named an object with external linkage
Douglas Gregor3e00bad2009-02-17 01:05:43 +00002918 Entity = Var;
Douglas Gregorb7a09262010-04-01 18:32:35 +00002919
2920 // If the template parameter has pointer type, we must have taken
2921 // the address of this object.
2922 if (ParamType->isReferenceType()) {
2923 if (AddressTaken) {
2924 // If we originally had an address-of operator, but the
2925 // parameter has reference type, complain and (if things look
2926 // like they will work) drop the address-of operator.
2927 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2928 ParamType.getNonReferenceType())) {
2929 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2930 << ParamType;
2931 S.Diag(Param->getLocation(), diag::note_template_param_here);
2932 return true;
2933 }
2934
2935 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2936 << ParamType
2937 << FixItHint::CreateRemoval(AddrOpLoc);
2938 S.Diag(Param->getLocation(), diag::note_template_param_here);
2939
2940 ArgType = Var->getType();
2941 }
2942 } else if (!AddressTaken && ParamType->isPointerType()) {
2943 if (Var->getType()->isArrayType()) {
2944 // Array-to-pointer decay.
2945 ArgType = S.Context.getArrayDecayedType(Var->getType());
2946 } else {
2947 // If the template parameter has pointer type but the address of
2948 // this object was not taken, complain and (possibly) recover by
2949 // taking the address of the entity.
2950 ArgType = S.Context.getPointerType(Var->getType());
2951 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2952 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2953 << ParamType;
2954 S.Diag(Param->getLocation(), diag::note_template_param_here);
2955 return true;
2956 }
2957
2958 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2959 << ParamType
2960 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2961
2962 S.Diag(Param->getLocation(), diag::note_template_param_here);
2963 }
2964 }
2965 } else {
2966 // We found something else, but we don't know specifically what it is.
2967 S.Diag(Arg->getSourceRange().getBegin(),
2968 diag::err_template_arg_not_object_or_func)
2969 << Arg->getSourceRange();
2970 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2971 return true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00002972 }
Mike Stump1eb44332009-09-09 15:08:12 +00002973
Douglas Gregorb7a09262010-04-01 18:32:35 +00002974 if (ParamType->isPointerType() &&
2975 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2976 S.IsQualificationConversion(ArgType, ParamType)) {
2977 // For pointer-to-object types, qualification conversions are
2978 // permitted.
2979 } else {
2980 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2981 if (!ParamRef->getPointeeType()->isFunctionType()) {
2982 // C++ [temp.arg.nontype]p5b3:
2983 // For a non-type template-parameter of type reference to
2984 // object, no conversions apply. The type referred to by the
2985 // reference may be more cv-qualified than the (otherwise
2986 // identical) type of the template- argument. The
2987 // template-parameter is bound directly to the
2988 // template-argument, which shall be an lvalue.
2989
2990 // FIXME: Other qualifiers?
2991 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2992 unsigned ArgQuals = ArgType.getCVRQualifiers();
2993
2994 if ((ParamQuals | ArgQuals) != ParamQuals) {
2995 S.Diag(Arg->getSourceRange().getBegin(),
2996 diag::err_template_arg_ref_bind_ignores_quals)
2997 << ParamType << Arg->getType()
2998 << Arg->getSourceRange();
2999 S.Diag(Param->getLocation(), diag::note_template_param_here);
3000 return true;
3001 }
3002 }
3003 }
3004
3005 // At this point, the template argument refers to an object or
3006 // function with external linkage. We now need to check whether the
3007 // argument and parameter types are compatible.
3008 if (!S.Context.hasSameUnqualifiedType(ArgType,
3009 ParamType.getNonReferenceType())) {
3010 // We can't perform this conversion or binding.
3011 if (ParamType->isReferenceType())
3012 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3013 << ParamType << Arg->getType() << Arg->getSourceRange();
3014 else
3015 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3016 << Arg->getType() << ParamType << Arg->getSourceRange();
3017 S.Diag(Param->getLocation(), diag::note_template_param_here);
3018 return true;
3019 }
3020 }
3021
3022 // Create the template argument.
3023 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor77c13e02010-04-24 18:20:53 +00003024 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb7a09262010-04-01 18:32:35 +00003025 return false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003026}
3027
3028/// \brief Checks whether the given template argument is a pointer to
3029/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003030bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
3031 TemplateArgument &Converted) {
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003032 bool Invalid = false;
3033
3034 // See through any implicit casts we added to fix the type.
Eli Friedman73c39ab2009-10-20 08:27:19 +00003035 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003036 Arg = Cast->getSubExpr();
3037
3038 // C++ [temp.arg.nontype]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00003039 //
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003040 // A template-argument for a non-type, non-template
3041 // template-parameter shall be one of: [...]
3042 //
3043 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregora2813ce2009-10-23 18:54:35 +00003044 DeclRefExpr *DRE = 0;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003045
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003046 // In C++98/03 mode, give an extension warning on any extra parentheses.
3047 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3048 bool ExtraParens = false;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003049 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003050 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
Mike Stump1eb44332009-09-09 15:08:12 +00003051 Diag(Arg->getSourceRange().getBegin(),
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003052 diag::ext_template_arg_extra_parens)
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003053 << Arg->getSourceRange();
Abramo Bagnara2c5399f2010-09-13 06:06:58 +00003054 ExtraParens = true;
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003055 }
3056
3057 Arg = Parens->getSubExpr();
3058 }
3059
Douglas Gregorcaddba02009-11-12 18:38:13 +00003060 // A pointer-to-member constant written &Class::member.
3061 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
John McCall2de56d12010-08-25 11:45:40 +00003062 if (UnOp->getOpcode() == UO_AddrOf) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00003063 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3064 if (DRE && !DRE->getQualifier())
3065 DRE = 0;
3066 }
Douglas Gregorcaddba02009-11-12 18:38:13 +00003067 }
3068 // A constant of pointer-to-member type.
3069 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3070 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3071 if (VD->getType()->isMemberPointerType()) {
3072 if (isa<NonTypeTemplateParmDecl>(VD) ||
3073 (isa<VarDecl>(VD) &&
3074 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3075 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003076 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003077 else
3078 Converted = TemplateArgument(VD->getCanonicalDecl());
3079 return Invalid;
3080 }
3081 }
3082 }
3083
3084 DRE = 0;
3085 }
3086
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003087 if (!DRE)
3088 return Diag(Arg->getSourceRange().getBegin(),
3089 diag::err_template_arg_not_pointer_to_member_form)
3090 << Arg->getSourceRange();
3091
3092 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3093 assert((isa<FieldDecl>(DRE->getDecl()) ||
3094 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3095 "Only non-static member pointers can make it here");
3096
3097 // Okay: this is the address of a non-static member, and therefore
3098 // a member pointer constant.
Douglas Gregorcaddba02009-11-12 18:38:13 +00003099 if (Arg->isTypeDependent() || Arg->isValueDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00003100 Converted = TemplateArgument(Arg);
Douglas Gregorcaddba02009-11-12 18:38:13 +00003101 else
3102 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003103 return Invalid;
3104 }
3105
3106 // We found something else, but we don't know specifically what it is.
Mike Stump1eb44332009-09-09 15:08:12 +00003107 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003108 diag::err_template_arg_not_pointer_to_member_form)
3109 << Arg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003110 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorcc45cb32009-02-11 19:52:55 +00003111 diag::note_template_arg_refers_here);
3112 return true;
3113}
3114
Douglas Gregorc15cb382009-02-09 23:23:08 +00003115/// \brief Check a template argument against its corresponding
3116/// non-type template parameter.
3117///
Douglas Gregor2943aed2009-03-03 04:44:36 +00003118/// This routine implements the semantics of C++ [temp.arg.nontype].
3119/// It returns true if an error occurred, and false otherwise. \p
3120/// InstantiatedParamType is the type of the non-type template
3121/// parameter after it has been instantiated.
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003122///
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003123/// If no error was detected, Converted receives the converted template argument.
Douglas Gregorc15cb382009-02-09 23:23:08 +00003124bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump1eb44332009-09-09 15:08:12 +00003125 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregor02024a92010-03-28 02:42:43 +00003126 TemplateArgument &Converted,
3127 CheckTemplateArgumentKind CTAK) {
Douglas Gregor40808ce2009-03-09 23:48:35 +00003128 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3129
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003130 // If either the parameter has a dependent type or the argument is
3131 // type-dependent, there's nothing we can check now.
Douglas Gregor40808ce2009-03-09 23:48:35 +00003132 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3133 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003134 Converted = TemplateArgument(Arg);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003135 return false;
Douglas Gregor40808ce2009-03-09 23:48:35 +00003136 }
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003137
3138 // C++ [temp.arg.nontype]p5:
3139 // The following conversions are performed on each expression used
3140 // as a non-type template-argument. If a non-type
3141 // template-argument cannot be converted to the type of the
3142 // corresponding template-parameter then the program is
3143 // ill-formed.
3144 //
3145 // -- for a non-type template-parameter of integral or
3146 // enumeration type, integral promotions (4.5) and integral
3147 // conversions (4.7) are applied.
Douglas Gregor2943aed2009-03-03 04:44:36 +00003148 QualType ParamType = InstantiatedParamType;
Douglas Gregora35284b2009-02-11 00:19:33 +00003149 QualType ArgType = Arg->getType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003150 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003151 // C++ [temp.arg.nontype]p1:
3152 // A template-argument for a non-type, non-template
3153 // template-parameter shall be one of:
3154 //
3155 // -- an integral constant-expression of integral or enumeration
3156 // type; or
3157 // -- the name of a non-type template-parameter; or
3158 SourceLocation NonConstantLoc;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003159 llvm::APSInt Value;
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003160 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003161 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003162 diag::err_template_arg_not_integral_or_enumeral)
3163 << ArgType << Arg->getSourceRange();
3164 Diag(Param->getLocation(), diag::note_template_param_here);
3165 return true;
3166 } else if (!Arg->isValueDependent() &&
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003167 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003168 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3169 << ArgType << Arg->getSourceRange();
3170 return true;
3171 }
3172
Douglas Gregor02024a92010-03-28 02:42:43 +00003173 // From here on out, all we care about are the unqualified forms
3174 // of the parameter and argument types.
3175 ParamType = ParamType.getUnqualifiedType();
3176 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003177
3178 // Try to convert the argument to the parameter's type.
Douglas Gregorff524392009-11-04 21:50:46 +00003179 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003180 // Okay: no conversion necessary
Douglas Gregor02024a92010-03-28 02:42:43 +00003181 } else if (CTAK == CTAK_Deduced) {
3182 // C++ [temp.deduct.type]p17:
3183 // If, in the declaration of a function template with a non-type
3184 // template-parameter, the non-type template- parameter is used
3185 // in an expression in the function parameter-list and, if the
3186 // corresponding template-argument is deduced, the
3187 // template-argument type shall match the type of the
3188 // template-parameter exactly, except that a template-argument
3189 // deduced from an array bound may be of any integral type.
3190 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3191 << ArgType << ParamType;
3192 Diag(Param->getLocation(), diag::note_template_param_here);
John McCalldaa8e4e2010-11-15 09:13:47 +00003193 return true;
3194 } else if (ParamType->isBooleanType()) {
3195 // This is an integral-to-boolean conversion.
3196 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003197 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3198 !ParamType->isEnumeralType()) {
3199 // This is an integral promotion or conversion.
John McCall2de56d12010-08-25 11:45:40 +00003200 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003201 } else {
3202 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003203 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003204 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003205 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003206 Diag(Param->getLocation(), diag::note_template_param_here);
3207 return true;
3208 }
3209
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003210 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall183700f2009-09-21 23:43:11 +00003211 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003212 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003213
3214 if (!Arg->isValueDependent()) {
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003215 llvm::APSInt OldValue = Value;
3216
3217 // Coerce the template argument's value to the value it will have
3218 // based on the template parameter's type.
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003219 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003220 if (Value.getBitWidth() != AllowedBits)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003221 Value = Value.extOrTrunc(AllowedBits);
Douglas Gregor0d4fd8e2010-03-26 00:39:40 +00003222 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregor1a6e0342010-03-26 02:38:37 +00003223
3224 // Complain if an unsigned parameter received a negative value.
3225 if (IntegerType->isUnsignedIntegerType()
3226 && (OldValue.isSigned() && OldValue.isNegative())) {
3227 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3228 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3229 << Arg->getSourceRange();
3230 Diag(Param->getLocation(), diag::note_template_param_here);
3231 }
3232
3233 // Complain if we overflowed the template parameter's type.
3234 unsigned RequiredBits;
3235 if (IntegerType->isUnsignedIntegerType())
3236 RequiredBits = OldValue.getActiveBits();
3237 else if (OldValue.isUnsigned())
3238 RequiredBits = OldValue.getActiveBits() + 1;
3239 else
3240 RequiredBits = OldValue.getMinSignedBits();
3241 if (RequiredBits > AllowedBits) {
3242 Diag(Arg->getSourceRange().getBegin(),
3243 diag::warn_template_arg_too_large)
3244 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3245 << Arg->getSourceRange();
3246 Diag(Param->getLocation(), diag::note_template_param_here);
3247 }
Douglas Gregorf80a9d52009-03-14 00:20:21 +00003248 }
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003249
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003250 // Add the value of this argument to the list of converted
3251 // arguments. We use the bitwidth and signedness of the template
3252 // parameter.
3253 if (Arg->isValueDependent()) {
3254 // The argument is value-dependent. Create a new
3255 // TemplateArgument with the converted expression.
3256 Converted = TemplateArgument(Arg);
3257 return false;
Douglas Gregor3e00bad2009-02-17 01:05:43 +00003258 }
3259
John McCall833ca992009-10-29 08:12:44 +00003260 Converted = TemplateArgument(Value,
Mike Stump1eb44332009-09-09 15:08:12 +00003261 ParamType->isEnumeralType() ? ParamType
Douglas Gregor02cbbd22009-06-11 18:10:32 +00003262 : IntegerType);
Douglas Gregor6ae5e662009-02-10 23:36:10 +00003263 return false;
3264 }
Douglas Gregora35284b2009-02-11 00:19:33 +00003265
John McCall6bb80172010-03-30 21:47:33 +00003266 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3267
Douglas Gregorb7a09262010-04-01 18:32:35 +00003268 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3269 // from a template argument of type std::nullptr_t to a non-type
3270 // template parameter of type pointer to object, pointer to
3271 // function, or pointer-to-member, respectively.
3272 if (ArgType->isNullPtrType() &&
3273 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3274 Converted = TemplateArgument((NamedDecl *)0);
3275 return false;
3276 }
3277
Douglas Gregorb86b0572009-02-11 01:18:59 +00003278 // Handle pointer-to-function, reference-to-function, and
3279 // pointer-to-member-function all in (roughly) the same way.
3280 if (// -- For a non-type template-parameter of type pointer to
3281 // function, only the function-to-pointer conversion (4.3) is
3282 // applied. If the template-argument represents a set of
3283 // overloaded functions (or a pointer to such), the matching
3284 // function is selected from the set (13.4).
3285 (ParamType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003286 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003287 // -- For a non-type template-parameter of type reference to
3288 // function, no conversions apply. If the template-argument
3289 // represents a set of overloaded functions, the matching
3290 // function is selected from the set (13.4).
3291 (ParamType->isReferenceType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003292 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregorb86b0572009-02-11 01:18:59 +00003293 // -- For a non-type template-parameter of type pointer to
3294 // member function, no conversions apply. If the
3295 // template-argument represents a set of overloaded member
3296 // functions, the matching member function is selected from
3297 // the set (13.4).
3298 (ParamType->isMemberPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003299 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregorb86b0572009-02-11 01:18:59 +00003300 ->isFunctionType())) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003301
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003302 if (Arg->getType() == Context.OverloadTy) {
3303 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3304 true,
3305 FoundResult)) {
3306 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3307 return true;
3308
3309 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3310 ArgType = Arg->getType();
3311 } else
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003312 return true;
Douglas Gregora35284b2009-02-11 00:19:33 +00003313 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003314
Douglas Gregorb7a09262010-04-01 18:32:35 +00003315 if (!ParamType->isMemberPointerType())
3316 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3317 ParamType,
3318 Arg, Converted);
3319
3320 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
John McCall2de56d12010-08-25 11:45:40 +00003321 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregorb7a09262010-04-01 18:32:35 +00003322 } else if (!Context.hasSameUnqualifiedType(ArgType,
3323 ParamType.getNonReferenceType())) {
Douglas Gregora35284b2009-02-11 00:19:33 +00003324 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003325 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregora35284b2009-02-11 00:19:33 +00003326 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003327 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregora35284b2009-02-11 00:19:33 +00003328 Diag(Param->getLocation(), diag::note_template_param_here);
3329 return true;
3330 }
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Douglas Gregorb7a09262010-04-01 18:32:35 +00003332 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregora35284b2009-02-11 00:19:33 +00003333 }
3334
Chris Lattnerfe90de72009-02-20 21:37:53 +00003335 if (ParamType->isPointerType()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003336 // -- for a non-type template-parameter of type pointer to
3337 // object, qualification conversions (4.4) and the
3338 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00003339 // C++0x also allows a value of std::nullptr_t.
Eli Friedman13578692010-08-05 02:49:48 +00003340 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003341 "Only object pointers allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003342
Douglas Gregorb7a09262010-04-01 18:32:35 +00003343 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3344 ParamType,
3345 Arg, Converted);
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003346 }
Mike Stump1eb44332009-09-09 15:08:12 +00003347
Ted Kremenek6217b802009-07-29 21:53:49 +00003348 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregorb86b0572009-02-11 01:18:59 +00003349 // -- For a non-type template-parameter of type reference to
3350 // object, no conversions apply. The type referred to by the
3351 // reference may be more cv-qualified than the (otherwise
3352 // identical) type of the template-argument. The
3353 // template-parameter is bound directly to the
3354 // template-argument, which must be an lvalue.
Eli Friedman13578692010-08-05 02:49:48 +00003355 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
Douglas Gregorb86b0572009-02-11 01:18:59 +00003356 "Only object references allowed here");
Douglas Gregorf684e6e2009-02-11 00:44:29 +00003357
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003358 if (Arg->getType() == Context.OverloadTy) {
3359 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3360 ParamRefType->getPointeeType(),
3361 true,
3362 FoundResult)) {
3363 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3364 return true;
3365
3366 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3367 ArgType = Arg->getType();
3368 } else
Douglas Gregorb7a09262010-04-01 18:32:35 +00003369 return true;
Douglas Gregorb86b0572009-02-11 01:18:59 +00003370 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00003371
Douglas Gregorb7a09262010-04-01 18:32:35 +00003372 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3373 ParamType,
3374 Arg, Converted);
Douglas Gregorb86b0572009-02-11 01:18:59 +00003375 }
Douglas Gregor658bbb52009-02-11 16:16:59 +00003376
3377 // -- For a non-type template-parameter of type pointer to data
3378 // member, qualification conversions (4.4) are applied.
3379 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3380
Douglas Gregor8e6563b2009-02-11 18:22:40 +00003381 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor658bbb52009-02-11 16:16:59 +00003382 // Types match exactly: nothing more to do here.
3383 } else if (IsQualificationConversion(ArgType, ParamType)) {
John McCall2de56d12010-08-25 11:45:40 +00003384 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
Douglas Gregor658bbb52009-02-11 16:16:59 +00003385 } else {
3386 // We can't perform this conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00003387 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor658bbb52009-02-11 16:16:59 +00003388 diag::err_template_arg_not_convertible)
Douglas Gregor2943aed2009-03-03 04:44:36 +00003389 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor658bbb52009-02-11 16:16:59 +00003390 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump1eb44332009-09-09 15:08:12 +00003391 return true;
Douglas Gregor658bbb52009-02-11 16:16:59 +00003392 }
3393
Douglas Gregorcaddba02009-11-12 18:38:13 +00003394 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregorc15cb382009-02-09 23:23:08 +00003395}
3396
3397/// \brief Check a template argument against its corresponding
3398/// template template parameter.
3399///
3400/// This routine implements the semantics of C++ [temp.arg.template].
3401/// It returns true if an error occurred, and false otherwise.
3402bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor788cd062009-11-11 01:00:40 +00003403 const TemplateArgumentLoc &Arg) {
3404 TemplateName Name = Arg.getArgument().getAsTemplate();
3405 TemplateDecl *Template = Name.getAsTemplateDecl();
3406 if (!Template) {
3407 // Any dependent template name is fine.
3408 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3409 return false;
3410 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003411
3412 // C++ [temp.arg.template]p1:
3413 // A template-argument for a template template-parameter shall be
3414 // the name of a class template, expressed as id-expression. Only
3415 // primary class templates are considered when matching the
3416 // template template argument with the corresponding parameter;
3417 // partial specializations are not considered even if their
3418 // parameter lists match that of the template template parameter.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003419 //
3420 // Note that we also allow template template parameters here, which
3421 // will happen when we are dealing with, e.g., class template
3422 // partial specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00003423 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregorba1ecb52009-06-12 19:43:02 +00003424 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003425 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregordd0574e2009-02-10 00:24:35 +00003426 "Only function templates are possible here");
Douglas Gregor788cd062009-11-11 01:00:40 +00003427 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregore53060f2009-06-25 22:08:12 +00003428 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003429 << Template;
3430 }
3431
3432 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3433 Param->getTemplateParameters(),
Douglas Gregorfb898e12009-11-12 16:20:59 +00003434 true,
3435 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor788cd062009-11-11 01:00:40 +00003436 Arg.getLocation());
Douglas Gregorc15cb382009-02-09 23:23:08 +00003437}
3438
Douglas Gregor02024a92010-03-28 02:42:43 +00003439/// \brief Given a non-type template argument that refers to a
3440/// declaration and the type of its corresponding non-type template
3441/// parameter, produce an expression that properly refers to that
3442/// declaration.
John McCall60d7b3a2010-08-24 06:29:42 +00003443ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003444Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3445 QualType ParamType,
3446 SourceLocation Loc) {
3447 assert(Arg.getKind() == TemplateArgument::Declaration &&
3448 "Only declaration template arguments permitted here");
3449 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3450
3451 if (VD->getDeclContext()->isRecord() &&
3452 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3453 // If the value is a class member, we might have a pointer-to-member.
3454 // Determine whether the non-type template template parameter is of
3455 // pointer-to-member type. If so, we need to build an appropriate
3456 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3457 // would refer to the member itself.
3458 if (ParamType->isMemberPointerType()) {
3459 QualType ClassType
3460 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3461 NestedNameSpecifier *Qualifier
John McCall9ae2f072010-08-23 23:25:46 +00003462 = NestedNameSpecifier::Create(Context, 0, false,
3463 ClassType.getTypePtr());
Douglas Gregor02024a92010-03-28 02:42:43 +00003464 CXXScopeSpec SS;
3465 SS.setScopeRep(Qualifier);
John McCalldfa1edb2010-11-23 20:48:44 +00003466
3467 // The actual value-ness of this is unimportant, but for
3468 // internal consistency's sake, references to instance methods
3469 // are r-values.
3470 ExprValueKind VK = VK_LValue;
3471 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3472 VK = VK_RValue;
3473
John McCall60d7b3a2010-08-24 06:29:42 +00003474 ExprResult RefExpr = BuildDeclRefExpr(VD,
John McCallf89e55a2010-11-18 06:31:45 +00003475 VD->getType().getNonReferenceType(),
John McCalldfa1edb2010-11-23 20:48:44 +00003476 VK,
John McCallf89e55a2010-11-18 06:31:45 +00003477 Loc,
3478 &SS);
Douglas Gregor02024a92010-03-28 02:42:43 +00003479 if (RefExpr.isInvalid())
3480 return ExprError();
3481
John McCall2de56d12010-08-25 11:45:40 +00003482 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregorc0c83002010-04-30 21:46:38 +00003483
3484 // We might need to perform a trailing qualification conversion, since
3485 // the element type on the parameter could be more qualified than the
3486 // element type in the expression we constructed.
3487 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3488 ParamType.getUnqualifiedType())) {
3489 Expr *RefE = RefExpr.takeAs<Expr>();
John McCall2de56d12010-08-25 11:45:40 +00003490 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
Douglas Gregorc0c83002010-04-30 21:46:38 +00003491 RefExpr = Owned(RefE);
3492 }
3493
Douglas Gregor02024a92010-03-28 02:42:43 +00003494 assert(!RefExpr.isInvalid() &&
3495 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorc0c83002010-04-30 21:46:38 +00003496 ParamType.getUnqualifiedType()));
Douglas Gregor02024a92010-03-28 02:42:43 +00003497 return move(RefExpr);
3498 }
3499 }
3500
3501 QualType T = VD->getType().getNonReferenceType();
3502 if (ParamType->isPointerType()) {
Douglas Gregorb7a09262010-04-01 18:32:35 +00003503 // When the non-type template parameter is a pointer, take the
3504 // address of the declaration.
John McCallf89e55a2010-11-18 06:31:45 +00003505 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003506 if (RefExpr.isInvalid())
3507 return ExprError();
Douglas Gregorb7a09262010-04-01 18:32:35 +00003508
3509 if (T->isFunctionType() || T->isArrayType()) {
3510 // Decay functions and arrays.
3511 Expr *RefE = (Expr *)RefExpr.get();
3512 DefaultFunctionArrayConversion(RefE);
3513 if (RefE != RefExpr.get()) {
3514 RefExpr.release();
3515 RefExpr = Owned(RefE);
3516 }
3517
3518 return move(RefExpr);
Douglas Gregor02024a92010-03-28 02:42:43 +00003519 }
3520
Douglas Gregorb7a09262010-04-01 18:32:35 +00003521 // Take the address of everything else
John McCall2de56d12010-08-25 11:45:40 +00003522 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
Douglas Gregor02024a92010-03-28 02:42:43 +00003523 }
3524
John McCallf89e55a2010-11-18 06:31:45 +00003525 ExprValueKind VK = VK_RValue;
3526
Douglas Gregor02024a92010-03-28 02:42:43 +00003527 // If the non-type template parameter has reference type, qualify the
3528 // resulting declaration reference with the extra qualifiers on the
3529 // type that the reference refers to.
John McCallf89e55a2010-11-18 06:31:45 +00003530 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3531 VK = VK_LValue;
3532 T = Context.getQualifiedType(T,
3533 TargetRef->getPointeeType().getQualifiers());
3534 }
Douglas Gregor02024a92010-03-28 02:42:43 +00003535
John McCallf89e55a2010-11-18 06:31:45 +00003536 return BuildDeclRefExpr(VD, T, VK, Loc);
Douglas Gregor02024a92010-03-28 02:42:43 +00003537}
3538
3539/// \brief Construct a new expression that refers to the given
3540/// integral template argument with the given source-location
3541/// information.
3542///
3543/// This routine takes care of the mapping from an integral template
3544/// argument (which may have any integral type) to the appropriate
3545/// literal value.
John McCall60d7b3a2010-08-24 06:29:42 +00003546ExprResult
Douglas Gregor02024a92010-03-28 02:42:43 +00003547Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3548 SourceLocation Loc) {
3549 assert(Arg.getKind() == TemplateArgument::Integral &&
3550 "Operation is only value for integral template arguments");
3551 QualType T = Arg.getIntegralType();
3552 if (T->isCharType() || T->isWideCharType())
3553 return Owned(new (Context) CharacterLiteral(
3554 Arg.getAsIntegral()->getZExtValue(),
3555 T->isWideCharType(),
3556 T,
3557 Loc));
3558 if (T->isBooleanType())
3559 return Owned(new (Context) CXXBoolLiteralExpr(
3560 Arg.getAsIntegral()->getBoolValue(),
3561 T,
3562 Loc));
3563
Peter Collingbournefb7b3632010-12-15 15:06:14 +00003564 QualType BT;
3565 if (const EnumType *ET = T->getAs<EnumType>())
3566 BT = ET->getDecl()->getPromotionType();
3567 else
3568 BT = T;
3569
3570 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3571 ImpCastExprToType(E, T, CK_IntegralCast);
3572
3573 return Owned(E);
Douglas Gregor02024a92010-03-28 02:42:43 +00003574}
3575
3576
Douglas Gregorddc29e12009-02-06 22:42:48 +00003577/// \brief Determine whether the given template parameter lists are
3578/// equivalent.
3579///
Mike Stump1eb44332009-09-09 15:08:12 +00003580/// \param New The new template parameter list, typically written in the
Douglas Gregorddc29e12009-02-06 22:42:48 +00003581/// source code as part of a new template declaration.
3582///
3583/// \param Old The old template parameter list, typically found via
3584/// name lookup of the template declared with this template parameter
3585/// list.
3586///
3587/// \param Complain If true, this routine will produce a diagnostic if
3588/// the template parameter lists are not equivalent.
3589///
Douglas Gregorfb898e12009-11-12 16:20:59 +00003590/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregordd0574e2009-02-10 00:24:35 +00003591///
3592/// \param TemplateArgLoc If this source location is valid, then we
3593/// are actually checking the template parameter list of a template
3594/// argument (New) against the template parameter list of its
3595/// corresponding template template parameter (Old). We produce
3596/// slightly different diagnostics in this scenario.
3597///
Douglas Gregorddc29e12009-02-06 22:42:48 +00003598/// \returns True if the template parameter lists are equal, false
3599/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00003600bool
Douglas Gregorddc29e12009-02-06 22:42:48 +00003601Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3602 TemplateParameterList *Old,
3603 bool Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003604 TemplateParameterListEqualKind Kind,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003605 SourceLocation TemplateArgLoc) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003606 if (Old->size() != New->size()) {
3607 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003608 unsigned NextDiag = diag::err_template_param_list_different_arity;
3609 if (TemplateArgLoc.isValid()) {
3610 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3611 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump1eb44332009-09-09 15:08:12 +00003612 }
Douglas Gregordd0574e2009-02-10 00:24:35 +00003613 Diag(New->getTemplateLoc(), NextDiag)
3614 << (New->size() > Old->size())
Douglas Gregorfb898e12009-11-12 16:20:59 +00003615 << (Kind != TPL_TemplateMatch)
Douglas Gregordd0574e2009-02-10 00:24:35 +00003616 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorddc29e12009-02-06 22:42:48 +00003617 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003618 << (Kind != TPL_TemplateMatch)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003619 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3620 }
3621
3622 return false;
3623 }
3624
3625 for (TemplateParameterList::iterator OldParm = Old->begin(),
3626 OldParmEnd = Old->end(), NewParm = New->begin();
3627 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3628 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003629 if (Complain) {
3630 unsigned NextDiag = diag::err_template_param_different_kind;
3631 if (TemplateArgLoc.isValid()) {
3632 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3633 NextDiag = diag::note_template_param_different_kind;
3634 }
3635 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003636 << (Kind != TPL_TemplateMatch);
Douglas Gregor34d1dc92009-06-24 16:50:40 +00003637 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregorfb898e12009-11-12 16:20:59 +00003638 << (Kind != TPL_TemplateMatch);
Douglas Gregordd0574e2009-02-10 00:24:35 +00003639 }
Douglas Gregorddc29e12009-02-06 22:42:48 +00003640 return false;
3641 }
3642
Douglas Gregora417b872010-06-04 08:34:32 +00003643 if (TemplateTypeParmDecl *OldTTP
3644 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3645 // Template type parameters are equivalent if either both are template
3646 // type parameter packs or neither are (since we know we're at the same
3647 // index).
3648 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3649 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3650 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3651 // allow one to match a template parameter pack in the template
3652 // parameter list of a template template parameter to one or more
3653 // template parameters in the template parameter list of the
3654 // corresponding template template argument.
3655 if (Complain) {
3656 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3657 if (TemplateArgLoc.isValid()) {
3658 Diag(TemplateArgLoc,
3659 diag::err_template_arg_template_params_mismatch);
3660 NextDiag = diag::note_template_parameter_pack_non_pack;
3661 }
3662 Diag(NewTTP->getLocation(), NextDiag)
3663 << 0 << NewTTP->isParameterPack();
3664 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3665 << 0 << OldTTP->isParameterPack();
3666 }
3667 return false;
3668 }
Mike Stump1eb44332009-09-09 15:08:12 +00003669 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003670 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3671 // The types of non-type template parameters must agree.
3672 NonTypeTemplateParmDecl *NewNTTP
3673 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregorfb898e12009-11-12 16:20:59 +00003674
3675 // If we are matching a template template argument to a template
3676 // template parameter and one of the non-type template parameter types
3677 // is dependent, then we must wait until template instantiation time
3678 // to actually compare the arguments.
3679 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3680 (OldNTTP->getType()->isDependentType() ||
3681 NewNTTP->getType()->isDependentType()))
3682 continue;
3683
Douglas Gregorddc29e12009-02-06 22:42:48 +00003684 if (Context.getCanonicalType(OldNTTP->getType()) !=
3685 Context.getCanonicalType(NewNTTP->getType())) {
3686 if (Complain) {
Douglas Gregordd0574e2009-02-10 00:24:35 +00003687 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3688 if (TemplateArgLoc.isValid()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003689 Diag(TemplateArgLoc,
Douglas Gregordd0574e2009-02-10 00:24:35 +00003690 diag::err_template_arg_template_params_mismatch);
3691 NextDiag = diag::note_template_nontype_parm_different_type;
3692 }
3693 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorddc29e12009-02-06 22:42:48 +00003694 << NewNTTP->getType()
Douglas Gregorfb898e12009-11-12 16:20:59 +00003695 << (Kind != TPL_TemplateMatch);
Mike Stump1eb44332009-09-09 15:08:12 +00003696 Diag(OldNTTP->getLocation(),
Douglas Gregorddc29e12009-02-06 22:42:48 +00003697 diag::note_template_nontype_parm_prev_declaration)
3698 << OldNTTP->getType();
3699 }
3700 return false;
3701 }
3702 } else {
3703 // The template parameter lists of template template
3704 // parameters must agree.
Mike Stump1eb44332009-09-09 15:08:12 +00003705 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorddc29e12009-02-06 22:42:48 +00003706 "Only template template parameters handled here");
Mike Stump1eb44332009-09-09 15:08:12 +00003707 TemplateTemplateParmDecl *OldTTP
Douglas Gregorddc29e12009-02-06 22:42:48 +00003708 = cast<TemplateTemplateParmDecl>(*OldParm);
3709 TemplateTemplateParmDecl *NewTTP
3710 = cast<TemplateTemplateParmDecl>(*NewParm);
3711 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3712 OldTTP->getTemplateParameters(),
3713 Complain,
Douglas Gregorfb898e12009-11-12 16:20:59 +00003714 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregordd0574e2009-02-10 00:24:35 +00003715 TemplateArgLoc))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003716 return false;
3717 }
3718 }
3719
3720 return true;
3721}
3722
3723/// \brief Check whether a template can be declared within this scope.
3724///
3725/// If the template declaration is valid in this scope, returns
3726/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump1eb44332009-09-09 15:08:12 +00003727bool
Douglas Gregor05396e22009-08-25 17:23:04 +00003728Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorddc29e12009-02-06 22:42:48 +00003729 // Find the nearest enclosing declaration scope.
3730 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3731 (S->getFlags() & Scope::TemplateParamScope) != 0)
3732 S = S->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Douglas Gregorddc29e12009-02-06 22:42:48 +00003734 // C++ [temp]p2:
3735 // A template-declaration can appear only as a namespace scope or
3736 // class scope declaration.
3737 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedman1503f772009-07-31 01:43:05 +00003738 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3739 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump1eb44332009-09-09 15:08:12 +00003740 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor05396e22009-08-25 17:23:04 +00003741 << TemplateParams->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003742
Eli Friedman1503f772009-07-31 01:43:05 +00003743 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorddc29e12009-02-06 22:42:48 +00003744 Ctx = Ctx->getParent();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003745
3746 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3747 return false;
3748
Mike Stump1eb44332009-09-09 15:08:12 +00003749 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00003750 diag::err_template_outside_namespace_or_class_scope)
3751 << TemplateParams->getSourceRange();
Douglas Gregorddc29e12009-02-06 22:42:48 +00003752}
Douglas Gregorcc636682009-02-17 23:15:12 +00003753
Douglas Gregord5cb8762009-10-07 00:13:32 +00003754/// \brief Determine what kind of template specialization the given declaration
3755/// is.
3756static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3757 if (!D)
3758 return TSK_Undeclared;
3759
Douglas Gregorf6b11852009-10-08 15:14:33 +00003760 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3761 return Record->getTemplateSpecializationKind();
Douglas Gregord5cb8762009-10-07 00:13:32 +00003762 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3763 return Function->getTemplateSpecializationKind();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003764 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3765 return Var->getTemplateSpecializationKind();
3766
Douglas Gregord5cb8762009-10-07 00:13:32 +00003767 return TSK_Undeclared;
3768}
3769
Douglas Gregor9302da62009-10-14 23:50:59 +00003770/// \brief Check whether a specialization is well-formed in the current
3771/// context.
Douglas Gregor88b70942009-02-25 22:02:03 +00003772///
Douglas Gregor9302da62009-10-14 23:50:59 +00003773/// This routine determines whether a template specialization can be declared
3774/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003775///
3776/// \param S the semantic analysis object for which this check is being
3777/// performed.
3778///
3779/// \param Specialized the entity being specialized or instantiated, which
3780/// may be a kind of template (class template, function template, etc.) or
3781/// a member of a class template (member function, static data member,
3782/// member class).
3783///
3784/// \param PrevDecl the previous declaration of this entity, if any.
3785///
3786/// \param Loc the location of the explicit specialization or instantiation of
3787/// this entity.
3788///
3789/// \param IsPartialSpecialization whether this is a partial specialization of
3790/// a class template.
3791///
Douglas Gregord5cb8762009-10-07 00:13:32 +00003792/// \returns true if there was an error that we cannot recover from, false
3793/// otherwise.
3794static bool CheckTemplateSpecializationScope(Sema &S,
3795 NamedDecl *Specialized,
3796 NamedDecl *PrevDecl,
3797 SourceLocation Loc,
Douglas Gregor9302da62009-10-14 23:50:59 +00003798 bool IsPartialSpecialization) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003799 // Keep these "kind" numbers in sync with the %select statements in the
3800 // various diagnostics emitted by this routine.
3801 int EntityKind = 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003802 bool isTemplateSpecialization = false;
3803 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003804 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003805 isTemplateSpecialization = true;
3806 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003807 EntityKind = 2;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00003808 isTemplateSpecialization = true;
3809 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregord5cb8762009-10-07 00:13:32 +00003810 EntityKind = 3;
3811 else if (isa<VarDecl>(Specialized))
3812 EntityKind = 4;
3813 else if (isa<RecordDecl>(Specialized))
3814 EntityKind = 5;
3815 else {
Douglas Gregor9302da62009-10-14 23:50:59 +00003816 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3817 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregord5cb8762009-10-07 00:13:32 +00003818 return true;
3819 }
3820
Douglas Gregor88b70942009-02-25 22:02:03 +00003821 // C++ [temp.expl.spec]p2:
3822 // An explicit specialization shall be declared in the namespace
3823 // of which the template is a member, or, for member templates, in
3824 // the namespace of which the enclosing class or enclosing class
3825 // template is a member. An explicit specialization of a member
3826 // function, member class or static data member of a class
3827 // template shall be declared in the namespace of which the class
3828 // template is a member. Such a declaration may also be a
3829 // definition. If the declaration is not a definition, the
3830 // specialization may be defined later in the name- space in which
3831 // the explicit specialization was declared, or in a namespace
3832 // that encloses the one in which the explicit specialization was
3833 // declared.
Sebastian Redl7a126a42010-08-31 00:36:30 +00003834 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003835 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003836 << Specialized;
Douglas Gregor88b70942009-02-25 22:02:03 +00003837 return true;
3838 }
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003839
Douglas Gregor0a407472009-10-07 17:30:37 +00003840 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3841 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregor9302da62009-10-14 23:50:59 +00003842 << Specialized;
Douglas Gregor0a407472009-10-07 17:30:37 +00003843 return true;
3844 }
3845
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003846 // C++ [temp.class.spec]p6:
3847 // A class template partial specialization may be declared or redeclared
3848 // in any namespace scope in which its definition may be defined (14.5.1
3849 // and 14.5.2).
Douglas Gregord5cb8762009-10-07 00:13:32 +00003850 bool ComplainedAboutScope = false;
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003851 DeclContext *SpecializedContext
Douglas Gregord5cb8762009-10-07 00:13:32 +00003852 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003853 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregor9302da62009-10-14 23:50:59 +00003854 if ((!PrevDecl ||
3855 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3856 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
Douglas Gregor121dc9a2010-09-12 05:08:28 +00003857 // C++ [temp.exp.spec]p2:
3858 // An explicit specialization shall be declared in the namespace of which
3859 // the template is a member, or, for member templates, in the namespace
3860 // of which the enclosing class or enclosing class template is a member.
3861 // An explicit specialization of a member function, member class or
3862 // static data member of a class template shall be declared in the
3863 // namespace of which the class template is a member.
3864 //
3865 // C++0x [temp.expl.spec]p2:
3866 // An explicit specialization shall be declared in a namespace enclosing
3867 // the specialized template.
3868 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
3869 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
Douglas Gregora4d5de52010-09-12 05:24:55 +00003870 bool IsCPlusPlus0xExtension
3871 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003872 if (isa<TranslationUnitDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003873 S.Diag(Loc, IsCPlusPlus0xExtension
3874 ? diag::ext_template_spec_decl_out_of_scope_global
3875 : diag::err_template_spec_decl_out_of_scope_global)
3876 << EntityKind << Specialized;
Douglas Gregor9302da62009-10-14 23:50:59 +00003877 else if (isa<NamespaceDecl>(SpecializedContext))
Douglas Gregora4d5de52010-09-12 05:24:55 +00003878 S.Diag(Loc, IsCPlusPlus0xExtension
3879 ? diag::ext_template_spec_decl_out_of_scope
3880 : diag::err_template_spec_decl_out_of_scope)
3881 << EntityKind << Specialized
3882 << cast<NamedDecl>(SpecializedContext);
Douglas Gregor9302da62009-10-14 23:50:59 +00003883
3884 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3885 ComplainedAboutScope = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00003886 }
Douglas Gregor88b70942009-02-25 22:02:03 +00003887 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003888
3889 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregor9302da62009-10-14 23:50:59 +00003890 // namespace.
Douglas Gregord5cb8762009-10-07 00:13:32 +00003891 // Note that HandleDeclarator() performs this check for explicit
3892 // specializations of function templates, static data members, and member
3893 // functions, so we skip the check here for those kinds of entities.
3894 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregor7974c3b2009-10-07 17:21:34 +00003895 // Should we refactor that check, so that it occurs later?
3896 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregor9302da62009-10-14 23:50:59 +00003897 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3898 isa<FunctionDecl>(Specialized))) {
Douglas Gregord5cb8762009-10-07 00:13:32 +00003899 if (isa<TranslationUnitDecl>(SpecializedContext))
3900 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3901 << EntityKind << Specialized;
3902 else if (isa<NamespaceDecl>(SpecializedContext))
3903 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3904 << EntityKind << Specialized
3905 << cast<NamedDecl>(SpecializedContext);
3906
Douglas Gregor9302da62009-10-14 23:50:59 +00003907 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor88b70942009-02-25 22:02:03 +00003908 }
Douglas Gregord5cb8762009-10-07 00:13:32 +00003909
3910 // FIXME: check for specialization-after-instantiation errors and such.
3911
Douglas Gregor88b70942009-02-25 22:02:03 +00003912 return false;
3913}
Douglas Gregord5cb8762009-10-07 00:13:32 +00003914
Douglas Gregore94866f2009-06-12 21:21:02 +00003915/// \brief Check the non-type template arguments of a class template
3916/// partial specialization according to C++ [temp.class.spec]p9.
3917///
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003918/// \param TemplateParams the template parameters of the primary class
3919/// template.
3920///
3921/// \param TemplateArg the template arguments of the class template
3922/// partial specialization.
3923///
Douglas Gregore94866f2009-06-12 21:21:02 +00003924/// \returns true if there was an error, false otherwise.
3925bool Sema::CheckClassTemplatePartialSpecializationArgs(
3926 TemplateParameterList *TemplateParams,
Douglas Gregorb9c66312010-12-23 17:13:55 +00003927 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
Douglas Gregor910f8002010-11-07 23:05:16 +00003928 const TemplateArgument *ArgList = TemplateArgs.data();
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Douglas Gregore94866f2009-06-12 21:21:02 +00003930 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00003931 NonTypeTemplateParmDecl *Param
Douglas Gregore94866f2009-06-12 21:21:02 +00003932 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregorb9c66312010-12-23 17:13:55 +00003933 if (!Param)
Douglas Gregore94866f2009-06-12 21:21:02 +00003934 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003935
Anders Carlsson6360be72009-06-13 18:20:51 +00003936 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003937 if (!ArgExpr) {
Douglas Gregore94866f2009-06-12 21:21:02 +00003938 continue;
Douglas Gregor6aa75cf2009-06-12 22:08:06 +00003939 }
Douglas Gregore94866f2009-06-12 21:21:02 +00003940
Douglas Gregorb9c66312010-12-23 17:13:55 +00003941 // FIXME: Variadic templates. Unwrap argument packs.
3942
Douglas Gregore94866f2009-06-12 21:21:02 +00003943 // C++ [temp.class.spec]p8:
3944 // A non-type argument is non-specialized if it is the name of a
3945 // non-type parameter. All other non-type arguments are
3946 // specialized.
3947 //
3948 // Below, we check the two conditions that only apply to
3949 // specialized non-type arguments, so skip any non-specialized
3950 // arguments.
3951 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Douglas Gregorb9c66312010-12-23 17:13:55 +00003952 if (llvm::isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
Douglas Gregore94866f2009-06-12 21:21:02 +00003953 continue;
Douglas Gregorb9c66312010-12-23 17:13:55 +00003954
Douglas Gregore94866f2009-06-12 21:21:02 +00003955 // C++ [temp.class.spec]p9:
3956 // Within the argument list of a class template partial
3957 // specialization, the following restrictions apply:
3958 // -- A partially specialized non-type argument expression
3959 // shall not involve a template parameter of the partial
3960 // specialization except when the argument expression is a
3961 // simple identifier.
3962 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003963 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003964 diag::err_dependent_non_type_arg_in_partial_spec)
3965 << ArgExpr->getSourceRange();
3966 return true;
3967 }
3968
3969 // -- The type of a template parameter corresponding to a
3970 // specialized non-type argument shall not be dependent on a
3971 // parameter of the specialization.
3972 if (Param->getType()->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003973 Diag(ArgExpr->getLocStart(),
Douglas Gregore94866f2009-06-12 21:21:02 +00003974 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3975 << Param->getType()
3976 << ArgExpr->getSourceRange();
3977 Diag(Param->getLocation(), diag::note_template_param_here);
3978 return true;
3979 }
3980 }
3981
3982 return false;
3983}
3984
Douglas Gregordc0a11c2010-02-26 06:03:23 +00003985/// \brief Retrieve the previous declaration of the given declaration.
3986static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3987 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3988 return VD->getPreviousDeclaration();
3989 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3990 return FD->getPreviousDeclaration();
3991 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3992 return TD->getPreviousDeclaration();
3993 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3994 return TD->getPreviousDeclaration();
3995 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3996 return FTD->getPreviousDeclaration();
3997 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3998 return CTD->getPreviousDeclaration();
3999 return 0;
4000}
4001
John McCalld226f652010-08-21 09:40:31 +00004002DeclResult
John McCall0f434ec2009-07-31 02:45:11 +00004003Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4004 TagUseKind TUK,
Mike Stump1eb44332009-09-09 15:08:12 +00004005 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00004006 CXXScopeSpec &SS,
Douglas Gregor7532dc62009-03-30 22:58:21 +00004007 TemplateTy TemplateD,
Douglas Gregorcc636682009-02-17 23:15:12 +00004008 SourceLocation TemplateNameLoc,
4009 SourceLocation LAngleLoc,
Douglas Gregor40808ce2009-03-09 23:48:35 +00004010 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregorcc636682009-02-17 23:15:12 +00004011 SourceLocation RAngleLoc,
4012 AttributeList *Attr,
4013 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004014 assert(TUK != TUK_Reference && "References are not specializations");
John McCallf1bbbb42009-09-04 01:14:41 +00004015
Douglas Gregorcc636682009-02-17 23:15:12 +00004016 // Find the class template we're specializing
Douglas Gregor7532dc62009-03-30 22:58:21 +00004017 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00004018 ClassTemplateDecl *ClassTemplate
Douglas Gregor8b13c082009-11-12 00:46:20 +00004019 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4020
4021 if (!ClassTemplate) {
4022 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4023 << (Name.getAsTemplateDecl() &&
4024 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4025 return true;
4026 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004027
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004028 bool isExplicitSpecialization = false;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004029 bool isPartialSpecialization = false;
4030
Douglas Gregor88b70942009-02-25 22:02:03 +00004031 // Check the validity of the template headers that introduce this
4032 // template.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004033 // FIXME: We probably shouldn't complain about these headers for
4034 // friend declarations.
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004035 bool Invalid = false;
Douglas Gregor05396e22009-08-25 17:23:04 +00004036 TemplateParameterList *TemplateParams
Mike Stump1eb44332009-09-09 15:08:12 +00004037 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4038 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004039 TemplateParameterLists.size(),
John McCall77e8b112010-04-13 20:37:33 +00004040 TUK == TUK_Friend,
Douglas Gregor0167f3c2010-07-14 23:14:12 +00004041 isExplicitSpecialization,
4042 Invalid);
4043 if (Invalid)
4044 return true;
4045
Abramo Bagnara9b934882010-06-12 08:15:14 +00004046 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4047 if (TemplateParams)
4048 --NumMatchedTemplateParamLists;
4049
Douglas Gregor05396e22009-08-25 17:23:04 +00004050 if (TemplateParams && TemplateParams->size() > 0) {
4051 isPartialSpecialization = true;
Douglas Gregor88b70942009-02-25 22:02:03 +00004052
Douglas Gregorb0ee93c2010-12-21 08:14:57 +00004053 if (TUK == TUK_Friend) {
4054 Diag(KWLoc, diag::err_partial_specialization_friend)
4055 << SourceRange(LAngleLoc, RAngleLoc);
4056 return true;
4057 }
4058
Douglas Gregor05396e22009-08-25 17:23:04 +00004059 // C++ [temp.class.spec]p10:
4060 // The template parameter list of a specialization shall not
4061 // contain default template argument values.
4062 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4063 Decl *Param = TemplateParams->getParam(I);
4064 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4065 if (TTP->hasDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004066 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004067 diag::err_default_arg_in_partial_spec);
John McCall833ca992009-10-29 08:12:44 +00004068 TTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004069 }
4070 } else if (NonTypeTemplateParmDecl *NTTP
4071 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4072 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004073 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004074 diag::err_default_arg_in_partial_spec)
4075 << DefArg->getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004076 NTTP->removeDefaultArgument();
Douglas Gregor05396e22009-08-25 17:23:04 +00004077 }
4078 } else {
4079 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor788cd062009-11-11 01:00:40 +00004080 if (TTP->hasDefaultArgument()) {
4081 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor05396e22009-08-25 17:23:04 +00004082 diag::err_default_arg_in_partial_spec)
Douglas Gregor788cd062009-11-11 01:00:40 +00004083 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00004084 TTP->removeDefaultArgument();
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004085 }
4086 }
4087 }
Douglas Gregora735b202009-10-13 14:39:41 +00004088 } else if (TemplateParams) {
4089 if (TUK == TUK_Friend)
4090 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregor849b2432010-03-31 17:46:05 +00004091 << FixItHint::CreateRemoval(
Douglas Gregora735b202009-10-13 14:39:41 +00004092 SourceRange(TemplateParams->getTemplateLoc(),
4093 TemplateParams->getRAngleLoc()))
4094 << SourceRange(LAngleLoc, RAngleLoc);
4095 else
4096 isExplicitSpecialization = true;
4097 } else if (TUK != TUK_Friend) {
Douglas Gregor05396e22009-08-25 17:23:04 +00004098 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregor849b2432010-03-31 17:46:05 +00004099 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004100 isExplicitSpecialization = true;
4101 }
Douglas Gregor88b70942009-02-25 22:02:03 +00004102
Douglas Gregorcc636682009-02-17 23:15:12 +00004103 // Check that the specialization uses the same tag kind as the
4104 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004105 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4106 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004107 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00004108 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00004109 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00004110 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora3a83512009-04-01 23:51:29 +00004111 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00004112 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora3a83512009-04-01 23:51:29 +00004113 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00004114 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004115 diag::note_previous_use);
4116 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4117 }
4118
Douglas Gregor40808ce2009-03-09 23:48:35 +00004119 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00004120 TemplateArgumentListInfo TemplateArgs;
4121 TemplateArgs.setLAngleLoc(LAngleLoc);
4122 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00004123 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor40808ce2009-03-09 23:48:35 +00004124
Douglas Gregorcc636682009-02-17 23:15:12 +00004125 // Check that the template argument list is well-formed for this
4126 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00004127 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00004128 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4129 TemplateArgs, false, Converted))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004130 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004131
Douglas Gregor910f8002010-11-07 23:05:16 +00004132 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregorcc636682009-02-17 23:15:12 +00004133 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004135 // Find the class template (partial) specialization declaration that
Douglas Gregorcc636682009-02-17 23:15:12 +00004136 // corresponds to these arguments.
Douglas Gregorba1ecb52009-06-12 19:43:02 +00004137 if (isPartialSpecialization) {
Douglas Gregore94866f2009-06-12 21:21:02 +00004138 if (CheckClassTemplatePartialSpecializationArgs(
4139 ClassTemplate->getTemplateParameters(),
Douglas Gregorb9c66312010-12-23 17:13:55 +00004140 Converted))
Douglas Gregore94866f2009-06-12 21:21:02 +00004141 return true;
4142
Douglas Gregorde090962010-02-09 00:37:32 +00004143 if (!Name.isDependent() &&
4144 !TemplateSpecializationType::anyDependentTemplateArguments(
4145 TemplateArgs.getArgumentArray(),
4146 TemplateArgs.size())) {
4147 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4148 << ClassTemplate->getDeclName();
4149 isPartialSpecialization = false;
Douglas Gregorde090962010-02-09 00:37:32 +00004150 }
4151 }
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004152
Douglas Gregorcc636682009-02-17 23:15:12 +00004153 void *InsertPos = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004154 ClassTemplateSpecializationDecl *PrevDecl = 0;
4155
4156 if (isPartialSpecialization)
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004157 // FIXME: Template parameter list matters, too
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004158 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004159 = ClassTemplate->findPartialSpecialization(Converted.data(),
4160 Converted.size(),
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004161 InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004162 else
4163 PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00004164 = ClassTemplate->findSpecialization(Converted.data(),
4165 Converted.size(), InsertPos);
Douglas Gregorcc636682009-02-17 23:15:12 +00004166
4167 ClassTemplateSpecializationDecl *Specialization = 0;
4168
Douglas Gregor88b70942009-02-25 22:02:03 +00004169 // Check whether we can declare a class template specialization in
4170 // the current scope.
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004171 if (TUK != TUK_Friend &&
Douglas Gregord5cb8762009-10-07 00:13:32 +00004172 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregor9302da62009-10-14 23:50:59 +00004173 TemplateNameLoc,
4174 isPartialSpecialization))
Douglas Gregor212e81c2009-03-25 00:13:59 +00004175 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004176
Douglas Gregorb88e8882009-07-30 17:40:51 +00004177 // The canonical type
4178 QualType CanonType;
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004179 if (PrevDecl &&
4180 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregorde090962010-02-09 00:37:32 +00004181 TUK == TUK_Friend)) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004182 // Since the only prior class template specialization with these
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004183 // arguments was referenced but not declared, or we're only
4184 // referencing this specialization as a friend, reuse that
Douglas Gregorcc636682009-02-17 23:15:12 +00004185 // declaration node as our own, updating its source location to
4186 // reflect our new declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004187 Specialization = PrevDecl;
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004188 Specialization->setLocation(TemplateNameLoc);
Douglas Gregorcc636682009-02-17 23:15:12 +00004189 PrevDecl = 0;
Douglas Gregorb88e8882009-07-30 17:40:51 +00004190 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004191 } else if (isPartialSpecialization) {
Douglas Gregorb88e8882009-07-30 17:40:51 +00004192 // Build the canonical type that describes the converted template
4193 // arguments of the class template partial specialization.
Douglas Gregorde090962010-02-09 00:37:32 +00004194 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4195 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregorb9c66312010-12-23 17:13:55 +00004196 Converted.data(),
4197 Converted.size());
4198
4199 if (Context.hasSameType(CanonType,
4200 ClassTemplate->getInjectedClassNameSpecialization())) {
4201 // C++ [temp.class.spec]p9b3:
4202 //
4203 // -- The argument list of the specialization shall not be identical
4204 // to the implicit argument list of the primary template.
4205 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4206 << (TUK == TUK_Definition)
4207 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4208 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4209 ClassTemplate->getIdentifier(),
4210 TemplateNameLoc,
4211 Attr,
4212 TemplateParams,
4213 AS_none);
4214 }
Douglas Gregorb88e8882009-07-30 17:40:51 +00004215
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004216 // Create a new class template partial specialization declaration node.
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004217 ClassTemplatePartialSpecializationDecl *PrevPartial
4218 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004219 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004220 : ClassTemplate->getNextPartialSpecSequenceNumber();
Mike Stump1eb44332009-09-09 15:08:12 +00004221 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregor13c85772010-05-06 00:28:52 +00004222 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004223 ClassTemplate->getDeclContext(),
Anders Carlsson91fdf6f2009-06-05 04:06:48 +00004224 TemplateNameLoc,
4225 TemplateParams,
4226 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004227 Converted.data(),
4228 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00004229 TemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00004230 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00004231 PrevPartial,
4232 SequenceNumber);
John McCallb6217662010-03-15 10:12:16 +00004233 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004234 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004235 Partial->setTemplateParameterListsInfo(Context,
4236 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004237 (TemplateParameterList**) TemplateParameterLists.release());
4238 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004239
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004240 if (!PrevPartial)
4241 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004242 Specialization = Partial;
Douglas Gregor031a5882009-06-13 00:26:55 +00004243
Douglas Gregored9c0f92009-10-29 00:04:11 +00004244 // If we are providing an explicit specialization of a member class
4245 // template specialization, make a note of that.
4246 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4247 PrevPartial->setMemberSpecialization();
4248
Douglas Gregor031a5882009-06-13 00:26:55 +00004249 // Check that all of the template parameters of the class template
4250 // partial specialization are deducible from the template
4251 // arguments. If not, this class template partial specialization
4252 // will never be used.
4253 llvm::SmallVector<bool, 8> DeducibleParams;
4254 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore73bb602009-09-14 21:25:05 +00004255 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregored9c0f92009-10-29 00:04:11 +00004256 TemplateParams->getDepth(),
Douglas Gregore73bb602009-09-14 21:25:05 +00004257 DeducibleParams);
Douglas Gregor031a5882009-06-13 00:26:55 +00004258 unsigned NumNonDeducible = 0;
4259 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4260 if (!DeducibleParams[I])
4261 ++NumNonDeducible;
4262
4263 if (NumNonDeducible) {
4264 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4265 << (NumNonDeducible > 1)
4266 << SourceRange(TemplateNameLoc, RAngleLoc);
4267 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4268 if (!DeducibleParams[I]) {
4269 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4270 if (Param->getDeclName())
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)
4273 << Param->getDeclName();
4274 else
Mike Stump1eb44332009-09-09 15:08:12 +00004275 Diag(Param->getLocation(),
Douglas Gregor031a5882009-06-13 00:26:55 +00004276 diag::note_partial_spec_unused_parameter)
Benjamin Kramer476d8b82010-08-11 14:47:12 +00004277 << "<anonymous>";
Douglas Gregor031a5882009-06-13 00:26:55 +00004278 }
4279 }
4280 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004281 } else {
4282 // Create a new class template specialization declaration node for
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004283 // this explicit specialization or friend declaration.
Douglas Gregorcc636682009-02-17 23:15:12 +00004284 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00004285 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregorcc636682009-02-17 23:15:12 +00004286 ClassTemplate->getDeclContext(),
4287 TemplateNameLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00004288 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00004289 Converted.data(),
4290 Converted.size(),
Douglas Gregorcc636682009-02-17 23:15:12 +00004291 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00004292 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor98c2e622010-07-28 23:59:57 +00004293 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
Douglas Gregorc722ea42010-06-15 17:44:38 +00004294 Specialization->setTemplateParameterListsInfo(Context,
4295 NumMatchedTemplateParamLists,
Abramo Bagnara9b934882010-06-12 08:15:14 +00004296 (TemplateParameterList**) TemplateParameterLists.release());
4297 }
Douglas Gregorcc636682009-02-17 23:15:12 +00004298
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00004299 if (!PrevDecl)
4300 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Douglas Gregorb88e8882009-07-30 17:40:51 +00004301
4302 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004303 }
4304
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004305 // C++ [temp.expl.spec]p6:
4306 // If a template, a member template or the member of a class template is
4307 // explicitly specialized then that specialization shall be declared
4308 // before the first use of that specialization that would cause an implicit
4309 // instantiation to take place, in every translation unit in which such a
4310 // use occurs; no diagnostic is required.
4311 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004312 bool Okay = false;
4313 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4314 // Is there any previous explicit specialization declaration?
4315 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4316 Okay = true;
4317 break;
4318 }
4319 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004320
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004321 if (!Okay) {
4322 SourceRange Range(TemplateNameLoc, RAngleLoc);
4323 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4324 << Context.getTypeDeclType(Specialization) << Range;
4325
4326 Diag(PrevDecl->getPointOfInstantiation(),
4327 diag::note_instantiation_required_here)
4328 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004329 != TSK_ImplicitInstantiation);
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004330 return true;
4331 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004332 }
4333
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004334 // If this is not a friend, note that this is an explicit specialization.
4335 if (TUK != TUK_Friend)
4336 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregorcc636682009-02-17 23:15:12 +00004337
4338 // Check that this isn't a redefinition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004339 if (TUK == TUK_Definition) {
Douglas Gregor952b0172010-02-11 01:04:33 +00004340 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregorcc636682009-02-17 23:15:12 +00004341 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004342 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregorc8ab2562009-05-31 09:31:02 +00004343 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregorcc636682009-02-17 23:15:12 +00004344 Diag(Def->getLocation(), diag::note_previous_definition);
4345 Specialization->setInvalidDecl();
Douglas Gregor212e81c2009-03-25 00:13:59 +00004346 return true;
Douglas Gregorcc636682009-02-17 23:15:12 +00004347 }
4348 }
4349
John McCall7f1b9872010-12-18 03:30:47 +00004350 if (Attr)
4351 ProcessDeclAttributeList(S, Specialization, Attr);
4352
Douglas Gregorfc705b82009-02-26 22:19:44 +00004353 // Build the fully-sugared type for this class template
4354 // specialization as the user wrote in the specialization
4355 // itself. This means that we'll pretty-print the type retrieved
4356 // from the specialization's declaration the way that the user
4357 // actually wrote the specialization, rather than formatting the
4358 // name based on the "canonical" representation used to store the
4359 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00004360 TypeSourceInfo *WrittenTy
4361 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4362 TemplateArgs, CanonType);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004363 if (TUK != TUK_Friend) {
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004364 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregor7e9b57b2010-07-06 18:33:12 +00004365 if (TemplateParams)
4366 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004367 }
Douglas Gregor40808ce2009-03-09 23:48:35 +00004368 TemplateArgsIn.release();
Douglas Gregorcc636682009-02-17 23:15:12 +00004369
Douglas Gregor6bc9f7e2009-02-25 22:18:32 +00004370 // C++ [temp.expl.spec]p9:
4371 // A template explicit specialization is in the scope of the
4372 // namespace in which the template was defined.
4373 //
4374 // We actually implement this paragraph where we set the semantic
4375 // context (in the creation of the ClassTemplateSpecializationDecl),
4376 // but we also maintain the lexical context where the actual
4377 // definition occurs.
Douglas Gregorcc636682009-02-17 23:15:12 +00004378 Specialization->setLexicalDeclContext(CurContext);
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Douglas Gregorcc636682009-02-17 23:15:12 +00004380 // We may be starting the definition of this specialization.
John McCall0f434ec2009-07-31 02:45:11 +00004381 if (TUK == TUK_Definition)
Douglas Gregorcc636682009-02-17 23:15:12 +00004382 Specialization->startDefinition();
4383
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004384 if (TUK == TUK_Friend) {
4385 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4386 TemplateNameLoc,
John McCall32f2fb52010-03-25 18:04:51 +00004387 WrittenTy,
Douglas Gregorfc9cd612009-09-26 20:57:03 +00004388 /*FIXME:*/KWLoc);
4389 Friend->setAccess(AS_public);
4390 CurContext->addDecl(Friend);
4391 } else {
4392 // Add the specialization into its lexical context, so that it can
4393 // be seen when iterating through the list of declarations in that
4394 // context. However, specializations are not found by name lookup.
4395 CurContext->addDecl(Specialization);
4396 }
John McCalld226f652010-08-21 09:40:31 +00004397 return Specialization;
Douglas Gregorcc636682009-02-17 23:15:12 +00004398}
Douglas Gregord57959a2009-03-27 23:10:48 +00004399
John McCalld226f652010-08-21 09:40:31 +00004400Decl *Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregore542c862009-06-23 23:11:28 +00004401 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004402 Declarator &D) {
Douglas Gregore542c862009-06-23 23:11:28 +00004403 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4404}
4405
John McCalld226f652010-08-21 09:40:31 +00004406Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor52591bf2009-06-24 00:54:41 +00004407 MultiTemplateParamsArg TemplateParameterLists,
John McCalld226f652010-08-21 09:40:31 +00004408 Declarator &D) {
Douglas Gregor52591bf2009-06-24 00:54:41 +00004409 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Abramo Bagnara075f8f12010-12-10 16:29:40 +00004410 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00004411
Douglas Gregor52591bf2009-06-24 00:54:41 +00004412 if (FTI.hasPrototype) {
Mike Stump1eb44332009-09-09 15:08:12 +00004413 // FIXME: Diagnose arguments without names in C.
Douglas Gregor52591bf2009-06-24 00:54:41 +00004414 }
Mike Stump1eb44332009-09-09 15:08:12 +00004415
Douglas Gregor52591bf2009-06-24 00:54:41 +00004416 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +00004417
John McCalld226f652010-08-21 09:40:31 +00004418 Decl *DP = HandleDeclarator(ParentScope, D,
4419 move(TemplateParameterLists),
4420 /*IsFunctionDefinition=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004421 if (FunctionTemplateDecl *FunctionTemplate
John McCalld226f652010-08-21 09:40:31 +00004422 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
Mike Stump1eb44332009-09-09 15:08:12 +00004423 return ActOnStartOfFunctionDef(FnBodyScope,
John McCalld226f652010-08-21 09:40:31 +00004424 FunctionTemplate->getTemplatedDecl());
4425 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4426 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4427 return 0;
Douglas Gregor52591bf2009-06-24 00:54:41 +00004428}
4429
John McCall75042392010-02-11 01:33:53 +00004430/// \brief Strips various properties off an implicit instantiation
4431/// that has just been explicitly specialized.
4432static void StripImplicitInstantiation(NamedDecl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00004433 D->dropAttrs();
John McCall75042392010-02-11 01:33:53 +00004434
4435 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4436 FD->setInlineSpecified(false);
4437 }
4438}
4439
Douglas Gregor454885e2009-10-15 15:54:05 +00004440/// \brief Diagnose cases where we have an explicit template specialization
4441/// before/after an explicit template instantiation, producing diagnostics
4442/// for those cases where they are required and determining whether the
4443/// new specialization/instantiation will have any effect.
4444///
Douglas Gregor454885e2009-10-15 15:54:05 +00004445/// \param NewLoc the location of the new explicit specialization or
4446/// instantiation.
4447///
4448/// \param NewTSK the kind of the new explicit specialization or instantiation.
4449///
4450/// \param PrevDecl the previous declaration of the entity.
4451///
4452/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4453///
4454/// \param PrevPointOfInstantiation if valid, indicates where the previus
4455/// declaration was instantiated (either implicitly or explicitly).
4456///
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004457/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregor454885e2009-10-15 15:54:05 +00004458/// specialization or instantiation has no effect and should be ignored.
4459///
4460/// \returns true if there was an error that should prevent the introduction of
4461/// the new declaration into the AST, false otherwise.
Douglas Gregor0d035142009-10-27 18:42:08 +00004462bool
4463Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4464 TemplateSpecializationKind NewTSK,
4465 NamedDecl *PrevDecl,
4466 TemplateSpecializationKind PrevTSK,
4467 SourceLocation PrevPointOfInstantiation,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004468 bool &HasNoEffect) {
4469 HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00004470
4471 switch (NewTSK) {
4472 case TSK_Undeclared:
4473 case TSK_ImplicitInstantiation:
4474 assert(false && "Don't check implicit instantiations here");
4475 return false;
4476
4477 case TSK_ExplicitSpecialization:
4478 switch (PrevTSK) {
4479 case TSK_Undeclared:
4480 case TSK_ExplicitSpecialization:
4481 // Okay, we're just specializing something that is either already
4482 // explicitly specialized or has merely been mentioned without any
4483 // instantiation.
4484 return false;
4485
4486 case TSK_ImplicitInstantiation:
4487 if (PrevPointOfInstantiation.isInvalid()) {
4488 // The declaration itself has not actually been instantiated, so it is
4489 // still okay to specialize it.
John McCall75042392010-02-11 01:33:53 +00004490 StripImplicitInstantiation(PrevDecl);
Douglas Gregor454885e2009-10-15 15:54:05 +00004491 return false;
4492 }
4493 // Fall through
4494
4495 case TSK_ExplicitInstantiationDeclaration:
4496 case TSK_ExplicitInstantiationDefinition:
4497 assert((PrevTSK == TSK_ImplicitInstantiation ||
4498 PrevPointOfInstantiation.isValid()) &&
4499 "Explicit instantiation without point of instantiation?");
4500
4501 // C++ [temp.expl.spec]p6:
4502 // If a template, a member template or the member of a class template
4503 // is explicitly specialized then that specialization shall be declared
4504 // before the first use of that specialization that would cause an
4505 // implicit instantiation to take place, in every translation unit in
4506 // which such a use occurs; no diagnostic is required.
Douglas Gregordc0a11c2010-02-26 06:03:23 +00004507 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4508 // Is there any previous explicit specialization declaration?
4509 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4510 return false;
4511 }
4512
Douglas Gregor0d035142009-10-27 18:42:08 +00004513 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregor454885e2009-10-15 15:54:05 +00004514 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004515 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregor454885e2009-10-15 15:54:05 +00004516 << (PrevTSK != TSK_ImplicitInstantiation);
4517
4518 return true;
4519 }
4520 break;
4521
4522 case TSK_ExplicitInstantiationDeclaration:
4523 switch (PrevTSK) {
4524 case TSK_ExplicitInstantiationDeclaration:
4525 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004526 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004527 return false;
4528
4529 case TSK_Undeclared:
4530 case TSK_ImplicitInstantiation:
4531 // We're explicitly instantiating something that may have already been
4532 // implicitly instantiated; that's fine.
4533 return false;
4534
4535 case TSK_ExplicitSpecialization:
4536 // C++0x [temp.explicit]p4:
4537 // For a given set of template parameters, if an explicit instantiation
4538 // of a template appears after a declaration of an explicit
4539 // specialization for that template, the explicit instantiation has no
4540 // effect.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004541 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004542 return false;
4543
4544 case TSK_ExplicitInstantiationDefinition:
4545 // C++0x [temp.explicit]p10:
4546 // If an entity is the subject of both an explicit instantiation
4547 // declaration and an explicit instantiation definition in the same
4548 // translation unit, the definition shall follow the declaration.
Douglas Gregor0d035142009-10-27 18:42:08 +00004549 Diag(NewLoc,
4550 diag::err_explicit_instantiation_declaration_after_definition);
4551 Diag(PrevPointOfInstantiation,
4552 diag::note_explicit_instantiation_definition_here);
Douglas Gregor454885e2009-10-15 15:54:05 +00004553 assert(PrevPointOfInstantiation.isValid() &&
4554 "Explicit instantiation without point of instantiation?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004555 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004556 return false;
4557 }
4558 break;
4559
4560 case TSK_ExplicitInstantiationDefinition:
4561 switch (PrevTSK) {
4562 case TSK_Undeclared:
4563 case TSK_ImplicitInstantiation:
4564 // We're explicitly instantiating something that may have already been
4565 // implicitly instantiated; that's fine.
4566 return false;
4567
4568 case TSK_ExplicitSpecialization:
4569 // C++ DR 259, C++0x [temp.explicit]p4:
4570 // For a given set of template parameters, if an explicit
4571 // instantiation of a template appears after a declaration of
4572 // an explicit specialization for that template, the explicit
4573 // instantiation has no effect.
4574 //
4575 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregorc42b6522010-04-09 21:02:29 +00004576 // is not harmful to try to explicitly instantiate something that
Douglas Gregor454885e2009-10-15 15:54:05 +00004577 // has been explicitly specialized.
Douglas Gregor0d035142009-10-27 18:42:08 +00004578 if (!getLangOptions().CPlusPlus0x) {
4579 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregor454885e2009-10-15 15:54:05 +00004580 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004581 Diag(PrevDecl->getLocation(),
Douglas Gregor454885e2009-10-15 15:54:05 +00004582 diag::note_previous_template_specialization);
4583 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004584 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004585 return false;
4586
4587 case TSK_ExplicitInstantiationDeclaration:
4588 // We're explicity instantiating a definition for something for which we
4589 // were previously asked to suppress instantiations. That's fine.
4590 return false;
4591
4592 case TSK_ExplicitInstantiationDefinition:
4593 // C++0x [temp.spec]p5:
4594 // For a given template and a given set of template-arguments,
4595 // - an explicit instantiation definition shall appear at most once
4596 // in a program,
Douglas Gregor0d035142009-10-27 18:42:08 +00004597 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregor454885e2009-10-15 15:54:05 +00004598 << PrevDecl;
Douglas Gregor0d035142009-10-27 18:42:08 +00004599 Diag(PrevPointOfInstantiation,
4600 diag::note_previous_explicit_instantiation);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004601 HasNoEffect = true;
Douglas Gregor454885e2009-10-15 15:54:05 +00004602 return false;
4603 }
4604 break;
4605 }
4606
4607 assert(false && "Missing specialization/instantiation case?");
4608
4609 return false;
4610}
4611
John McCallaf2094e2010-04-08 09:05:18 +00004612/// \brief Perform semantic analysis for the given dependent function
4613/// template specialization. The only possible way to get a dependent
4614/// function template specialization is with a friend declaration,
4615/// like so:
4616///
4617/// template <class T> void foo(T);
4618/// template <class T> class A {
4619/// friend void foo<>(T);
4620/// };
4621///
4622/// There really isn't any useful analysis we can do here, so we
4623/// just store the information.
4624bool
4625Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4626 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4627 LookupResult &Previous) {
4628 // Remove anything from Previous that isn't a function template in
4629 // the correct context.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004630 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCallaf2094e2010-04-08 09:05:18 +00004631 LookupResult::Filter F = Previous.makeFilter();
4632 while (F.hasNext()) {
4633 NamedDecl *D = F.next()->getUnderlyingDecl();
4634 if (!isa<FunctionTemplateDecl>(D) ||
Sebastian Redl7a126a42010-08-31 00:36:30 +00004635 !FDLookupContext->InEnclosingNamespaceSetOf(
4636 D->getDeclContext()->getRedeclContext()))
John McCallaf2094e2010-04-08 09:05:18 +00004637 F.erase();
4638 }
4639 F.done();
4640
4641 // Should this be diagnosed here?
4642 if (Previous.empty()) return true;
4643
4644 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4645 ExplicitTemplateArgs);
4646 return false;
4647}
4648
Abramo Bagnarae03db982010-05-20 15:32:11 +00004649/// \brief Perform semantic analysis for the given function template
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004650/// specialization.
4651///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004652/// This routine performs all of the semantic analysis required for an
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004653/// explicit function template specialization. On successful completion,
4654/// the function declaration \p FD will become a function template
4655/// specialization.
4656///
4657/// \param FD the function declaration, which will be updated to become a
4658/// function template specialization.
4659///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004660/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4661/// if any. Note that this may be valid info even when 0 arguments are
4662/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4663/// as it anyway contains info on the angle brackets locations.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004664///
Abramo Bagnarae03db982010-05-20 15:32:11 +00004665/// \param PrevDecl the set of declarations that may be specialized by
4666/// this function specialization.
4667bool
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004668Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCalld5532b62009-11-23 01:53:49 +00004669 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall68263142009-11-18 22:49:29 +00004670 LookupResult &Previous) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004671 // The set of function template specializations that could match this
4672 // explicit function template specialization.
John McCallc373d482010-01-27 01:50:18 +00004673 UnresolvedSet<8> Candidates;
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004674
Sebastian Redl7a126a42010-08-31 00:36:30 +00004675 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
John McCall68263142009-11-18 22:49:29 +00004676 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4677 I != E; ++I) {
4678 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4679 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004680 // Only consider templates found within the same semantic lookup scope as
4681 // FD.
Sebastian Redl7a126a42010-08-31 00:36:30 +00004682 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4683 Ovl->getDeclContext()->getRedeclContext()))
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004684 continue;
4685
4686 // C++ [temp.expl.spec]p11:
4687 // A trailing template-argument can be left unspecified in the
4688 // template-id naming an explicit function template specialization
4689 // provided it can be deduced from the function argument type.
4690 // Perform template argument deduction to determine whether we may be
4691 // specializing this template.
4692 // FIXME: It is somewhat wasteful to build
John McCall5769d612010-02-08 23:07:23 +00004693 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004694 FunctionDecl *Specialization = 0;
4695 if (TemplateDeductionResult TDK
John McCalld5532b62009-11-23 01:53:49 +00004696 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004697 FD->getType(),
4698 Specialization,
4699 Info)) {
4700 // FIXME: Template argument deduction failed; record why it failed, so
4701 // that we can provide nifty diagnostics.
4702 (void)TDK;
4703 continue;
4704 }
4705
4706 // Record this candidate.
John McCallc373d482010-01-27 01:50:18 +00004707 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004708 }
4709 }
4710
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004711 // Find the most specialized function template.
John McCallc373d482010-01-27 01:50:18 +00004712 UnresolvedSetIterator Result
4713 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4714 TPOC_Other, FD->getLocation(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004715 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregorc5df30f2009-09-26 03:41:46 +00004716 << FD->getDeclName(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004717 PDiag(diag::err_function_template_spec_ambiguous)
John McCalld5532b62009-11-23 01:53:49 +00004718 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00004719 PDiag(diag::note_function_template_spec_matched));
John McCallc373d482010-01-27 01:50:18 +00004720 if (Result == Candidates.end())
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004721 return true;
John McCallc373d482010-01-27 01:50:18 +00004722
4723 // Ignore access information; it doesn't figure into redeclaration checking.
4724 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregorc42b6522010-04-09 21:02:29 +00004725 Specialization->setLocation(FD->getLocation());
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004726
4727 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004728 // If so, we have run afoul of .
John McCall7ad650f2010-03-24 07:46:06 +00004729
4730 // If this is a friend declaration, then we're not really declaring
4731 // an explicit specialization.
4732 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004733
Douglas Gregord5cb8762009-10-07 00:13:32 +00004734 // Check the scope of this explicit specialization.
John McCall7ad650f2010-03-24 07:46:06 +00004735 if (!isFriend &&
4736 CheckTemplateSpecializationScope(*this,
Douglas Gregord5cb8762009-10-07 00:13:32 +00004737 Specialization->getPrimaryTemplate(),
4738 Specialization, FD->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004739 false))
Douglas Gregord5cb8762009-10-07 00:13:32 +00004740 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004741
4742 // C++ [temp.expl.spec]p6:
4743 // If a template, a member template or the member of a class template is
Douglas Gregor0d035142009-10-27 18:42:08 +00004744 // explicitly specialized then that specialization shall be declared
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004745 // before the first use of that specialization that would cause an implicit
4746 // instantiation to take place, in every translation unit in which such a
4747 // use occurs; no diagnostic is required.
4748 FunctionTemplateSpecializationInfo *SpecInfo
4749 = Specialization->getTemplateSpecializationInfo();
4750 assert(SpecInfo && "Function template specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004751
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004752 bool HasNoEffect = false;
John McCall7ad650f2010-03-24 07:46:06 +00004753 if (!isFriend &&
4754 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall75042392010-02-11 01:33:53 +00004755 TSK_ExplicitSpecialization,
4756 Specialization,
4757 SpecInfo->getTemplateSpecializationKind(),
4758 SpecInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004759 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004760 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00004761
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004762 // Mark the prior declaration as an explicit specialization, so that later
4763 // clients know that this is an explicit specialization.
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004764 if (!isFriend) {
John McCall7ad650f2010-03-24 07:46:06 +00004765 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004766 MarkUnusedFileScopedDecl(Specialization);
4767 }
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004768
4769 // Turn the given function declaration into a function template
4770 // specialization, with the template arguments from the previous
4771 // specialization.
Abramo Bagnarae03db982010-05-20 15:32:11 +00004772 // Take copies of (semantic and syntactic) template argument lists.
4773 const TemplateArgumentList* TemplArgs = new (Context)
4774 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4775 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4776 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregor838db382010-02-11 01:19:42 +00004777 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnarae03db982010-05-20 15:32:11 +00004778 TemplArgs, /*InsertPos=*/0,
4779 SpecInfo->getTemplateSpecializationKind(),
4780 TemplArgsAsWritten);
4781
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004782 // The "previous declaration" for this function template specialization is
4783 // the prior function template specialization.
John McCall68263142009-11-18 22:49:29 +00004784 Previous.clear();
4785 Previous.addDecl(Specialization);
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00004786 return false;
4787}
4788
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004789/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004790/// specialization.
4791///
4792/// This routine performs all of the semantic analysis required for an
4793/// explicit member function specialization. On successful completion,
4794/// the function declaration \p FD will become a member function
4795/// specialization.
4796///
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004797/// \param Member the member declaration, which will be updated to become a
4798/// specialization.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004799///
John McCall68263142009-11-18 22:49:29 +00004800/// \param Previous the set of declarations, one of which may be specialized
4801/// by this function specialization; the set will be modified to contain the
4802/// redeclared member.
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004803bool
John McCall68263142009-11-18 22:49:29 +00004804Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004805 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCall77e8b112010-04-13 20:37:33 +00004806
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004807 // Try to find the member we are instantiating.
4808 NamedDecl *Instantiation = 0;
4809 NamedDecl *InstantiatedFrom = 0;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004810 MemberSpecializationInfo *MSInfo = 0;
4811
John McCall68263142009-11-18 22:49:29 +00004812 if (Previous.empty()) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004813 // Nowhere to look anyway.
4814 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004815 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4816 I != E; ++I) {
4817 NamedDecl *D = (*I)->getUnderlyingDecl();
4818 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004819 if (Context.hasSameType(Function->getType(), Method->getType())) {
4820 Instantiation = Method;
4821 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004822 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004823 break;
4824 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004825 }
4826 }
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004827 } else if (isa<VarDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004828 VarDecl *PrevVar;
4829 if (Previous.isSingleResult() &&
4830 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004831 if (PrevVar->isStaticDataMember()) {
John McCall68263142009-11-18 22:49:29 +00004832 Instantiation = PrevVar;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004833 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004834 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004835 }
4836 } else if (isa<RecordDecl>(Member)) {
John McCall68263142009-11-18 22:49:29 +00004837 CXXRecordDecl *PrevRecord;
4838 if (Previous.isSingleResult() &&
4839 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4840 Instantiation = PrevRecord;
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004841 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004842 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004843 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004844 }
4845
4846 if (!Instantiation) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004847 // There is no previous declaration that matches. Since member
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004848 // specializations are always out-of-line, the caller will complain about
4849 // this mismatch later.
4850 return false;
4851 }
John McCall77e8b112010-04-13 20:37:33 +00004852
4853 // If this is a friend, just bail out here before we start turning
4854 // things into explicit specializations.
4855 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4856 // Preserve instantiation information.
4857 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4858 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4859 cast<CXXMethodDecl>(InstantiatedFrom),
4860 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4861 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4862 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4863 cast<CXXRecordDecl>(InstantiatedFrom),
4864 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4865 }
4866
4867 Previous.clear();
4868 Previous.addDecl(Instantiation);
4869 return false;
4870 }
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004871
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004872 // Make sure that this is a specialization of a member.
4873 if (!InstantiatedFrom) {
4874 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4875 << Member;
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004876 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4877 return true;
4878 }
4879
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004880 // C++ [temp.expl.spec]p6:
4881 // If a template, a member template or the member of a class template is
4882 // explicitly specialized then that spe- cialization shall be declared
4883 // before the first use of that specialization that would cause an implicit
4884 // instantiation to take place, in every translation unit in which such a
4885 // use occurs; no diagnostic is required.
4886 assert(MSInfo && "Member specialization info missing?");
John McCall75042392010-02-11 01:33:53 +00004887
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004888 bool HasNoEffect = false;
John McCall75042392010-02-11 01:33:53 +00004889 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4890 TSK_ExplicitSpecialization,
4891 Instantiation,
4892 MSInfo->getTemplateSpecializationKind(),
4893 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00004894 HasNoEffect))
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004895 return true;
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00004896
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004897 // Check the scope of this explicit specialization.
4898 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004899 InstantiatedFrom,
4900 Instantiation, Member->getLocation(),
Douglas Gregor9302da62009-10-14 23:50:59 +00004901 false))
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004902 return true;
Douglas Gregor2db32322009-10-07 23:56:10 +00004903
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004904 // Note that this is an explicit instantiation of a member.
Douglas Gregorf6b11852009-10-08 15:14:33 +00004905 // the original declaration to note that it is an explicit specialization
4906 // (if it was previously an implicit instantiation). This latter step
4907 // makes bookkeeping easier.
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004908 if (isa<FunctionDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004909 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4910 if (InstantiationFunction->getTemplateSpecializationKind() ==
4911 TSK_ImplicitInstantiation) {
4912 InstantiationFunction->setTemplateSpecializationKind(
4913 TSK_ExplicitSpecialization);
4914 InstantiationFunction->setLocation(Member->getLocation());
4915 }
4916
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004917 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4918 cast<CXXMethodDecl>(InstantiatedFrom),
4919 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004920 MarkUnusedFileScopedDecl(InstantiationFunction);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004921 } else if (isa<VarDecl>(Member)) {
Douglas Gregorf6b11852009-10-08 15:14:33 +00004922 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4923 if (InstantiationVar->getTemplateSpecializationKind() ==
4924 TSK_ImplicitInstantiation) {
4925 InstantiationVar->setTemplateSpecializationKind(
4926 TSK_ExplicitSpecialization);
4927 InstantiationVar->setLocation(Member->getLocation());
4928 }
4929
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004930 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4931 cast<VarDecl>(InstantiatedFrom),
4932 TSK_ExplicitSpecialization);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00004933 MarkUnusedFileScopedDecl(InstantiationVar);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004934 } else {
4935 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorf6b11852009-10-08 15:14:33 +00004936 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4937 if (InstantiationClass->getTemplateSpecializationKind() ==
4938 TSK_ImplicitInstantiation) {
4939 InstantiationClass->setTemplateSpecializationKind(
4940 TSK_ExplicitSpecialization);
4941 InstantiationClass->setLocation(Member->getLocation());
4942 }
4943
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004944 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorf6b11852009-10-08 15:14:33 +00004945 cast<CXXRecordDecl>(InstantiatedFrom),
4946 TSK_ExplicitSpecialization);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00004947 }
4948
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004949 // Save the caller the trouble of having to figure out which declaration
4950 // this specialization matches.
John McCall68263142009-11-18 22:49:29 +00004951 Previous.clear();
4952 Previous.addDecl(Instantiation);
Douglas Gregor1fef4e62009-10-07 22:35:40 +00004953 return false;
4954}
4955
Douglas Gregor558c0322009-10-14 23:41:34 +00004956/// \brief Check the scope of an explicit instantiation.
Douglas Gregor669eed82010-07-13 00:10:04 +00004957///
4958/// \returns true if a serious error occurs, false otherwise.
4959static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
Douglas Gregor558c0322009-10-14 23:41:34 +00004960 SourceLocation InstLoc,
4961 bool WasQualifiedName) {
Sebastian Redl7a126a42010-08-31 00:36:30 +00004962 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
4963 DeclContext *CurContext = S.CurContext->getRedeclContext();
Douglas Gregor558c0322009-10-14 23:41:34 +00004964
Douglas Gregor669eed82010-07-13 00:10:04 +00004965 if (CurContext->isRecord()) {
4966 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
4967 << D;
4968 return true;
4969 }
4970
Douglas Gregor558c0322009-10-14 23:41:34 +00004971 // C++0x [temp.explicit]p2:
4972 // An explicit instantiation shall appear in an enclosing namespace of its
4973 // template.
4974 //
4975 // This is DR275, which we do not retroactively apply to C++98/03.
4976 if (S.getLangOptions().CPlusPlus0x &&
Sebastian Redl7a126a42010-08-31 00:36:30 +00004977 !CurContext->Encloses(OrigContext)) {
4978 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
Douglas Gregor2166beb2010-05-11 17:39:34 +00004979 S.Diag(InstLoc,
4980 S.getLangOptions().CPlusPlus0x?
4981 diag::err_explicit_instantiation_out_of_scope
4982 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004983 << D << NS;
4984 else
Douglas Gregor2166beb2010-05-11 17:39:34 +00004985 S.Diag(InstLoc,
4986 S.getLangOptions().CPlusPlus0x?
4987 diag::err_explicit_instantiation_must_be_global
4988 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregor558c0322009-10-14 23:41:34 +00004989 << D;
4990 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00004991 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00004992 }
Sebastian Redl7a126a42010-08-31 00:36:30 +00004993
Douglas Gregor558c0322009-10-14 23:41:34 +00004994 // C++0x [temp.explicit]p2:
4995 // If the name declared in the explicit instantiation is an unqualified
4996 // name, the explicit instantiation shall appear in the namespace where
4997 // its template is declared or, if that namespace is inline (7.3.1), any
4998 // namespace from its enclosing namespace set.
4999 if (WasQualifiedName)
Douglas Gregor669eed82010-07-13 00:10:04 +00005000 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005001
5002 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
Douglas Gregor669eed82010-07-13 00:10:04 +00005003 return false;
Sebastian Redl7a126a42010-08-31 00:36:30 +00005004
Douglas Gregor2166beb2010-05-11 17:39:34 +00005005 S.Diag(InstLoc,
5006 S.getLangOptions().CPlusPlus0x?
5007 diag::err_explicit_instantiation_unqualified_wrong_namespace
5008 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Sebastian Redl7a126a42010-08-31 00:36:30 +00005009 << D << OrigContext;
Douglas Gregor558c0322009-10-14 23:41:34 +00005010 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor669eed82010-07-13 00:10:04 +00005011 return false;
Douglas Gregor558c0322009-10-14 23:41:34 +00005012}
5013
5014/// \brief Determine whether the given scope specifier has a template-id in it.
5015static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5016 if (!SS.isSet())
5017 return false;
5018
5019 // C++0x [temp.explicit]p2:
5020 // If the explicit instantiation is for a member function, a member class
5021 // or a static data member of a class template specialization, the name of
5022 // the class template specialization in the qualified-id for the member
5023 // name shall be a simple-template-id.
5024 //
5025 // C++98 has the same restriction, just worded differently.
5026 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5027 NNS; NNS = NNS->getPrefix())
5028 if (Type *T = NNS->getAsType())
5029 if (isa<TemplateSpecializationType>(T))
5030 return true;
5031
5032 return false;
5033}
5034
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005035// Explicit instantiation of a class template specialization
John McCallf312b1e2010-08-26 23:41:50 +00005036DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005037Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005038 SourceLocation ExternLoc,
5039 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005040 unsigned TagSpec,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005041 SourceLocation KWLoc,
5042 const CXXScopeSpec &SS,
5043 TemplateTy TemplateD,
5044 SourceLocation TemplateNameLoc,
5045 SourceLocation LAngleLoc,
5046 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005047 SourceLocation RAngleLoc,
5048 AttributeList *Attr) {
5049 // Find the class template we're specializing
5050 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump1eb44332009-09-09 15:08:12 +00005051 ClassTemplateDecl *ClassTemplate
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005052 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5053
5054 // Check that the specialization uses the same tag kind as the
5055 // original template.
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005056 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5057 assert(Kind != TTK_Enum &&
5058 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005059 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump1eb44332009-09-09 15:08:12 +00005060 Kind, KWLoc,
Douglas Gregor501c5ce2009-05-14 16:41:31 +00005061 *ClassTemplate->getIdentifier())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005062 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005063 << ClassTemplate
Douglas Gregor849b2432010-03-31 17:46:05 +00005064 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005065 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump1eb44332009-09-09 15:08:12 +00005066 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005067 diag::note_previous_use);
5068 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5069 }
5070
Douglas Gregor558c0322009-10-14 23:41:34 +00005071 // C++0x [temp.explicit]p2:
5072 // There are two forms of explicit instantiation: an explicit instantiation
5073 // definition and an explicit instantiation declaration. An explicit
5074 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5cb8762009-10-07 00:13:32 +00005075 TemplateSpecializationKind TSK
5076 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5077 : TSK_ExplicitInstantiationDeclaration;
5078
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005079 // Translate the parser's template argument list in our AST format.
John McCalld5532b62009-11-23 01:53:49 +00005080 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregor314b97f2009-11-10 19:49:08 +00005081 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005082
5083 // Check that the template argument list is well-formed for this
5084 // template.
Douglas Gregor910f8002010-11-07 23:05:16 +00005085 llvm::SmallVector<TemplateArgument, 4> Converted;
John McCalld5532b62009-11-23 01:53:49 +00005086 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5087 TemplateArgs, false, Converted))
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005088 return true;
5089
Douglas Gregor910f8002010-11-07 23:05:16 +00005090 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005091 "Converted template argument list is too short!");
Mike Stump1eb44332009-09-09 15:08:12 +00005092
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005093 // Find the class template specialization declaration that
5094 // corresponds to these arguments.
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005095 void *InsertPos = 0;
5096 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00005097 = ClassTemplate->findSpecialization(Converted.data(),
5098 Converted.size(), InsertPos);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005099
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005100 TemplateSpecializationKind PrevDecl_TSK
5101 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5102
Douglas Gregord5cb8762009-10-07 00:13:32 +00005103 // C++0x [temp.explicit]p2:
5104 // [...] An explicit instantiation shall appear in an enclosing
5105 // namespace of its template. [...]
5106 //
5107 // This is C++ DR 275.
Douglas Gregor669eed82010-07-13 00:10:04 +00005108 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5109 SS.isSet()))
5110 return true;
Douglas Gregord5cb8762009-10-07 00:13:32 +00005111
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005112 ClassTemplateSpecializationDecl *Specialization = 0;
5113
Douglas Gregord78f5982009-11-25 06:01:46 +00005114 bool ReusedDecl = false;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005115 bool HasNoEffect = false;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005116 if (PrevDecl) {
Douglas Gregor0d035142009-10-27 18:42:08 +00005117 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005118 PrevDecl, PrevDecl_TSK,
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005119 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005120 HasNoEffect))
John McCalld226f652010-08-21 09:40:31 +00005121 return PrevDecl;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005122
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005123 // Even though HasNoEffect == true means that this explicit instantiation
5124 // has no effect on semantics, we go on to put its syntax in the AST.
5125
5126 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5127 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor52604ab2009-09-11 21:19:12 +00005128 // Since the only prior class template specialization with these
5129 // arguments was referenced but not declared, reuse that
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005130 // declaration node as our own, updating the source location
5131 // for the template name to reflect our new declaration.
5132 // (Other source locations will be updated later.)
Douglas Gregor52604ab2009-09-11 21:19:12 +00005133 Specialization = PrevDecl;
5134 Specialization->setLocation(TemplateNameLoc);
5135 PrevDecl = 0;
Douglas Gregord78f5982009-11-25 06:01:46 +00005136 ReusedDecl = true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00005137 }
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005138 }
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005139
Douglas Gregor52604ab2009-09-11 21:19:12 +00005140 if (!Specialization) {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005141 // Create a new class template specialization declaration node for
5142 // this explicit specialization.
5143 Specialization
Douglas Gregor13c85772010-05-06 00:28:52 +00005144 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005145 ClassTemplate->getDeclContext(),
5146 TemplateNameLoc,
5147 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00005148 Converted.data(),
5149 Converted.size(),
5150 PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00005151 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005152
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005153 if (!HasNoEffect && !PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005154 // Insert the new specialization.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00005155 ClassTemplate->AddSpecialization(Specialization, InsertPos);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005156 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005157 }
5158
5159 // Build the fully-sugared type for this explicit instantiation as
5160 // the user wrote in the explicit instantiation itself. This means
5161 // that we'll pretty-print the type retrieved from the
5162 // specialization's declaration the way that the user actually wrote
5163 // the explicit instantiation, rather than formatting the name based
5164 // on the "canonical" representation used to store the template
5165 // arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00005166 TypeSourceInfo *WrittenTy
5167 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5168 TemplateArgs,
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005169 Context.getTypeDeclType(Specialization));
5170 Specialization->setTypeAsWritten(WrittenTy);
5171 TemplateArgsIn.release();
5172
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005173 // Set source locations for keywords.
5174 Specialization->setExternLoc(ExternLoc);
5175 Specialization->setTemplateKeywordLoc(TemplateLoc);
5176
5177 // Add the explicit instantiation into its lexical context. However,
5178 // since explicit instantiations are never found by name lookup, we
5179 // just put it into the declaration context directly.
5180 Specialization->setLexicalDeclContext(CurContext);
5181 CurContext->addDecl(Specialization);
5182
5183 // Syntax is now OK, so return if it has no other effect on semantics.
5184 if (HasNoEffect) {
5185 // Set the template specialization kind.
5186 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005187 return Specialization;
Douglas Gregord78f5982009-11-25 06:01:46 +00005188 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005189
5190 // C++ [temp.explicit]p3:
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005191 // A definition of a class template or class member template
5192 // shall be in scope at the point of the explicit instantiation of
5193 // the class template or class member template.
5194 //
5195 // This check comes when we actually try to perform the
5196 // instantiation.
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005197 ClassTemplateSpecializationDecl *Def
5198 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005199 Specialization->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005200 if (!Def)
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005201 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005202 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005203 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005204 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5205 }
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005206
Douglas Gregor0d035142009-10-27 18:42:08 +00005207 // Instantiate the members of this class template specialization.
5208 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor952b0172010-02-11 01:04:33 +00005209 Specialization->getDefinition());
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005210 if (Def) {
Rafael Espindolaf075b222010-03-23 19:55:22 +00005211 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5212
5213 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5214 // TSK_ExplicitInstantiationDefinition
5215 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5216 TSK == TSK_ExplicitInstantiationDefinition)
5217 Def->setTemplateSpecializationKind(TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005218
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005219 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindolab0f65ca2010-03-22 23:12:48 +00005220 }
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005221
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005222 // Set the template specialization kind.
5223 Specialization->setTemplateSpecializationKind(TSK);
John McCalld226f652010-08-21 09:40:31 +00005224 return Specialization;
Douglas Gregor93dfdb12009-05-13 00:25:59 +00005225}
5226
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005227// Explicit instantiation of a member class of a class template.
John McCalld226f652010-08-21 09:40:31 +00005228DeclResult
Mike Stump1eb44332009-09-09 15:08:12 +00005229Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor45f96552009-09-04 06:33:52 +00005230 SourceLocation ExternLoc,
5231 SourceLocation TemplateLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005232 unsigned TagSpec,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005233 SourceLocation KWLoc,
Jeffrey Yasskin9ab14542010-04-08 16:38:48 +00005234 CXXScopeSpec &SS,
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005235 IdentifierInfo *Name,
5236 SourceLocation NameLoc,
5237 AttributeList *Attr) {
5238
Douglas Gregor402abb52009-05-28 23:31:59 +00005239 bool Owned = false;
John McCallc4e70192009-09-11 04:59:25 +00005240 bool IsDependent = false;
John McCallf312b1e2010-08-26 23:41:50 +00005241 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
John McCalld226f652010-08-21 09:40:31 +00005242 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5243 MultiTemplateParamsArg(*this, 0, 0),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +00005244 Owned, IsDependent, false, false,
Douglas Gregor1274ccd2010-10-08 23:50:27 +00005245 TypeResult());
John McCallc4e70192009-09-11 04:59:25 +00005246 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5247
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005248 if (!TagD)
5249 return true;
5250
John McCalld226f652010-08-21 09:40:31 +00005251 TagDecl *Tag = cast<TagDecl>(TagD);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005252 if (Tag->isEnum()) {
5253 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5254 << Context.getTypeDeclType(Tag);
5255 return true;
5256 }
5257
Douglas Gregord0c87372009-05-27 17:30:49 +00005258 if (Tag->isInvalidDecl())
5259 return true;
Douglas Gregor558c0322009-10-14 23:41:34 +00005260
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005261 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5262 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5263 if (!Pattern) {
5264 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5265 << Context.getTypeDeclType(Record);
5266 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5267 return true;
5268 }
5269
Douglas Gregor558c0322009-10-14 23:41:34 +00005270 // C++0x [temp.explicit]p2:
5271 // If the explicit instantiation is for a class or member class, the
5272 // elaborated-type-specifier in the declaration shall include a
5273 // simple-template-id.
5274 //
5275 // C++98 has the same restriction, just worded differently.
5276 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregora2dd8282010-06-16 16:26:47 +00005277 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005278 << Record << SS.getRange();
5279
5280 // C++0x [temp.explicit]p2:
5281 // There are two forms of explicit instantiation: an explicit instantiation
5282 // definition and an explicit instantiation declaration. An explicit
5283 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregora74bbe22009-10-14 21:46:58 +00005284 TemplateSpecializationKind TSK
5285 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5286 : TSK_ExplicitInstantiationDeclaration;
5287
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005288 // C++0x [temp.explicit]p2:
5289 // [...] An explicit instantiation shall appear in an enclosing
5290 // namespace of its template. [...]
5291 //
5292 // This is C++ DR 275.
Douglas Gregor558c0322009-10-14 23:41:34 +00005293 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregor454885e2009-10-15 15:54:05 +00005294
5295 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor583f33b2009-10-15 18:07:02 +00005296 CXXRecordDecl *PrevDecl
5297 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor952b0172010-02-11 01:04:33 +00005298 if (!PrevDecl && Record->getDefinition())
Douglas Gregor583f33b2009-10-15 18:07:02 +00005299 PrevDecl = Record;
5300 if (PrevDecl) {
Douglas Gregor454885e2009-10-15 15:54:05 +00005301 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005302 bool HasNoEffect = false;
Douglas Gregor454885e2009-10-15 15:54:05 +00005303 assert(MSInfo && "No member specialization information?");
Douglas Gregor0d035142009-10-27 18:42:08 +00005304 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregor454885e2009-10-15 15:54:05 +00005305 PrevDecl,
5306 MSInfo->getTemplateSpecializationKind(),
5307 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005308 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005309 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005310 if (HasNoEffect)
Douglas Gregor454885e2009-10-15 15:54:05 +00005311 return TagD;
5312 }
5313
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005314 CXXRecordDecl *RecordDef
Douglas Gregor952b0172010-02-11 01:04:33 +00005315 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor89a5bea2009-10-15 22:53:21 +00005316 if (!RecordDef) {
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005317 // C++ [temp.explicit]p3:
5318 // A definition of a member class of a class template shall be in scope
5319 // at the point of an explicit instantiation of the member class.
5320 CXXRecordDecl *Def
Douglas Gregor952b0172010-02-11 01:04:33 +00005321 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005322 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00005323 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5324 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregorbf7643e2009-10-15 12:53:22 +00005325 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5326 << Pattern;
5327 return true;
Douglas Gregor0d035142009-10-27 18:42:08 +00005328 } else {
5329 if (InstantiateClass(NameLoc, Record, Def,
5330 getTemplateInstantiationArgs(Record),
5331 TSK))
5332 return true;
5333
Douglas Gregor952b0172010-02-11 01:04:33 +00005334 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00005335 if (!RecordDef)
5336 return true;
5337 }
5338 }
5339
5340 // Instantiate all of the members of the class.
5341 InstantiateClassMembers(NameLoc, RecordDef,
5342 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005343
Douglas Gregor6fb745b2010-05-13 16:44:06 +00005344 if (TSK == TSK_ExplicitInstantiationDefinition)
5345 MarkVTableUsed(NameLoc, RecordDef, true);
5346
Mike Stump390b4cc2009-05-16 07:39:55 +00005347 // FIXME: We don't have any representation for explicit instantiations of
5348 // member classes. Such a representation is not needed for compilation, but it
5349 // should be available for clients that want to see all of the declarations in
5350 // the source code.
Douglas Gregor3f5b61c2009-05-14 00:28:11 +00005351 return TagD;
5352}
5353
John McCallf312b1e2010-08-26 23:41:50 +00005354DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5355 SourceLocation ExternLoc,
5356 SourceLocation TemplateLoc,
5357 Declarator &D) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005358 // Explicit instantiations always require a name.
Abramo Bagnara25777432010-08-11 22:01:17 +00005359 // TODO: check if/when DNInfo should replace Name.
5360 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5361 DeclarationName Name = NameInfo.getName();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005362 if (!Name) {
5363 if (!D.isInvalidType())
5364 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5365 diag::err_explicit_instantiation_requires_name)
5366 << D.getDeclSpec().getSourceRange()
5367 << D.getSourceRange();
5368
5369 return true;
5370 }
5371
5372 // The scope passed in may not be a decl scope. Zip up the scope tree until
5373 // we find one that is.
5374 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5375 (S->getFlags() & Scope::TemplateParamScope) != 0)
5376 S = S->getParent();
5377
5378 // Determine the type of the declaration.
John McCallbf1a0282010-06-04 23:28:52 +00005379 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5380 QualType R = T->getType();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005381 if (R.isNull())
5382 return true;
5383
5384 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5385 // Cannot explicitly instantiate a typedef.
5386 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5387 << Name;
5388 return true;
5389 }
5390
Douglas Gregor663b5a02009-10-14 20:14:33 +00005391 // C++0x [temp.explicit]p1:
5392 // [...] An explicit instantiation of a function template shall not use the
5393 // inline or constexpr specifiers.
5394 // Presumably, this also applies to member functions of class templates as
5395 // well.
5396 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5397 Diag(D.getDeclSpec().getInlineSpecLoc(),
5398 diag::err_explicit_instantiation_inline)
Douglas Gregor849b2432010-03-31 17:46:05 +00005399 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor663b5a02009-10-14 20:14:33 +00005400
5401 // FIXME: check for constexpr specifier.
5402
Douglas Gregor558c0322009-10-14 23:41:34 +00005403 // C++0x [temp.explicit]p2:
5404 // There are two forms of explicit instantiation: an explicit instantiation
5405 // definition and an explicit instantiation declaration. An explicit
5406 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregord5a423b2009-09-25 18:43:00 +00005407 TemplateSpecializationKind TSK
5408 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5409 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregor558c0322009-10-14 23:41:34 +00005410
Abramo Bagnara25777432010-08-11 22:01:17 +00005411 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005412 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005413
5414 if (!R->isFunctionType()) {
5415 // C++ [temp.explicit]p1:
5416 // A [...] static data member of a class template can be explicitly
5417 // instantiated from the member definition associated with its class
5418 // template.
John McCalla24dc2e2009-11-17 02:14:36 +00005419 if (Previous.isAmbiguous())
5420 return true;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005421
John McCall1bcee0a2009-12-02 08:25:40 +00005422 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregord5a423b2009-09-25 18:43:00 +00005423 if (!Prev || !Prev->isStaticDataMember()) {
5424 // We expect to see a data data member here.
5425 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5426 << Name;
5427 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5428 P != PEnd; ++P)
John McCallf36e02d2009-10-09 21:13:30 +00005429 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005430 return true;
5431 }
5432
5433 if (!Prev->getInstantiatedFromStaticDataMember()) {
5434 // FIXME: Check for explicit specialization?
5435 Diag(D.getIdentifierLoc(),
5436 diag::err_explicit_instantiation_data_member_not_instantiated)
5437 << Prev;
5438 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5439 // FIXME: Can we provide a note showing where this was declared?
5440 return true;
5441 }
5442
Douglas Gregor558c0322009-10-14 23:41:34 +00005443 // C++0x [temp.explicit]p2:
5444 // If the explicit instantiation is for a member function, a member class
5445 // or a static data member of a class template specialization, the name of
5446 // the class template specialization in the qualified-id for the member
5447 // name shall be a simple-template-id.
5448 //
5449 // C++98 has the same restriction, just worded differently.
5450 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5451 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005452 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005453 << Prev << D.getCXXScopeSpec().getRange();
5454
5455 // Check the scope of this explicit instantiation.
5456 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5457
Douglas Gregor454885e2009-10-15 15:54:05 +00005458 // Verify that it is okay to explicitly instantiate here.
5459 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5460 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005461 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005462 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregor454885e2009-10-15 15:54:05 +00005463 MSInfo->getTemplateSpecializationKind(),
5464 MSInfo->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005465 HasNoEffect))
Douglas Gregor454885e2009-10-15 15:54:05 +00005466 return true;
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005467 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005468 return (Decl*) 0;
Douglas Gregor454885e2009-10-15 15:54:05 +00005469
Douglas Gregord5a423b2009-09-25 18:43:00 +00005470 // Instantiate static data member.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005471 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005472 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005473 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005474
5475 // FIXME: Create an ExplicitInstantiation node?
John McCalld226f652010-08-21 09:40:31 +00005476 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005477 }
5478
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005479 // If the declarator is a template-id, translate the parser's template
5480 // argument list into our AST format.
Douglas Gregordb422df2009-09-25 21:45:23 +00005481 bool HasExplicitTemplateArgs = false;
John McCalld5532b62009-11-23 01:53:49 +00005482 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005483 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5484 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCalld5532b62009-11-23 01:53:49 +00005485 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5486 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregordb422df2009-09-25 21:45:23 +00005487 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5488 TemplateId->getTemplateArgs(),
Douglas Gregordb422df2009-09-25 21:45:23 +00005489 TemplateId->NumArgs);
John McCalld5532b62009-11-23 01:53:49 +00005490 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregordb422df2009-09-25 21:45:23 +00005491 HasExplicitTemplateArgs = true;
Douglas Gregorb2f81cf2009-10-01 23:51:25 +00005492 TemplateArgsPtr.release();
Douglas Gregordb422df2009-09-25 21:45:23 +00005493 }
Douglas Gregor0b60d9e2009-09-25 23:53:26 +00005494
Douglas Gregord5a423b2009-09-25 18:43:00 +00005495 // C++ [temp.explicit]p1:
5496 // A [...] function [...] can be explicitly instantiated from its template.
5497 // A member function [...] of a class template can be explicitly
5498 // instantiated from the member definition associated with its class
5499 // template.
John McCallc373d482010-01-27 01:50:18 +00005500 UnresolvedSet<8> Matches;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005501 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5502 P != PEnd; ++P) {
5503 NamedDecl *Prev = *P;
Douglas Gregordb422df2009-09-25 21:45:23 +00005504 if (!HasExplicitTemplateArgs) {
5505 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5506 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5507 Matches.clear();
Douglas Gregor48026d22010-01-11 18:40:55 +00005508
John McCallc373d482010-01-27 01:50:18 +00005509 Matches.addDecl(Method, P.getAccess());
Douglas Gregor48026d22010-01-11 18:40:55 +00005510 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5511 break;
Douglas Gregordb422df2009-09-25 21:45:23 +00005512 }
Douglas Gregord5a423b2009-09-25 18:43:00 +00005513 }
5514 }
5515
5516 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5517 if (!FunTmpl)
5518 continue;
5519
John McCall5769d612010-02-08 23:07:23 +00005520 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005521 FunctionDecl *Specialization = 0;
5522 if (TemplateDeductionResult TDK
Douglas Gregor48026d22010-01-11 18:40:55 +00005523 = DeduceTemplateArguments(FunTmpl,
John McCalld5532b62009-11-23 01:53:49 +00005524 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregord5a423b2009-09-25 18:43:00 +00005525 R, Specialization, Info)) {
5526 // FIXME: Keep track of almost-matches?
5527 (void)TDK;
5528 continue;
5529 }
5530
John McCallc373d482010-01-27 01:50:18 +00005531 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregord5a423b2009-09-25 18:43:00 +00005532 }
5533
5534 // Find the most specialized function template specialization.
John McCallc373d482010-01-27 01:50:18 +00005535 UnresolvedSetIterator Result
5536 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregord5a423b2009-09-25 18:43:00 +00005537 D.getIdentifierLoc(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005538 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5539 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5540 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregord5a423b2009-09-25 18:43:00 +00005541
John McCallc373d482010-01-27 01:50:18 +00005542 if (Result == Matches.end())
Douglas Gregord5a423b2009-09-25 18:43:00 +00005543 return true;
John McCallc373d482010-01-27 01:50:18 +00005544
5545 // Ignore access control bits, we don't need them for redeclaration checking.
5546 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregord5a423b2009-09-25 18:43:00 +00005547
Douglas Gregor0a897e32009-10-15 17:21:20 +00005548 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregord5a423b2009-09-25 18:43:00 +00005549 Diag(D.getIdentifierLoc(),
5550 diag::err_explicit_instantiation_member_function_not_instantiated)
5551 << Specialization
5552 << (Specialization->getTemplateSpecializationKind() ==
5553 TSK_ExplicitSpecialization);
5554 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5555 return true;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005556 }
Douglas Gregor558c0322009-10-14 23:41:34 +00005557
Douglas Gregor0a897e32009-10-15 17:21:20 +00005558 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor583f33b2009-10-15 18:07:02 +00005559 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5560 PrevDecl = Specialization;
5561
Douglas Gregor0a897e32009-10-15 17:21:20 +00005562 if (PrevDecl) {
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005563 bool HasNoEffect = false;
Douglas Gregor0d035142009-10-27 18:42:08 +00005564 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor0a897e32009-10-15 17:21:20 +00005565 PrevDecl,
5566 PrevDecl->getTemplateSpecializationKind(),
5567 PrevDecl->getPointOfInstantiation(),
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005568 HasNoEffect))
Douglas Gregor0a897e32009-10-15 17:21:20 +00005569 return true;
5570
5571 // FIXME: We may still want to build some representation of this
5572 // explicit specialization.
Abramo Bagnarac98971d2010-06-12 07:44:57 +00005573 if (HasNoEffect)
John McCalld226f652010-08-21 09:40:31 +00005574 return (Decl*) 0;
Douglas Gregor0a897e32009-10-15 17:21:20 +00005575 }
Anders Carlsson26d6e9d2009-11-24 05:34:41 +00005576
5577 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor0a897e32009-10-15 17:21:20 +00005578
5579 if (TSK == TSK_ExplicitInstantiationDefinition)
Chandler Carruth58e390e2010-08-25 08:27:02 +00005580 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
Douglas Gregor0a897e32009-10-15 17:21:20 +00005581
Douglas Gregor558c0322009-10-14 23:41:34 +00005582 // C++0x [temp.explicit]p2:
5583 // If the explicit instantiation is for a member function, a member class
5584 // or a static data member of a class template specialization, the name of
5585 // the class template specialization in the qualified-id for the member
5586 // name shall be a simple-template-id.
5587 //
5588 // C++98 has the same restriction, just worded differently.
Douglas Gregor0a897e32009-10-15 17:21:20 +00005589 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor3f9a0562009-11-03 01:35:08 +00005590 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregor558c0322009-10-14 23:41:34 +00005591 D.getCXXScopeSpec().isSet() &&
5592 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5593 Diag(D.getIdentifierLoc(),
Douglas Gregora2dd8282010-06-16 16:26:47 +00005594 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregor558c0322009-10-14 23:41:34 +00005595 << Specialization << D.getCXXScopeSpec().getRange();
5596
5597 CheckExplicitInstantiationScope(*this,
5598 FunTmpl? (NamedDecl *)FunTmpl
5599 : Specialization->getInstantiatedFromMemberFunction(),
5600 D.getIdentifierLoc(),
5601 D.getCXXScopeSpec().isSet());
5602
Douglas Gregord5a423b2009-09-25 18:43:00 +00005603 // FIXME: Create some kind of ExplicitInstantiationDecl here.
John McCalld226f652010-08-21 09:40:31 +00005604 return (Decl*) 0;
Douglas Gregord5a423b2009-09-25 18:43:00 +00005605}
5606
John McCallf312b1e2010-08-26 23:41:50 +00005607TypeResult
John McCallc4e70192009-09-11 04:59:25 +00005608Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5609 const CXXScopeSpec &SS, IdentifierInfo *Name,
5610 SourceLocation TagLoc, SourceLocation NameLoc) {
5611 // This has to hold, because SS is expected to be defined.
5612 assert(Name && "Expected a name in a dependent tag");
5613
5614 NestedNameSpecifier *NNS
5615 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5616 if (!NNS)
5617 return true;
5618
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005619 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbar12c0ade2010-04-01 16:50:48 +00005620
Douglas Gregor48c89f42010-04-24 16:38:41 +00005621 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5622 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005623 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregor48c89f42010-04-24 16:38:41 +00005624 return true;
5625 }
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005626
5627 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
John McCallb3d87482010-08-24 05:47:05 +00005628 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
John McCallc4e70192009-09-11 04:59:25 +00005629}
5630
John McCallf312b1e2010-08-26 23:41:50 +00005631TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005632Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5633 const CXXScopeSpec &SS, const IdentifierInfo &II,
5634 SourceLocation IdLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00005635 NestedNameSpecifier *NNS
Douglas Gregord57959a2009-03-27 23:10:48 +00005636 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5637 if (!NNS)
5638 return true;
5639
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005640 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5641 !getLangOptions().CPlusPlus0x)
5642 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5643 << FixItHint::CreateRemoval(TypenameLoc);
5644
Douglas Gregor107de902010-04-24 15:35:55 +00005645 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005646 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregor31a19b62009-04-01 21:51:26 +00005647 if (T.isNull())
5648 return true;
John McCall63b43852010-04-29 23:50:39 +00005649
5650 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5651 if (isa<DependentNameType>(T)) {
5652 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005653 TL.setKeywordLoc(TypenameLoc);
5654 TL.setQualifierRange(SS.getRange());
5655 TL.setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005656 } else {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005657 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCall4e449832010-05-28 23:32:21 +00005658 TL.setKeywordLoc(TypenameLoc);
5659 TL.setQualifierRange(SS.getRange());
5660 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall63b43852010-04-29 23:50:39 +00005661 }
5662
John McCallb3d87482010-08-24 05:47:05 +00005663 return CreateParsedType(T, TSI);
Douglas Gregord57959a2009-03-27 23:10:48 +00005664}
5665
John McCallf312b1e2010-08-26 23:41:50 +00005666TypeResult
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005667Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5668 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
John McCallb3d87482010-08-24 05:47:05 +00005669 ParsedType Ty) {
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005670 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5671 !getLangOptions().CPlusPlus0x)
5672 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5673 << FixItHint::CreateRemoval(TypenameLoc);
5674
John McCall4e449832010-05-28 23:32:21 +00005675 TypeSourceInfo *InnerTSI = 0;
5676 QualType T = GetTypeFromParser(Ty, &InnerTSI);
John McCall4e449832010-05-28 23:32:21 +00005677
5678 assert(isa<TemplateSpecializationType>(T) &&
5679 "Expected a template specialization type");
Douglas Gregor17343172009-04-01 00:28:59 +00005680
Douglas Gregor6946baf2009-09-02 13:05:45 +00005681 if (computeDeclContext(SS, false)) {
5682 // If we can compute a declaration context, then the "typename"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005683 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor6946baf2009-09-02 13:05:45 +00005684 // track of the nested-name-specifier.
John McCall4e449832010-05-28 23:32:21 +00005685
5686 // Push the inner type, preserving its source locations if possible.
5687 TypeLocBuilder Builder;
5688 if (InnerTSI)
5689 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5690 else
5691 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5692
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005693 /* Note: NNS already embedded in template specialization type T. */
5694 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
John McCall4e449832010-05-28 23:32:21 +00005695 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5696 TL.setKeywordLoc(TypenameLoc);
5697 TL.setQualifierRange(SS.getRange());
5698
5699 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCallb3d87482010-08-24 05:47:05 +00005700 return CreateParsedType(T, TSI);
Douglas Gregor6946baf2009-09-02 13:05:45 +00005701 }
Mike Stump1eb44332009-09-09 15:08:12 +00005702
John McCall33500952010-06-11 00:33:02 +00005703 // TODO: it's really silly that we make a template specialization
5704 // type earlier only to drop it again here.
5705 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5706 DependentTemplateName *DTN =
5707 TST->getTemplateName().getAsDependentTemplateName();
5708 assert(DTN && "dependent template has non-dependent name?");
Abramo Bagnara22f638a2010-08-10 13:46:45 +00005709 assert(DTN->getQualifier()
5710 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5711 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5712 DTN->getQualifier(),
John McCall33500952010-06-11 00:33:02 +00005713 DTN->getIdentifier(),
5714 TST->getNumArgs(),
5715 TST->getArgs());
John McCall63b43852010-04-29 23:50:39 +00005716 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCall33500952010-06-11 00:33:02 +00005717 DependentTemplateSpecializationTypeLoc TL =
5718 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5719 if (InnerTSI) {
5720 TemplateSpecializationTypeLoc TSTL =
5721 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5722 TL.setLAngleLoc(TSTL.getLAngleLoc());
5723 TL.setRAngleLoc(TSTL.getRAngleLoc());
5724 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5725 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5726 } else {
5727 TL.initializeLocal(SourceLocation());
5728 }
John McCall4e449832010-05-28 23:32:21 +00005729 TL.setKeywordLoc(TypenameLoc);
5730 TL.setQualifierRange(SS.getRange());
John McCallb3d87482010-08-24 05:47:05 +00005731 return CreateParsedType(T, TSI);
Douglas Gregor17343172009-04-01 00:28:59 +00005732}
5733
Douglas Gregord57959a2009-03-27 23:10:48 +00005734/// \brief Build the type that describes a C++ typename specifier,
5735/// e.g., "typename T::type".
5736QualType
Douglas Gregor107de902010-04-24 15:35:55 +00005737Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5738 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005739 SourceLocation KeywordLoc, SourceRange NNSRange,
5740 SourceLocation IILoc) {
John McCall77bb1aa2010-05-01 00:40:08 +00005741 CXXScopeSpec SS;
5742 SS.setScopeRep(NNS);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005743 SS.setRange(NNSRange);
Douglas Gregord57959a2009-03-27 23:10:48 +00005744
John McCall77bb1aa2010-05-01 00:40:08 +00005745 DeclContext *Ctx = computeDeclContext(SS);
5746 if (!Ctx) {
5747 // If the nested-name-specifier is dependent and couldn't be
5748 // resolved to a type, build a typename type.
5749 assert(NNS->isDependent());
5750 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor42af25f2009-05-11 19:58:34 +00005751 }
Douglas Gregord57959a2009-03-27 23:10:48 +00005752
John McCall77bb1aa2010-05-01 00:40:08 +00005753 // If the nested-name-specifier refers to the current instantiation,
5754 // the "typename" keyword itself is superfluous. In C++03, the
5755 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5756 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregor732281d2010-06-14 22:07:54 +00005757 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregor42af25f2009-05-11 19:58:34 +00005758
John McCall77bb1aa2010-05-01 00:40:08 +00005759 if (RequireCompleteDeclContext(SS, Ctx))
5760 return QualType();
Douglas Gregord57959a2009-03-27 23:10:48 +00005761
5762 DeclarationName Name(&II);
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005763 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCalla24dc2e2009-11-17 02:14:36 +00005764 LookupQualifiedName(Result, Ctx);
Douglas Gregord57959a2009-03-27 23:10:48 +00005765 unsigned DiagID = 0;
5766 Decl *Referenced = 0;
John McCalla24dc2e2009-11-17 02:14:36 +00005767 switch (Result.getResultKind()) {
Douglas Gregord57959a2009-03-27 23:10:48 +00005768 case LookupResult::NotFound:
Douglas Gregor3f093272009-10-13 21:16:44 +00005769 DiagID = diag::err_typename_nested_not_found;
Douglas Gregord57959a2009-03-27 23:10:48 +00005770 break;
Douglas Gregord9545042010-12-09 00:06:27 +00005771
5772 case LookupResult::FoundUnresolvedValue: {
5773 // We found a using declaration that is a value. Most likely, the using
5774 // declaration itself is meant to have the 'typename' keyword.
5775 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5776 IILoc);
5777 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
5778 << Name << Ctx << FullRange;
5779 if (UnresolvedUsingValueDecl *Using
5780 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
5781 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
5782 Diag(Loc, diag::note_using_value_decl_missing_typename)
5783 << FixItHint::CreateInsertion(Loc, "typename ");
5784 }
5785 }
5786 // Fall through to create a dependent typename type, from which we can recover
5787 // better.
Douglas Gregor7d3f5762010-01-15 01:44:47 +00005788
5789 case LookupResult::NotFoundInCurrentInstantiation:
5790 // Okay, it's a member of an unknown instantiation.
Douglas Gregor107de902010-04-24 15:35:55 +00005791 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregord57959a2009-03-27 23:10:48 +00005792
5793 case LookupResult::Found:
Douglas Gregor1a15dae2010-06-16 22:31:08 +00005794 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005795 // We found a type. Build an ElaboratedType, since the
5796 // typename-specifier was just sugar.
5797 return Context.getElaboratedType(ETK_Typename, NNS,
5798 Context.getTypeDeclType(Type));
Douglas Gregord57959a2009-03-27 23:10:48 +00005799 }
5800
5801 DiagID = diag::err_typename_nested_not_type;
John McCallf36e02d2009-10-09 21:13:30 +00005802 Referenced = Result.getFoundDecl();
Douglas Gregord57959a2009-03-27 23:10:48 +00005803 break;
5804
Douglas Gregord9545042010-12-09 00:06:27 +00005805
Jeffrey Yasskin9f61aa92009-12-12 05:05:38 +00005806 llvm_unreachable("unresolved using decl in non-dependent context");
John McCall7ba107a2009-11-18 02:36:19 +00005807 return QualType();
5808
Douglas Gregord57959a2009-03-27 23:10:48 +00005809 case LookupResult::FoundOverloaded:
5810 DiagID = diag::err_typename_nested_not_type;
5811 Referenced = *Result.begin();
5812 break;
5813
John McCall6e247262009-10-10 05:48:19 +00005814 case LookupResult::Ambiguous:
Douglas Gregord57959a2009-03-27 23:10:48 +00005815 return QualType();
5816 }
5817
5818 // If we get here, it's because name lookup did not find a
5819 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarae4da7a02010-05-19 21:37:53 +00005820 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5821 IILoc);
5822 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregord57959a2009-03-27 23:10:48 +00005823 if (Referenced)
5824 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5825 << Name;
5826 return QualType();
5827}
Douglas Gregor4a959d82009-08-06 16:20:37 +00005828
5829namespace {
5830 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer85b45212009-11-28 19:45:26 +00005831 class CurrentInstantiationRebuilder
Mike Stump1eb44332009-09-09 15:08:12 +00005832 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor4a959d82009-08-06 16:20:37 +00005833 SourceLocation Loc;
5834 DeclarationName Entity;
Mike Stump1eb44332009-09-09 15:08:12 +00005835
Douglas Gregor4a959d82009-08-06 16:20:37 +00005836 public:
Douglas Gregor895162d2010-04-30 18:55:50 +00005837 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5838
Mike Stump1eb44332009-09-09 15:08:12 +00005839 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005840 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +00005841 DeclarationName Entity)
5842 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor4a959d82009-08-06 16:20:37 +00005843 Loc(Loc), Entity(Entity) { }
Mike Stump1eb44332009-09-09 15:08:12 +00005844
5845 /// \brief Determine whether the given type \p T has already been
Douglas Gregor4a959d82009-08-06 16:20:37 +00005846 /// transformed.
5847 ///
5848 /// For the purposes of type reconstruction, a type has already been
5849 /// transformed if it is NULL or if it is not dependent.
5850 bool AlreadyTransformed(QualType T) {
5851 return T.isNull() || !T->isDependentType();
5852 }
Mike Stump1eb44332009-09-09 15:08:12 +00005853
5854 /// \brief Returns the location of the entity whose type is being
Douglas Gregor4a959d82009-08-06 16:20:37 +00005855 /// rebuilt.
5856 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +00005857
Douglas Gregor4a959d82009-08-06 16:20:37 +00005858 /// \brief Returns the name of the entity whose type is being rebuilt.
5859 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +00005860
Douglas Gregor972e6ce2009-10-27 06:26:26 +00005861 /// \brief Sets the "base" location and entity when that
5862 /// information is known based on another transformation.
5863 void setBase(SourceLocation Loc, DeclarationName Entity) {
5864 this->Loc = Loc;
5865 this->Entity = Entity;
5866 }
Douglas Gregor4a959d82009-08-06 16:20:37 +00005867 };
5868}
5869
Douglas Gregor4a959d82009-08-06 16:20:37 +00005870/// \brief Rebuilds a type within the context of the current instantiation.
5871///
Mike Stump1eb44332009-09-09 15:08:12 +00005872/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor4a959d82009-08-06 16:20:37 +00005873/// a class template (or class template partial specialization) that was parsed
Mike Stump1eb44332009-09-09 15:08:12 +00005874/// and constructed before we entered the scope of the class template (or
Douglas Gregor4a959d82009-08-06 16:20:37 +00005875/// partial specialization thereof). This routine will rebuild that type now
5876/// that we have entered the declarator's scope, which may produce different
5877/// canonical types, e.g.,
5878///
5879/// \code
5880/// template<typename T>
5881/// struct X {
5882/// typedef T* pointer;
5883/// pointer data();
5884/// };
5885///
5886/// template<typename T>
5887/// typename X<T>::pointer X<T>::data() { ... }
5888/// \endcode
5889///
Douglas Gregor4714c122010-03-31 17:34:00 +00005890/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor4a959d82009-08-06 16:20:37 +00005891/// since we do not know that we can look into X<T> when we parsed the type.
5892/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005893/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor4a959d82009-08-06 16:20:37 +00005894/// as the canonical type of T*, allowing the return types of the out-of-line
5895/// definition and the declaration to match.
John McCall63b43852010-04-29 23:50:39 +00005896TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5897 SourceLocation Loc,
5898 DeclarationName Name) {
5899 if (!T || !T->getType()->isDependentType())
Douglas Gregor4a959d82009-08-06 16:20:37 +00005900 return T;
Mike Stump1eb44332009-09-09 15:08:12 +00005901
Douglas Gregor4a959d82009-08-06 16:20:37 +00005902 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5903 return Rebuilder.TransformType(T);
Benjamin Kramer27ba2f02009-08-11 22:33:06 +00005904}
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005905
John McCall60d7b3a2010-08-24 06:29:42 +00005906ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
John McCallb3d87482010-08-24 05:47:05 +00005907 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
5908 DeclarationName());
5909 return Rebuilder.TransformExpr(E);
5910}
5911
John McCall63b43852010-04-29 23:50:39 +00005912bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5913 if (SS.isInvalid()) return true;
John McCall31f17ec2010-04-27 00:57:59 +00005914
5915 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5916 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5917 DeclarationName());
5918 NestedNameSpecifier *Rebuilt =
5919 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall63b43852010-04-29 23:50:39 +00005920 if (!Rebuilt) return true;
5921
5922 SS.setScopeRep(Rebuilt);
5923 return false;
John McCall31f17ec2010-04-27 00:57:59 +00005924}
5925
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005926/// \brief Produces a formatted string that describes the binding of
5927/// template parameters to template arguments.
5928std::string
5929Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5930 const TemplateArgumentList &Args) {
Douglas Gregor910f8002010-11-07 23:05:16 +00005931 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005932}
5933
5934std::string
5935Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5936 const TemplateArgument *Args,
5937 unsigned NumArgs) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00005938 llvm::SmallString<128> Str;
5939 llvm::raw_svector_ostream Out(Str);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005940
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005941 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00005942 return std::string();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005943
5944 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregor9148c3f2009-11-11 19:13:48 +00005945 if (I >= NumArgs)
5946 break;
5947
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005948 if (I == 0)
Douglas Gregor87dd6972010-12-20 16:52:59 +00005949 Out << "[with ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005950 else
Douglas Gregor87dd6972010-12-20 16:52:59 +00005951 Out << ", ";
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005952
5953 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
Douglas Gregor87dd6972010-12-20 16:52:59 +00005954 Out << Id->getName();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005955 } else {
Douglas Gregor87dd6972010-12-20 16:52:59 +00005956 Out << '$' << I;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005957 }
5958
Douglas Gregor87dd6972010-12-20 16:52:59 +00005959 Out << " = ";
5960 Args[I].print(Context.PrintingPolicy, Out);
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005961 }
Douglas Gregor87dd6972010-12-20 16:52:59 +00005962
5963 Out << ']';
5964 return Out.str();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00005965}
Douglas Gregord0937222010-12-13 22:49:22 +00005966