blob: b30d4e3e9c31f908751d75ae8b6579ecb93aedd5 [file] [log] [blame]
Douglas Gregor5101c242008-12-05 18:15:24 +00001//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
Douglas Gregor5101c242008-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 Gregorfe1e1102009-02-27 19:31:52 +00007//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +00008//
9// This file implements semantic analysis for C++ templates.
Douglas Gregorfe1e1102009-02-27 19:31:52 +000010//===----------------------------------------------------------------------===/
Douglas Gregor5101c242008-12-05 18:15:24 +000011
12#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor15acfb92009-08-06 16:20:37 +000014#include "TreeTransform.h"
Douglas Gregorcd72ba92009-02-06 22:42:48 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor4619e432008-12-05 23:32:09 +000016#include "clang/AST/Expr.h"
Douglas Gregorccb07762009-02-11 19:52:55 +000017#include "clang/AST/ExprCXX.h"
John McCallbbbbe4e2010-03-11 07:50:04 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000020#include "clang/Parse/DeclSpec.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000021#include "clang/Parse/Template.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000022#include "clang/Basic/LangOptions.h"
Douglas Gregor450f00842009-09-25 18:43:00 +000023#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbe999392009-09-15 16:23:51 +000024#include "llvm/ADT/StringExtras.h"
Douglas Gregor5101c242008-12-05 18:15:24 +000025using namespace clang;
26
Douglas Gregorb7bfe792009-09-02 22:59:36 +000027/// \brief Determine whether the declaration found is acceptable as the name
28/// of a template and, if so, return that template declaration. Otherwise,
29/// returns NULL.
John McCalle9cccd82010-06-16 08:42:20 +000030static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
31 NamedDecl *Orig) {
32 NamedDecl *D = Orig->getUnderlyingDecl();
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
John McCalle9cccd82010-06-16 08:42:20 +000035 return Orig;
Mike Stump11289f42009-09-09 15:08:12 +000036
Douglas Gregorb7bfe792009-09-02 22:59:36 +000037 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
48 // specialization.
49 if (Record->isInjectedClassName()) {
Douglas Gregor568a0712009-10-14 17:30:58 +000050 Record = cast<CXXRecordDecl>(Record->getDeclContext());
Douglas Gregorb7bfe792009-09-02 22:59:36 +000051 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
53
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
57 }
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregorb7bfe792009-09-02 22:59:36 +000059 return 0;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregorb7bfe792009-09-02 22:59:36 +000062 return 0;
63}
64
John McCalle66edc12009-11-24 19:00:30 +000065static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
Douglas Gregor41f90302010-04-12 20:54:26 +000066 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
John McCalle66edc12009-11-24 19:00:30 +000068 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
John McCalle9cccd82010-06-16 08:42:20 +000071 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
John McCalle66edc12009-11-24 19:00:30 +000072 if (!Repl)
73 filter.erase();
Douglas Gregor41f90302010-04-12 20:54:26 +000074 else if (Repl != Orig) {
75
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
83 // ambiguous.
84 //
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
88 filter.erase();
89 continue;
90 }
91
John McCalle66edc12009-11-24 19:00:30 +000092 filter.replace(Repl);
Douglas Gregor41f90302010-04-12 20:54:26 +000093 }
John McCalle66edc12009-11-24 19:00:30 +000094 }
95 filter.done();
96}
97
Douglas Gregorb7bfe792009-09-02 22:59:36 +000098TemplateNameKind Sema::isTemplateName(Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +000099 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +0000100 UnqualifiedId &Name,
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000101 TypeTy *ObjectTypePtr,
Douglas Gregore861bac2009-08-25 22:51:20 +0000102 bool EnteringContext,
Douglas Gregor786123d2010-05-21 23:18:07 +0000103 TemplateTy &TemplateResult,
104 bool &MemberOfUnknownSpecialization) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000105 assert(getLangOptions().CPlusPlus && "No template names in C!");
106
Douglas Gregor3cf81312009-11-03 23:16:33 +0000107 DeclarationName TName;
Douglas Gregor786123d2010-05-21 23:18:07 +0000108 MemberOfUnknownSpecialization = false;
Douglas Gregor3cf81312009-11-03 23:16:33 +0000109
110 switch (Name.getKind()) {
111 case UnqualifiedId::IK_Identifier:
112 TName = DeclarationName(Name.Identifier);
113 break;
114
115 case UnqualifiedId::IK_OperatorFunctionId:
116 TName = Context.DeclarationNames.getCXXOperatorName(
117 Name.OperatorFunctionId.Operator);
118 break;
119
Alexis Hunted0530f2009-11-28 08:58:14 +0000120 case UnqualifiedId::IK_LiteralOperatorId:
Alexis Hunt3d221f22009-11-29 07:34:05 +0000121 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
122 break;
Alexis Hunted0530f2009-11-28 08:58:14 +0000123
Douglas Gregor3cf81312009-11-03 23:16:33 +0000124 default:
125 return TNK_Non_template;
126 }
Mike Stump11289f42009-09-09 15:08:12 +0000127
John McCalle66edc12009-11-24 19:00:30 +0000128 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
Mike Stump11289f42009-09-09 15:08:12 +0000129
Douglas Gregorff18cc12009-12-31 08:11:17 +0000130 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
131 LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +0000132 R.suppressDiagnostics();
Douglas Gregor786123d2010-05-21 23:18:07 +0000133 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
134 MemberOfUnknownSpecialization);
Douglas Gregor41f90302010-04-12 20:54:26 +0000135 if (R.empty() || R.isAmbiguous())
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000136 return TNK_Non_template;
137
John McCalld28ae272009-12-02 08:04:21 +0000138 TemplateName Template;
139 TemplateNameKind TemplateKind;
Mike Stump11289f42009-09-09 15:08:12 +0000140
John McCalld28ae272009-12-02 08:04:21 +0000141 unsigned ResultCount = R.end() - R.begin();
142 if (ResultCount > 1) {
143 // We assume that we'll preserve the qualifier from a function
144 // template name in other ways.
145 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
146 TemplateKind = TNK_Function_template;
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000147 } else {
John McCalld28ae272009-12-02 08:04:21 +0000148 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
149
150 if (SS.isSet() && !SS.isInvalid()) {
151 NestedNameSpecifier *Qualifier
152 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
153 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
154 } else {
155 Template = TemplateName(TD);
156 }
157
158 if (isa<FunctionTemplateDecl>(TD))
159 TemplateKind = TNK_Function_template;
160 else {
161 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
162 TemplateKind = TNK_Type_template;
163 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +0000164 }
Mike Stump11289f42009-09-09 15:08:12 +0000165
John McCalld28ae272009-12-02 08:04:21 +0000166 TemplateResult = TemplateTy::make(Template);
167 return TemplateKind;
John McCalle66edc12009-11-24 19:00:30 +0000168}
169
Douglas Gregor18473f32010-01-12 21:28:44 +0000170bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
171 SourceLocation IILoc,
172 Scope *S,
173 const CXXScopeSpec *SS,
174 TemplateTy &SuggestedTemplate,
175 TemplateNameKind &SuggestedKind) {
176 // We can't recover unless there's a dependent scope specifier preceding the
177 // template name.
Douglas Gregor20c38a72010-05-21 23:43:39 +0000178 // FIXME: Typo correction?
Douglas Gregor18473f32010-01-12 21:28:44 +0000179 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
180 computeDeclContext(*SS))
181 return false;
182
183 // The code is missing a 'template' keyword prior to the dependent template
184 // name.
185 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
186 Diag(IILoc, diag::err_template_kw_missing)
187 << Qualifier << II.getName()
Douglas Gregora771f462010-03-31 17:46:05 +0000188 << FixItHint::CreateInsertion(IILoc, "template ");
Douglas Gregor18473f32010-01-12 21:28:44 +0000189 SuggestedTemplate
190 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
191 SuggestedKind = TNK_Dependent_template_name;
192 return true;
193}
194
John McCalle66edc12009-11-24 19:00:30 +0000195void Sema::LookupTemplateName(LookupResult &Found,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000196 Scope *S, CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +0000197 QualType ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +0000198 bool EnteringContext,
199 bool &MemberOfUnknownSpecialization) {
John McCalle66edc12009-11-24 19:00:30 +0000200 // Determine where to perform name lookup
Douglas Gregor786123d2010-05-21 23:18:07 +0000201 MemberOfUnknownSpecialization = false;
John McCalle66edc12009-11-24 19:00:30 +0000202 DeclContext *LookupCtx = 0;
203 bool isDependent = false;
204 if (!ObjectType.isNull()) {
205 // This nested-name-specifier occurs in a member access expression, e.g.,
206 // x->B::f, and we are looking into the type of the object.
207 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
208 LookupCtx = computeDeclContext(ObjectType);
209 isDependent = ObjectType->isDependentType();
210 assert((isDependent || !ObjectType->isIncompleteType()) &&
211 "Caller should have completed object type");
212 } else if (SS.isSet()) {
213 // This nested-name-specifier occurs after another nested-name-specifier,
214 // so long into the context associated with the prior nested-name-specifier.
215 LookupCtx = computeDeclContext(SS, EnteringContext);
216 isDependent = isDependentScopeSpecifier(SS);
217
218 // The declaration context must be complete.
John McCall0b66eb32010-05-01 00:40:08 +0000219 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
John McCalle66edc12009-11-24 19:00:30 +0000220 return;
221 }
222
223 bool ObjectTypeSearchedInScope = false;
224 if (LookupCtx) {
225 // Perform "qualified" name lookup into the declaration context we
226 // computed, which is either the type of the base of a member access
227 // expression or the declaration context associated with a prior
228 // nested-name-specifier.
229 LookupQualifiedName(Found, LookupCtx);
230
231 if (!ObjectType.isNull() && Found.empty()) {
232 // C++ [basic.lookup.classref]p1:
233 // In a class member access expression (5.2.5), if the . or -> token is
234 // immediately followed by an identifier followed by a <, the
235 // identifier must be looked up to determine whether the < is the
236 // beginning of a template argument list (14.2) or a less-than operator.
237 // The identifier is first looked up in the class of the object
238 // expression. If the identifier is not found, it is then looked up in
239 // the context of the entire postfix-expression and shall name a class
240 // or function template.
241 //
242 // FIXME: When we're instantiating a template, do we actually have to
243 // look in the scope of the template? Seems fishy...
244 if (S) LookupName(Found, S);
245 ObjectTypeSearchedInScope = true;
246 }
247 } else if (isDependent) {
Douglas Gregorc119dd52010-01-12 17:06:20 +0000248 // We cannot look into a dependent object type or nested nme
249 // specifier.
Douglas Gregor786123d2010-05-21 23:18:07 +0000250 MemberOfUnknownSpecialization = true;
John McCalle66edc12009-11-24 19:00:30 +0000251 return;
252 } else {
253 // Perform unqualified name lookup in the current scope.
254 LookupName(Found, S);
255 }
256
Douglas Gregorc119dd52010-01-12 17:06:20 +0000257 if (Found.empty() && !isDependent) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000258 // If we did not find any names, attempt to correct any typos.
259 DeclarationName Name = Found.getLookupName();
Douglas Gregor280e1ee2010-04-14 20:04:41 +0000260 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
261 false, CTC_CXXCasts)) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000262 FilterAcceptableTemplateNames(Context, Found);
John McCalle9cccd82010-06-16 08:42:20 +0000263 if (!Found.empty()) {
Douglas Gregorff18cc12009-12-31 08:11:17 +0000264 if (LookupCtx)
265 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
266 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +0000267 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000268 Found.getLookupName().getAsString());
269 else
270 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
271 << Name << Found.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +0000272 << FixItHint::CreateReplacement(Found.getNameLoc(),
Douglas Gregorff18cc12009-12-31 08:11:17 +0000273 Found.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +0000274 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
275 Diag(Template->getLocation(), diag::note_previous_decl)
276 << Template->getDeclName();
John McCalle9cccd82010-06-16 08:42:20 +0000277 }
Douglas Gregorff18cc12009-12-31 08:11:17 +0000278 } else {
279 Found.clear();
280 }
281 }
282
John McCalle66edc12009-11-24 19:00:30 +0000283 FilterAcceptableTemplateNames(Context, Found);
284 if (Found.empty())
285 return;
286
287 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
288 // C++ [basic.lookup.classref]p1:
289 // [...] If the lookup in the class of the object expression finds a
290 // template, the name is also looked up in the context of the entire
291 // postfix-expression and [...]
292 //
293 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
294 LookupOrdinaryName);
295 LookupName(FoundOuter, S);
296 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000297
John McCalle66edc12009-11-24 19:00:30 +0000298 if (FoundOuter.empty()) {
299 // - if the name is not found, the name found in the class of the
300 // object expression is used, otherwise
301 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
302 // - if the name is found in the context of the entire
303 // postfix-expression and does not name a class template, the name
304 // found in the class of the object expression is used, otherwise
John McCalle9cccd82010-06-16 08:42:20 +0000305 } else if (!Found.isSuppressingDiagnostics()) {
John McCalle66edc12009-11-24 19:00:30 +0000306 // - if the name found is a class template, it must refer to the same
307 // entity as the one found in the class of the object expression,
308 // otherwise the program is ill-formed.
309 if (!Found.isSingleResult() ||
310 Found.getFoundDecl()->getCanonicalDecl()
311 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
312 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000313 diag::ext_nested_name_member_ref_lookup_ambiguous)
314 << Found.getLookupName()
315 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000316 Diag(Found.getRepresentativeDecl()->getLocation(),
317 diag::note_ambig_member_ref_object_type)
318 << ObjectType;
319 Diag(FoundOuter.getFoundDecl()->getLocation(),
320 diag::note_ambig_member_ref_scope);
321
322 // Recover by taking the template that we found in the object
323 // expression's type.
324 }
325 }
326 }
327}
328
John McCallcd4b4772009-12-02 03:53:29 +0000329/// ActOnDependentIdExpression - Handle a dependent id-expression that
330/// was just parsed. This is only possible with an explicit scope
331/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000332Sema::OwningExprResult
333Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
334 DeclarationName Name,
335 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000336 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000337 const TemplateArgumentListInfo *TemplateArgs) {
338 NestedNameSpecifier *Qualifier
339 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000340
341 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000342
John McCallcd4b4772009-12-02 03:53:29 +0000343 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000344 isa<CXXMethodDecl>(DC) &&
345 cast<CXXMethodDecl>(DC)->isInstance()) {
346 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000347
John McCalle66edc12009-11-24 19:00:30 +0000348 // Since the 'this' expression is synthesized, we don't need to
349 // perform the double-lookup check.
350 NamedDecl *FirstQualifierInScope = 0;
351
John McCall2d74de92009-12-01 22:10:20 +0000352 return Owned(CXXDependentScopeMemberExpr::Create(Context,
353 /*This*/ 0, ThisType,
354 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000355 /*Op*/ SourceLocation(),
356 Qualifier, SS.getRange(),
357 FirstQualifierInScope,
358 Name, NameLoc,
359 TemplateArgs));
360 }
361
362 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
363}
364
365Sema::OwningExprResult
366Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
367 DeclarationName Name,
368 SourceLocation NameLoc,
369 const TemplateArgumentListInfo *TemplateArgs) {
370 return Owned(DependentScopeDeclRefExpr::Create(Context,
371 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
372 SS.getRange(),
373 Name, NameLoc,
374 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000375}
376
Douglas Gregor5101c242008-12-05 18:15:24 +0000377/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
378/// that the template parameter 'PrevDecl' is being shadowed by a new
379/// declaration at location Loc. Returns true to indicate that this is
380/// an error, and false otherwise.
381bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000382 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000383
384 // Microsoft Visual C++ permits template parameters to be shadowed.
385 if (getLangOptions().Microsoft)
386 return false;
387
388 // C++ [temp.local]p4:
389 // A template-parameter shall not be redeclared within its
390 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000391 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000392 << cast<NamedDecl>(PrevDecl)->getDeclName();
393 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
394 return true;
395}
396
Douglas Gregor463421d2009-03-03 04:44:36 +0000397/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000398/// the parameter D to reference the templated declaration and return a pointer
399/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000400TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000401 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000402 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000403 return Temp;
404 }
405 return 0;
406}
407
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000408static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
409 const ParsedTemplateArgument &Arg) {
410
411 switch (Arg.getKind()) {
412 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000413 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000414 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
415 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000416 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000417 return TemplateArgumentLoc(TemplateArgument(T), DI);
418 }
419
420 case ParsedTemplateArgument::NonType: {
421 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
422 return TemplateArgumentLoc(TemplateArgument(E), E);
423 }
424
425 case ParsedTemplateArgument::Template: {
426 TemplateName Template
427 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
428 return TemplateArgumentLoc(TemplateArgument(Template),
429 Arg.getScopeSpec().getRange(),
430 Arg.getLocation());
431 }
432 }
433
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000434 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000435 return TemplateArgumentLoc();
436}
437
438/// \brief Translates template arguments as provided by the parser
439/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000440void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
441 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000442 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000443 TemplateArgs.addArgument(translateTemplateArgument(*this,
444 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000445}
446
Douglas Gregor5101c242008-12-05 18:15:24 +0000447/// ActOnTypeParameter - Called when a C++ template type parameter
448/// (e.g., "typename T") has been parsed. Typename specifies whether
449/// the keyword "typename" was used to declare the type parameter
450/// (otherwise, "class" was used), and KeyLoc is the location of the
451/// "class" or "typename" keyword. ParamName is the name of the
452/// parameter (NULL indicates an unnamed template parameter) and
Douglas Gregor2ebcae12010-06-16 15:23:05 +0000453/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000454/// If the type parameter has a default argument, it will be added
455/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000456Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000457 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000458 SourceLocation KeyLoc,
459 IdentifierInfo *ParamName,
460 SourceLocation ParamNameLoc,
461 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000462 assert(S->isTemplateParamScope() &&
463 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000464 bool Invalid = false;
465
466 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000467 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000468 LookupOrdinaryName,
469 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000470 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000471 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000472 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000473 }
474
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000475 SourceLocation Loc = ParamNameLoc;
476 if (!ParamName)
477 Loc = KeyLoc;
478
Douglas Gregor5101c242008-12-05 18:15:24 +0000479 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000480 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
481 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000482 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000483 if (Invalid)
484 Param->setInvalidDecl();
485
486 if (ParamName) {
487 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000488 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000489 IdResolver.AddDecl(Param);
490 }
491
Chris Lattner83f095c2009-03-28 19:18:32 +0000492 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000493}
494
Douglas Gregordba32632009-02-10 19:49:53 +0000495/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000496/// Default) to the given template type parameter (TypeParam).
497void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000498 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000499 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000500 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000501 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000502 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000503
John McCallbcd03502009-12-07 02:54:59 +0000504 TypeSourceInfo *DefaultTInfo;
505 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000506
John McCallbcd03502009-12-07 02:54:59 +0000507 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000508
Anders Carlssond3824352009-06-12 22:30:13 +0000509 // C++0x [temp.param]p9:
510 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000511 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000512 if (Parm->isParameterPack()) {
513 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000514 return;
515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
Douglas Gregordba32632009-02-10 19:49:53 +0000517 // C++ [temp.param]p14:
518 // A template-parameter shall not be used in its own default argument.
519 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000520
Douglas Gregordba32632009-02-10 19:49:53 +0000521 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000522 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000523 Parm->setInvalidDecl();
524 return;
525 }
526
John McCallbcd03502009-12-07 02:54:59 +0000527 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000528}
529
Douglas Gregor463421d2009-03-03 04:44:36 +0000530/// \brief Check that the type of a non-type template parameter is
531/// well-formed.
532///
533/// \returns the (possibly-promoted) parameter type if valid;
534/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000535QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000536Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000537 // We don't allow variably-modified types as the type of non-type template
538 // parameters.
539 if (T->isVariablyModifiedType()) {
540 Diag(Loc, diag::err_variably_modified_nontype_template_param)
541 << T;
542 return QualType();
543 }
544
Douglas Gregor463421d2009-03-03 04:44:36 +0000545 // C++ [temp.param]p4:
546 //
547 // A non-type template-parameter shall have one of the following
548 // (optionally cv-qualified) types:
549 //
550 // -- integral or enumeration type,
Douglas Gregorb90df602010-06-16 00:17:44 +0000551 if (T->isIntegralOrEnumerationType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000552 // -- pointer to object or pointer to function,
553 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000554 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
555 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000556 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000557 T->isReferenceType() ||
558 // -- pointer to member.
559 T->isMemberPointerType() ||
560 // If T is a dependent type, we can't do the check now, so we
561 // assume that it is well-formed.
562 T->isDependentType())
563 return T;
564 // C++ [temp.param]p8:
565 //
566 // A non-type template-parameter of type "array of T" or
567 // "function returning T" is adjusted to be of type "pointer to
568 // T" or "pointer to function returning T", respectively.
569 else if (T->isArrayType())
570 // FIXME: Keep the type prior to promotion?
571 return Context.getArrayDecayedType(T);
572 else if (T->isFunctionType())
573 // FIXME: Keep the type prior to promotion?
574 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000575
Douglas Gregor463421d2009-03-03 04:44:36 +0000576 Diag(Loc, diag::err_template_nontype_parm_bad_type)
577 << T;
578
579 return QualType();
580}
581
Douglas Gregor5101c242008-12-05 18:15:24 +0000582/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
583/// template parameter (e.g., "int Size" in "template<int Size>
584/// class Array") has been parsed. S is the current scope and D is
585/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000586Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000587 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000588 unsigned Position) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000589 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
590 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000591
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000592 assert(S->isTemplateParamScope() &&
593 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000594 bool Invalid = false;
595
596 IdentifierInfo *ParamName = D.getIdentifier();
597 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000598 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000599 LookupOrdinaryName,
600 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000601 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000602 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000603 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000604 }
605
Douglas Gregor463421d2009-03-03 04:44:36 +0000606 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000607 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000608 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000609 Invalid = true;
610 }
Douglas Gregor81338792009-02-10 17:43:50 +0000611
Douglas Gregor5101c242008-12-05 18:15:24 +0000612 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000613 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
614 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000615 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000616 if (Invalid)
617 Param->setInvalidDecl();
618
619 if (D.getIdentifier()) {
620 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000621 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000622 IdResolver.AddDecl(Param);
623 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000624 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000625}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000626
Douglas Gregordba32632009-02-10 19:49:53 +0000627/// \brief Adds a default argument to the given non-type template
628/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000629void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000630 SourceLocation EqualLoc,
631 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000632 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000633 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000634 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000635
Douglas Gregordba32632009-02-10 19:49:53 +0000636 // C++ [temp.param]p14:
637 // A template-parameter shall not be used in its own default argument.
638 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000639
Douglas Gregordba32632009-02-10 19:49:53 +0000640 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000641 TemplateArgument Converted;
642 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
643 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000644 TemplateParm->setInvalidDecl();
645 return;
646 }
647
Abramo Bagnara656e3002010-06-09 09:26:05 +0000648 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>(), false);
Douglas Gregordba32632009-02-10 19:49:53 +0000649}
650
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000651
652/// ActOnTemplateTemplateParameter - Called when a C++ template template
653/// parameter (e.g. T in template <template <typename> class T> class array)
654/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000655Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
656 SourceLocation TmpLoc,
657 TemplateParamsTy *Params,
658 IdentifierInfo *Name,
659 SourceLocation NameLoc,
660 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000661 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000662 assert(S->isTemplateParamScope() &&
663 "Template template parameter not in template parameter scope!");
664
665 // Construct the parameter object.
666 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000667 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
668 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000669 (TemplateParameterList*)Params);
670
671 // Make sure the parameter is valid.
672 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
673 // do anything yet. However, if the template parameter list or (eventual)
674 // default value is ever invalidated, that will propagate here.
675 bool Invalid = false;
676 if (Invalid) {
677 Param->setInvalidDecl();
678 }
679
680 // If the tt-param has a name, then link the identifier into the scope
681 // and lookup mechanisms.
682 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000683 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000684 IdResolver.AddDecl(Param);
685 }
686
Chris Lattner83f095c2009-03-28 19:18:32 +0000687 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000688}
689
Douglas Gregordba32632009-02-10 19:49:53 +0000690/// \brief Adds a default argument to the given template template
691/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000692void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000693 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000694 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000695 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000696 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000697
Douglas Gregordba32632009-02-10 19:49:53 +0000698 // C++ [temp.param]p14:
699 // A template-parameter shall not be used in its own default argument.
700 // FIXME: Implement this check! Needs a recursive walk over the types.
701
Douglas Gregore62e6a02009-11-11 19:13:48 +0000702 // Check only that we have a template template argument. We don't want to
703 // try to check well-formedness now, because our template template parameter
704 // might have dependent types in its template parameters, which we wouldn't
705 // be able to match now.
706 //
707 // If none of the template template parameter's template arguments mention
708 // other template parameters, we could actually perform more checking here.
709 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000710 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000711 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
712 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
713 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000714 return;
715 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000716
Abramo Bagnara656e3002010-06-09 09:26:05 +0000717 TemplateParm->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000718}
719
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000720/// ActOnTemplateParameterList - Builds a TemplateParameterList that
721/// contains the template parameters in Params/NumParams.
722Sema::TemplateParamsTy *
723Sema::ActOnTemplateParameterList(unsigned Depth,
724 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000725 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000726 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000727 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000728 SourceLocation RAngleLoc) {
729 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000730 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000731
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000732 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000733 (NamedDecl**)Params, NumParams,
734 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000735}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000736
John McCall3e11ebe2010-03-15 10:12:16 +0000737static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
738 if (SS.isSet())
739 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
740 SS.getRange());
741}
742
Douglas Gregorc08f4892009-03-25 00:13:59 +0000743Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000744Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000745 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000746 IdentifierInfo *Name, SourceLocation NameLoc,
747 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000748 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000749 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000750 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000751 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000752 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000753 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000754
755 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000756 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000757 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000758
Abramo Bagnara6150c882010-05-11 21:36:43 +0000759 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
760 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000761
762 // There is no such thing as an unnamed class template.
763 if (!Name) {
764 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000765 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000766 }
767
768 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000769 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000770 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000771 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000772 if (SS.isNotEmpty() && !SS.isInvalid()) {
773 SemanticContext = computeDeclContext(SS, true);
774 if (!SemanticContext) {
775 // FIXME: Produce a reasonable diagnostic here
776 return true;
777 }
Mike Stump11289f42009-09-09 15:08:12 +0000778
John McCall0b66eb32010-05-01 00:40:08 +0000779 if (RequireCompleteDeclContext(SS, SemanticContext))
780 return true;
781
John McCall27b18f82009-11-17 02:14:36 +0000782 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000783 } else {
784 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000785 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000786 }
Mike Stump11289f42009-09-09 15:08:12 +0000787
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000788 if (Previous.isAmbiguous())
789 return true;
790
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000791 NamedDecl *PrevDecl = 0;
792 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000793 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000794
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000795 // If there is a previous declaration with the same name, check
796 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000797 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000798 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000799
800 // We may have found the injected-class-name of a class template,
801 // class template partial specialization, or class template specialization.
802 // In these cases, grab the template that is being defined or specialized.
803 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
804 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
805 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
806 PrevClassTemplate
807 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
808 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
809 PrevClassTemplate
810 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
811 ->getSpecializedTemplate();
812 }
813 }
814
John McCalld43784f2009-12-18 11:25:59 +0000815 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000816 // C++ [namespace.memdef]p3:
817 // [...] When looking for a prior declaration of a class or a function
818 // declared as a friend, and when the name of the friend class or
819 // function is neither a qualified name nor a template-id, scopes outside
820 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000821 if (!SS.isSet()) {
822 DeclContext *OutermostContext = CurContext;
823 while (!OutermostContext->isFileContext())
824 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000825
Douglas Gregorb74b1032010-04-18 17:37:40 +0000826 if (PrevDecl &&
827 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
828 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
829 SemanticContext = PrevDecl->getDeclContext();
830 } else {
831 // Declarations in outer scopes don't matter. However, the outermost
832 // context we computed is the semantic context for our new
833 // declaration.
834 PrevDecl = PrevClassTemplate = 0;
835 SemanticContext = OutermostContext;
836 }
John McCall90d3bb92009-12-17 23:21:11 +0000837 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000838
John McCall90d3bb92009-12-17 23:21:11 +0000839 if (CurContext->isDependentContext()) {
840 // If this is a dependent context, we don't want to link the friend
841 // class template to the template in scope, because that would perform
842 // checking of the template parameter lists that can't be performed
843 // until the outer context is instantiated.
844 PrevDecl = PrevClassTemplate = 0;
845 }
846 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
847 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000848
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000849 if (PrevClassTemplate) {
850 // Ensure that the template parameter lists are compatible.
851 if (!TemplateParameterListsAreEqual(TemplateParams,
852 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000853 /*Complain=*/true,
854 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000855 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000856
857 // C++ [temp.class]p4:
858 // In a redeclaration, partial specialization, explicit
859 // specialization or explicit instantiation of a class template,
860 // the class-key shall agree in kind with the original class
861 // template declaration (7.1.5.3).
862 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000863 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000864 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000865 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000866 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000867 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000868 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000869 }
870
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000871 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000872 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000873 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000874 Diag(NameLoc, diag::err_redefinition) << Name;
875 Diag(Def->getLocation(), diag::note_previous_definition);
876 // FIXME: Would it make sense to try to "forget" the previous
877 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000878 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000879 }
880 }
881 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
882 // Maybe we will complain about the shadowed template parameter.
883 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
884 // Just pretend that we didn't see the previous declaration.
885 PrevDecl = 0;
886 } else if (PrevDecl) {
887 // C++ [temp]p5:
888 // A class template shall not have the same name as any other
889 // template, class, function, object, enumeration, enumerator,
890 // namespace, or type in the same scope (3.3), except as specified
891 // in (14.5.4).
892 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
893 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000894 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000895 }
896
Douglas Gregordba32632009-02-10 19:49:53 +0000897 // Check the template parameter list of this declaration, possibly
898 // merging in the template parameter list from the previous class
899 // template declaration.
900 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000901 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
902 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000903 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000904
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000905 if (SS.isSet()) {
906 // If the name of the template was qualified, we must be defining the
907 // template out-of-line.
908 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
909 !(TUK == TUK_Friend && CurContext->isDependentContext()))
910 Diag(NameLoc, diag::err_member_def_does_not_match)
911 << Name << SemanticContext << SS.getRange();
912 }
913
Mike Stump11289f42009-09-09 15:08:12 +0000914 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000915 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000916 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000917 PrevClassTemplate->getTemplatedDecl() : 0,
918 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000919 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000920
921 ClassTemplateDecl *NewTemplate
922 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
923 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000924 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000925 NewClass->setDescribedClassTemplate(NewTemplate);
926
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000927 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000928 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
929 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000930 assert(T->isDependentType() && "Class template type is not dependent?");
931 (void)T;
932
Douglas Gregorcf915552009-10-13 16:30:37 +0000933 // If we are providing an explicit specialization of a member that is a
934 // class template, make a note of that.
935 if (PrevClassTemplate &&
936 PrevClassTemplate->getInstantiatedFromMemberTemplate())
937 PrevClassTemplate->setMemberSpecialization();
938
Anders Carlsson137108d2009-03-26 01:24:28 +0000939 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000940 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000941 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000943 // Set the lexical context of these templates
944 NewClass->setLexicalDeclContext(CurContext);
945 NewTemplate->setLexicalDeclContext(CurContext);
946
John McCall9bb74a52009-07-31 02:45:11 +0000947 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000948 NewClass->startDefinition();
949
950 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000951 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000952
John McCall27b5c252009-09-14 21:59:20 +0000953 if (TUK != TUK_Friend)
954 PushOnScopeChains(NewTemplate, S);
955 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000956 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000957 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000958 NewClass->setAccess(PrevClassTemplate->getAccess());
959 }
John McCall27b5c252009-09-14 21:59:20 +0000960
Douglas Gregor3dad8422009-09-26 06:47:28 +0000961 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
962 PrevClassTemplate != NULL);
963
John McCall27b5c252009-09-14 21:59:20 +0000964 // Friend templates are visible in fairly strange ways.
965 if (!CurContext->isDependentContext()) {
966 DeclContext *DC = SemanticContext->getLookupContext();
967 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
968 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
969 PushOnScopeChains(NewTemplate, EnclosingScope,
970 /* AddToContext = */ false);
971 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000972
973 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
974 NewClass->getLocation(),
975 NewTemplate,
976 /*FIXME:*/NewClass->getLocation());
977 Friend->setAccess(AS_public);
978 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000979 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000980
Douglas Gregordba32632009-02-10 19:49:53 +0000981 if (Invalid) {
982 NewTemplate->setInvalidDecl();
983 NewClass->setInvalidDecl();
984 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000985 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000986}
987
Douglas Gregored5731f2009-11-25 17:50:39 +0000988/// \brief Diagnose the presence of a default template argument on a
989/// template parameter, which is ill-formed in certain contexts.
990///
991/// \returns true if the default template argument should be dropped.
992static bool DiagnoseDefaultTemplateArgument(Sema &S,
993 Sema::TemplateParamListContext TPC,
994 SourceLocation ParamLoc,
995 SourceRange DefArgRange) {
996 switch (TPC) {
997 case Sema::TPC_ClassTemplate:
998 return false;
999
1000 case Sema::TPC_FunctionTemplate:
1001 // C++ [temp.param]p9:
1002 // A default template-argument shall not be specified in a
1003 // function template declaration or a function template
1004 // definition [...]
1005 // (This sentence is not in C++0x, per DR226).
1006 if (!S.getLangOptions().CPlusPlus0x)
1007 S.Diag(ParamLoc,
1008 diag::err_template_parameter_default_in_function_template)
1009 << DefArgRange;
1010 return false;
1011
1012 case Sema::TPC_ClassTemplateMember:
1013 // C++0x [temp.param]p9:
1014 // A default template-argument shall not be specified in the
1015 // template-parameter-lists of the definition of a member of a
1016 // class template that appears outside of the member's class.
1017 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1018 << DefArgRange;
1019 return true;
1020
1021 case Sema::TPC_FriendFunctionTemplate:
1022 // C++ [temp.param]p9:
1023 // A default template-argument shall not be specified in a
1024 // friend template declaration.
1025 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1026 << DefArgRange;
1027 return true;
1028
1029 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1030 // for friend function templates if there is only a single
1031 // declaration (and it is a definition). Strange!
1032 }
1033
1034 return false;
1035}
1036
Douglas Gregordba32632009-02-10 19:49:53 +00001037/// \brief Checks the validity of a template parameter list, possibly
1038/// considering the template parameter list from a previous
1039/// declaration.
1040///
1041/// If an "old" template parameter list is provided, it must be
1042/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1043/// template parameter list.
1044///
1045/// \param NewParams Template parameter list for a new template
1046/// declaration. This template parameter list will be updated with any
1047/// default arguments that are carried through from the previous
1048/// template parameter list.
1049///
1050/// \param OldParams If provided, template parameter list from a
1051/// previous declaration of the same template. Default template
1052/// arguments will be merged from the old template parameter list to
1053/// the new template parameter list.
1054///
Douglas Gregored5731f2009-11-25 17:50:39 +00001055/// \param TPC Describes the context in which we are checking the given
1056/// template parameter list.
1057///
Douglas Gregordba32632009-02-10 19:49:53 +00001058/// \returns true if an error occurred, false otherwise.
1059bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001060 TemplateParameterList *OldParams,
1061 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001062 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001063
Douglas Gregordba32632009-02-10 19:49:53 +00001064 // C++ [temp.param]p10:
1065 // The set of default template-arguments available for use with a
1066 // template declaration or definition is obtained by merging the
1067 // default arguments from the definition (if in scope) and all
1068 // declarations in scope in the same way default function
1069 // arguments are (8.3.6).
1070 bool SawDefaultArgument = false;
1071 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001072
Anders Carlsson327865d2009-06-12 23:20:15 +00001073 bool SawParameterPack = false;
1074 SourceLocation ParameterPackLoc;
1075
Mike Stumpc89c8e32009-02-11 23:03:27 +00001076 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001077 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001078 if (OldParams)
1079 OldParam = OldParams->begin();
1080
1081 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1082 NewParamEnd = NewParams->end();
1083 NewParam != NewParamEnd; ++NewParam) {
1084 // Variables used to diagnose redundant default arguments
1085 bool RedundantDefaultArg = false;
1086 SourceLocation OldDefaultLoc;
1087 SourceLocation NewDefaultLoc;
1088
1089 // Variables used to diagnose missing default arguments
1090 bool MissingDefaultArg = false;
1091
Anders Carlsson327865d2009-06-12 23:20:15 +00001092 // C++0x [temp.param]p11:
1093 // If a template parameter of a class template is a template parameter pack,
1094 // it must be the last template parameter.
1095 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001096 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001097 diag::err_template_param_pack_must_be_last_template_parameter);
1098 Invalid = true;
1099 }
1100
Douglas Gregordba32632009-02-10 19:49:53 +00001101 if (TemplateTypeParmDecl *NewTypeParm
1102 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001103 // Check the presence of a default argument here.
1104 if (NewTypeParm->hasDefaultArgument() &&
1105 DiagnoseDefaultTemplateArgument(*this, TPC,
1106 NewTypeParm->getLocation(),
1107 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001108 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001109 NewTypeParm->removeDefaultArgument();
1110
1111 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001112 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001113 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001114
Anders Carlsson327865d2009-06-12 23:20:15 +00001115 if (NewTypeParm->isParameterPack()) {
1116 assert(!NewTypeParm->hasDefaultArgument() &&
1117 "Parameter packs can't have a default argument!");
1118 SawParameterPack = true;
1119 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001120 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001121 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001122 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1123 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1124 SawDefaultArgument = true;
1125 RedundantDefaultArg = true;
1126 PreviousDefaultArgLoc = NewDefaultLoc;
1127 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1128 // Merge the default argument from the old declaration to the
1129 // new declaration.
1130 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001131 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001132 true);
1133 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1134 } else if (NewTypeParm->hasDefaultArgument()) {
1135 SawDefaultArgument = true;
1136 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1137 } else if (SawDefaultArgument)
1138 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001139 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001140 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001141 // Check the presence of a default argument here.
1142 if (NewNonTypeParm->hasDefaultArgument() &&
1143 DiagnoseDefaultTemplateArgument(*this, TPC,
1144 NewNonTypeParm->getLocation(),
1145 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1146 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
Abramo Bagnara656e3002010-06-09 09:26:05 +00001147 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001148 }
1149
Mike Stump12b8ce12009-08-04 21:02:39 +00001150 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001151 NonTypeTemplateParmDecl *OldNonTypeParm
1152 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001153 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001154 NewNonTypeParm->hasDefaultArgument()) {
1155 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1156 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1157 SawDefaultArgument = true;
1158 RedundantDefaultArg = true;
1159 PreviousDefaultArgLoc = NewDefaultLoc;
1160 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1161 // Merge the default argument from the old declaration to the
1162 // new declaration.
1163 SawDefaultArgument = true;
1164 // FIXME: We need to create a new kind of "default argument"
1165 // expression that points to a previous template template
1166 // parameter.
1167 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001168 OldNonTypeParm->getDefaultArgument(),
1169 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001170 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1171 } else if (NewNonTypeParm->hasDefaultArgument()) {
1172 SawDefaultArgument = true;
1173 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1174 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001175 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001176 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001177 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001178 TemplateTemplateParmDecl *NewTemplateParm
1179 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001180 if (NewTemplateParm->hasDefaultArgument() &&
1181 DiagnoseDefaultTemplateArgument(*this, TPC,
1182 NewTemplateParm->getLocation(),
1183 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001184 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001185
1186 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001187 TemplateTemplateParmDecl *OldTemplateParm
1188 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001189 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001190 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001191 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1192 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001193 SawDefaultArgument = true;
1194 RedundantDefaultArg = true;
1195 PreviousDefaultArgLoc = NewDefaultLoc;
1196 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1197 // Merge the default argument from the old declaration to the
1198 // new declaration.
1199 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001200 // FIXME: We need to create a new kind of "default argument" expression
1201 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001202 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001203 OldTemplateParm->getDefaultArgument(),
1204 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001205 PreviousDefaultArgLoc
1206 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001207 } else if (NewTemplateParm->hasDefaultArgument()) {
1208 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001209 PreviousDefaultArgLoc
1210 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001211 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001212 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001213 }
1214
1215 if (RedundantDefaultArg) {
1216 // C++ [temp.param]p12:
1217 // A template-parameter shall not be given default arguments
1218 // by two different declarations in the same scope.
1219 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1220 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1221 Invalid = true;
1222 } else if (MissingDefaultArg) {
1223 // C++ [temp.param]p11:
1224 // If a template-parameter has a default template-argument,
1225 // all subsequent template-parameters shall have a default
1226 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001227 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001228 diag::err_template_param_default_arg_missing);
1229 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1230 Invalid = true;
1231 }
1232
1233 // If we have an old template parameter list that we're merging
1234 // in, move on to the next parameter.
1235 if (OldParams)
1236 ++OldParam;
1237 }
1238
1239 return Invalid;
1240}
Douglas Gregord32e0282009-02-09 23:23:08 +00001241
Mike Stump11289f42009-09-09 15:08:12 +00001242/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001243/// specifier, returning the template parameter list that applies to the
1244/// name.
1245///
1246/// \param DeclStartLoc the start of the declaration that has a scope
1247/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001248///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001249/// \param SS the scope specifier that will be matched to the given template
1250/// parameter lists. This scope specifier precedes a qualified name that is
1251/// being declared.
1252///
1253/// \param ParamLists the template parameter lists, from the outermost to the
1254/// innermost template parameter lists.
1255///
1256/// \param NumParamLists the number of template parameter lists in ParamLists.
1257///
John McCalle820e5e2010-04-13 20:37:33 +00001258/// \param IsFriend Whether to apply the slightly different rules for
1259/// matching template parameters to scope specifiers in friend
1260/// declarations.
1261///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001262/// \param IsExplicitSpecialization will be set true if the entity being
1263/// declared is an explicit specialization, false otherwise.
1264///
Mike Stump11289f42009-09-09 15:08:12 +00001265/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001266/// name that is preceded by the scope specifier @p SS. This template
1267/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001268/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001269/// template specialization), or may be NULL (if we were's declaring isn't
1270/// itself a template).
1271TemplateParameterList *
1272Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1273 const CXXScopeSpec &SS,
1274 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001275 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001276 bool IsFriend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001277 bool &IsExplicitSpecialization) {
1278 IsExplicitSpecialization = false;
1279
Douglas Gregord8d297c2009-07-21 23:53:31 +00001280 // Find the template-ids that occur within the nested-name-specifier. These
1281 // template-ids will match up with the template parameter lists.
1282 llvm::SmallVector<const TemplateSpecializationType *, 4>
1283 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001284 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1285 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001286 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1287 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001288 const Type *T = NNS->getAsType();
1289 if (!T) break;
1290
1291 // C++0x [temp.expl.spec]p17:
1292 // A member or a member template may be nested within many
1293 // enclosing class templates. In an explicit specialization for
1294 // such a member, the member declaration shall be preceded by a
1295 // template<> for each enclosing class template that is
1296 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001297 //
1298 // Following the existing practice of GNU and EDG, we allow a typedef of a
1299 // template specialization type.
1300 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1301 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001302
Mike Stump11289f42009-09-09 15:08:12 +00001303 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001304 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001305 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1306 if (!Template)
1307 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001308
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001309 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001310 ClassTemplateSpecializationDecl *SpecDecl
1311 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1312 // If the nested name specifier refers to an explicit specialization,
1313 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001314 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1315 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001316 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001317 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001318 }
Mike Stump11289f42009-09-09 15:08:12 +00001319
Douglas Gregord8d297c2009-07-21 23:53:31 +00001320 TemplateIdsInSpecifier.push_back(SpecType);
1321 }
1322 }
Mike Stump11289f42009-09-09 15:08:12 +00001323
Douglas Gregord8d297c2009-07-21 23:53:31 +00001324 // Reverse the list of template-ids in the scope specifier, so that we can
1325 // more easily match up the template-ids and the template parameter lists.
1326 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001327
Douglas Gregord8d297c2009-07-21 23:53:31 +00001328 SourceLocation FirstTemplateLoc = DeclStartLoc;
1329 if (NumParamLists)
1330 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001331
Douglas Gregord8d297c2009-07-21 23:53:31 +00001332 // Match the template-ids found in the specifier to the template parameter
1333 // lists.
1334 unsigned Idx = 0;
1335 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1336 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001337 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1338 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001339 if (Idx >= NumParamLists) {
1340 // We have a template-id without a corresponding template parameter
1341 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001342
1343 // ...which is fine if this is a friend declaration.
1344 if (IsFriend) {
1345 IsExplicitSpecialization = true;
1346 break;
1347 }
1348
Douglas Gregord8d297c2009-07-21 23:53:31 +00001349 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001350 // FIXME: the location information here isn't great.
1351 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001352 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001353 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001354 << SS.getRange();
1355 } else {
1356 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1357 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001358 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001359 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001360 }
1361 return 0;
1362 }
Mike Stump11289f42009-09-09 15:08:12 +00001363
Douglas Gregord8d297c2009-07-21 23:53:31 +00001364 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001365 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001366 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001367
John McCall2408e322010-04-27 00:57:59 +00001368 // Are there cases in (e.g.) friends where this won't match?
1369 if (const InjectedClassNameType *Injected
1370 = TemplateId->getAs<InjectedClassNameType>()) {
1371 CXXRecordDecl *Record = Injected->getDecl();
1372 if (ClassTemplatePartialSpecializationDecl *Partial =
1373 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1374 ExpectedTemplateParams = Partial->getTemplateParameters();
1375 else
1376 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1377 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001378 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001379
John McCall2408e322010-04-27 00:57:59 +00001380 if (ExpectedTemplateParams)
1381 TemplateParameterListsAreEqual(ParamLists[Idx],
1382 ExpectedTemplateParams,
1383 true, TPL_TemplateMatch);
1384
Douglas Gregored5731f2009-11-25 17:50:39 +00001385 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001386 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001387 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001388 diag::err_template_param_list_matches_nontemplate)
1389 << TemplateId
1390 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001391 else
1392 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001393 }
Mike Stump11289f42009-09-09 15:08:12 +00001394
Douglas Gregord8d297c2009-07-21 23:53:31 +00001395 // If there were at least as many template-ids as there were template
1396 // parameter lists, then there are no template parameter lists remaining for
1397 // the declaration itself.
1398 if (Idx >= NumParamLists)
1399 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001400
Douglas Gregord8d297c2009-07-21 23:53:31 +00001401 // If there were too many template parameter lists, complain about that now.
1402 if (Idx != NumParamLists - 1) {
1403 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001404 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001405 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001406 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1407 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001408 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1409 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001410
1411 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1412 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1413 diag::note_explicit_template_spec_does_not_need_header)
1414 << ExplicitSpecializationsInSpecifier.back();
1415 ExplicitSpecializationsInSpecifier.pop_back();
1416 }
1417
Douglas Gregord8d297c2009-07-21 23:53:31 +00001418 ++Idx;
1419 }
1420 }
Mike Stump11289f42009-09-09 15:08:12 +00001421
Douglas Gregord8d297c2009-07-21 23:53:31 +00001422 // Return the last template parameter list, which corresponds to the
1423 // entity being declared.
1424 return ParamLists[NumParamLists - 1];
1425}
1426
Douglas Gregordc572a32009-03-30 22:58:21 +00001427QualType Sema::CheckTemplateIdType(TemplateName Name,
1428 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001429 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001430 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001431 if (!Template) {
1432 // The template name does not resolve to a template, so we just
1433 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001434 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001435 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001436
Douglas Gregorc40290e2009-03-09 23:48:35 +00001437 // Check that the template argument list is well-formed for this
1438 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001439 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001440 TemplateArgs.size());
1441 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001442 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001443 return QualType();
1444
Mike Stump11289f42009-09-09 15:08:12 +00001445 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001446 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001447 "Converted template argument list is too short!");
1448
1449 QualType CanonType;
1450
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001451 if (Name.isDependent() ||
1452 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001453 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001454 // This class template specialization is a dependent
1455 // type. Therefore, its canonical type is another class template
1456 // specialization type that contains all of the converted
1457 // arguments in canonical form. This ensures that, e.g., A<T> and
1458 // A<T, T> have identical types when A is declared as:
1459 //
1460 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001461 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001462 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001463 Converted.getFlatArguments(),
1464 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001465
Douglas Gregora8e02e72009-07-28 23:00:59 +00001466 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001467 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001468 // In the future, we need to teach getTemplateSpecializationType to only
1469 // build the canonical type and return that to us.
1470 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001471
1472 // This might work out to be a current instantiation, in which
1473 // case the canonical type needs to be the InjectedClassNameType.
1474 //
1475 // TODO: in theory this could be a simple hashtable lookup; most
1476 // changes to CurContext don't change the set of current
1477 // instantiations.
1478 if (isa<ClassTemplateDecl>(Template)) {
1479 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1480 // If we get out to a namespace, we're done.
1481 if (Ctx->isFileContext()) break;
1482
1483 // If this isn't a record, keep looking.
1484 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1485 if (!Record) continue;
1486
1487 // Look for one of the two cases with InjectedClassNameTypes
1488 // and check whether it's the same template.
1489 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1490 !Record->getDescribedClassTemplate())
1491 continue;
1492
1493 // Fetch the injected class name type and check whether its
1494 // injected type is equal to the type we just built.
1495 QualType ICNT = Context.getTypeDeclType(Record);
1496 QualType Injected = cast<InjectedClassNameType>(ICNT)
1497 ->getInjectedSpecializationType();
1498
1499 if (CanonType != Injected->getCanonicalTypeInternal())
1500 continue;
1501
1502 // If so, the canonical type of this TST is the injected
1503 // class name type of the record we just found.
1504 assert(ICNT.isCanonical());
1505 CanonType = ICNT;
John McCall2408e322010-04-27 00:57:59 +00001506 break;
1507 }
1508 }
Mike Stump11289f42009-09-09 15:08:12 +00001509 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001510 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001511 // Find the class template specialization declaration that
1512 // corresponds to these arguments.
1513 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001514 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001515 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001516 Converted.flatSize(),
1517 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001518 void *InsertPos = 0;
1519 ClassTemplateSpecializationDecl *Decl
1520 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1521 if (!Decl) {
1522 // This is the first time we have referenced this class template
1523 // specialization. Create the canonical declaration and add it to
1524 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001525 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001526 ClassTemplate->getTemplatedDecl()->getTagKind(),
1527 ClassTemplate->getDeclContext(),
1528 ClassTemplate->getLocation(),
1529 ClassTemplate,
1530 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001531 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1532 Decl->setLexicalDeclContext(CurContext);
1533 }
1534
1535 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001536 assert(isa<RecordType>(CanonType) &&
1537 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001538 }
Mike Stump11289f42009-09-09 15:08:12 +00001539
Douglas Gregorc40290e2009-03-09 23:48:35 +00001540 // Build the fully-sugared type for this class template
1541 // specialization, which refers back to the class template
1542 // specialization we created or found.
John McCall30576cd2010-06-13 09:25:03 +00001543 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001544}
1545
Douglas Gregor67a65642009-02-17 23:15:12 +00001546Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001547Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001548 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001549 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001550 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001551 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001552
Douglas Gregorc40290e2009-03-09 23:48:35 +00001553 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001554 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001555 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001556
John McCall6b51f282009-11-23 01:53:49 +00001557 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001558 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001559
1560 if (Result.isNull())
1561 return true;
1562
John McCallbcd03502009-12-07 02:54:59 +00001563 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001564 TemplateSpecializationTypeLoc TL
1565 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1566 TL.setTemplateNameLoc(TemplateLoc);
1567 TL.setLAngleLoc(LAngleLoc);
1568 TL.setRAngleLoc(RAngleLoc);
1569 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1570 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1571
1572 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001573}
John McCall06f6fe8d2009-09-04 01:14:41 +00001574
John McCalld8fe9af2009-09-08 17:47:29 +00001575Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1576 TagUseKind TUK,
1577 DeclSpec::TST TagSpec,
1578 SourceLocation TagLoc) {
1579 if (TypeResult.isInvalid())
1580 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001581
John McCall0ad16662009-10-29 08:12:44 +00001582 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001583 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001584 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001585
John McCalld8fe9af2009-09-08 17:47:29 +00001586 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001587 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001588
John McCalld8fe9af2009-09-08 17:47:29 +00001589 if (const RecordType *RT = Type->getAs<RecordType>()) {
1590 RecordDecl *D = RT->getDecl();
1591
1592 IdentifierInfo *Id = D->getIdentifier();
1593 assert(Id && "templated class must have an identifier");
1594
1595 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1596 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001597 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001598 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001599 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001600 }
1601 }
1602
Abramo Bagnara6150c882010-05-11 21:36:43 +00001603 ElaboratedTypeKeyword Keyword
1604 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1605 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001606
1607 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001608}
1609
John McCalle66edc12009-11-24 19:00:30 +00001610Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1611 LookupResult &R,
1612 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001613 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001614 // FIXME: Can we do any checking at this point? I guess we could check the
1615 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001616 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001617 // though.
John McCalle66edc12009-11-24 19:00:30 +00001618
1619 // These should be filtered out by our callers.
1620 assert(!R.empty() && "empty lookup results when building templateid");
1621 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1622
1623 NestedNameSpecifier *Qualifier = 0;
1624 SourceRange QualifierRange;
1625 if (SS.isSet()) {
1626 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1627 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001628 }
John McCall58cc69d2010-01-27 01:50:18 +00001629
1630 // We don't want lookup warnings at this point.
1631 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001632
John McCalle66edc12009-11-24 19:00:30 +00001633 bool Dependent
1634 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1635 &TemplateArgs);
1636 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001637 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001638 Qualifier, QualifierRange,
1639 R.getLookupName(), R.getNameLoc(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001640 RequiresADL, TemplateArgs,
1641 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001642
1643 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001644}
1645
John McCalle66edc12009-11-24 19:00:30 +00001646// We actually only call this from template instantiation.
1647Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001648Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001649 DeclarationName Name,
1650 SourceLocation NameLoc,
1651 const TemplateArgumentListInfo &TemplateArgs) {
1652 DeclContext *DC;
1653 if (!(DC = computeDeclContext(SS, false)) ||
1654 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001655 RequireCompleteDeclContext(SS, DC))
John McCalle66edc12009-11-24 19:00:30 +00001656 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001657
Douglas Gregor786123d2010-05-21 23:18:07 +00001658 bool MemberOfUnknownSpecialization;
John McCalle66edc12009-11-24 19:00:30 +00001659 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001660 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1661 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001662
John McCalle66edc12009-11-24 19:00:30 +00001663 if (R.isAmbiguous())
1664 return ExprError();
1665
1666 if (R.empty()) {
1667 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1668 << Name << SS.getRange();
1669 return ExprError();
1670 }
1671
1672 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1673 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1674 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1675 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1676 return ExprError();
1677 }
1678
1679 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001680}
1681
Douglas Gregorb67535d2009-03-31 00:43:58 +00001682/// \brief Form a dependent template name.
1683///
1684/// This action forms a dependent template name given the template
1685/// name and its (presumably dependent) scope specifier. For
1686/// example, given "MetaFun::template apply", the scope specifier \p
1687/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1688/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001689Sema::TemplateTy
Douglas Gregorf7d77712010-06-16 22:31:08 +00001690Sema::ActOnDependentTemplateName(Scope *S, SourceLocation TemplateKWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001691 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001692 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001693 TypeTy *ObjectType,
1694 bool EnteringContext) {
Douglas Gregorf7d77712010-06-16 22:31:08 +00001695 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1696 !getLangOptions().CPlusPlus0x)
1697 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1698 << FixItHint::CreateRemoval(TemplateKWLoc);
1699
Douglas Gregor9abe2372010-01-19 16:01:07 +00001700 DeclContext *LookupCtx = 0;
1701 if (SS.isSet())
1702 LookupCtx = computeDeclContext(SS, EnteringContext);
1703 if (!LookupCtx && ObjectType)
1704 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1705 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001706 // C++0x [temp.names]p5:
1707 // If a name prefixed by the keyword template is not the name of
1708 // a template, the program is ill-formed. [Note: the keyword
1709 // template may not be applied to non-template members of class
1710 // templates. -end note ] [ Note: as is the case with the
1711 // typename prefix, the template prefix is allowed in cases
1712 // where it is not strictly necessary; i.e., when the
1713 // nested-name-specifier or the expression on the left of the ->
1714 // or . is not dependent on a template-parameter, or the use
1715 // does not appear in the scope of a template. -end note]
1716 //
1717 // Note: C++03 was more strict here, because it banned the use of
1718 // the "template" keyword prior to a template-name that was not a
1719 // dependent name. C++ DR468 relaxed this requirement (the
1720 // "template" keyword is now permitted). We follow the C++0x
Douglas Gregorc9d26822010-06-14 22:07:54 +00001721 // rules, even in C++03 mode with a warning, retroactively applying the DR.
Douglas Gregorb67535d2009-03-31 00:43:58 +00001722 TemplateTy Template;
Douglas Gregor786123d2010-05-21 23:18:07 +00001723 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001724 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001725 EnteringContext, Template,
1726 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001727 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1728 isa<CXXRecordDecl>(LookupCtx) &&
1729 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001730 // This is a dependent template.
1731 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001732 Diag(Name.getSourceRange().getBegin(),
1733 diag::err_template_kw_refers_to_non_template)
1734 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001735 << Name.getSourceRange()
1736 << TemplateKWLoc;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001737 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001738 } else {
1739 // We found something; return it.
1740 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001741 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001742 }
1743
Mike Stump11289f42009-09-09 15:08:12 +00001744 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001745 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001746
1747 switch (Name.getKind()) {
1748 case UnqualifiedId::IK_Identifier:
1749 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1750 Name.Identifier));
1751
Douglas Gregor71395fa2009-11-04 00:56:37 +00001752 case UnqualifiedId::IK_OperatorFunctionId:
1753 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1754 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001755
1756 case UnqualifiedId::IK_LiteralOperatorId:
1757 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1758
Douglas Gregor3cf81312009-11-03 23:16:33 +00001759 default:
1760 break;
1761 }
1762
1763 Diag(Name.getSourceRange().getBegin(),
1764 diag::err_template_kw_refers_to_non_template)
1765 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001766 << Name.getSourceRange()
1767 << TemplateKWLoc;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001768 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001769}
1770
Mike Stump11289f42009-09-09 15:08:12 +00001771bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001772 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001773 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001774 const TemplateArgument &Arg = AL.getArgument();
1775
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001776 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001777 switch(Arg.getKind()) {
1778 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001779 // C++ [temp.arg.type]p1:
1780 // A template-argument for a template-parameter which is a
1781 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001782 break;
1783 case TemplateArgument::Template: {
1784 // We have a template type parameter but the template argument
1785 // is a template without any arguments.
1786 SourceRange SR = AL.getSourceRange();
1787 TemplateName Name = Arg.getAsTemplate();
1788 Diag(SR.getBegin(), diag::err_template_missing_args)
1789 << Name << SR;
1790 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1791 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001792
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001793 return true;
1794 }
1795 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001796 // We have a template type parameter but the template argument
1797 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001798 SourceRange SR = AL.getSourceRange();
1799 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001800 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001801
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001802 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001803 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001804 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001805
John McCallbcd03502009-12-07 02:54:59 +00001806 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001807 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001808
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001809 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001810 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001811 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001812 return false;
1813}
1814
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001815/// \brief Substitute template arguments into the default template argument for
1816/// the given template type parameter.
1817///
1818/// \param SemaRef the semantic analysis object for which we are performing
1819/// the substitution.
1820///
1821/// \param Template the template that we are synthesizing template arguments
1822/// for.
1823///
1824/// \param TemplateLoc the location of the template name that started the
1825/// template-id we are checking.
1826///
1827/// \param RAngleLoc the location of the right angle bracket ('>') that
1828/// terminates the template-id.
1829///
1830/// \param Param the template template parameter whose default we are
1831/// substituting into.
1832///
1833/// \param Converted the list of template arguments provided for template
1834/// parameters that precede \p Param in the template parameter list.
1835///
1836/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001837static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001838SubstDefaultTemplateArgument(Sema &SemaRef,
1839 TemplateDecl *Template,
1840 SourceLocation TemplateLoc,
1841 SourceLocation RAngleLoc,
1842 TemplateTypeParmDecl *Param,
1843 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001844 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001845
1846 // If the argument type is dependent, instantiate it now based
1847 // on the previously-computed template arguments.
1848 if (ArgType->getType()->isDependentType()) {
1849 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1850 /*TakeArgs=*/false);
1851
1852 MultiLevelTemplateArgumentList AllTemplateArgs
1853 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1854
1855 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1856 Template, Converted.getFlatArguments(),
1857 Converted.flatSize(),
1858 SourceRange(TemplateLoc, RAngleLoc));
1859
1860 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1861 Param->getDefaultArgumentLoc(),
1862 Param->getDeclName());
1863 }
1864
1865 return ArgType;
1866}
1867
1868/// \brief Substitute template arguments into the default template argument for
1869/// the given non-type template parameter.
1870///
1871/// \param SemaRef the semantic analysis object for which we are performing
1872/// the substitution.
1873///
1874/// \param Template the template that we are synthesizing template arguments
1875/// for.
1876///
1877/// \param TemplateLoc the location of the template name that started the
1878/// template-id we are checking.
1879///
1880/// \param RAngleLoc the location of the right angle bracket ('>') that
1881/// terminates the template-id.
1882///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001883/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001884/// substituting into.
1885///
1886/// \param Converted the list of template arguments provided for template
1887/// parameters that precede \p Param in the template parameter list.
1888///
1889/// \returns the substituted template argument, or NULL if an error occurred.
1890static Sema::OwningExprResult
1891SubstDefaultTemplateArgument(Sema &SemaRef,
1892 TemplateDecl *Template,
1893 SourceLocation TemplateLoc,
1894 SourceLocation RAngleLoc,
1895 NonTypeTemplateParmDecl *Param,
1896 TemplateArgumentListBuilder &Converted) {
1897 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1898 /*TakeArgs=*/false);
1899
1900 MultiLevelTemplateArgumentList AllTemplateArgs
1901 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1902
1903 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1904 Template, Converted.getFlatArguments(),
1905 Converted.flatSize(),
1906 SourceRange(TemplateLoc, RAngleLoc));
1907
1908 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1909}
1910
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001911/// \brief Substitute template arguments into the default template argument for
1912/// the given template template parameter.
1913///
1914/// \param SemaRef the semantic analysis object for which we are performing
1915/// the substitution.
1916///
1917/// \param Template the template that we are synthesizing template arguments
1918/// for.
1919///
1920/// \param TemplateLoc the location of the template name that started the
1921/// template-id we are checking.
1922///
1923/// \param RAngleLoc the location of the right angle bracket ('>') that
1924/// terminates the template-id.
1925///
1926/// \param Param the template template parameter whose default we are
1927/// substituting into.
1928///
1929/// \param Converted the list of template arguments provided for template
1930/// parameters that precede \p Param in the template parameter list.
1931///
1932/// \returns the substituted template argument, or NULL if an error occurred.
1933static TemplateName
1934SubstDefaultTemplateArgument(Sema &SemaRef,
1935 TemplateDecl *Template,
1936 SourceLocation TemplateLoc,
1937 SourceLocation RAngleLoc,
1938 TemplateTemplateParmDecl *Param,
1939 TemplateArgumentListBuilder &Converted) {
1940 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1941 /*TakeArgs=*/false);
1942
1943 MultiLevelTemplateArgumentList AllTemplateArgs
1944 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1945
1946 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1947 Template, Converted.getFlatArguments(),
1948 Converted.flatSize(),
1949 SourceRange(TemplateLoc, RAngleLoc));
1950
1951 return SemaRef.SubstTemplateName(
1952 Param->getDefaultArgument().getArgument().getAsTemplate(),
1953 Param->getDefaultArgument().getTemplateNameLoc(),
1954 AllTemplateArgs);
1955}
1956
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001957/// \brief If the given template parameter has a default template
1958/// argument, substitute into that default template argument and
1959/// return the corresponding template argument.
1960TemplateArgumentLoc
1961Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1962 SourceLocation TemplateLoc,
1963 SourceLocation RAngleLoc,
1964 Decl *Param,
1965 TemplateArgumentListBuilder &Converted) {
1966 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1967 if (!TypeParm->hasDefaultArgument())
1968 return TemplateArgumentLoc();
1969
John McCallbcd03502009-12-07 02:54:59 +00001970 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001971 TemplateLoc,
1972 RAngleLoc,
1973 TypeParm,
1974 Converted);
1975 if (DI)
1976 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1977
1978 return TemplateArgumentLoc();
1979 }
1980
1981 if (NonTypeTemplateParmDecl *NonTypeParm
1982 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1983 if (!NonTypeParm->hasDefaultArgument())
1984 return TemplateArgumentLoc();
1985
1986 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1987 TemplateLoc,
1988 RAngleLoc,
1989 NonTypeParm,
1990 Converted);
1991 if (Arg.isInvalid())
1992 return TemplateArgumentLoc();
1993
1994 Expr *ArgE = Arg.takeAs<Expr>();
1995 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1996 }
1997
1998 TemplateTemplateParmDecl *TempTempParm
1999 = cast<TemplateTemplateParmDecl>(Param);
2000 if (!TempTempParm->hasDefaultArgument())
2001 return TemplateArgumentLoc();
2002
2003 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2004 TemplateLoc,
2005 RAngleLoc,
2006 TempTempParm,
2007 Converted);
2008 if (TName.isNull())
2009 return TemplateArgumentLoc();
2010
2011 return TemplateArgumentLoc(TemplateArgument(TName),
2012 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2013 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2014}
2015
Douglas Gregorda0fb532009-11-11 19:31:23 +00002016/// \brief Check that the given template argument corresponds to the given
2017/// template parameter.
2018bool Sema::CheckTemplateArgument(NamedDecl *Param,
2019 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002020 TemplateDecl *Template,
2021 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002022 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002023 TemplateArgumentListBuilder &Converted,
2024 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002025 // Check template type parameters.
2026 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002027 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002028
Douglas Gregoreebed722009-11-11 19:41:09 +00002029 // Check non-type template parameters.
2030 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002031 // Do substitution on the type of the non-type template parameter
2032 // with the template arguments we've seen thus far.
2033 QualType NTTPType = NTTP->getType();
2034 if (NTTPType->isDependentType()) {
2035 // Do substitution on the type of the non-type template parameter.
2036 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2037 NTTP, Converted.getFlatArguments(),
2038 Converted.flatSize(),
2039 SourceRange(TemplateLoc, RAngleLoc));
2040
2041 TemplateArgumentList TemplateArgs(Context, Converted,
2042 /*TakeArgs=*/false);
2043 NTTPType = SubstType(NTTPType,
2044 MultiLevelTemplateArgumentList(TemplateArgs),
2045 NTTP->getLocation(),
2046 NTTP->getDeclName());
2047 // If that worked, check the non-type template parameter type
2048 // for validity.
2049 if (!NTTPType.isNull())
2050 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2051 NTTP->getLocation());
2052 if (NTTPType.isNull())
2053 return true;
2054 }
2055
2056 switch (Arg.getArgument().getKind()) {
2057 case TemplateArgument::Null:
2058 assert(false && "Should never see a NULL template argument here");
2059 return true;
2060
2061 case TemplateArgument::Expression: {
2062 Expr *E = Arg.getArgument().getAsExpr();
2063 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002064 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002065 return true;
2066
2067 Converted.Append(Result);
2068 break;
2069 }
2070
2071 case TemplateArgument::Declaration:
2072 case TemplateArgument::Integral:
2073 // We've already checked this template argument, so just copy
2074 // it to the list of converted arguments.
2075 Converted.Append(Arg.getArgument());
2076 break;
2077
2078 case TemplateArgument::Template:
2079 // We were given a template template argument. It may not be ill-formed;
2080 // see below.
2081 if (DependentTemplateName *DTN
2082 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2083 // We have a template argument such as \c T::template X, which we
2084 // parsed as a template template argument. However, since we now
2085 // know that we need a non-type template argument, convert this
2086 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00002087 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2088 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002089 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002090 DTN->getIdentifier(),
2091 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002092
2093 TemplateArgument Result;
2094 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2095 return true;
2096
2097 Converted.Append(Result);
2098 break;
2099 }
2100
2101 // We have a template argument that actually does refer to a class
2102 // template, template alias, or template template parameter, and
2103 // therefore cannot be a non-type template argument.
2104 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2105 << Arg.getSourceRange();
2106
2107 Diag(Param->getLocation(), diag::note_template_param_here);
2108 return true;
2109
2110 case TemplateArgument::Type: {
2111 // We have a non-type template parameter but the template
2112 // argument is a type.
2113
2114 // C++ [temp.arg]p2:
2115 // In a template-argument, an ambiguity between a type-id and
2116 // an expression is resolved to a type-id, regardless of the
2117 // form of the corresponding template-parameter.
2118 //
2119 // We warn specifically about this case, since it can be rather
2120 // confusing for users.
2121 QualType T = Arg.getArgument().getAsType();
2122 SourceRange SR = Arg.getSourceRange();
2123 if (T->isFunctionType())
2124 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2125 else
2126 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2127 Diag(Param->getLocation(), diag::note_template_param_here);
2128 return true;
2129 }
2130
2131 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002132 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002133 break;
2134 }
2135
2136 return false;
2137 }
2138
2139
2140 // Check template template parameters.
2141 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2142
2143 // Substitute into the template parameter list of the template
2144 // template parameter, since previously-supplied template arguments
2145 // may appear within the template template parameter.
2146 {
2147 // Set up a template instantiation context.
2148 LocalInstantiationScope Scope(*this);
2149 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2150 TempParm, Converted.getFlatArguments(),
2151 Converted.flatSize(),
2152 SourceRange(TemplateLoc, RAngleLoc));
2153
2154 TemplateArgumentList TemplateArgs(Context, Converted,
2155 /*TakeArgs=*/false);
2156 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2157 SubstDecl(TempParm, CurContext,
2158 MultiLevelTemplateArgumentList(TemplateArgs)));
2159 if (!TempParm)
2160 return true;
2161
2162 // FIXME: TempParam is leaked.
2163 }
2164
2165 switch (Arg.getArgument().getKind()) {
2166 case TemplateArgument::Null:
2167 assert(false && "Should never see a NULL template argument here");
2168 return true;
2169
2170 case TemplateArgument::Template:
2171 if (CheckTemplateArgument(TempParm, Arg))
2172 return true;
2173
2174 Converted.Append(Arg.getArgument());
2175 break;
2176
2177 case TemplateArgument::Expression:
2178 case TemplateArgument::Type:
2179 // We have a template template parameter but the template
2180 // argument does not refer to a template.
2181 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2182 return true;
2183
2184 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002185 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002186 "Declaration argument with template template parameter");
2187 break;
2188 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002189 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002190 "Integral argument with template template parameter");
2191 break;
2192
2193 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002194 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002195 break;
2196 }
2197
2198 return false;
2199}
2200
Douglas Gregord32e0282009-02-09 23:23:08 +00002201/// \brief Check that the given template argument list is well-formed
2202/// for specializing the given template.
2203bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2204 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002205 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002206 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002207 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002208 TemplateParameterList *Params = Template->getTemplateParameters();
2209 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002210 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002211 bool Invalid = false;
2212
John McCall6b51f282009-11-23 01:53:49 +00002213 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2214
Mike Stump11289f42009-09-09 15:08:12 +00002215 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002216 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002217
Anders Carlsson15201f12009-06-13 02:08:00 +00002218 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002219 (NumArgs < Params->getMinRequiredArguments() &&
2220 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002221 // FIXME: point at either the first arg beyond what we can handle,
2222 // or the '>', depending on whether we have too many or too few
2223 // arguments.
2224 SourceRange Range;
2225 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002226 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002227 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2228 << (NumArgs > NumParams)
2229 << (isa<ClassTemplateDecl>(Template)? 0 :
2230 isa<FunctionTemplateDecl>(Template)? 1 :
2231 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2232 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002233 Diag(Template->getLocation(), diag::note_template_decl_here)
2234 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002235 Invalid = true;
2236 }
Mike Stump11289f42009-09-09 15:08:12 +00002237
2238 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002239 // [...] The type and form of each template-argument specified in
2240 // a template-id shall match the type and form specified for the
2241 // corresponding parameter declared by the template in its
2242 // template-parameter-list.
2243 unsigned ArgIdx = 0;
2244 for (TemplateParameterList::iterator Param = Params->begin(),
2245 ParamEnd = Params->end();
2246 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002247 if (ArgIdx > NumArgs && PartialTemplateArgs)
2248 break;
Mike Stump11289f42009-09-09 15:08:12 +00002249
Douglas Gregoreebed722009-11-11 19:41:09 +00002250 // If we have a template parameter pack, check every remaining template
2251 // argument against that template parameter pack.
2252 if ((*Param)->isTemplateParameterPack()) {
2253 Converted.BeginPack();
2254 for (; ArgIdx < NumArgs; ++ArgIdx) {
2255 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2256 TemplateLoc, RAngleLoc, Converted)) {
2257 Invalid = true;
2258 break;
2259 }
2260 }
2261 Converted.EndPack();
2262 continue;
2263 }
2264
Douglas Gregor84d49a22009-11-11 21:54:23 +00002265 if (ArgIdx < NumArgs) {
2266 // Check the template argument we were given.
2267 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2268 TemplateLoc, RAngleLoc, Converted))
2269 return true;
2270
2271 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002272 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002273
Douglas Gregor84d49a22009-11-11 21:54:23 +00002274 // We have a default template argument that we will use.
2275 TemplateArgumentLoc Arg;
2276
2277 // Retrieve the default template argument from the template
2278 // parameter. For each kind of template parameter, we substitute the
2279 // template arguments provided thus far and any "outer" template arguments
2280 // (when the template parameter was part of a nested template) into
2281 // the default argument.
2282 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2283 if (!TTP->hasDefaultArgument()) {
2284 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2285 break;
2286 }
2287
John McCallbcd03502009-12-07 02:54:59 +00002288 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002289 Template,
2290 TemplateLoc,
2291 RAngleLoc,
2292 TTP,
2293 Converted);
2294 if (!ArgType)
2295 return true;
2296
2297 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2298 ArgType);
2299 } else if (NonTypeTemplateParmDecl *NTTP
2300 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2301 if (!NTTP->hasDefaultArgument()) {
2302 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2303 break;
2304 }
2305
2306 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2307 TemplateLoc,
2308 RAngleLoc,
2309 NTTP,
2310 Converted);
2311 if (E.isInvalid())
2312 return true;
2313
2314 Expr *Ex = E.takeAs<Expr>();
2315 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2316 } else {
2317 TemplateTemplateParmDecl *TempParm
2318 = cast<TemplateTemplateParmDecl>(*Param);
2319
2320 if (!TempParm->hasDefaultArgument()) {
2321 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2322 break;
2323 }
2324
2325 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2326 TemplateLoc,
2327 RAngleLoc,
2328 TempParm,
2329 Converted);
2330 if (Name.isNull())
2331 return true;
2332
2333 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2334 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2335 TempParm->getDefaultArgument().getTemplateNameLoc());
2336 }
2337
2338 // Introduce an instantiation record that describes where we are using
2339 // the default template argument.
2340 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2341 Converted.getFlatArguments(),
2342 Converted.flatSize(),
2343 SourceRange(TemplateLoc, RAngleLoc));
2344
2345 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002346 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002347 RAngleLoc, Converted))
2348 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002349 }
2350
2351 return Invalid;
2352}
2353
2354/// \brief Check a template argument against its corresponding
2355/// template type parameter.
2356///
2357/// This routine implements the semantics of C++ [temp.arg.type]. It
2358/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002359bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002360 TypeSourceInfo *ArgInfo) {
2361 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002362 QualType Arg = ArgInfo->getType();
2363
Douglas Gregord32e0282009-02-09 23:23:08 +00002364 // C++ [temp.arg.type]p2:
2365 // A local type, a type with no linkage, an unnamed type or a type
2366 // compounded from any of these types shall not be used as a
2367 // template-argument for a template type-parameter.
2368 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002369 // FIXME: Perform the unnamed type check.
2370 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002371 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002372 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002373 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002374 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002375 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002376 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002377 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002378 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2379 << QualType(Tag, 0) << SR;
2380 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002381 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002382 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002383 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2384 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002385 } else if (Arg->isVariablyModifiedType()) {
2386 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2387 << Arg;
2388 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002389 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002390 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002391 }
2392
2393 return false;
2394}
2395
Douglas Gregorccb07762009-02-11 19:52:55 +00002396/// \brief Checks whether the given template argument is the address
2397/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002398static bool
2399CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2400 NonTypeTemplateParmDecl *Param,
2401 QualType ParamType,
2402 Expr *ArgIn,
2403 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002404 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002405 Expr *Arg = ArgIn;
2406 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002407
2408 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002409 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002410 Arg = Cast->getSubExpr();
2411
2412 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002413 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002414 // A template-argument for a non-type, non-template
2415 // template-parameter shall be one of: [...]
2416 //
2417 // -- the address of an object or function with external
2418 // linkage, including function templates and function
2419 // template-ids but excluding non-static class members,
2420 // expressed as & id-expression where the & is optional if
2421 // the name refers to a function or array, or if the
2422 // corresponding template-parameter is a reference; or
2423 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002424
Douglas Gregorccb07762009-02-11 19:52:55 +00002425 // Ignore (and complain about) any excess parentheses.
2426 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2427 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002428 S.Diag(Arg->getSourceRange().getBegin(),
2429 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002430 << Arg->getSourceRange();
2431 Invalid = true;
2432 }
2433
2434 Arg = Parens->getSubExpr();
2435 }
2436
Douglas Gregorb242683d2010-04-01 18:32:35 +00002437 bool AddressTaken = false;
2438 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002439 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002440 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002441 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002442 AddressTaken = true;
2443 AddrOpLoc = UnOp->getOperatorLoc();
2444 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002445 } else
2446 DRE = dyn_cast<DeclRefExpr>(Arg);
2447
Douglas Gregorb242683d2010-04-01 18:32:35 +00002448 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002449 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2450 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002451 S.Diag(Param->getLocation(), diag::note_template_param_here);
2452 return true;
2453 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002454
2455 // Stop checking the precise nature of the argument if it is value dependent,
2456 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002457 if (Arg->isValueDependent()) {
2458 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002459 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002460 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002461
Douglas Gregorb242683d2010-04-01 18:32:35 +00002462 if (!isa<ValueDecl>(DRE->getDecl())) {
2463 S.Diag(Arg->getSourceRange().getBegin(),
2464 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002465 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002466 S.Diag(Param->getLocation(), diag::note_template_param_here);
2467 return true;
2468 }
2469
2470 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002471
2472 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002473 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2474 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002475 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002476 S.Diag(Param->getLocation(), diag::note_template_param_here);
2477 return true;
2478 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002479
2480 // Cannot refer to non-static member functions
2481 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002482 if (!Method->isStatic()) {
2483 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002484 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002485 S.Diag(Param->getLocation(), diag::note_template_param_here);
2486 return true;
2487 }
Mike Stump11289f42009-09-09 15:08:12 +00002488
Douglas Gregorccb07762009-02-11 19:52:55 +00002489 // Functions must have external linkage.
2490 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002491 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002492 S.Diag(Arg->getSourceRange().getBegin(),
2493 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002494 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002495 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002496 << true;
2497 return true;
2498 }
2499
2500 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002501 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002502
Douglas Gregorb242683d2010-04-01 18:32:35 +00002503 // If the template parameter has pointer type, the function decays.
2504 if (ParamType->isPointerType() && !AddressTaken)
2505 ArgType = S.Context.getPointerType(Func->getType());
2506 else if (AddressTaken && ParamType->isReferenceType()) {
2507 // If we originally had an address-of operator, but the
2508 // parameter has reference type, complain and (if things look
2509 // like they will work) drop the address-of operator.
2510 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2511 ParamType.getNonReferenceType())) {
2512 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2513 << ParamType;
2514 S.Diag(Param->getLocation(), diag::note_template_param_here);
2515 return true;
2516 }
2517
2518 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2519 << ParamType
2520 << FixItHint::CreateRemoval(AddrOpLoc);
2521 S.Diag(Param->getLocation(), diag::note_template_param_here);
2522
2523 ArgType = Func->getType();
2524 }
2525 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002526 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002527 S.Diag(Arg->getSourceRange().getBegin(),
2528 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002529 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002530 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002531 << true;
2532 return true;
2533 }
2534
Douglas Gregorb242683d2010-04-01 18:32:35 +00002535 // A value of reference type is not an object.
2536 if (Var->getType()->isReferenceType()) {
2537 S.Diag(Arg->getSourceRange().getBegin(),
2538 diag::err_template_arg_reference_var)
2539 << Var->getType() << Arg->getSourceRange();
2540 S.Diag(Param->getLocation(), diag::note_template_param_here);
2541 return true;
2542 }
2543
Douglas Gregorccb07762009-02-11 19:52:55 +00002544 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002545 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002546
2547 // If the template parameter has pointer type, we must have taken
2548 // the address of this object.
2549 if (ParamType->isReferenceType()) {
2550 if (AddressTaken) {
2551 // If we originally had an address-of operator, but the
2552 // parameter has reference type, complain and (if things look
2553 // like they will work) drop the address-of operator.
2554 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2555 ParamType.getNonReferenceType())) {
2556 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2557 << ParamType;
2558 S.Diag(Param->getLocation(), diag::note_template_param_here);
2559 return true;
2560 }
2561
2562 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2563 << ParamType
2564 << FixItHint::CreateRemoval(AddrOpLoc);
2565 S.Diag(Param->getLocation(), diag::note_template_param_here);
2566
2567 ArgType = Var->getType();
2568 }
2569 } else if (!AddressTaken && ParamType->isPointerType()) {
2570 if (Var->getType()->isArrayType()) {
2571 // Array-to-pointer decay.
2572 ArgType = S.Context.getArrayDecayedType(Var->getType());
2573 } else {
2574 // If the template parameter has pointer type but the address of
2575 // this object was not taken, complain and (possibly) recover by
2576 // taking the address of the entity.
2577 ArgType = S.Context.getPointerType(Var->getType());
2578 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2579 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2580 << ParamType;
2581 S.Diag(Param->getLocation(), diag::note_template_param_here);
2582 return true;
2583 }
2584
2585 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2586 << ParamType
2587 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2588
2589 S.Diag(Param->getLocation(), diag::note_template_param_here);
2590 }
2591 }
2592 } else {
2593 // We found something else, but we don't know specifically what it is.
2594 S.Diag(Arg->getSourceRange().getBegin(),
2595 diag::err_template_arg_not_object_or_func)
2596 << Arg->getSourceRange();
2597 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2598 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002599 }
Mike Stump11289f42009-09-09 15:08:12 +00002600
Douglas Gregorb242683d2010-04-01 18:32:35 +00002601 if (ParamType->isPointerType() &&
2602 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2603 S.IsQualificationConversion(ArgType, ParamType)) {
2604 // For pointer-to-object types, qualification conversions are
2605 // permitted.
2606 } else {
2607 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2608 if (!ParamRef->getPointeeType()->isFunctionType()) {
2609 // C++ [temp.arg.nontype]p5b3:
2610 // For a non-type template-parameter of type reference to
2611 // object, no conversions apply. The type referred to by the
2612 // reference may be more cv-qualified than the (otherwise
2613 // identical) type of the template- argument. The
2614 // template-parameter is bound directly to the
2615 // template-argument, which shall be an lvalue.
2616
2617 // FIXME: Other qualifiers?
2618 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2619 unsigned ArgQuals = ArgType.getCVRQualifiers();
2620
2621 if ((ParamQuals | ArgQuals) != ParamQuals) {
2622 S.Diag(Arg->getSourceRange().getBegin(),
2623 diag::err_template_arg_ref_bind_ignores_quals)
2624 << ParamType << Arg->getType()
2625 << Arg->getSourceRange();
2626 S.Diag(Param->getLocation(), diag::note_template_param_here);
2627 return true;
2628 }
2629 }
2630 }
2631
2632 // At this point, the template argument refers to an object or
2633 // function with external linkage. We now need to check whether the
2634 // argument and parameter types are compatible.
2635 if (!S.Context.hasSameUnqualifiedType(ArgType,
2636 ParamType.getNonReferenceType())) {
2637 // We can't perform this conversion or binding.
2638 if (ParamType->isReferenceType())
2639 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2640 << ParamType << Arg->getType() << Arg->getSourceRange();
2641 else
2642 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2643 << Arg->getType() << ParamType << Arg->getSourceRange();
2644 S.Diag(Param->getLocation(), diag::note_template_param_here);
2645 return true;
2646 }
2647 }
2648
2649 // Create the template argument.
2650 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002651 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002652 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002653}
2654
2655/// \brief Checks whether the given template argument is a pointer to
2656/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002657bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2658 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002659 bool Invalid = false;
2660
2661 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002662 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002663 Arg = Cast->getSubExpr();
2664
2665 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002666 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002667 // A template-argument for a non-type, non-template
2668 // template-parameter shall be one of: [...]
2669 //
2670 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002671 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002672
2673 // Ignore (and complain about) any excess parentheses.
2674 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2675 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002676 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002677 diag::err_template_arg_extra_parens)
2678 << Arg->getSourceRange();
2679 Invalid = true;
2680 }
2681
2682 Arg = Parens->getSubExpr();
2683 }
2684
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002685 // A pointer-to-member constant written &Class::member.
2686 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002687 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2688 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2689 if (DRE && !DRE->getQualifier())
2690 DRE = 0;
2691 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002692 }
2693 // A constant of pointer-to-member type.
2694 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2695 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2696 if (VD->getType()->isMemberPointerType()) {
2697 if (isa<NonTypeTemplateParmDecl>(VD) ||
2698 (isa<VarDecl>(VD) &&
2699 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2700 if (Arg->isTypeDependent() || Arg->isValueDependent())
2701 Converted = TemplateArgument(Arg->Retain());
2702 else
2703 Converted = TemplateArgument(VD->getCanonicalDecl());
2704 return Invalid;
2705 }
2706 }
2707 }
2708
2709 DRE = 0;
2710 }
2711
Douglas Gregorccb07762009-02-11 19:52:55 +00002712 if (!DRE)
2713 return Diag(Arg->getSourceRange().getBegin(),
2714 diag::err_template_arg_not_pointer_to_member_form)
2715 << Arg->getSourceRange();
2716
2717 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2718 assert((isa<FieldDecl>(DRE->getDecl()) ||
2719 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2720 "Only non-static member pointers can make it here");
2721
2722 // Okay: this is the address of a non-static member, and therefore
2723 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002724 if (Arg->isTypeDependent() || Arg->isValueDependent())
2725 Converted = TemplateArgument(Arg->Retain());
2726 else
2727 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002728 return Invalid;
2729 }
2730
2731 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002732 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002733 diag::err_template_arg_not_pointer_to_member_form)
2734 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002735 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002736 diag::note_template_arg_refers_here);
2737 return true;
2738}
2739
Douglas Gregord32e0282009-02-09 23:23:08 +00002740/// \brief Check a template argument against its corresponding
2741/// non-type template parameter.
2742///
Douglas Gregor463421d2009-03-03 04:44:36 +00002743/// This routine implements the semantics of C++ [temp.arg.nontype].
2744/// It returns true if an error occurred, and false otherwise. \p
2745/// InstantiatedParamType is the type of the non-type template
2746/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002747///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002748/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002749bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002750 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002751 TemplateArgument &Converted,
2752 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002753 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2754
Douglas Gregor86560402009-02-10 23:36:10 +00002755 // If either the parameter has a dependent type or the argument is
2756 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002757 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2758 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002759 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002760 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002761 }
Douglas Gregor86560402009-02-10 23:36:10 +00002762
2763 // C++ [temp.arg.nontype]p5:
2764 // The following conversions are performed on each expression used
2765 // as a non-type template-argument. If a non-type
2766 // template-argument cannot be converted to the type of the
2767 // corresponding template-parameter then the program is
2768 // ill-formed.
2769 //
2770 // -- for a non-type template-parameter of integral or
2771 // enumeration type, integral promotions (4.5) and integral
2772 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002773 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002774 QualType ArgType = Arg->getType();
Douglas Gregorb90df602010-06-16 00:17:44 +00002775 if (ParamType->isIntegralOrEnumerationType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002776 // C++ [temp.arg.nontype]p1:
2777 // A template-argument for a non-type, non-template
2778 // template-parameter shall be one of:
2779 //
2780 // -- an integral constant-expression of integral or enumeration
2781 // type; or
2782 // -- the name of a non-type template-parameter; or
2783 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002784 llvm::APSInt Value;
Douglas Gregorb90df602010-06-16 00:17:44 +00002785 if (!ArgType->isIntegralOrEnumerationType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002786 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002787 diag::err_template_arg_not_integral_or_enumeral)
2788 << ArgType << Arg->getSourceRange();
2789 Diag(Param->getLocation(), diag::note_template_param_here);
2790 return true;
2791 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002792 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002793 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2794 << ArgType << Arg->getSourceRange();
2795 return true;
2796 }
2797
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002798 // From here on out, all we care about are the unqualified forms
2799 // of the parameter and argument types.
2800 ParamType = ParamType.getUnqualifiedType();
2801 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002802
2803 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002804 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002805 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002806 } else if (CTAK == CTAK_Deduced) {
2807 // C++ [temp.deduct.type]p17:
2808 // If, in the declaration of a function template with a non-type
2809 // template-parameter, the non-type template- parameter is used
2810 // in an expression in the function parameter-list and, if the
2811 // corresponding template-argument is deduced, the
2812 // template-argument type shall match the type of the
2813 // template-parameter exactly, except that a template-argument
2814 // deduced from an array bound may be of any integral type.
2815 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2816 << ArgType << ParamType;
2817 Diag(Param->getLocation(), diag::note_template_param_here);
2818 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002819 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2820 !ParamType->isEnumeralType()) {
2821 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002822 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002823 } else {
2824 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002825 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002826 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002827 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002828 Diag(Param->getLocation(), diag::note_template_param_here);
2829 return true;
2830 }
2831
Douglas Gregor52aba872009-03-14 00:20:21 +00002832 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002833 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002834 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002835
2836 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002837 llvm::APSInt OldValue = Value;
2838
2839 // Coerce the template argument's value to the value it will have
2840 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002841 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002842 if (Value.getBitWidth() != AllowedBits)
2843 Value.extOrTrunc(AllowedBits);
2844 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002845
2846 // Complain if an unsigned parameter received a negative value.
2847 if (IntegerType->isUnsignedIntegerType()
2848 && (OldValue.isSigned() && OldValue.isNegative())) {
2849 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2850 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2851 << Arg->getSourceRange();
2852 Diag(Param->getLocation(), diag::note_template_param_here);
2853 }
2854
2855 // Complain if we overflowed the template parameter's type.
2856 unsigned RequiredBits;
2857 if (IntegerType->isUnsignedIntegerType())
2858 RequiredBits = OldValue.getActiveBits();
2859 else if (OldValue.isUnsigned())
2860 RequiredBits = OldValue.getActiveBits() + 1;
2861 else
2862 RequiredBits = OldValue.getMinSignedBits();
2863 if (RequiredBits > AllowedBits) {
2864 Diag(Arg->getSourceRange().getBegin(),
2865 diag::warn_template_arg_too_large)
2866 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2867 << Arg->getSourceRange();
2868 Diag(Param->getLocation(), diag::note_template_param_here);
2869 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002870 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002871
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002872 // Add the value of this argument to the list of converted
2873 // arguments. We use the bitwidth and signedness of the template
2874 // parameter.
2875 if (Arg->isValueDependent()) {
2876 // The argument is value-dependent. Create a new
2877 // TemplateArgument with the converted expression.
2878 Converted = TemplateArgument(Arg);
2879 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002880 }
2881
John McCall0ad16662009-10-29 08:12:44 +00002882 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002883 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002884 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002885 return false;
2886 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002887
John McCall16df1e52010-03-30 21:47:33 +00002888 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2889
Douglas Gregorb242683d2010-04-01 18:32:35 +00002890 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2891 // from a template argument of type std::nullptr_t to a non-type
2892 // template parameter of type pointer to object, pointer to
2893 // function, or pointer-to-member, respectively.
2894 if (ArgType->isNullPtrType() &&
2895 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2896 Converted = TemplateArgument((NamedDecl *)0);
2897 return false;
2898 }
2899
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002900 // Handle pointer-to-function, reference-to-function, and
2901 // pointer-to-member-function all in (roughly) the same way.
2902 if (// -- For a non-type template-parameter of type pointer to
2903 // function, only the function-to-pointer conversion (4.3) is
2904 // applied. If the template-argument represents a set of
2905 // overloaded functions (or a pointer to such), the matching
2906 // function is selected from the set (13.4).
2907 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002908 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002909 // -- For a non-type template-parameter of type reference to
2910 // function, no conversions apply. If the template-argument
2911 // represents a set of overloaded functions, the matching
2912 // function is selected from the set (13.4).
2913 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002914 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002915 // -- For a non-type template-parameter of type pointer to
2916 // member function, no conversions apply. If the
2917 // template-argument represents a set of overloaded member
2918 // functions, the matching member function is selected from
2919 // the set (13.4).
2920 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002921 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002922 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002923
Douglas Gregor064fdb22010-04-14 23:11:21 +00002924 if (Arg->getType() == Context.OverloadTy) {
2925 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2926 true,
2927 FoundResult)) {
2928 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2929 return true;
2930
2931 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2932 ArgType = Arg->getType();
2933 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002934 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002935 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002936
Douglas Gregorb242683d2010-04-01 18:32:35 +00002937 if (!ParamType->isMemberPointerType())
2938 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2939 ParamType,
2940 Arg, Converted);
2941
2942 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2943 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2944 Arg->isLvalue(Context) == Expr::LV_Valid);
2945 } else if (!Context.hasSameUnqualifiedType(ArgType,
2946 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002947 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002948 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002949 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002950 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002951 Diag(Param->getLocation(), diag::note_template_param_here);
2952 return true;
2953 }
Mike Stump11289f42009-09-09 15:08:12 +00002954
Douglas Gregorb242683d2010-04-01 18:32:35 +00002955 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002956 }
2957
Chris Lattner696197c2009-02-20 21:37:53 +00002958 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002959 // -- for a non-type template-parameter of type pointer to
2960 // object, qualification conversions (4.4) and the
2961 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002962 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002963 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002964 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002965
Douglas Gregorb242683d2010-04-01 18:32:35 +00002966 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2967 ParamType,
2968 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002969 }
Mike Stump11289f42009-09-09 15:08:12 +00002970
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002971 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002972 // -- For a non-type template-parameter of type reference to
2973 // object, no conversions apply. The type referred to by the
2974 // reference may be more cv-qualified than the (otherwise
2975 // identical) type of the template-argument. The
2976 // template-parameter is bound directly to the
2977 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002978 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002979 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002980
Douglas Gregor064fdb22010-04-14 23:11:21 +00002981 if (Arg->getType() == Context.OverloadTy) {
2982 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2983 ParamRefType->getPointeeType(),
2984 true,
2985 FoundResult)) {
2986 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2987 return true;
2988
2989 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2990 ArgType = Arg->getType();
2991 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002992 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002993 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002994
Douglas Gregorb242683d2010-04-01 18:32:35 +00002995 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2996 ParamType,
2997 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002998 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002999
3000 // -- For a non-type template-parameter of type pointer to data
3001 // member, qualification conversions (4.4) are applied.
3002 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3003
Douglas Gregor1515f762009-02-11 18:22:40 +00003004 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003005 // Types match exactly: nothing more to do here.
3006 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003007 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
3008 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor0e558532009-02-11 16:16:59 +00003009 } else {
3010 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003011 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003012 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003013 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003014 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003015 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003016 }
3017
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003018 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003019}
3020
3021/// \brief Check a template argument against its corresponding
3022/// template template parameter.
3023///
3024/// This routine implements the semantics of C++ [temp.arg.template].
3025/// It returns true if an error occurred, and false otherwise.
3026bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003027 const TemplateArgumentLoc &Arg) {
3028 TemplateName Name = Arg.getArgument().getAsTemplate();
3029 TemplateDecl *Template = Name.getAsTemplateDecl();
3030 if (!Template) {
3031 // Any dependent template name is fine.
3032 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3033 return false;
3034 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003035
3036 // C++ [temp.arg.template]p1:
3037 // A template-argument for a template template-parameter shall be
3038 // the name of a class template, expressed as id-expression. Only
3039 // primary class templates are considered when matching the
3040 // template template argument with the corresponding parameter;
3041 // partial specializations are not considered even if their
3042 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003043 //
3044 // Note that we also allow template template parameters here, which
3045 // will happen when we are dealing with, e.g., class template
3046 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003047 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003048 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003049 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003050 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003051 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003052 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003053 << Template;
3054 }
3055
3056 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3057 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003058 true,
3059 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003060 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003061}
3062
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003063/// \brief Given a non-type template argument that refers to a
3064/// declaration and the type of its corresponding non-type template
3065/// parameter, produce an expression that properly refers to that
3066/// declaration.
3067Sema::OwningExprResult
3068Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3069 QualType ParamType,
3070 SourceLocation Loc) {
3071 assert(Arg.getKind() == TemplateArgument::Declaration &&
3072 "Only declaration template arguments permitted here");
3073 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3074
3075 if (VD->getDeclContext()->isRecord() &&
3076 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3077 // If the value is a class member, we might have a pointer-to-member.
3078 // Determine whether the non-type template template parameter is of
3079 // pointer-to-member type. If so, we need to build an appropriate
3080 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3081 // would refer to the member itself.
3082 if (ParamType->isMemberPointerType()) {
3083 QualType ClassType
3084 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3085 NestedNameSpecifier *Qualifier
3086 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3087 CXXScopeSpec SS;
3088 SS.setScopeRep(Qualifier);
3089 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3090 VD->getType().getNonReferenceType(),
3091 Loc,
3092 &SS);
3093 if (RefExpr.isInvalid())
3094 return ExprError();
3095
3096 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003097
3098 // We might need to perform a trailing qualification conversion, since
3099 // the element type on the parameter could be more qualified than the
3100 // element type in the expression we constructed.
3101 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3102 ParamType.getUnqualifiedType())) {
3103 Expr *RefE = RefExpr.takeAs<Expr>();
3104 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3105 CastExpr::CK_NoOp);
3106 RefExpr = Owned(RefE);
3107 }
3108
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003109 assert(!RefExpr.isInvalid() &&
3110 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003111 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003112 return move(RefExpr);
3113 }
3114 }
3115
3116 QualType T = VD->getType().getNonReferenceType();
3117 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003118 // When the non-type template parameter is a pointer, take the
3119 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003120 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3121 if (RefExpr.isInvalid())
3122 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003123
3124 if (T->isFunctionType() || T->isArrayType()) {
3125 // Decay functions and arrays.
3126 Expr *RefE = (Expr *)RefExpr.get();
3127 DefaultFunctionArrayConversion(RefE);
3128 if (RefE != RefExpr.get()) {
3129 RefExpr.release();
3130 RefExpr = Owned(RefE);
3131 }
3132
3133 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003134 }
3135
Douglas Gregorb242683d2010-04-01 18:32:35 +00003136 // Take the address of everything else
3137 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003138 }
3139
3140 // If the non-type template parameter has reference type, qualify the
3141 // resulting declaration reference with the extra qualifiers on the
3142 // type that the reference refers to.
3143 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3144 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3145
3146 return BuildDeclRefExpr(VD, T, Loc);
3147}
3148
3149/// \brief Construct a new expression that refers to the given
3150/// integral template argument with the given source-location
3151/// information.
3152///
3153/// This routine takes care of the mapping from an integral template
3154/// argument (which may have any integral type) to the appropriate
3155/// literal value.
3156Sema::OwningExprResult
3157Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3158 SourceLocation Loc) {
3159 assert(Arg.getKind() == TemplateArgument::Integral &&
3160 "Operation is only value for integral template arguments");
3161 QualType T = Arg.getIntegralType();
3162 if (T->isCharType() || T->isWideCharType())
3163 return Owned(new (Context) CharacterLiteral(
3164 Arg.getAsIntegral()->getZExtValue(),
3165 T->isWideCharType(),
3166 T,
3167 Loc));
3168 if (T->isBooleanType())
3169 return Owned(new (Context) CXXBoolLiteralExpr(
3170 Arg.getAsIntegral()->getBoolValue(),
3171 T,
3172 Loc));
3173
3174 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3175}
3176
3177
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003178/// \brief Determine whether the given template parameter lists are
3179/// equivalent.
3180///
Mike Stump11289f42009-09-09 15:08:12 +00003181/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003182/// source code as part of a new template declaration.
3183///
3184/// \param Old The old template parameter list, typically found via
3185/// name lookup of the template declared with this template parameter
3186/// list.
3187///
3188/// \param Complain If true, this routine will produce a diagnostic if
3189/// the template parameter lists are not equivalent.
3190///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003191/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003192///
3193/// \param TemplateArgLoc If this source location is valid, then we
3194/// are actually checking the template parameter list of a template
3195/// argument (New) against the template parameter list of its
3196/// corresponding template template parameter (Old). We produce
3197/// slightly different diagnostics in this scenario.
3198///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003199/// \returns True if the template parameter lists are equal, false
3200/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003201bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003202Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3203 TemplateParameterList *Old,
3204 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003205 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003206 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003207 if (Old->size() != New->size()) {
3208 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003209 unsigned NextDiag = diag::err_template_param_list_different_arity;
3210 if (TemplateArgLoc.isValid()) {
3211 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3212 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003213 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003214 Diag(New->getTemplateLoc(), NextDiag)
3215 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003216 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003217 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003218 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003219 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003220 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3221 }
3222
3223 return false;
3224 }
3225
3226 for (TemplateParameterList::iterator OldParm = Old->begin(),
3227 OldParmEnd = Old->end(), NewParm = New->begin();
3228 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3229 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003230 if (Complain) {
3231 unsigned NextDiag = diag::err_template_param_different_kind;
3232 if (TemplateArgLoc.isValid()) {
3233 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3234 NextDiag = diag::note_template_param_different_kind;
3235 }
3236 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003237 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003238 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003239 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003240 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003241 return false;
3242 }
3243
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003244 if (TemplateTypeParmDecl *OldTTP
3245 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3246 // Template type parameters are equivalent if either both are template
3247 // type parameter packs or neither are (since we know we're at the same
3248 // index).
3249 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3250 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3251 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3252 // allow one to match a template parameter pack in the template
3253 // parameter list of a template template parameter to one or more
3254 // template parameters in the template parameter list of the
3255 // corresponding template template argument.
3256 if (Complain) {
3257 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3258 if (TemplateArgLoc.isValid()) {
3259 Diag(TemplateArgLoc,
3260 diag::err_template_arg_template_params_mismatch);
3261 NextDiag = diag::note_template_parameter_pack_non_pack;
3262 }
3263 Diag(NewTTP->getLocation(), NextDiag)
3264 << 0 << NewTTP->isParameterPack();
3265 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3266 << 0 << OldTTP->isParameterPack();
3267 }
3268 return false;
3269 }
Mike Stump11289f42009-09-09 15:08:12 +00003270 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003271 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3272 // The types of non-type template parameters must agree.
3273 NonTypeTemplateParmDecl *NewNTTP
3274 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003275
3276 // If we are matching a template template argument to a template
3277 // template parameter and one of the non-type template parameter types
3278 // is dependent, then we must wait until template instantiation time
3279 // to actually compare the arguments.
3280 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3281 (OldNTTP->getType()->isDependentType() ||
3282 NewNTTP->getType()->isDependentType()))
3283 continue;
3284
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003285 if (Context.getCanonicalType(OldNTTP->getType()) !=
3286 Context.getCanonicalType(NewNTTP->getType())) {
3287 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003288 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3289 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003290 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003291 diag::err_template_arg_template_params_mismatch);
3292 NextDiag = diag::note_template_nontype_parm_different_type;
3293 }
3294 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003295 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003296 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003297 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003298 diag::note_template_nontype_parm_prev_declaration)
3299 << OldNTTP->getType();
3300 }
3301 return false;
3302 }
3303 } else {
3304 // The template parameter lists of template template
3305 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003306 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003307 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003308 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003309 = cast<TemplateTemplateParmDecl>(*OldParm);
3310 TemplateTemplateParmDecl *NewTTP
3311 = cast<TemplateTemplateParmDecl>(*NewParm);
3312 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3313 OldTTP->getTemplateParameters(),
3314 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003315 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003316 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003317 return false;
3318 }
3319 }
3320
3321 return true;
3322}
3323
3324/// \brief Check whether a template can be declared within this scope.
3325///
3326/// If the template declaration is valid in this scope, returns
3327/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003328bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003329Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003330 // Find the nearest enclosing declaration scope.
3331 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3332 (S->getFlags() & Scope::TemplateParamScope) != 0)
3333 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003334
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003335 // C++ [temp]p2:
3336 // A template-declaration can appear only as a namespace scope or
3337 // class scope declaration.
3338 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003339 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3340 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003341 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003342 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003343
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003344 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003345 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003346
3347 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3348 return false;
3349
Mike Stump11289f42009-09-09 15:08:12 +00003350 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003351 diag::err_template_outside_namespace_or_class_scope)
3352 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003353}
Douglas Gregor67a65642009-02-17 23:15:12 +00003354
Douglas Gregor54888652009-10-07 00:13:32 +00003355/// \brief Determine what kind of template specialization the given declaration
3356/// is.
3357static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3358 if (!D)
3359 return TSK_Undeclared;
3360
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003361 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3362 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003363 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3364 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003365 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3366 return Var->getTemplateSpecializationKind();
3367
Douglas Gregor54888652009-10-07 00:13:32 +00003368 return TSK_Undeclared;
3369}
3370
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003371/// \brief Check whether a specialization is well-formed in the current
3372/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003373///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003374/// This routine determines whether a template specialization can be declared
3375/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003376///
3377/// \param S the semantic analysis object for which this check is being
3378/// performed.
3379///
3380/// \param Specialized the entity being specialized or instantiated, which
3381/// may be a kind of template (class template, function template, etc.) or
3382/// a member of a class template (member function, static data member,
3383/// member class).
3384///
3385/// \param PrevDecl the previous declaration of this entity, if any.
3386///
3387/// \param Loc the location of the explicit specialization or instantiation of
3388/// this entity.
3389///
3390/// \param IsPartialSpecialization whether this is a partial specialization of
3391/// a class template.
3392///
Douglas Gregor54888652009-10-07 00:13:32 +00003393/// \returns true if there was an error that we cannot recover from, false
3394/// otherwise.
3395static bool CheckTemplateSpecializationScope(Sema &S,
3396 NamedDecl *Specialized,
3397 NamedDecl *PrevDecl,
3398 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003399 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003400 // Keep these "kind" numbers in sync with the %select statements in the
3401 // various diagnostics emitted by this routine.
3402 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003403 bool isTemplateSpecialization = false;
3404 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003405 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003406 isTemplateSpecialization = true;
3407 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003408 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003409 isTemplateSpecialization = true;
3410 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003411 EntityKind = 3;
3412 else if (isa<VarDecl>(Specialized))
3413 EntityKind = 4;
3414 else if (isa<RecordDecl>(Specialized))
3415 EntityKind = 5;
3416 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003417 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3418 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003419 return true;
3420 }
3421
Douglas Gregorf47b9112009-02-25 22:02:03 +00003422 // C++ [temp.expl.spec]p2:
3423 // An explicit specialization shall be declared in the namespace
3424 // of which the template is a member, or, for member templates, in
3425 // the namespace of which the enclosing class or enclosing class
3426 // template is a member. An explicit specialization of a member
3427 // function, member class or static data member of a class
3428 // template shall be declared in the namespace of which the class
3429 // template is a member. Such a declaration may also be a
3430 // definition. If the declaration is not a definition, the
3431 // specialization may be defined later in the name- space in which
3432 // the explicit specialization was declared, or in a namespace
3433 // that encloses the one in which the explicit specialization was
3434 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003435 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3436 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003437 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003438 return true;
3439 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003440
Douglas Gregor40fb7442009-10-07 17:30:37 +00003441 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3442 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003443 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003444 return true;
3445 }
3446
Douglas Gregore4b05162009-10-07 17:21:34 +00003447 // C++ [temp.class.spec]p6:
3448 // A class template partial specialization may be declared or redeclared
3449 // in any namespace scope in which its definition may be defined (14.5.1
3450 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003451 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003452 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003453 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003454 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003455 if ((!PrevDecl ||
3456 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3457 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3458 // There is no prior declaration of this entity, so this
3459 // specialization must be in the same context as the template
3460 // itself.
3461 if (!DC->Equals(SpecializedContext)) {
3462 if (isa<TranslationUnitDecl>(SpecializedContext))
3463 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3464 << EntityKind << Specialized;
3465 else if (isa<NamespaceDecl>(SpecializedContext))
3466 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3467 << EntityKind << Specialized
3468 << cast<NamedDecl>(SpecializedContext);
3469
3470 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3471 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003472 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003473 }
Douglas Gregor54888652009-10-07 00:13:32 +00003474
3475 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003476 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003477 // Note that HandleDeclarator() performs this check for explicit
3478 // specializations of function templates, static data members, and member
3479 // functions, so we skip the check here for those kinds of entities.
3480 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003481 // Should we refactor that check, so that it occurs later?
3482 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003483 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3484 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003485 if (isa<TranslationUnitDecl>(SpecializedContext))
3486 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3487 << EntityKind << Specialized;
3488 else if (isa<NamespaceDecl>(SpecializedContext))
3489 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3490 << EntityKind << Specialized
3491 << cast<NamedDecl>(SpecializedContext);
3492
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003493 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003494 }
Douglas Gregor54888652009-10-07 00:13:32 +00003495
3496 // FIXME: check for specialization-after-instantiation errors and such.
3497
Douglas Gregorf47b9112009-02-25 22:02:03 +00003498 return false;
3499}
Douglas Gregor54888652009-10-07 00:13:32 +00003500
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003501/// \brief Check the non-type template arguments of a class template
3502/// partial specialization according to C++ [temp.class.spec]p9.
3503///
Douglas Gregor09a30232009-06-12 22:08:06 +00003504/// \param TemplateParams the template parameters of the primary class
3505/// template.
3506///
3507/// \param TemplateArg the template arguments of the class template
3508/// partial specialization.
3509///
3510/// \param MirrorsPrimaryTemplate will be set true if the class
3511/// template partial specialization arguments are identical to the
3512/// implicit template arguments of the primary template. This is not
3513/// necessarily an error (C++0x), and it is left to the caller to diagnose
3514/// this condition when it is an error.
3515///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003516/// \returns true if there was an error, false otherwise.
3517bool Sema::CheckClassTemplatePartialSpecializationArgs(
3518 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003519 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003520 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003521 // FIXME: the interface to this function will have to change to
3522 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003523 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003524
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003525 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003526
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003527 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003528 // Determine whether the template argument list of the partial
3529 // specialization is identical to the implicit argument list of
3530 // the primary template. The caller may need to diagnostic this as
3531 // an error per C++ [temp.class.spec]p9b3.
3532 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003533 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003534 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3535 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003536 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003537 MirrorsPrimaryTemplate = false;
3538 } else if (TemplateTemplateParmDecl *TTP
3539 = dyn_cast<TemplateTemplateParmDecl>(
3540 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003541 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003542 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003543 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003544 if (!ArgDecl ||
3545 ArgDecl->getIndex() != TTP->getIndex() ||
3546 ArgDecl->getDepth() != TTP->getDepth())
3547 MirrorsPrimaryTemplate = false;
3548 }
3549 }
3550
Mike Stump11289f42009-09-09 15:08:12 +00003551 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003552 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003553 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003554 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003555 }
3556
Anders Carlsson40c1d492009-06-13 18:20:51 +00003557 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003558 if (!ArgExpr) {
3559 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003560 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003561 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003562
3563 // C++ [temp.class.spec]p8:
3564 // A non-type argument is non-specialized if it is the name of a
3565 // non-type parameter. All other non-type arguments are
3566 // specialized.
3567 //
3568 // Below, we check the two conditions that only apply to
3569 // specialized non-type arguments, so skip any non-specialized
3570 // arguments.
3571 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003572 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003573 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003574 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003575 (Param->getIndex() != NTTP->getIndex() ||
3576 Param->getDepth() != NTTP->getDepth()))
3577 MirrorsPrimaryTemplate = false;
3578
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003579 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003580 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003581
3582 // C++ [temp.class.spec]p9:
3583 // Within the argument list of a class template partial
3584 // specialization, the following restrictions apply:
3585 // -- A partially specialized non-type argument expression
3586 // shall not involve a template parameter of the partial
3587 // specialization except when the argument expression is a
3588 // simple identifier.
3589 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003590 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003591 diag::err_dependent_non_type_arg_in_partial_spec)
3592 << ArgExpr->getSourceRange();
3593 return true;
3594 }
3595
3596 // -- The type of a template parameter corresponding to a
3597 // specialized non-type argument shall not be dependent on a
3598 // parameter of the specialization.
3599 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003600 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003601 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3602 << Param->getType()
3603 << ArgExpr->getSourceRange();
3604 Diag(Param->getLocation(), diag::note_template_param_here);
3605 return true;
3606 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003607
3608 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003609 }
3610
3611 return false;
3612}
3613
Douglas Gregorc854c662010-02-26 06:03:23 +00003614/// \brief Retrieve the previous declaration of the given declaration.
3615static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3616 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3617 return VD->getPreviousDeclaration();
3618 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3619 return FD->getPreviousDeclaration();
3620 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3621 return TD->getPreviousDeclaration();
3622 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3623 return TD->getPreviousDeclaration();
3624 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3625 return FTD->getPreviousDeclaration();
3626 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3627 return CTD->getPreviousDeclaration();
3628 return 0;
3629}
3630
Douglas Gregorc08f4892009-03-25 00:13:59 +00003631Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003632Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3633 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003634 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003635 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003636 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003637 SourceLocation TemplateNameLoc,
3638 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003639 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003640 SourceLocation RAngleLoc,
3641 AttributeList *Attr,
3642 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003643 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003644
Douglas Gregor67a65642009-02-17 23:15:12 +00003645 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003646 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003647 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003648 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3649
3650 if (!ClassTemplate) {
3651 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3652 << (Name.getAsTemplateDecl() &&
3653 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3654 return true;
3655 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003656
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003657 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003658 bool isPartialSpecialization = false;
3659
Douglas Gregorf47b9112009-02-25 22:02:03 +00003660 // Check the validity of the template headers that introduce this
3661 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003662 // FIXME: We probably shouldn't complain about these headers for
3663 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003664 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003665 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3666 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003667 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003668 TUK == TUK_Friend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003669 isExplicitSpecialization);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003670 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
3671 if (TemplateParams)
3672 --NumMatchedTemplateParamLists;
3673
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003674 if (TemplateParams && TemplateParams->size() > 0) {
3675 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003676
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003677 // C++ [temp.class.spec]p10:
3678 // The template parameter list of a specialization shall not
3679 // contain default template argument values.
3680 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3681 Decl *Param = TemplateParams->getParam(I);
3682 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3683 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003684 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003685 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003686 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003687 }
3688 } else if (NonTypeTemplateParmDecl *NTTP
3689 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3690 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003691 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003692 diag::err_default_arg_in_partial_spec)
3693 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003694 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003695 DefArg->Destroy(Context);
3696 }
3697 } else {
3698 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003699 if (TTP->hasDefaultArgument()) {
3700 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003701 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003702 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003703 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003704 }
3705 }
3706 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003707 } else if (TemplateParams) {
3708 if (TUK == TUK_Friend)
3709 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003710 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003711 SourceRange(TemplateParams->getTemplateLoc(),
3712 TemplateParams->getRAngleLoc()))
3713 << SourceRange(LAngleLoc, RAngleLoc);
3714 else
3715 isExplicitSpecialization = true;
3716 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003717 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003718 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003719 isExplicitSpecialization = true;
3720 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003721
Douglas Gregor67a65642009-02-17 23:15:12 +00003722 // Check that the specialization uses the same tag kind as the
3723 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003724 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3725 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003726 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003727 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003728 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003729 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003730 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003731 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003732 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003733 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003734 diag::note_previous_use);
3735 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3736 }
3737
Douglas Gregorc40290e2009-03-09 23:48:35 +00003738 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003739 TemplateArgumentListInfo TemplateArgs;
3740 TemplateArgs.setLAngleLoc(LAngleLoc);
3741 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003742 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003743
Douglas Gregor67a65642009-02-17 23:15:12 +00003744 // Check that the template argument list is well-formed for this
3745 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003746 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3747 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003748 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3749 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003750 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003751
Mike Stump11289f42009-09-09 15:08:12 +00003752 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003753 ClassTemplate->getTemplateParameters()->size()) &&
3754 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003755
Douglas Gregor2373c592009-05-31 09:31:02 +00003756 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003757 // corresponds to these arguments.
3758 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003759 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003760 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003761 if (CheckClassTemplatePartialSpecializationArgs(
3762 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003763 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003764 return true;
3765
Douglas Gregor09a30232009-06-12 22:08:06 +00003766 if (MirrorsPrimaryTemplate) {
3767 // C++ [temp.class.spec]p9b3:
3768 //
Mike Stump11289f42009-09-09 15:08:12 +00003769 // -- The argument list of the specialization shall not be identical
3770 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003771 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003772 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003773 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003774 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003775 ClassTemplate->getIdentifier(),
3776 TemplateNameLoc,
3777 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003778 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003779 AS_none);
3780 }
3781
Douglas Gregor2208a292009-09-26 20:57:03 +00003782 // FIXME: Diagnose friend partial specializations
3783
Douglas Gregor92354b62010-02-09 00:37:32 +00003784 if (!Name.isDependent() &&
3785 !TemplateSpecializationType::anyDependentTemplateArguments(
3786 TemplateArgs.getArgumentArray(),
3787 TemplateArgs.size())) {
3788 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3789 << ClassTemplate->getDeclName();
3790 isPartialSpecialization = false;
3791 } else {
3792 // FIXME: Template parameter list matters, too
3793 ClassTemplatePartialSpecializationDecl::Profile(ID,
3794 Converted.getFlatArguments(),
3795 Converted.flatSize(),
3796 Context);
3797 }
3798 }
3799
3800 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003801 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003802 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003803 Converted.flatSize(),
3804 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003805 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003806 ClassTemplateSpecializationDecl *PrevDecl = 0;
3807
3808 if (isPartialSpecialization)
3809 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003810 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003811 InsertPos);
3812 else
3813 PrevDecl
3814 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003815
3816 ClassTemplateSpecializationDecl *Specialization = 0;
3817
Douglas Gregorf47b9112009-02-25 22:02:03 +00003818 // Check whether we can declare a class template specialization in
3819 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003820 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003821 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003822 TemplateNameLoc,
3823 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003824 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003825
Douglas Gregor15301382009-07-30 17:40:51 +00003826 // The canonical type
3827 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003828 if (PrevDecl &&
3829 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003830 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003831 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003832 // arguments was referenced but not declared, or we're only
3833 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003834 // declaration node as our own, updating its source location to
3835 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003836 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003837 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003838 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003839 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003840 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003841 // Build the canonical type that describes the converted template
3842 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003843 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3844 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003845 Converted.getFlatArguments(),
3846 Converted.flatSize());
3847
Douglas Gregor2373c592009-05-31 09:31:02 +00003848 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003849 ClassTemplatePartialSpecializationDecl *PrevPartial
3850 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003851 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3852 : ClassTemplate->getPartialSpecializations().size();
Mike Stump11289f42009-09-09 15:08:12 +00003853 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003854 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003855 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003856 TemplateNameLoc,
3857 TemplateParams,
3858 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003859 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003860 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003861 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003862 PrevPartial,
3863 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003864 SetNestedNameSpecifier(Partial, SS);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003865 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003866 Partial->setTemplateParameterListsInfo(Context,
3867 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003868 (TemplateParameterList**) TemplateParameterLists.release());
3869 }
Douglas Gregor2373c592009-05-31 09:31:02 +00003870
3871 if (PrevPartial) {
3872 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3873 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3874 } else {
3875 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3876 }
3877 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003878
Douglas Gregor21610382009-10-29 00:04:11 +00003879 // If we are providing an explicit specialization of a member class
3880 // template specialization, make a note of that.
3881 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3882 PrevPartial->setMemberSpecialization();
3883
Douglas Gregor91772d12009-06-13 00:26:55 +00003884 // Check that all of the template parameters of the class template
3885 // partial specialization are deducible from the template
3886 // arguments. If not, this class template partial specialization
3887 // will never be used.
3888 llvm::SmallVector<bool, 8> DeducibleParams;
3889 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003890 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003891 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003892 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003893 unsigned NumNonDeducible = 0;
3894 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3895 if (!DeducibleParams[I])
3896 ++NumNonDeducible;
3897
3898 if (NumNonDeducible) {
3899 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3900 << (NumNonDeducible > 1)
3901 << SourceRange(TemplateNameLoc, RAngleLoc);
3902 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3903 if (!DeducibleParams[I]) {
3904 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3905 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003906 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003907 diag::note_partial_spec_unused_parameter)
3908 << Param->getDeclName();
3909 else
Mike Stump11289f42009-09-09 15:08:12 +00003910 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003911 diag::note_partial_spec_unused_parameter)
3912 << std::string("<anonymous>");
3913 }
3914 }
3915 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003916 } else {
3917 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003918 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003919 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003920 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003921 ClassTemplate->getDeclContext(),
3922 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003923 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003924 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003925 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003926 SetNestedNameSpecifier(Specialization, SS);
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003927 if (NumMatchedTemplateParamLists > 0) {
Douglas Gregor20527e22010-06-15 17:44:38 +00003928 Specialization->setTemplateParameterListsInfo(Context,
3929 NumMatchedTemplateParamLists,
Abramo Bagnarada41d0c2010-06-12 08:15:14 +00003930 (TemplateParameterList**) TemplateParameterLists.release());
3931 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003932
3933 if (PrevDecl) {
3934 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3935 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3936 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003937 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003938 InsertPos);
3939 }
Douglas Gregor15301382009-07-30 17:40:51 +00003940
3941 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003942 }
3943
Douglas Gregor06db9f52009-10-12 20:18:28 +00003944 // C++ [temp.expl.spec]p6:
3945 // If a template, a member template or the member of a class template is
3946 // explicitly specialized then that specialization shall be declared
3947 // before the first use of that specialization that would cause an implicit
3948 // instantiation to take place, in every translation unit in which such a
3949 // use occurs; no diagnostic is required.
3950 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003951 bool Okay = false;
3952 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3953 // Is there any previous explicit specialization declaration?
3954 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3955 Okay = true;
3956 break;
3957 }
3958 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003959
Douglas Gregorc854c662010-02-26 06:03:23 +00003960 if (!Okay) {
3961 SourceRange Range(TemplateNameLoc, RAngleLoc);
3962 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3963 << Context.getTypeDeclType(Specialization) << Range;
3964
3965 Diag(PrevDecl->getPointOfInstantiation(),
3966 diag::note_instantiation_required_here)
3967 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003968 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003969 return true;
3970 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003971 }
3972
Douglas Gregor2208a292009-09-26 20:57:03 +00003973 // If this is not a friend, note that this is an explicit specialization.
3974 if (TUK != TUK_Friend)
3975 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003976
3977 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003978 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003979 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003980 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003981 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003982 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003983 Diag(Def->getLocation(), diag::note_previous_definition);
3984 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003985 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003986 }
3987 }
3988
Douglas Gregord56a91e2009-02-26 22:19:44 +00003989 // Build the fully-sugared type for this class template
3990 // specialization as the user wrote in the specialization
3991 // itself. This means that we'll pretty-print the type retrieved
3992 // from the specialization's declaration the way that the user
3993 // actually wrote the specialization, rather than formatting the
3994 // name based on the "canonical" representation used to store the
3995 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003996 TypeSourceInfo *WrittenTy
3997 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3998 TemplateArgs, CanonType);
Abramo Bagnara8075c852010-06-12 07:44:57 +00003999 if (TUK != TUK_Friend) {
Douglas Gregor2208a292009-09-26 20:57:03 +00004000 Specialization->setTypeAsWritten(WrittenTy);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004001 Specialization->setTemplateKeywordLoc(KWLoc);
4002 }
Douglas Gregorc40290e2009-03-09 23:48:35 +00004003 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00004004
Douglas Gregor1e249f82009-02-25 22:18:32 +00004005 // C++ [temp.expl.spec]p9:
4006 // A template explicit specialization is in the scope of the
4007 // namespace in which the template was defined.
4008 //
4009 // We actually implement this paragraph where we set the semantic
4010 // context (in the creation of the ClassTemplateSpecializationDecl),
4011 // but we also maintain the lexical context where the actual
4012 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00004013 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00004014
Douglas Gregor67a65642009-02-17 23:15:12 +00004015 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00004016 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00004017 Specialization->startDefinition();
4018
Douglas Gregor2208a292009-09-26 20:57:03 +00004019 if (TUK == TUK_Friend) {
4020 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4021 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004022 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004023 /*FIXME:*/KWLoc);
4024 Friend->setAccess(AS_public);
4025 CurContext->addDecl(Friend);
4026 } else {
4027 // Add the specialization into its lexical context, so that it can
4028 // be seen when iterating through the list of declarations in that
4029 // context. However, specializations are not found by name lookup.
4030 CurContext->addDecl(Specialization);
4031 }
Chris Lattner83f095c2009-03-28 19:18:32 +00004032 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004033}
Douglas Gregor333489b2009-03-27 23:10:48 +00004034
Mike Stump11289f42009-09-09 15:08:12 +00004035Sema::DeclPtrTy
4036Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004037 MultiTemplateParamsArg TemplateParameterLists,
4038 Declarator &D) {
4039 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4040}
4041
Mike Stump11289f42009-09-09 15:08:12 +00004042Sema::DeclPtrTy
4043Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004044 MultiTemplateParamsArg TemplateParameterLists,
4045 Declarator &D) {
4046 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4047 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4048 "Not a function declarator!");
4049 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004050
Douglas Gregor17a7c122009-06-24 00:54:41 +00004051 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004052 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004053 }
Mike Stump11289f42009-09-09 15:08:12 +00004054
Douglas Gregor17a7c122009-06-24 00:54:41 +00004055 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004056
4057 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004058 move(TemplateParameterLists),
4059 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004060 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00004061 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00004062 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004063 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00004064 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4065 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004066 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00004067}
4068
John McCall4f7ced62010-02-11 01:33:53 +00004069/// \brief Strips various properties off an implicit instantiation
4070/// that has just been explicitly specialized.
4071static void StripImplicitInstantiation(NamedDecl *D) {
4072 D->invalidateAttrs();
4073
4074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4075 FD->setInlineSpecified(false);
4076 }
4077}
4078
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004079/// \brief Diagnose cases where we have an explicit template specialization
4080/// before/after an explicit template instantiation, producing diagnostics
4081/// for those cases where they are required and determining whether the
4082/// new specialization/instantiation will have any effect.
4083///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004084/// \param NewLoc the location of the new explicit specialization or
4085/// instantiation.
4086///
4087/// \param NewTSK the kind of the new explicit specialization or instantiation.
4088///
4089/// \param PrevDecl the previous declaration of the entity.
4090///
4091/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4092///
4093/// \param PrevPointOfInstantiation if valid, indicates where the previus
4094/// declaration was instantiated (either implicitly or explicitly).
4095///
Abramo Bagnara8075c852010-06-12 07:44:57 +00004096/// \param HasNoEffect will be set to true to indicate that the new
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004097/// specialization or instantiation has no effect and should be ignored.
4098///
4099/// \returns true if there was an error that should prevent the introduction of
4100/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004101bool
4102Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4103 TemplateSpecializationKind NewTSK,
4104 NamedDecl *PrevDecl,
4105 TemplateSpecializationKind PrevTSK,
4106 SourceLocation PrevPointOfInstantiation,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004107 bool &HasNoEffect) {
4108 HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004109
4110 switch (NewTSK) {
4111 case TSK_Undeclared:
4112 case TSK_ImplicitInstantiation:
4113 assert(false && "Don't check implicit instantiations here");
4114 return false;
4115
4116 case TSK_ExplicitSpecialization:
4117 switch (PrevTSK) {
4118 case TSK_Undeclared:
4119 case TSK_ExplicitSpecialization:
4120 // Okay, we're just specializing something that is either already
4121 // explicitly specialized or has merely been mentioned without any
4122 // instantiation.
4123 return false;
4124
4125 case TSK_ImplicitInstantiation:
4126 if (PrevPointOfInstantiation.isInvalid()) {
4127 // The declaration itself has not actually been instantiated, so it is
4128 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004129 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004130 return false;
4131 }
4132 // Fall through
4133
4134 case TSK_ExplicitInstantiationDeclaration:
4135 case TSK_ExplicitInstantiationDefinition:
4136 assert((PrevTSK == TSK_ImplicitInstantiation ||
4137 PrevPointOfInstantiation.isValid()) &&
4138 "Explicit instantiation without point of instantiation?");
4139
4140 // C++ [temp.expl.spec]p6:
4141 // If a template, a member template or the member of a class template
4142 // is explicitly specialized then that specialization shall be declared
4143 // before the first use of that specialization that would cause an
4144 // implicit instantiation to take place, in every translation unit in
4145 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004146 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4147 // Is there any previous explicit specialization declaration?
4148 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4149 return false;
4150 }
4151
Douglas Gregor1d957a32009-10-27 18:42:08 +00004152 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004153 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004154 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004155 << (PrevTSK != TSK_ImplicitInstantiation);
4156
4157 return true;
4158 }
4159 break;
4160
4161 case TSK_ExplicitInstantiationDeclaration:
4162 switch (PrevTSK) {
4163 case TSK_ExplicitInstantiationDeclaration:
4164 // This explicit instantiation declaration is redundant (that's okay).
Abramo Bagnara8075c852010-06-12 07:44:57 +00004165 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004166 return false;
4167
4168 case TSK_Undeclared:
4169 case TSK_ImplicitInstantiation:
4170 // We're explicitly instantiating something that may have already been
4171 // implicitly instantiated; that's fine.
4172 return false;
4173
4174 case TSK_ExplicitSpecialization:
4175 // C++0x [temp.explicit]p4:
4176 // For a given set of template parameters, if an explicit instantiation
4177 // of a template appears after a declaration of an explicit
4178 // specialization for that template, the explicit instantiation has no
4179 // effect.
Abramo Bagnara8075c852010-06-12 07:44:57 +00004180 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004181 return false;
4182
4183 case TSK_ExplicitInstantiationDefinition:
4184 // C++0x [temp.explicit]p10:
4185 // If an entity is the subject of both an explicit instantiation
4186 // declaration and an explicit instantiation definition in the same
4187 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004188 Diag(NewLoc,
4189 diag::err_explicit_instantiation_declaration_after_definition);
4190 Diag(PrevPointOfInstantiation,
4191 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004192 assert(PrevPointOfInstantiation.isValid() &&
4193 "Explicit instantiation without point of instantiation?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00004194 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004195 return false;
4196 }
4197 break;
4198
4199 case TSK_ExplicitInstantiationDefinition:
4200 switch (PrevTSK) {
4201 case TSK_Undeclared:
4202 case TSK_ImplicitInstantiation:
4203 // We're explicitly instantiating something that may have already been
4204 // implicitly instantiated; that's fine.
4205 return false;
4206
4207 case TSK_ExplicitSpecialization:
4208 // C++ DR 259, C++0x [temp.explicit]p4:
4209 // For a given set of template parameters, if an explicit
4210 // instantiation of a template appears after a declaration of
4211 // an explicit specialization for that template, the explicit
4212 // instantiation has no effect.
4213 //
4214 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004215 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004216 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004217 if (!getLangOptions().CPlusPlus0x) {
4218 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004219 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004220 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004221 diag::note_previous_template_specialization);
4222 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004223 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004224 return false;
4225
4226 case TSK_ExplicitInstantiationDeclaration:
4227 // We're explicity instantiating a definition for something for which we
4228 // were previously asked to suppress instantiations. That's fine.
4229 return false;
4230
4231 case TSK_ExplicitInstantiationDefinition:
4232 // C++0x [temp.spec]p5:
4233 // For a given template and a given set of template-arguments,
4234 // - an explicit instantiation definition shall appear at most once
4235 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004236 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004237 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004238 Diag(PrevPointOfInstantiation,
4239 diag::note_previous_explicit_instantiation);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004240 HasNoEffect = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004241 return false;
4242 }
4243 break;
4244 }
4245
4246 assert(false && "Missing specialization/instantiation case?");
4247
4248 return false;
4249}
4250
John McCallb9c78482010-04-08 09:05:18 +00004251/// \brief Perform semantic analysis for the given dependent function
4252/// template specialization. The only possible way to get a dependent
4253/// function template specialization is with a friend declaration,
4254/// like so:
4255///
4256/// template <class T> void foo(T);
4257/// template <class T> class A {
4258/// friend void foo<>(T);
4259/// };
4260///
4261/// There really isn't any useful analysis we can do here, so we
4262/// just store the information.
4263bool
4264Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4265 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4266 LookupResult &Previous) {
4267 // Remove anything from Previous that isn't a function template in
4268 // the correct context.
4269 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4270 LookupResult::Filter F = Previous.makeFilter();
4271 while (F.hasNext()) {
4272 NamedDecl *D = F.next()->getUnderlyingDecl();
4273 if (!isa<FunctionTemplateDecl>(D) ||
4274 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4275 F.erase();
4276 }
4277 F.done();
4278
4279 // Should this be diagnosed here?
4280 if (Previous.empty()) return true;
4281
4282 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4283 ExplicitTemplateArgs);
4284 return false;
4285}
4286
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004287/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004288/// specialization.
4289///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004290/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004291/// explicit function template specialization. On successful completion,
4292/// the function declaration \p FD will become a function template
4293/// specialization.
4294///
4295/// \param FD the function declaration, which will be updated to become a
4296/// function template specialization.
4297///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004298/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4299/// if any. Note that this may be valid info even when 0 arguments are
4300/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4301/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004302///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004303/// \param PrevDecl the set of declarations that may be specialized by
4304/// this function specialization.
4305bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004306Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004307 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004308 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004309 // The set of function template specializations that could match this
4310 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004311 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004312
4313 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004314 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4315 I != E; ++I) {
4316 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4317 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004318 // Only consider templates found within the same semantic lookup scope as
4319 // FD.
4320 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4321 continue;
4322
4323 // C++ [temp.expl.spec]p11:
4324 // A trailing template-argument can be left unspecified in the
4325 // template-id naming an explicit function template specialization
4326 // provided it can be deduced from the function argument type.
4327 // Perform template argument deduction to determine whether we may be
4328 // specializing this template.
4329 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004330 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004331 FunctionDecl *Specialization = 0;
4332 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004333 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004334 FD->getType(),
4335 Specialization,
4336 Info)) {
4337 // FIXME: Template argument deduction failed; record why it failed, so
4338 // that we can provide nifty diagnostics.
4339 (void)TDK;
4340 continue;
4341 }
4342
4343 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004344 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004345 }
4346 }
4347
Douglas Gregor5de279c2009-09-26 03:41:46 +00004348 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004349 UnresolvedSetIterator Result
4350 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4351 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004352 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004353 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004354 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004355 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004356 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004357 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004358 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004359
4360 // Ignore access information; it doesn't figure into redeclaration checking.
4361 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004362 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004363
4364 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004365 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004366
4367 // If this is a friend declaration, then we're not really declaring
4368 // an explicit specialization.
4369 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004370
Douglas Gregor54888652009-10-07 00:13:32 +00004371 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004372 if (!isFriend &&
4373 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004374 Specialization->getPrimaryTemplate(),
4375 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004376 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004377 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004378
4379 // C++ [temp.expl.spec]p6:
4380 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004381 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004382 // before the first use of that specialization that would cause an implicit
4383 // instantiation to take place, in every translation unit in which such a
4384 // use occurs; no diagnostic is required.
4385 FunctionTemplateSpecializationInfo *SpecInfo
4386 = Specialization->getTemplateSpecializationInfo();
4387 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004388
Abramo Bagnara8075c852010-06-12 07:44:57 +00004389 bool HasNoEffect = false;
John McCall816d75b2010-03-24 07:46:06 +00004390 if (!isFriend &&
4391 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004392 TSK_ExplicitSpecialization,
4393 Specialization,
4394 SpecInfo->getTemplateSpecializationKind(),
4395 SpecInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004396 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004397 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004398
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004399 // Mark the prior declaration as an explicit specialization, so that later
4400 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004401 if (!isFriend)
4402 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004403
4404 // Turn the given function declaration into a function template
4405 // specialization, with the template arguments from the previous
4406 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004407 // Take copies of (semantic and syntactic) template argument lists.
4408 const TemplateArgumentList* TemplArgs = new (Context)
4409 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4410 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4411 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004412 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004413 TemplArgs, /*InsertPos=*/0,
4414 SpecInfo->getTemplateSpecializationKind(),
4415 TemplArgsAsWritten);
4416
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004417 // The "previous declaration" for this function template specialization is
4418 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004419 Previous.clear();
4420 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004421 return false;
4422}
4423
Douglas Gregor86d142a2009-10-08 07:24:58 +00004424/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004425/// specialization.
4426///
4427/// This routine performs all of the semantic analysis required for an
4428/// explicit member function specialization. On successful completion,
4429/// the function declaration \p FD will become a member function
4430/// specialization.
4431///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004432/// \param Member the member declaration, which will be updated to become a
4433/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004434///
John McCall1f82f242009-11-18 22:49:29 +00004435/// \param Previous the set of declarations, one of which may be specialized
4436/// by this function specialization; the set will be modified to contain the
4437/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004438bool
John McCall1f82f242009-11-18 22:49:29 +00004439Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004440 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004441
Douglas Gregor86d142a2009-10-08 07:24:58 +00004442 // Try to find the member we are instantiating.
4443 NamedDecl *Instantiation = 0;
4444 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004445 MemberSpecializationInfo *MSInfo = 0;
4446
John McCall1f82f242009-11-18 22:49:29 +00004447 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004448 // Nowhere to look anyway.
4449 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004450 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4451 I != E; ++I) {
4452 NamedDecl *D = (*I)->getUnderlyingDecl();
4453 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004454 if (Context.hasSameType(Function->getType(), Method->getType())) {
4455 Instantiation = Method;
4456 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004457 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004458 break;
4459 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004460 }
4461 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004462 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004463 VarDecl *PrevVar;
4464 if (Previous.isSingleResult() &&
4465 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004466 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004467 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004468 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004469 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004470 }
4471 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004472 CXXRecordDecl *PrevRecord;
4473 if (Previous.isSingleResult() &&
4474 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4475 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004476 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004477 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004478 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004479 }
4480
4481 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004482 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004483 // specializations are always out-of-line, the caller will complain about
4484 // this mismatch later.
4485 return false;
4486 }
John McCalle820e5e2010-04-13 20:37:33 +00004487
4488 // If this is a friend, just bail out here before we start turning
4489 // things into explicit specializations.
4490 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4491 // Preserve instantiation information.
4492 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4493 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4494 cast<CXXMethodDecl>(InstantiatedFrom),
4495 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4496 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4497 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4498 cast<CXXRecordDecl>(InstantiatedFrom),
4499 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4500 }
4501
4502 Previous.clear();
4503 Previous.addDecl(Instantiation);
4504 return false;
4505 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004506
Douglas Gregor86d142a2009-10-08 07:24:58 +00004507 // Make sure that this is a specialization of a member.
4508 if (!InstantiatedFrom) {
4509 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4510 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004511 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4512 return true;
4513 }
4514
Douglas Gregor06db9f52009-10-12 20:18:28 +00004515 // C++ [temp.expl.spec]p6:
4516 // If a template, a member template or the member of a class template is
4517 // explicitly specialized then that spe- cialization shall be declared
4518 // before the first use of that specialization that would cause an implicit
4519 // instantiation to take place, in every translation unit in which such a
4520 // use occurs; no diagnostic is required.
4521 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004522
Abramo Bagnara8075c852010-06-12 07:44:57 +00004523 bool HasNoEffect = false;
John McCall4f7ced62010-02-11 01:33:53 +00004524 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4525 TSK_ExplicitSpecialization,
4526 Instantiation,
4527 MSInfo->getTemplateSpecializationKind(),
4528 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004529 HasNoEffect))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004530 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004531
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004532 // Check the scope of this explicit specialization.
4533 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004534 InstantiatedFrom,
4535 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004536 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004537 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004538
Douglas Gregor86d142a2009-10-08 07:24:58 +00004539 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004540 // the original declaration to note that it is an explicit specialization
4541 // (if it was previously an implicit instantiation). This latter step
4542 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004543 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004544 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4545 if (InstantiationFunction->getTemplateSpecializationKind() ==
4546 TSK_ImplicitInstantiation) {
4547 InstantiationFunction->setTemplateSpecializationKind(
4548 TSK_ExplicitSpecialization);
4549 InstantiationFunction->setLocation(Member->getLocation());
4550 }
4551
Douglas Gregor86d142a2009-10-08 07:24:58 +00004552 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4553 cast<CXXMethodDecl>(InstantiatedFrom),
4554 TSK_ExplicitSpecialization);
4555 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004556 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4557 if (InstantiationVar->getTemplateSpecializationKind() ==
4558 TSK_ImplicitInstantiation) {
4559 InstantiationVar->setTemplateSpecializationKind(
4560 TSK_ExplicitSpecialization);
4561 InstantiationVar->setLocation(Member->getLocation());
4562 }
4563
Douglas Gregor86d142a2009-10-08 07:24:58 +00004564 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4565 cast<VarDecl>(InstantiatedFrom),
4566 TSK_ExplicitSpecialization);
4567 } else {
4568 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004569 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4570 if (InstantiationClass->getTemplateSpecializationKind() ==
4571 TSK_ImplicitInstantiation) {
4572 InstantiationClass->setTemplateSpecializationKind(
4573 TSK_ExplicitSpecialization);
4574 InstantiationClass->setLocation(Member->getLocation());
4575 }
4576
Douglas Gregor86d142a2009-10-08 07:24:58 +00004577 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004578 cast<CXXRecordDecl>(InstantiatedFrom),
4579 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004580 }
4581
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004582 // Save the caller the trouble of having to figure out which declaration
4583 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004584 Previous.clear();
4585 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004586 return false;
4587}
4588
Douglas Gregore47f5a72009-10-14 23:41:34 +00004589/// \brief Check the scope of an explicit instantiation.
4590static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4591 SourceLocation InstLoc,
4592 bool WasQualifiedName) {
4593 DeclContext *ExpectedContext
4594 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4595 DeclContext *CurContext = S.CurContext->getLookupContext();
4596
4597 // C++0x [temp.explicit]p2:
4598 // An explicit instantiation shall appear in an enclosing namespace of its
4599 // template.
4600 //
4601 // This is DR275, which we do not retroactively apply to C++98/03.
4602 if (S.getLangOptions().CPlusPlus0x &&
4603 !CurContext->Encloses(ExpectedContext)) {
4604 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004605 S.Diag(InstLoc,
4606 S.getLangOptions().CPlusPlus0x?
4607 diag::err_explicit_instantiation_out_of_scope
4608 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004609 << D << NS;
4610 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004611 S.Diag(InstLoc,
4612 S.getLangOptions().CPlusPlus0x?
4613 diag::err_explicit_instantiation_must_be_global
4614 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004615 << D;
4616 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4617 return;
4618 }
4619
4620 // C++0x [temp.explicit]p2:
4621 // If the name declared in the explicit instantiation is an unqualified
4622 // name, the explicit instantiation shall appear in the namespace where
4623 // its template is declared or, if that namespace is inline (7.3.1), any
4624 // namespace from its enclosing namespace set.
4625 if (WasQualifiedName)
4626 return;
4627
4628 if (CurContext->Equals(ExpectedContext))
4629 return;
4630
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004631 S.Diag(InstLoc,
4632 S.getLangOptions().CPlusPlus0x?
4633 diag::err_explicit_instantiation_unqualified_wrong_namespace
4634 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004635 << D << ExpectedContext;
4636 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4637}
4638
4639/// \brief Determine whether the given scope specifier has a template-id in it.
4640static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4641 if (!SS.isSet())
4642 return false;
4643
4644 // C++0x [temp.explicit]p2:
4645 // If the explicit instantiation is for a member function, a member class
4646 // or a static data member of a class template specialization, the name of
4647 // the class template specialization in the qualified-id for the member
4648 // name shall be a simple-template-id.
4649 //
4650 // C++98 has the same restriction, just worded differently.
4651 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4652 NNS; NNS = NNS->getPrefix())
4653 if (Type *T = NNS->getAsType())
4654 if (isa<TemplateSpecializationType>(T))
4655 return true;
4656
4657 return false;
4658}
4659
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004660// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004661Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004662Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004663 SourceLocation ExternLoc,
4664 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004665 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004666 SourceLocation KWLoc,
4667 const CXXScopeSpec &SS,
4668 TemplateTy TemplateD,
4669 SourceLocation TemplateNameLoc,
4670 SourceLocation LAngleLoc,
4671 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004672 SourceLocation RAngleLoc,
4673 AttributeList *Attr) {
4674 // Find the class template we're specializing
4675 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004676 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004677 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4678
4679 // Check that the specialization uses the same tag kind as the
4680 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004681 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4682 assert(Kind != TTK_Enum &&
4683 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004684 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004685 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004686 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004687 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004688 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004689 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004690 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004691 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004692 diag::note_previous_use);
4693 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4694 }
4695
Douglas Gregore47f5a72009-10-14 23:41:34 +00004696 // C++0x [temp.explicit]p2:
4697 // There are two forms of explicit instantiation: an explicit instantiation
4698 // definition and an explicit instantiation declaration. An explicit
4699 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004700 TemplateSpecializationKind TSK
4701 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4702 : TSK_ExplicitInstantiationDeclaration;
4703
Douglas Gregora1f49972009-05-13 00:25:59 +00004704 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004705 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004706 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004707
4708 // Check that the template argument list is well-formed for this
4709 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004710 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4711 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004712 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4713 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004714 return true;
4715
Mike Stump11289f42009-09-09 15:08:12 +00004716 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004717 ClassTemplate->getTemplateParameters()->size()) &&
4718 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004719
Douglas Gregora1f49972009-05-13 00:25:59 +00004720 // Find the class template specialization declaration that
4721 // corresponds to these arguments.
4722 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004723 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004724 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004725 Converted.flatSize(),
4726 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004727 void *InsertPos = 0;
4728 ClassTemplateSpecializationDecl *PrevDecl
4729 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4730
Abramo Bagnara8075c852010-06-12 07:44:57 +00004731 TemplateSpecializationKind PrevDecl_TSK
4732 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
4733
Douglas Gregor54888652009-10-07 00:13:32 +00004734 // C++0x [temp.explicit]p2:
4735 // [...] An explicit instantiation shall appear in an enclosing
4736 // namespace of its template. [...]
4737 //
4738 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004739 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4740 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004741
Douglas Gregora1f49972009-05-13 00:25:59 +00004742 ClassTemplateSpecializationDecl *Specialization = 0;
4743
Douglas Gregor0681a352009-11-25 06:01:46 +00004744 bool ReusedDecl = false;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004745 bool HasNoEffect = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004746 if (PrevDecl) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00004747 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Abramo Bagnara8075c852010-06-12 07:44:57 +00004748 PrevDecl, PrevDecl_TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004749 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004750 HasNoEffect))
Douglas Gregora1f49972009-05-13 00:25:59 +00004751 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004752
Abramo Bagnara8075c852010-06-12 07:44:57 +00004753 // Even though HasNoEffect == true means that this explicit instantiation
4754 // has no effect on semantics, we go on to put its syntax in the AST.
4755
4756 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
4757 PrevDecl_TSK == TSK_Undeclared) {
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004758 // Since the only prior class template specialization with these
4759 // arguments was referenced but not declared, reuse that
Abramo Bagnara8075c852010-06-12 07:44:57 +00004760 // declaration node as our own, updating the source location
4761 // for the template name to reflect our new declaration.
4762 // (Other source locations will be updated later.)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004763 Specialization = PrevDecl;
4764 Specialization->setLocation(TemplateNameLoc);
4765 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004766 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004767 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004768 }
Abramo Bagnara8075c852010-06-12 07:44:57 +00004769
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004770 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004771 // Create a new class template specialization declaration node for
4772 // this explicit specialization.
4773 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004774 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004775 ClassTemplate->getDeclContext(),
4776 TemplateNameLoc,
4777 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004778 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004779 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004780
Abramo Bagnara8075c852010-06-12 07:44:57 +00004781 if (!HasNoEffect) {
4782 if (PrevDecl) {
4783 // Remove the previous declaration from the folding set, since we want
4784 // to introduce a new declaration.
4785 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4786 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4787 }
4788 // Insert the new specialization.
4789 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
4790 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004791 }
4792
4793 // Build the fully-sugared type for this explicit instantiation as
4794 // the user wrote in the explicit instantiation itself. This means
4795 // that we'll pretty-print the type retrieved from the
4796 // specialization's declaration the way that the user actually wrote
4797 // the explicit instantiation, rather than formatting the name based
4798 // on the "canonical" representation used to store the template
4799 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004800 TypeSourceInfo *WrittenTy
4801 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4802 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004803 Context.getTypeDeclType(Specialization));
4804 Specialization->setTypeAsWritten(WrittenTy);
4805 TemplateArgsIn.release();
4806
Abramo Bagnara8075c852010-06-12 07:44:57 +00004807 // Set source locations for keywords.
4808 Specialization->setExternLoc(ExternLoc);
4809 Specialization->setTemplateKeywordLoc(TemplateLoc);
4810
4811 // Add the explicit instantiation into its lexical context. However,
4812 // since explicit instantiations are never found by name lookup, we
4813 // just put it into the declaration context directly.
4814 Specialization->setLexicalDeclContext(CurContext);
4815 CurContext->addDecl(Specialization);
4816
4817 // Syntax is now OK, so return if it has no other effect on semantics.
4818 if (HasNoEffect) {
4819 // Set the template specialization kind.
4820 Specialization->setTemplateSpecializationKind(TSK);
4821 return DeclPtrTy::make(Specialization);
Douglas Gregor0681a352009-11-25 06:01:46 +00004822 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004823
4824 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004825 // A definition of a class template or class member template
4826 // shall be in scope at the point of the explicit instantiation of
4827 // the class template or class member template.
4828 //
4829 // This check comes when we actually try to perform the
4830 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004831 ClassTemplateSpecializationDecl *Def
4832 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004833 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004834 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004835 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004836 else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00004837 MarkVTableUsed(TemplateNameLoc, Specialization, true);
Abramo Bagnara8075c852010-06-12 07:44:57 +00004838 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
4839 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00004840
Douglas Gregor1d957a32009-10-27 18:42:08 +00004841 // Instantiate the members of this class template specialization.
4842 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004843 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004844 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004845 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4846
4847 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4848 // TSK_ExplicitInstantiationDefinition
4849 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4850 TSK == TSK_ExplicitInstantiationDefinition)
4851 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004852
Douglas Gregor12e49d32009-10-15 22:53:21 +00004853 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004854 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004855
Abramo Bagnara8075c852010-06-12 07:44:57 +00004856 // Set the template specialization kind.
4857 Specialization->setTemplateSpecializationKind(TSK);
Douglas Gregora1f49972009-05-13 00:25:59 +00004858 return DeclPtrTy::make(Specialization);
4859}
4860
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004861// Explicit instantiation of a member class of a class template.
4862Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004863Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004864 SourceLocation ExternLoc,
4865 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004866 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004867 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004868 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004869 IdentifierInfo *Name,
4870 SourceLocation NameLoc,
4871 AttributeList *Attr) {
4872
Douglas Gregord6ab8742009-05-28 23:31:59 +00004873 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004874 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004875 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004876 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004877 MultiTemplateParamsArg(*this, 0, 0),
4878 Owned, IsDependent);
4879 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4880
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004881 if (!TagD)
4882 return true;
4883
4884 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4885 if (Tag->isEnum()) {
4886 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4887 << Context.getTypeDeclType(Tag);
4888 return true;
4889 }
4890
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004891 if (Tag->isInvalidDecl())
4892 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004893
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004894 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4895 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4896 if (!Pattern) {
4897 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4898 << Context.getTypeDeclType(Record);
4899 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4900 return true;
4901 }
4902
Douglas Gregore47f5a72009-10-14 23:41:34 +00004903 // C++0x [temp.explicit]p2:
4904 // If the explicit instantiation is for a class or member class, the
4905 // elaborated-type-specifier in the declaration shall include a
4906 // simple-template-id.
4907 //
4908 // C++98 has the same restriction, just worded differently.
4909 if (!ScopeSpecifierHasTemplateId(SS))
Douglas Gregor010815a2010-06-16 16:26:47 +00004910 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004911 << Record << SS.getRange();
4912
4913 // C++0x [temp.explicit]p2:
4914 // There are two forms of explicit instantiation: an explicit instantiation
4915 // definition and an explicit instantiation declaration. An explicit
4916 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004917 TemplateSpecializationKind TSK
4918 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4919 : TSK_ExplicitInstantiationDeclaration;
4920
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004921 // C++0x [temp.explicit]p2:
4922 // [...] An explicit instantiation shall appear in an enclosing
4923 // namespace of its template. [...]
4924 //
4925 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004926 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004927
4928 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004929 CXXRecordDecl *PrevDecl
4930 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004931 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004932 PrevDecl = Record;
4933 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004934 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
Abramo Bagnara8075c852010-06-12 07:44:57 +00004935 bool HasNoEffect = false;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004936 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004937 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004938 PrevDecl,
4939 MSInfo->getTemplateSpecializationKind(),
4940 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00004941 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004942 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00004943 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004944 return TagD;
4945 }
4946
Douglas Gregor12e49d32009-10-15 22:53:21 +00004947 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004948 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004949 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004950 // C++ [temp.explicit]p3:
4951 // A definition of a member class of a class template shall be in scope
4952 // at the point of an explicit instantiation of the member class.
4953 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004954 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004955 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004956 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4957 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004958 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4959 << Pattern;
4960 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004961 } else {
4962 if (InstantiateClass(NameLoc, Record, Def,
4963 getTemplateInstantiationArgs(Record),
4964 TSK))
4965 return true;
4966
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004967 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004968 if (!RecordDef)
4969 return true;
4970 }
4971 }
4972
4973 // Instantiate all of the members of the class.
4974 InstantiateClassMembers(NameLoc, RecordDef,
4975 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004976
Douglas Gregor88d292c2010-05-13 16:44:06 +00004977 if (TSK == TSK_ExplicitInstantiationDefinition)
4978 MarkVTableUsed(NameLoc, RecordDef, true);
4979
Mike Stump87c57ac2009-05-16 07:39:55 +00004980 // FIXME: We don't have any representation for explicit instantiations of
4981 // member classes. Such a representation is not needed for compilation, but it
4982 // should be available for clients that want to see all of the declarations in
4983 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004984 return TagD;
4985}
4986
Douglas Gregor450f00842009-09-25 18:43:00 +00004987Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4988 SourceLocation ExternLoc,
4989 SourceLocation TemplateLoc,
4990 Declarator &D) {
4991 // Explicit instantiations always require a name.
4992 DeclarationName Name = GetNameForDeclarator(D);
4993 if (!Name) {
4994 if (!D.isInvalidType())
4995 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4996 diag::err_explicit_instantiation_requires_name)
4997 << D.getDeclSpec().getSourceRange()
4998 << D.getSourceRange();
4999
5000 return true;
5001 }
5002
5003 // The scope passed in may not be a decl scope. Zip up the scope tree until
5004 // we find one that is.
5005 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5006 (S->getFlags() & Scope::TemplateParamScope) != 0)
5007 S = S->getParent();
5008
5009 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00005010 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5011 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00005012 if (R.isNull())
5013 return true;
5014
5015 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5016 // Cannot explicitly instantiate a typedef.
5017 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5018 << Name;
5019 return true;
5020 }
5021
Douglas Gregor3c74d412009-10-14 20:14:33 +00005022 // C++0x [temp.explicit]p1:
5023 // [...] An explicit instantiation of a function template shall not use the
5024 // inline or constexpr specifiers.
5025 // Presumably, this also applies to member functions of class templates as
5026 // well.
5027 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5028 Diag(D.getDeclSpec().getInlineSpecLoc(),
5029 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00005030 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00005031
5032 // FIXME: check for constexpr specifier.
5033
Douglas Gregore47f5a72009-10-14 23:41:34 +00005034 // C++0x [temp.explicit]p2:
5035 // There are two forms of explicit instantiation: an explicit instantiation
5036 // definition and an explicit instantiation declaration. An explicit
5037 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005038 TemplateSpecializationKind TSK
5039 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5040 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005041
John McCall27b18f82009-11-17 02:14:36 +00005042 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
5043 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005044
5045 if (!R->isFunctionType()) {
5046 // C++ [temp.explicit]p1:
5047 // A [...] static data member of a class template can be explicitly
5048 // instantiated from the member definition associated with its class
5049 // template.
John McCall27b18f82009-11-17 02:14:36 +00005050 if (Previous.isAmbiguous())
5051 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005052
John McCall67c00872009-12-02 08:25:40 +00005053 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005054 if (!Prev || !Prev->isStaticDataMember()) {
5055 // We expect to see a data data member here.
5056 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5057 << Name;
5058 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5059 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005060 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005061 return true;
5062 }
5063
5064 if (!Prev->getInstantiatedFromStaticDataMember()) {
5065 // FIXME: Check for explicit specialization?
5066 Diag(D.getIdentifierLoc(),
5067 diag::err_explicit_instantiation_data_member_not_instantiated)
5068 << Prev;
5069 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5070 // FIXME: Can we provide a note showing where this was declared?
5071 return true;
5072 }
5073
Douglas Gregore47f5a72009-10-14 23:41:34 +00005074 // C++0x [temp.explicit]p2:
5075 // If the explicit instantiation is for a member function, a member class
5076 // or a static data member of a class template specialization, the name of
5077 // the class template specialization in the qualified-id for the member
5078 // name shall be a simple-template-id.
5079 //
5080 // C++98 has the same restriction, just worded differently.
5081 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5082 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005083 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005084 << Prev << D.getCXXScopeSpec().getRange();
5085
5086 // Check the scope of this explicit instantiation.
5087 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5088
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005089 // Verify that it is okay to explicitly instantiate here.
5090 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5091 assert(MSInfo && "Missing static data member specialization info?");
Abramo Bagnara8075c852010-06-12 07:44:57 +00005092 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005093 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005094 MSInfo->getTemplateSpecializationKind(),
5095 MSInfo->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005096 HasNoEffect))
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005097 return true;
Abramo Bagnara8075c852010-06-12 07:44:57 +00005098 if (HasNoEffect)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005099 return DeclPtrTy();
5100
Douglas Gregor450f00842009-09-25 18:43:00 +00005101 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005102 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005103 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005104 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5105 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005106
5107 // FIXME: Create an ExplicitInstantiation node?
5108 return DeclPtrTy();
5109 }
5110
Douglas Gregor0e876e02009-09-25 23:53:26 +00005111 // If the declarator is a template-id, translate the parser's template
5112 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005113 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005114 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005115 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5116 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005117 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5118 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005119 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5120 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005121 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005122 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005123 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005124 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005125 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005126
Douglas Gregor450f00842009-09-25 18:43:00 +00005127 // C++ [temp.explicit]p1:
5128 // A [...] function [...] can be explicitly instantiated from its template.
5129 // A member function [...] of a class template can be explicitly
5130 // instantiated from the member definition associated with its class
5131 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005132 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005133 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5134 P != PEnd; ++P) {
5135 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005136 if (!HasExplicitTemplateArgs) {
5137 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5138 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5139 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005140
John McCall58cc69d2010-01-27 01:50:18 +00005141 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005142 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5143 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005144 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005145 }
5146 }
5147
5148 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5149 if (!FunTmpl)
5150 continue;
5151
John McCallbc077cf2010-02-08 23:07:23 +00005152 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005153 FunctionDecl *Specialization = 0;
5154 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005155 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005156 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005157 R, Specialization, Info)) {
5158 // FIXME: Keep track of almost-matches?
5159 (void)TDK;
5160 continue;
5161 }
5162
John McCall58cc69d2010-01-27 01:50:18 +00005163 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005164 }
5165
5166 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005167 UnresolvedSetIterator Result
5168 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005169 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005170 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5171 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5172 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005173
John McCall58cc69d2010-01-27 01:50:18 +00005174 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005175 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005176
5177 // Ignore access control bits, we don't need them for redeclaration checking.
5178 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005179
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005180 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005181 Diag(D.getIdentifierLoc(),
5182 diag::err_explicit_instantiation_member_function_not_instantiated)
5183 << Specialization
5184 << (Specialization->getTemplateSpecializationKind() ==
5185 TSK_ExplicitSpecialization);
5186 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5187 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005188 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005189
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005190 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005191 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5192 PrevDecl = Specialization;
5193
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005194 if (PrevDecl) {
Abramo Bagnara8075c852010-06-12 07:44:57 +00005195 bool HasNoEffect = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005196 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005197 PrevDecl,
5198 PrevDecl->getTemplateSpecializationKind(),
5199 PrevDecl->getPointOfInstantiation(),
Abramo Bagnara8075c852010-06-12 07:44:57 +00005200 HasNoEffect))
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005201 return true;
5202
5203 // FIXME: We may still want to build some representation of this
5204 // explicit specialization.
Abramo Bagnara8075c852010-06-12 07:44:57 +00005205 if (HasNoEffect)
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005206 return DeclPtrTy();
5207 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005208
5209 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005210
5211 if (TSK == TSK_ExplicitInstantiationDefinition)
5212 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5213 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005214
Douglas Gregore47f5a72009-10-14 23:41:34 +00005215 // C++0x [temp.explicit]p2:
5216 // If the explicit instantiation is for a member function, a member class
5217 // or a static data member of a class template specialization, the name of
5218 // the class template specialization in the qualified-id for the member
5219 // name shall be a simple-template-id.
5220 //
5221 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005222 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005223 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005224 D.getCXXScopeSpec().isSet() &&
5225 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5226 Diag(D.getIdentifierLoc(),
Douglas Gregor010815a2010-06-16 16:26:47 +00005227 diag::ext_explicit_instantiation_without_qualified_id)
Douglas Gregore47f5a72009-10-14 23:41:34 +00005228 << Specialization << D.getCXXScopeSpec().getRange();
5229
5230 CheckExplicitInstantiationScope(*this,
5231 FunTmpl? (NamedDecl *)FunTmpl
5232 : Specialization->getInstantiatedFromMemberFunction(),
5233 D.getIdentifierLoc(),
5234 D.getCXXScopeSpec().isSet());
5235
Douglas Gregor450f00842009-09-25 18:43:00 +00005236 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5237 return DeclPtrTy();
5238}
5239
Douglas Gregor333489b2009-03-27 23:10:48 +00005240Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005241Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5242 const CXXScopeSpec &SS, IdentifierInfo *Name,
5243 SourceLocation TagLoc, SourceLocation NameLoc) {
5244 // This has to hold, because SS is expected to be defined.
5245 assert(Name && "Expected a name in a dependent tag");
5246
5247 NestedNameSpecifier *NNS
5248 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5249 if (!NNS)
5250 return true;
5251
Abramo Bagnara6150c882010-05-11 21:36:43 +00005252 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005253
Douglas Gregorba41d012010-04-24 16:38:41 +00005254 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5255 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005256 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005257 return true;
5258 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005259
5260 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5261 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005262}
5263
5264Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005265Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5266 const CXXScopeSpec &SS, const IdentifierInfo &II,
5267 SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005268 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005269 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5270 if (!NNS)
5271 return true;
5272
Douglas Gregorf7d77712010-06-16 22:31:08 +00005273 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5274 !getLangOptions().CPlusPlus0x)
5275 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5276 << FixItHint::CreateRemoval(TypenameLoc);
5277
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005278 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005279 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005280 if (T.isNull())
5281 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005282
5283 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5284 if (isa<DependentNameType>(T)) {
5285 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005286 TL.setKeywordLoc(TypenameLoc);
5287 TL.setQualifierRange(SS.getRange());
5288 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005289 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005290 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005291 TL.setKeywordLoc(TypenameLoc);
5292 TL.setQualifierRange(SS.getRange());
5293 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005294 }
5295
5296 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor333489b2009-03-27 23:10:48 +00005297}
5298
Douglas Gregordce2b622009-04-01 00:28:59 +00005299Sema::TypeResult
Douglas Gregorf7d77712010-06-16 22:31:08 +00005300Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5301 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5302 TypeTy *Ty) {
5303 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5304 !getLangOptions().CPlusPlus0x)
5305 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5306 << FixItHint::CreateRemoval(TypenameLoc);
5307
John McCallf7bcc812010-05-28 23:32:21 +00005308 TypeSourceInfo *InnerTSI = 0;
5309 QualType T = GetTypeFromParser(Ty, &InnerTSI);
Mike Stump11289f42009-09-09 15:08:12 +00005310 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00005311 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
John McCallf7bcc812010-05-28 23:32:21 +00005312
5313 assert(isa<TemplateSpecializationType>(T) &&
5314 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005315
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005316 if (computeDeclContext(SS, false)) {
5317 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005318 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005319 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005320
5321 // Push the inner type, preserving its source locations if possible.
5322 TypeLocBuilder Builder;
5323 if (InnerTSI)
5324 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5325 else
5326 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5327
Abramo Bagnara6150c882010-05-11 21:36:43 +00005328 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCallf7bcc812010-05-28 23:32:21 +00005329 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5330 TL.setKeywordLoc(TypenameLoc);
5331 TL.setQualifierRange(SS.getRange());
5332
5333 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall99b2fe52010-04-29 23:50:39 +00005334 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005335 }
Mike Stump11289f42009-09-09 15:08:12 +00005336
John McCallc392f372010-06-11 00:33:02 +00005337 // TODO: it's really silly that we make a template specialization
5338 // type earlier only to drop it again here.
5339 TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5340 DependentTemplateName *DTN =
5341 TST->getTemplateName().getAsDependentTemplateName();
5342 assert(DTN && "dependent template has non-dependent name?");
5343 T = Context.getDependentTemplateSpecializationType(ETK_Typename, NNS,
5344 DTN->getIdentifier(),
5345 TST->getNumArgs(),
5346 TST->getArgs());
John McCall99b2fe52010-04-29 23:50:39 +00005347 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
John McCallc392f372010-06-11 00:33:02 +00005348 DependentTemplateSpecializationTypeLoc TL =
5349 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5350 if (InnerTSI) {
5351 TemplateSpecializationTypeLoc TSTL =
5352 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5353 TL.setLAngleLoc(TSTL.getLAngleLoc());
5354 TL.setRAngleLoc(TSTL.getRAngleLoc());
5355 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5356 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5357 } else {
5358 TL.initializeLocal(SourceLocation());
5359 }
John McCallf7bcc812010-05-28 23:32:21 +00005360 TL.setKeywordLoc(TypenameLoc);
5361 TL.setQualifierRange(SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005362 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005363}
5364
Douglas Gregor333489b2009-03-27 23:10:48 +00005365/// \brief Build the type that describes a C++ typename specifier,
5366/// e.g., "typename T::type".
5367QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005368Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5369 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005370 SourceLocation KeywordLoc, SourceRange NNSRange,
5371 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005372 CXXScopeSpec SS;
5373 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005374 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005375
John McCall0b66eb32010-05-01 00:40:08 +00005376 DeclContext *Ctx = computeDeclContext(SS);
5377 if (!Ctx) {
5378 // If the nested-name-specifier is dependent and couldn't be
5379 // resolved to a type, build a typename type.
5380 assert(NNS->isDependent());
5381 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005382 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005383
John McCall0b66eb32010-05-01 00:40:08 +00005384 // If the nested-name-specifier refers to the current instantiation,
5385 // the "typename" keyword itself is superfluous. In C++03, the
5386 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5387 // allows such extraneous "typename" keywords, and we retroactively
Douglas Gregorc9d26822010-06-14 22:07:54 +00005388 // apply this DR to C++03 code with only a warning. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005389
John McCall0b66eb32010-05-01 00:40:08 +00005390 if (RequireCompleteDeclContext(SS, Ctx))
5391 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005392
5393 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005394 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005395 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005396 unsigned DiagID = 0;
5397 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005398 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005399 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005400 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005401 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005402
5403 case LookupResult::NotFoundInCurrentInstantiation:
5404 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005405 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005406
5407 case LookupResult::Found:
Douglas Gregorf7d77712010-06-16 22:31:08 +00005408 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005409 // We found a type. Build an ElaboratedType, since the
5410 // typename-specifier was just sugar.
5411 return Context.getElaboratedType(ETK_Typename, NNS,
5412 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005413 }
5414
5415 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005416 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005417 break;
5418
John McCalle61f2ba2009-11-18 02:36:19 +00005419 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005420 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005421 return QualType();
5422
Douglas Gregor333489b2009-03-27 23:10:48 +00005423 case LookupResult::FoundOverloaded:
5424 DiagID = diag::err_typename_nested_not_type;
5425 Referenced = *Result.begin();
5426 break;
5427
John McCall6538c932009-10-10 05:48:19 +00005428 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005429 return QualType();
5430 }
5431
5432 // If we get here, it's because name lookup did not find a
5433 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005434 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5435 IILoc);
5436 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005437 if (Referenced)
5438 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5439 << Name;
5440 return QualType();
5441}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005442
5443namespace {
5444 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005445 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005446 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005447 SourceLocation Loc;
5448 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005449
Douglas Gregor15acfb92009-08-06 16:20:37 +00005450 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005451 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5452
Mike Stump11289f42009-09-09 15:08:12 +00005453 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005454 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005455 DeclarationName Entity)
5456 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005457 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005458
5459 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005460 /// transformed.
5461 ///
5462 /// For the purposes of type reconstruction, a type has already been
5463 /// transformed if it is NULL or if it is not dependent.
5464 bool AlreadyTransformed(QualType T) {
5465 return T.isNull() || !T->isDependentType();
5466 }
Mike Stump11289f42009-09-09 15:08:12 +00005467
5468 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005469 /// rebuilt.
5470 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005471
Douglas Gregor15acfb92009-08-06 16:20:37 +00005472 /// \brief Returns the name of the entity whose type is being rebuilt.
5473 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005474
Douglas Gregoref6ab412009-10-27 06:26:26 +00005475 /// \brief Sets the "base" location and entity when that
5476 /// information is known based on another transformation.
5477 void setBase(SourceLocation Loc, DeclarationName Entity) {
5478 this->Loc = Loc;
5479 this->Entity = Entity;
5480 }
5481
Douglas Gregor15acfb92009-08-06 16:20:37 +00005482 /// \brief Transforms an expression by returning the expression itself
5483 /// (an identity function).
5484 ///
5485 /// FIXME: This is completely unsafe; we will need to actually clone the
5486 /// expressions.
5487 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00005488 return getSema().Owned(E->Retain());
Douglas Gregor15acfb92009-08-06 16:20:37 +00005489 }
Douglas Gregor15acfb92009-08-06 16:20:37 +00005490 };
5491}
5492
Douglas Gregor15acfb92009-08-06 16:20:37 +00005493/// \brief Rebuilds a type within the context of the current instantiation.
5494///
Mike Stump11289f42009-09-09 15:08:12 +00005495/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005496/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005497/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005498/// partial specialization thereof). This routine will rebuild that type now
5499/// that we have entered the declarator's scope, which may produce different
5500/// canonical types, e.g.,
5501///
5502/// \code
5503/// template<typename T>
5504/// struct X {
5505/// typedef T* pointer;
5506/// pointer data();
5507/// };
5508///
5509/// template<typename T>
5510/// typename X<T>::pointer X<T>::data() { ... }
5511/// \endcode
5512///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005513/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005514/// since we do not know that we can look into X<T> when we parsed the type.
5515/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005516/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005517/// as the canonical type of T*, allowing the return types of the out-of-line
5518/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005519TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5520 SourceLocation Loc,
5521 DeclarationName Name) {
5522 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005523 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005524
Douglas Gregor15acfb92009-08-06 16:20:37 +00005525 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5526 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005527}
Douglas Gregorbe999392009-09-15 16:23:51 +00005528
John McCall99b2fe52010-04-29 23:50:39 +00005529bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5530 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005531
5532 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5533 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5534 DeclarationName());
5535 NestedNameSpecifier *Rebuilt =
5536 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005537 if (!Rebuilt) return true;
5538
5539 SS.setScopeRep(Rebuilt);
5540 return false;
John McCall2408e322010-04-27 00:57:59 +00005541}
5542
Douglas Gregorbe999392009-09-15 16:23:51 +00005543/// \brief Produces a formatted string that describes the binding of
5544/// template parameters to template arguments.
5545std::string
5546Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5547 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005548 // FIXME: For variadic templates, we'll need to get the structured list.
5549 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5550 Args.flat_size());
5551}
5552
5553std::string
5554Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5555 const TemplateArgument *Args,
5556 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005557 std::string Result;
5558
Douglas Gregore62e6a02009-11-11 19:13:48 +00005559 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005560 return Result;
5561
5562 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005563 if (I >= NumArgs)
5564 break;
5565
Douglas Gregorbe999392009-09-15 16:23:51 +00005566 if (I == 0)
5567 Result += "[with ";
5568 else
5569 Result += ", ";
5570
5571 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5572 Result += Id->getName();
5573 } else {
5574 Result += '$';
5575 Result += llvm::utostr(I);
5576 }
5577
5578 Result += " = ";
5579
5580 switch (Args[I].getKind()) {
5581 case TemplateArgument::Null:
5582 Result += "<no value>";
5583 break;
5584
5585 case TemplateArgument::Type: {
5586 std::string TypeStr;
5587 Args[I].getAsType().getAsStringInternal(TypeStr,
5588 Context.PrintingPolicy);
5589 Result += TypeStr;
5590 break;
5591 }
5592
5593 case TemplateArgument::Declaration: {
5594 bool Unnamed = true;
5595 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5596 if (ND->getDeclName()) {
5597 Unnamed = false;
5598 Result += ND->getNameAsString();
5599 }
5600 }
5601
5602 if (Unnamed) {
5603 Result += "<anonymous>";
5604 }
5605 break;
5606 }
5607
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005608 case TemplateArgument::Template: {
5609 std::string Str;
5610 llvm::raw_string_ostream OS(Str);
5611 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5612 Result += OS.str();
5613 break;
5614 }
5615
Douglas Gregorbe999392009-09-15 16:23:51 +00005616 case TemplateArgument::Integral: {
5617 Result += Args[I].getAsIntegral()->toString(10);
5618 break;
5619 }
5620
5621 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005622 // FIXME: This is non-optimal, since we're regurgitating the
5623 // expression we were given.
5624 std::string Str;
5625 {
5626 llvm::raw_string_ostream OS(Str);
5627 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5628 Context.PrintingPolicy);
5629 }
5630 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005631 break;
5632 }
5633
5634 case TemplateArgument::Pack:
5635 // FIXME: Format template argument packs
5636 Result += "<template argument pack>";
5637 break;
5638 }
5639 }
5640
5641 Result += ']';
5642 return Result;
5643}