blob: 2f18711e2466700212a4faaae07883fc160c4b16 [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.
30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
31 if (!D)
32 return 0;
Mike Stump11289f42009-09-09 15:08:12 +000033
Douglas Gregorb7bfe792009-09-02 22:59:36 +000034 if (isa<TemplateDecl>(D))
35 return D;
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();
71 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
72 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);
263 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
264 if (LookupCtx)
265 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
266 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
Douglas 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();
Douglas Gregorff18cc12009-12-31 08:11:17 +0000277 } else
278 Found.clear();
279 } else {
280 Found.clear();
281 }
282 }
283
John McCalle66edc12009-11-24 19:00:30 +0000284 FilterAcceptableTemplateNames(Context, Found);
285 if (Found.empty())
286 return;
287
288 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
289 // C++ [basic.lookup.classref]p1:
290 // [...] If the lookup in the class of the object expression finds a
291 // template, the name is also looked up in the context of the entire
292 // postfix-expression and [...]
293 //
294 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
295 LookupOrdinaryName);
296 LookupName(FoundOuter, S);
297 FilterAcceptableTemplateNames(Context, FoundOuter);
Douglas Gregor41f90302010-04-12 20:54:26 +0000298
John McCalle66edc12009-11-24 19:00:30 +0000299 if (FoundOuter.empty()) {
300 // - if the name is not found, the name found in the class of the
301 // object expression is used, otherwise
302 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
303 // - if the name is found in the context of the entire
304 // postfix-expression and does not name a class template, the name
305 // found in the class of the object expression is used, otherwise
306 } else {
307 // - if the name found is a class template, it must refer to the same
308 // entity as the one found in the class of the object expression,
309 // otherwise the program is ill-formed.
310 if (!Found.isSingleResult() ||
311 Found.getFoundDecl()->getCanonicalDecl()
312 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
313 Diag(Found.getNameLoc(),
Jeffrey Yasskin2f96e9f2010-06-05 01:39:57 +0000314 diag::ext_nested_name_member_ref_lookup_ambiguous)
315 << Found.getLookupName()
316 << ObjectType;
John McCalle66edc12009-11-24 19:00:30 +0000317 Diag(Found.getRepresentativeDecl()->getLocation(),
318 diag::note_ambig_member_ref_object_type)
319 << ObjectType;
320 Diag(FoundOuter.getFoundDecl()->getLocation(),
321 diag::note_ambig_member_ref_scope);
322
323 // Recover by taking the template that we found in the object
324 // expression's type.
325 }
326 }
327 }
328}
329
John McCallcd4b4772009-12-02 03:53:29 +0000330/// ActOnDependentIdExpression - Handle a dependent id-expression that
331/// was just parsed. This is only possible with an explicit scope
332/// specifier naming a dependent type.
John McCalle66edc12009-11-24 19:00:30 +0000333Sema::OwningExprResult
334Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
335 DeclarationName Name,
336 SourceLocation NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000337 bool isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000338 const TemplateArgumentListInfo *TemplateArgs) {
339 NestedNameSpecifier *Qualifier
340 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCall87fe5d52010-05-20 01:18:31 +0000341
342 DeclContext *DC = getFunctionLevelDeclContext();
John McCalle66edc12009-11-24 19:00:30 +0000343
John McCallcd4b4772009-12-02 03:53:29 +0000344 if (!isAddressOfOperand &&
John McCall87fe5d52010-05-20 01:18:31 +0000345 isa<CXXMethodDecl>(DC) &&
346 cast<CXXMethodDecl>(DC)->isInstance()) {
347 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
John McCallcd4b4772009-12-02 03:53:29 +0000348
John McCalle66edc12009-11-24 19:00:30 +0000349 // Since the 'this' expression is synthesized, we don't need to
350 // perform the double-lookup check.
351 NamedDecl *FirstQualifierInScope = 0;
352
John McCall2d74de92009-12-01 22:10:20 +0000353 return Owned(CXXDependentScopeMemberExpr::Create(Context,
354 /*This*/ 0, ThisType,
355 /*IsArrow*/ true,
John McCalle66edc12009-11-24 19:00:30 +0000356 /*Op*/ SourceLocation(),
357 Qualifier, SS.getRange(),
358 FirstQualifierInScope,
359 Name, NameLoc,
360 TemplateArgs));
361 }
362
363 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
364}
365
366Sema::OwningExprResult
367Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
368 DeclarationName Name,
369 SourceLocation NameLoc,
370 const TemplateArgumentListInfo *TemplateArgs) {
371 return Owned(DependentScopeDeclRefExpr::Create(Context,
372 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
373 SS.getRange(),
374 Name, NameLoc,
375 TemplateArgs));
Douglas Gregor55ad91f2008-12-18 19:37:40 +0000376}
377
Douglas Gregor5101c242008-12-05 18:15:24 +0000378/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
379/// that the template parameter 'PrevDecl' is being shadowed by a new
380/// declaration at location Loc. Returns true to indicate that this is
381/// an error, and false otherwise.
382bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
Douglas Gregor5daeee22008-12-08 18:40:42 +0000383 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
Douglas Gregor5101c242008-12-05 18:15:24 +0000384
385 // Microsoft Visual C++ permits template parameters to be shadowed.
386 if (getLangOptions().Microsoft)
387 return false;
388
389 // C++ [temp.local]p4:
390 // A template-parameter shall not be redeclared within its
391 // scope (including nested scopes).
Mike Stump11289f42009-09-09 15:08:12 +0000392 Diag(Loc, diag::err_template_param_shadow)
Douglas Gregor5101c242008-12-05 18:15:24 +0000393 << cast<NamedDecl>(PrevDecl)->getDeclName();
394 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
395 return true;
396}
397
Douglas Gregor463421d2009-03-03 04:44:36 +0000398/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000399/// the parameter D to reference the templated declaration and return a pointer
400/// to the template declaration. Otherwise, do nothing to D and return null.
Chris Lattner83f095c2009-03-28 19:18:32 +0000401TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
Douglas Gregor27c26e92009-10-06 21:27:51 +0000402 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000403 D = DeclPtrTy::make(Temp->getTemplatedDecl());
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000404 return Temp;
405 }
406 return 0;
407}
408
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000409static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
410 const ParsedTemplateArgument &Arg) {
411
412 switch (Arg.getKind()) {
413 case ParsedTemplateArgument::Type: {
John McCallbcd03502009-12-07 02:54:59 +0000414 TypeSourceInfo *DI;
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000415 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
416 if (!DI)
John McCallbcd03502009-12-07 02:54:59 +0000417 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000418 return TemplateArgumentLoc(TemplateArgument(T), DI);
419 }
420
421 case ParsedTemplateArgument::NonType: {
422 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
423 return TemplateArgumentLoc(TemplateArgument(E), E);
424 }
425
426 case ParsedTemplateArgument::Template: {
427 TemplateName Template
428 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
429 return TemplateArgumentLoc(TemplateArgument(Template),
430 Arg.getScopeSpec().getRange(),
431 Arg.getLocation());
432 }
433 }
434
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000435 llvm_unreachable("Unhandled parsed template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000436 return TemplateArgumentLoc();
437}
438
439/// \brief Translates template arguments as provided by the parser
440/// into template arguments used by semantic analysis.
John McCall6b51f282009-11-23 01:53:49 +0000441void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
442 TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000443 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
John McCall6b51f282009-11-23 01:53:49 +0000444 TemplateArgs.addArgument(translateTemplateArgument(*this,
445 TemplateArgsIn[I]));
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000446}
447
Douglas Gregor5101c242008-12-05 18:15:24 +0000448/// ActOnTypeParameter - Called when a C++ template type parameter
449/// (e.g., "typename T") has been parsed. Typename specifies whether
450/// the keyword "typename" was used to declare the type parameter
451/// (otherwise, "class" was used), and KeyLoc is the location of the
452/// "class" or "typename" keyword. ParamName is the name of the
453/// parameter (NULL indicates an unnamed template parameter) and
Mike Stump11289f42009-09-09 15:08:12 +0000454/// ParamName is the location of the parameter name (if any).
Douglas Gregor5101c242008-12-05 18:15:24 +0000455/// If the type parameter has a default argument, it will be added
456/// later via ActOnTypeParameterDefault.
Mike Stump11289f42009-09-09 15:08:12 +0000457Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
Anders Carlsson01e9e932009-06-12 19:58:00 +0000458 SourceLocation EllipsisLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000459 SourceLocation KeyLoc,
460 IdentifierInfo *ParamName,
461 SourceLocation ParamNameLoc,
462 unsigned Depth, unsigned Position) {
Mike Stump11289f42009-09-09 15:08:12 +0000463 assert(S->isTemplateParamScope() &&
464 "Template type parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000465 bool Invalid = false;
466
467 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000468 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000469 LookupOrdinaryName,
470 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000471 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000472 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000473 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000474 }
475
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000476 SourceLocation Loc = ParamNameLoc;
477 if (!ParamName)
478 Loc = KeyLoc;
479
Douglas Gregor5101c242008-12-05 18:15:24 +0000480 TemplateTypeParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000481 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
482 Loc, Depth, Position, ParamName, Typename,
Anders Carlssonfb1d7762009-06-12 22:23:22 +0000483 Ellipsis);
Douglas Gregor5101c242008-12-05 18:15:24 +0000484 if (Invalid)
485 Param->setInvalidDecl();
486
487 if (ParamName) {
488 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000489 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000490 IdResolver.AddDecl(Param);
491 }
492
Chris Lattner83f095c2009-03-28 19:18:32 +0000493 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000494}
495
Douglas Gregordba32632009-02-10 19:49:53 +0000496/// ActOnTypeParameterDefault - Adds a default argument (the type
Mike Stump11289f42009-09-09 15:08:12 +0000497/// Default) to the given template type parameter (TypeParam).
498void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
Douglas Gregordba32632009-02-10 19:49:53 +0000499 SourceLocation EqualLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000500 SourceLocation DefaultLoc,
Douglas Gregordba32632009-02-10 19:49:53 +0000501 TypeTy *DefaultT) {
Mike Stump11289f42009-09-09 15:08:12 +0000502 TemplateTypeParmDecl *Parm
Chris Lattner83f095c2009-03-28 19:18:32 +0000503 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
John McCall0ad16662009-10-29 08:12:44 +0000504
John McCallbcd03502009-12-07 02:54:59 +0000505 TypeSourceInfo *DefaultTInfo;
506 GetTypeFromParser(DefaultT, &DefaultTInfo);
John McCall0ad16662009-10-29 08:12:44 +0000507
John McCallbcd03502009-12-07 02:54:59 +0000508 assert(DefaultTInfo && "expected source information for type");
Douglas Gregordba32632009-02-10 19:49:53 +0000509
Anders Carlssond3824352009-06-12 22:30:13 +0000510 // C++0x [temp.param]p9:
511 // A default template-argument may be specified for any kind of
Mike Stump11289f42009-09-09 15:08:12 +0000512 // template-parameter that is not a template parameter pack.
Anders Carlssond3824352009-06-12 22:30:13 +0000513 if (Parm->isParameterPack()) {
514 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
Anders Carlssond3824352009-06-12 22:30:13 +0000515 return;
516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Douglas Gregordba32632009-02-10 19:49:53 +0000518 // C++ [temp.param]p14:
519 // A template-parameter shall not be used in its own default argument.
520 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000521
Douglas Gregordba32632009-02-10 19:49:53 +0000522 // Check the template argument itself.
John McCallbcd03502009-12-07 02:54:59 +0000523 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000524 Parm->setInvalidDecl();
525 return;
526 }
527
John McCallbcd03502009-12-07 02:54:59 +0000528 Parm->setDefaultArgument(DefaultTInfo, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000529}
530
Douglas Gregor463421d2009-03-03 04:44:36 +0000531/// \brief Check that the type of a non-type template parameter is
532/// well-formed.
533///
534/// \returns the (possibly-promoted) parameter type if valid;
535/// otherwise, produces a diagnostic and returns a NULL type.
Mike Stump11289f42009-09-09 15:08:12 +0000536QualType
Douglas Gregor463421d2009-03-03 04:44:36 +0000537Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
Douglas Gregora09387d2010-05-23 19:57:01 +0000538 // We don't allow variably-modified types as the type of non-type template
539 // parameters.
540 if (T->isVariablyModifiedType()) {
541 Diag(Loc, diag::err_variably_modified_nontype_template_param)
542 << T;
543 return QualType();
544 }
545
Douglas Gregor463421d2009-03-03 04:44:36 +0000546 // C++ [temp.param]p4:
547 //
548 // A non-type template-parameter shall have one of the following
549 // (optionally cv-qualified) types:
550 //
551 // -- integral or enumeration type,
552 if (T->isIntegralType() || T->isEnumeralType() ||
Mike Stump11289f42009-09-09 15:08:12 +0000553 // -- pointer to object or pointer to function,
554 (T->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000555 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
556 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000557 // -- reference to object or reference to function,
Douglas Gregor463421d2009-03-03 04:44:36 +0000558 T->isReferenceType() ||
559 // -- pointer to member.
560 T->isMemberPointerType() ||
561 // If T is a dependent type, we can't do the check now, so we
562 // assume that it is well-formed.
563 T->isDependentType())
564 return T;
565 // C++ [temp.param]p8:
566 //
567 // A non-type template-parameter of type "array of T" or
568 // "function returning T" is adjusted to be of type "pointer to
569 // T" or "pointer to function returning T", respectively.
570 else if (T->isArrayType())
571 // FIXME: Keep the type prior to promotion?
572 return Context.getArrayDecayedType(T);
573 else if (T->isFunctionType())
574 // FIXME: Keep the type prior to promotion?
575 return Context.getPointerType(T);
Douglas Gregor959d5a02010-05-22 16:17:30 +0000576
Douglas Gregor463421d2009-03-03 04:44:36 +0000577 Diag(Loc, diag::err_template_nontype_parm_bad_type)
578 << T;
579
580 return QualType();
581}
582
Douglas Gregor5101c242008-12-05 18:15:24 +0000583/// ActOnNonTypeTemplateParameter - Called when a C++ non-type
584/// template parameter (e.g., "int Size" in "template<int Size>
585/// class Array") has been parsed. S is the current scope and D is
586/// the parsed declarator.
Chris Lattner83f095c2009-03-28 19:18:32 +0000587Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
Mike Stump11289f42009-09-09 15:08:12 +0000588 unsigned Depth,
Chris Lattner83f095c2009-03-28 19:18:32 +0000589 unsigned Position) {
John McCall8cb7bdf2010-06-04 23:28:52 +0000590 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
591 QualType T = TInfo->getType();
Douglas Gregor5101c242008-12-05 18:15:24 +0000592
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000593 assert(S->isTemplateParamScope() &&
594 "Non-type template parameter not in template parameter scope!");
Douglas Gregor5101c242008-12-05 18:15:24 +0000595 bool Invalid = false;
596
597 IdentifierInfo *ParamName = D.getIdentifier();
598 if (ParamName) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000599 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000600 LookupOrdinaryName,
601 ForRedeclaration);
Douglas Gregor5daeee22008-12-08 18:40:42 +0000602 if (PrevDecl && PrevDecl->isTemplateParameter())
Douglas Gregor5101c242008-12-05 18:15:24 +0000603 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000604 PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +0000605 }
606
Douglas Gregor463421d2009-03-03 04:44:36 +0000607 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000608 if (T.isNull()) {
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 T = Context.IntTy; // Recover with an 'int' type.
Douglas Gregorce0fc86f2009-03-09 16:46:39 +0000610 Invalid = true;
611 }
Douglas Gregor81338792009-02-10 17:43:50 +0000612
Douglas Gregor5101c242008-12-05 18:15:24 +0000613 NonTypeTemplateParmDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +0000614 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
615 D.getIdentifierLoc(),
John McCallbcd03502009-12-07 02:54:59 +0000616 Depth, Position, ParamName, T, TInfo);
Douglas Gregor5101c242008-12-05 18:15:24 +0000617 if (Invalid)
618 Param->setInvalidDecl();
619
620 if (D.getIdentifier()) {
621 // Add the template parameter into the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000622 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor5101c242008-12-05 18:15:24 +0000623 IdResolver.AddDecl(Param);
624 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000625 return DeclPtrTy::make(Param);
Douglas Gregor5101c242008-12-05 18:15:24 +0000626}
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000627
Douglas Gregordba32632009-02-10 19:49:53 +0000628/// \brief Adds a default argument to the given non-type template
629/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000630void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000631 SourceLocation EqualLoc,
632 ExprArg DefaultE) {
Mike Stump11289f42009-09-09 15:08:12 +0000633 NonTypeTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000634 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregordba32632009-02-10 19:49:53 +0000635 Expr *Default = static_cast<Expr *>(DefaultE.get());
Mike Stump11289f42009-09-09 15:08:12 +0000636
Douglas Gregordba32632009-02-10 19:49:53 +0000637 // C++ [temp.param]p14:
638 // A template-parameter shall not be used in its own default argument.
639 // FIXME: Implement this check! Needs a recursive walk over the types.
Mike Stump11289f42009-09-09 15:08:12 +0000640
Douglas Gregordba32632009-02-10 19:49:53 +0000641 // Check the well-formedness of the default template argument.
Douglas Gregor74eba0b2009-06-11 18:10:32 +0000642 TemplateArgument Converted;
643 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
644 Converted)) {
Douglas Gregordba32632009-02-10 19:49:53 +0000645 TemplateParm->setInvalidDecl();
646 return;
647 }
648
Abramo Bagnara656e3002010-06-09 09:26:05 +0000649 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>(), false);
Douglas Gregordba32632009-02-10 19:49:53 +0000650}
651
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000652
653/// ActOnTemplateTemplateParameter - Called when a C++ template template
654/// parameter (e.g. T in template <template <typename> class T> class array)
655/// has been parsed. S is the current scope.
Chris Lattner83f095c2009-03-28 19:18:32 +0000656Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
657 SourceLocation TmpLoc,
658 TemplateParamsTy *Params,
659 IdentifierInfo *Name,
660 SourceLocation NameLoc,
661 unsigned Depth,
Mike Stump11289f42009-09-09 15:08:12 +0000662 unsigned Position) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000663 assert(S->isTemplateParamScope() &&
664 "Template template parameter not in template parameter scope!");
665
666 // Construct the parameter object.
667 TemplateTemplateParmDecl *Param =
John McCallf7b2fb52010-01-22 00:28:27 +0000668 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
669 TmpLoc, Depth, Position, Name,
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000670 (TemplateParameterList*)Params);
671
672 // Make sure the parameter is valid.
673 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
674 // do anything yet. However, if the template parameter list or (eventual)
675 // default value is ever invalidated, that will propagate here.
676 bool Invalid = false;
677 if (Invalid) {
678 Param->setInvalidDecl();
679 }
680
681 // If the tt-param has a name, then link the identifier into the scope
682 // and lookup mechanisms.
683 if (Name) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000684 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000685 IdResolver.AddDecl(Param);
686 }
687
Chris Lattner83f095c2009-03-28 19:18:32 +0000688 return DeclPtrTy::make(Param);
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000689}
690
Douglas Gregordba32632009-02-10 19:49:53 +0000691/// \brief Adds a default argument to the given template template
692/// parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +0000693void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
Douglas Gregordba32632009-02-10 19:49:53 +0000694 SourceLocation EqualLoc,
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000695 const ParsedTemplateArgument &Default) {
Mike Stump11289f42009-09-09 15:08:12 +0000696 TemplateTemplateParmDecl *TemplateParm
Chris Lattner83f095c2009-03-28 19:18:32 +0000697 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000698
Douglas Gregordba32632009-02-10 19:49:53 +0000699 // C++ [temp.param]p14:
700 // A template-parameter shall not be used in its own default argument.
701 // FIXME: Implement this check! Needs a recursive walk over the types.
702
Douglas Gregore62e6a02009-11-11 19:13:48 +0000703 // Check only that we have a template template argument. We don't want to
704 // try to check well-formedness now, because our template template parameter
705 // might have dependent types in its template parameters, which we wouldn't
706 // be able to match now.
707 //
708 // If none of the template template parameter's template arguments mention
709 // other template parameters, we could actually perform more checking here.
710 // However, it isn't worth doing.
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000711 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000712 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
713 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
714 << DefaultArg.getSourceRange();
Douglas Gregordba32632009-02-10 19:49:53 +0000715 return;
716 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000717
Abramo Bagnara656e3002010-06-09 09:26:05 +0000718 TemplateParm->setDefaultArgument(DefaultArg, false);
Douglas Gregordba32632009-02-10 19:49:53 +0000719}
720
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000721/// ActOnTemplateParameterList - Builds a TemplateParameterList that
722/// contains the template parameters in Params/NumParams.
723Sema::TemplateParamsTy *
724Sema::ActOnTemplateParameterList(unsigned Depth,
725 SourceLocation ExportLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000726 SourceLocation TemplateLoc,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000727 SourceLocation LAngleLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +0000728 DeclPtrTy *Params, unsigned NumParams,
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000729 SourceLocation RAngleLoc) {
730 if (ExportLoc.isValid())
Douglas Gregor5c80a27b2009-11-25 18:55:14 +0000731 Diag(ExportLoc, diag::warn_template_export_unsupported);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000732
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000733 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
Douglas Gregorbe999392009-09-15 16:23:51 +0000734 (NamedDecl**)Params, NumParams,
735 RAngleLoc);
Douglas Gregorb9bd8a92008-12-24 02:52:09 +0000736}
Douglas Gregorded2d7b2009-02-04 19:02:06 +0000737
John McCall3e11ebe2010-03-15 10:12:16 +0000738static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
739 if (SS.isSet())
740 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
741 SS.getRange());
742}
743
Douglas Gregorc08f4892009-03-25 00:13:59 +0000744Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +0000745Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000746 SourceLocation KWLoc, CXXScopeSpec &SS,
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000747 IdentifierInfo *Name, SourceLocation NameLoc,
748 AttributeList *Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000749 TemplateParameterList *TemplateParams,
Anders Carlssondfbbdf62009-03-26 00:52:18 +0000750 AccessSpecifier AS) {
Mike Stump11289f42009-09-09 15:08:12 +0000751 assert(TemplateParams && TemplateParams->size() > 0 &&
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000752 "No template parameters");
John McCall9bb74a52009-07-31 02:45:11 +0000753 assert(TUK != TUK_Reference && "Can only declare or define class templates");
Douglas Gregordba32632009-02-10 19:49:53 +0000754 bool Invalid = false;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000755
756 // Check that we can declare a template here.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000757 if (CheckTemplateDeclScope(S, TemplateParams))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000758 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000759
Abramo Bagnara6150c882010-05-11 21:36:43 +0000760 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
761 assert(Kind != TTK_Enum && "can't build template of enumerated type");
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000762
763 // There is no such thing as an unnamed class template.
764 if (!Name) {
765 Diag(KWLoc, diag::err_template_unnamed_class);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000766 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000767 }
768
769 // Find any previous declaration with this name.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000770 DeclContext *SemanticContext;
John McCall27b18f82009-11-17 02:14:36 +0000771 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +0000772 ForRedeclaration);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000773 if (SS.isNotEmpty() && !SS.isInvalid()) {
774 SemanticContext = computeDeclContext(SS, true);
775 if (!SemanticContext) {
776 // FIXME: Produce a reasonable diagnostic here
777 return true;
778 }
Mike Stump11289f42009-09-09 15:08:12 +0000779
John McCall0b66eb32010-05-01 00:40:08 +0000780 if (RequireCompleteDeclContext(SS, SemanticContext))
781 return true;
782
John McCall27b18f82009-11-17 02:14:36 +0000783 LookupQualifiedName(Previous, SemanticContext);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000784 } else {
785 SemanticContext = CurContext;
John McCall27b18f82009-11-17 02:14:36 +0000786 LookupName(Previous, S);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +0000787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000789 if (Previous.isAmbiguous())
790 return true;
791
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000792 NamedDecl *PrevDecl = 0;
793 if (Previous.begin() != Previous.end())
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000794 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000795
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000796 // If there is a previous declaration with the same name, check
797 // whether this is a valid redeclaration.
Mike Stump11289f42009-09-09 15:08:12 +0000798 ClassTemplateDecl *PrevClassTemplate
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000799 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
Douglas Gregor7f34bae2009-10-09 21:11:42 +0000800
801 // We may have found the injected-class-name of a class template,
802 // class template partial specialization, or class template specialization.
803 // In these cases, grab the template that is being defined or specialized.
804 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
805 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
806 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
807 PrevClassTemplate
808 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
809 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
810 PrevClassTemplate
811 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
812 ->getSpecializedTemplate();
813 }
814 }
815
John McCalld43784f2009-12-18 11:25:59 +0000816 if (TUK == TUK_Friend) {
John McCall90d3bb92009-12-17 23:21:11 +0000817 // C++ [namespace.memdef]p3:
818 // [...] When looking for a prior declaration of a class or a function
819 // declared as a friend, and when the name of the friend class or
820 // function is neither a qualified name nor a template-id, scopes outside
821 // the innermost enclosing namespace scope are not considered.
Douglas Gregorb74b1032010-04-18 17:37:40 +0000822 if (!SS.isSet()) {
823 DeclContext *OutermostContext = CurContext;
824 while (!OutermostContext->isFileContext())
825 OutermostContext = OutermostContext->getLookupParent();
John McCalld43784f2009-12-18 11:25:59 +0000826
Douglas Gregorb74b1032010-04-18 17:37:40 +0000827 if (PrevDecl &&
828 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
829 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
830 SemanticContext = PrevDecl->getDeclContext();
831 } else {
832 // Declarations in outer scopes don't matter. However, the outermost
833 // context we computed is the semantic context for our new
834 // declaration.
835 PrevDecl = PrevClassTemplate = 0;
836 SemanticContext = OutermostContext;
837 }
John McCall90d3bb92009-12-17 23:21:11 +0000838 }
Douglas Gregorb74b1032010-04-18 17:37:40 +0000839
John McCall90d3bb92009-12-17 23:21:11 +0000840 if (CurContext->isDependentContext()) {
841 // If this is a dependent context, we don't want to link the friend
842 // class template to the template in scope, because that would perform
843 // checking of the template parameter lists that can't be performed
844 // until the outer context is instantiated.
845 PrevDecl = PrevClassTemplate = 0;
846 }
847 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
848 PrevDecl = PrevClassTemplate = 0;
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000849
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000850 if (PrevClassTemplate) {
851 // Ensure that the template parameter lists are compatible.
852 if (!TemplateParameterListsAreEqual(TemplateParams,
853 PrevClassTemplate->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +0000854 /*Complain=*/true,
855 TPL_TemplateMatch))
Douglas Gregorc08f4892009-03-25 00:13:59 +0000856 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000857
858 // C++ [temp.class]p4:
859 // In a redeclaration, partial specialization, explicit
860 // specialization or explicit instantiation of a class template,
861 // the class-key shall agree in kind with the original class
862 // template declaration (7.1.5.3).
863 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
Douglas Gregord9034f02009-05-14 16:41:31 +0000864 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
Mike Stump11289f42009-09-09 15:08:12 +0000865 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +0000866 << Name
Douglas Gregora771f462010-03-31 17:46:05 +0000867 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000868 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
Douglas Gregor170512f2009-04-01 23:51:29 +0000869 Kind = PrevRecordDecl->getTagKind();
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000870 }
871
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000872 // Check for redefinition of this class template.
John McCall9bb74a52009-07-31 02:45:11 +0000873 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000874 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000875 Diag(NameLoc, diag::err_redefinition) << Name;
876 Diag(Def->getLocation(), diag::note_previous_definition);
877 // FIXME: Would it make sense to try to "forget" the previous
878 // definition, as part of error recovery?
Douglas Gregorc08f4892009-03-25 00:13:59 +0000879 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000880 }
881 }
882 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
883 // Maybe we will complain about the shadowed template parameter.
884 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
885 // Just pretend that we didn't see the previous declaration.
886 PrevDecl = 0;
887 } else if (PrevDecl) {
888 // C++ [temp]p5:
889 // A class template shall not have the same name as any other
890 // template, class, function, object, enumeration, enumerator,
891 // namespace, or type in the same scope (3.3), except as specified
892 // in (14.5.4).
893 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
894 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregorc08f4892009-03-25 00:13:59 +0000895 return true;
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000896 }
897
Douglas Gregordba32632009-02-10 19:49:53 +0000898 // Check the template parameter list of this declaration, possibly
899 // merging in the template parameter list from the previous class
900 // template declaration.
901 if (CheckTemplateParameterList(TemplateParams,
Douglas Gregored5731f2009-11-25 17:50:39 +0000902 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
903 TPC_ClassTemplate))
Douglas Gregordba32632009-02-10 19:49:53 +0000904 Invalid = true;
Mike Stump11289f42009-09-09 15:08:12 +0000905
Douglas Gregorce40e2e2010-04-12 16:00:01 +0000906 if (SS.isSet()) {
907 // If the name of the template was qualified, we must be defining the
908 // template out-of-line.
909 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
910 !(TUK == TUK_Friend && CurContext->isDependentContext()))
911 Diag(NameLoc, diag::err_member_def_does_not_match)
912 << Name << SemanticContext << SS.getRange();
913 }
914
Mike Stump11289f42009-09-09 15:08:12 +0000915 CXXRecordDecl *NewClass =
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000916 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
Mike Stump11289f42009-09-09 15:08:12 +0000917 PrevClassTemplate?
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000918 PrevClassTemplate->getTemplatedDecl() : 0,
919 /*DelayTypeCreation=*/true);
John McCall3e11ebe2010-03-15 10:12:16 +0000920 SetNestedNameSpecifier(NewClass, SS);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000921
922 ClassTemplateDecl *NewTemplate
923 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
924 DeclarationName(Name), TemplateParams,
Douglas Gregor90a1a652009-03-19 17:26:29 +0000925 NewClass, PrevClassTemplate);
Douglas Gregor97f1f1c2009-03-26 00:10:35 +0000926 NewClass->setDescribedClassTemplate(NewTemplate);
927
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000928 // Build the type for the class template declaration now.
John McCalle78aac42010-03-10 03:28:59 +0000929 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
930 T = Context.getInjectedClassNameType(NewClass, T);
Douglas Gregor1ec5e9f2009-05-15 19:11:46 +0000931 assert(T->isDependentType() && "Class template type is not dependent?");
932 (void)T;
933
Douglas Gregorcf915552009-10-13 16:30:37 +0000934 // If we are providing an explicit specialization of a member that is a
935 // class template, make a note of that.
936 if (PrevClassTemplate &&
937 PrevClassTemplate->getInstantiatedFromMemberTemplate())
938 PrevClassTemplate->setMemberSpecialization();
939
Anders Carlsson137108d2009-03-26 01:24:28 +0000940 // Set the access specifier.
Douglas Gregor3dad8422009-09-26 06:47:28 +0000941 if (!Invalid && TUK != TUK_Friend)
John McCall27b5c252009-09-14 21:59:20 +0000942 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
Mike Stump11289f42009-09-09 15:08:12 +0000943
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000944 // Set the lexical context of these templates
945 NewClass->setLexicalDeclContext(CurContext);
946 NewTemplate->setLexicalDeclContext(CurContext);
947
John McCall9bb74a52009-07-31 02:45:11 +0000948 if (TUK == TUK_Definition)
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000949 NewClass->startDefinition();
950
951 if (Attr)
Douglas Gregor758a8692009-06-17 21:51:59 +0000952 ProcessDeclAttributeList(S, NewClass, Attr);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000953
John McCall27b5c252009-09-14 21:59:20 +0000954 if (TUK != TUK_Friend)
955 PushOnScopeChains(NewTemplate, S);
956 else {
Douglas Gregor3dad8422009-09-26 06:47:28 +0000957 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
John McCall27b5c252009-09-14 21:59:20 +0000958 NewTemplate->setAccess(PrevClassTemplate->getAccess());
Douglas Gregor3dad8422009-09-26 06:47:28 +0000959 NewClass->setAccess(PrevClassTemplate->getAccess());
960 }
John McCall27b5c252009-09-14 21:59:20 +0000961
Douglas Gregor3dad8422009-09-26 06:47:28 +0000962 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
963 PrevClassTemplate != NULL);
964
John McCall27b5c252009-09-14 21:59:20 +0000965 // Friend templates are visible in fairly strange ways.
966 if (!CurContext->isDependentContext()) {
967 DeclContext *DC = SemanticContext->getLookupContext();
968 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
969 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
970 PushOnScopeChains(NewTemplate, EnclosingScope,
971 /* AddToContext = */ false);
972 }
Douglas Gregor3dad8422009-09-26 06:47:28 +0000973
974 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
975 NewClass->getLocation(),
976 NewTemplate,
977 /*FIXME:*/NewClass->getLocation());
978 Friend->setAccess(AS_public);
979 CurContext->addDecl(Friend);
John McCall27b5c252009-09-14 21:59:20 +0000980 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000981
Douglas Gregordba32632009-02-10 19:49:53 +0000982 if (Invalid) {
983 NewTemplate->setInvalidDecl();
984 NewClass->setInvalidDecl();
985 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000986 return DeclPtrTy::make(NewTemplate);
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000987}
988
Douglas Gregored5731f2009-11-25 17:50:39 +0000989/// \brief Diagnose the presence of a default template argument on a
990/// template parameter, which is ill-formed in certain contexts.
991///
992/// \returns true if the default template argument should be dropped.
993static bool DiagnoseDefaultTemplateArgument(Sema &S,
994 Sema::TemplateParamListContext TPC,
995 SourceLocation ParamLoc,
996 SourceRange DefArgRange) {
997 switch (TPC) {
998 case Sema::TPC_ClassTemplate:
999 return false;
1000
1001 case Sema::TPC_FunctionTemplate:
1002 // C++ [temp.param]p9:
1003 // A default template-argument shall not be specified in a
1004 // function template declaration or a function template
1005 // definition [...]
1006 // (This sentence is not in C++0x, per DR226).
1007 if (!S.getLangOptions().CPlusPlus0x)
1008 S.Diag(ParamLoc,
1009 diag::err_template_parameter_default_in_function_template)
1010 << DefArgRange;
1011 return false;
1012
1013 case Sema::TPC_ClassTemplateMember:
1014 // C++0x [temp.param]p9:
1015 // A default template-argument shall not be specified in the
1016 // template-parameter-lists of the definition of a member of a
1017 // class template that appears outside of the member's class.
1018 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1019 << DefArgRange;
1020 return true;
1021
1022 case Sema::TPC_FriendFunctionTemplate:
1023 // C++ [temp.param]p9:
1024 // A default template-argument shall not be specified in a
1025 // friend template declaration.
1026 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1027 << DefArgRange;
1028 return true;
1029
1030 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1031 // for friend function templates if there is only a single
1032 // declaration (and it is a definition). Strange!
1033 }
1034
1035 return false;
1036}
1037
Douglas Gregordba32632009-02-10 19:49:53 +00001038/// \brief Checks the validity of a template parameter list, possibly
1039/// considering the template parameter list from a previous
1040/// declaration.
1041///
1042/// If an "old" template parameter list is provided, it must be
1043/// equivalent (per TemplateParameterListsAreEqual) to the "new"
1044/// template parameter list.
1045///
1046/// \param NewParams Template parameter list for a new template
1047/// declaration. This template parameter list will be updated with any
1048/// default arguments that are carried through from the previous
1049/// template parameter list.
1050///
1051/// \param OldParams If provided, template parameter list from a
1052/// previous declaration of the same template. Default template
1053/// arguments will be merged from the old template parameter list to
1054/// the new template parameter list.
1055///
Douglas Gregored5731f2009-11-25 17:50:39 +00001056/// \param TPC Describes the context in which we are checking the given
1057/// template parameter list.
1058///
Douglas Gregordba32632009-02-10 19:49:53 +00001059/// \returns true if an error occurred, false otherwise.
1060bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
Douglas Gregored5731f2009-11-25 17:50:39 +00001061 TemplateParameterList *OldParams,
1062 TemplateParamListContext TPC) {
Douglas Gregordba32632009-02-10 19:49:53 +00001063 bool Invalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00001064
Douglas Gregordba32632009-02-10 19:49:53 +00001065 // C++ [temp.param]p10:
1066 // The set of default template-arguments available for use with a
1067 // template declaration or definition is obtained by merging the
1068 // default arguments from the definition (if in scope) and all
1069 // declarations in scope in the same way default function
1070 // arguments are (8.3.6).
1071 bool SawDefaultArgument = false;
1072 SourceLocation PreviousDefaultArgLoc;
Douglas Gregord32e0282009-02-09 23:23:08 +00001073
Anders Carlsson327865d2009-06-12 23:20:15 +00001074 bool SawParameterPack = false;
1075 SourceLocation ParameterPackLoc;
1076
Mike Stumpc89c8e32009-02-11 23:03:27 +00001077 // Dummy initialization to avoid warnings.
Douglas Gregor5bd22da2009-02-11 20:46:19 +00001078 TemplateParameterList::iterator OldParam = NewParams->end();
Douglas Gregordba32632009-02-10 19:49:53 +00001079 if (OldParams)
1080 OldParam = OldParams->begin();
1081
1082 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1083 NewParamEnd = NewParams->end();
1084 NewParam != NewParamEnd; ++NewParam) {
1085 // Variables used to diagnose redundant default arguments
1086 bool RedundantDefaultArg = false;
1087 SourceLocation OldDefaultLoc;
1088 SourceLocation NewDefaultLoc;
1089
1090 // Variables used to diagnose missing default arguments
1091 bool MissingDefaultArg = false;
1092
Anders Carlsson327865d2009-06-12 23:20:15 +00001093 // C++0x [temp.param]p11:
1094 // If a template parameter of a class template is a template parameter pack,
1095 // it must be the last template parameter.
1096 if (SawParameterPack) {
Mike Stump11289f42009-09-09 15:08:12 +00001097 Diag(ParameterPackLoc,
Anders Carlsson327865d2009-06-12 23:20:15 +00001098 diag::err_template_param_pack_must_be_last_template_parameter);
1099 Invalid = true;
1100 }
1101
Douglas Gregordba32632009-02-10 19:49:53 +00001102 if (TemplateTypeParmDecl *NewTypeParm
1103 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001104 // Check the presence of a default argument here.
1105 if (NewTypeParm->hasDefaultArgument() &&
1106 DiagnoseDefaultTemplateArgument(*this, TPC,
1107 NewTypeParm->getLocation(),
1108 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001109 .getSourceRange()))
Douglas Gregored5731f2009-11-25 17:50:39 +00001110 NewTypeParm->removeDefaultArgument();
1111
1112 // Merge default arguments for template type parameters.
Mike Stump11289f42009-09-09 15:08:12 +00001113 TemplateTypeParmDecl *OldTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001114 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001115
Anders Carlsson327865d2009-06-12 23:20:15 +00001116 if (NewTypeParm->isParameterPack()) {
1117 assert(!NewTypeParm->hasDefaultArgument() &&
1118 "Parameter packs can't have a default argument!");
1119 SawParameterPack = true;
1120 ParameterPackLoc = NewTypeParm->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +00001121 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
John McCall0ad16662009-10-29 08:12:44 +00001122 NewTypeParm->hasDefaultArgument()) {
Douglas Gregordba32632009-02-10 19:49:53 +00001123 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1124 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1125 SawDefaultArgument = true;
1126 RedundantDefaultArg = true;
1127 PreviousDefaultArgLoc = NewDefaultLoc;
1128 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1129 // Merge the default argument from the old declaration to the
1130 // new declaration.
1131 SawDefaultArgument = true;
John McCall0ad16662009-10-29 08:12:44 +00001132 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
Douglas Gregordba32632009-02-10 19:49:53 +00001133 true);
1134 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1135 } else if (NewTypeParm->hasDefaultArgument()) {
1136 SawDefaultArgument = true;
1137 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1138 } else if (SawDefaultArgument)
1139 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001140 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
Douglas Gregordba32632009-02-10 19:49:53 +00001141 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
Douglas Gregored5731f2009-11-25 17:50:39 +00001142 // Check the presence of a default argument here.
1143 if (NewNonTypeParm->hasDefaultArgument() &&
1144 DiagnoseDefaultTemplateArgument(*this, TPC,
1145 NewNonTypeParm->getLocation(),
1146 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1147 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
Abramo Bagnara656e3002010-06-09 09:26:05 +00001148 NewNonTypeParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001149 }
1150
Mike Stump12b8ce12009-08-04 21:02:39 +00001151 // Merge default arguments for non-type template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001152 NonTypeTemplateParmDecl *OldNonTypeParm
1153 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001154 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001155 NewNonTypeParm->hasDefaultArgument()) {
1156 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1157 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1158 SawDefaultArgument = true;
1159 RedundantDefaultArg = true;
1160 PreviousDefaultArgLoc = NewDefaultLoc;
1161 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1162 // Merge the default argument from the old declaration to the
1163 // new declaration.
1164 SawDefaultArgument = true;
1165 // FIXME: We need to create a new kind of "default argument"
1166 // expression that points to a previous template template
1167 // parameter.
1168 NewNonTypeParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001169 OldNonTypeParm->getDefaultArgument(),
1170 /*Inherited=*/ true);
Douglas Gregordba32632009-02-10 19:49:53 +00001171 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1172 } else if (NewNonTypeParm->hasDefaultArgument()) {
1173 SawDefaultArgument = true;
1174 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1175 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001176 MissingDefaultArg = true;
Mike Stump12b8ce12009-08-04 21:02:39 +00001177 } else {
Douglas Gregored5731f2009-11-25 17:50:39 +00001178 // Check the presence of a default argument here.
Douglas Gregordba32632009-02-10 19:49:53 +00001179 TemplateTemplateParmDecl *NewTemplateParm
1180 = cast<TemplateTemplateParmDecl>(*NewParam);
Douglas Gregored5731f2009-11-25 17:50:39 +00001181 if (NewTemplateParm->hasDefaultArgument() &&
1182 DiagnoseDefaultTemplateArgument(*this, TPC,
1183 NewTemplateParm->getLocation(),
1184 NewTemplateParm->getDefaultArgument().getSourceRange()))
Abramo Bagnara656e3002010-06-09 09:26:05 +00001185 NewTemplateParm->removeDefaultArgument();
Douglas Gregored5731f2009-11-25 17:50:39 +00001186
1187 // Merge default arguments for template template parameters
Douglas Gregordba32632009-02-10 19:49:53 +00001188 TemplateTemplateParmDecl *OldTemplateParm
1189 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
Mike Stump11289f42009-09-09 15:08:12 +00001190 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
Douglas Gregordba32632009-02-10 19:49:53 +00001191 NewTemplateParm->hasDefaultArgument()) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001192 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1193 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001194 SawDefaultArgument = true;
1195 RedundantDefaultArg = true;
1196 PreviousDefaultArgLoc = NewDefaultLoc;
1197 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1198 // Merge the default argument from the old declaration to the
1199 // new declaration.
1200 SawDefaultArgument = true;
Mike Stump87c57ac2009-05-16 07:39:55 +00001201 // FIXME: We need to create a new kind of "default argument" expression
1202 // that points to a previous template template parameter.
Douglas Gregordba32632009-02-10 19:49:53 +00001203 NewTemplateParm->setDefaultArgument(
Abramo Bagnara656e3002010-06-09 09:26:05 +00001204 OldTemplateParm->getDefaultArgument(),
1205 /*Inherited=*/ true);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001206 PreviousDefaultArgLoc
1207 = OldTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001208 } else if (NewTemplateParm->hasDefaultArgument()) {
1209 SawDefaultArgument = true;
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001210 PreviousDefaultArgLoc
1211 = NewTemplateParm->getDefaultArgument().getLocation();
Douglas Gregordba32632009-02-10 19:49:53 +00001212 } else if (SawDefaultArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001213 MissingDefaultArg = true;
Douglas Gregordba32632009-02-10 19:49:53 +00001214 }
1215
1216 if (RedundantDefaultArg) {
1217 // C++ [temp.param]p12:
1218 // A template-parameter shall not be given default arguments
1219 // by two different declarations in the same scope.
1220 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1221 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1222 Invalid = true;
1223 } else if (MissingDefaultArg) {
1224 // C++ [temp.param]p11:
1225 // If a template-parameter has a default template-argument,
1226 // all subsequent template-parameters shall have a default
1227 // template-argument supplied.
Mike Stump11289f42009-09-09 15:08:12 +00001228 Diag((*NewParam)->getLocation(),
Douglas Gregordba32632009-02-10 19:49:53 +00001229 diag::err_template_param_default_arg_missing);
1230 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1231 Invalid = true;
1232 }
1233
1234 // If we have an old template parameter list that we're merging
1235 // in, move on to the next parameter.
1236 if (OldParams)
1237 ++OldParam;
1238 }
1239
1240 return Invalid;
1241}
Douglas Gregord32e0282009-02-09 23:23:08 +00001242
Mike Stump11289f42009-09-09 15:08:12 +00001243/// \brief Match the given template parameter lists to the given scope
Douglas Gregord8d297c2009-07-21 23:53:31 +00001244/// specifier, returning the template parameter list that applies to the
1245/// name.
1246///
1247/// \param DeclStartLoc the start of the declaration that has a scope
1248/// specifier or a template parameter list.
Mike Stump11289f42009-09-09 15:08:12 +00001249///
Douglas Gregord8d297c2009-07-21 23:53:31 +00001250/// \param SS the scope specifier that will be matched to the given template
1251/// parameter lists. This scope specifier precedes a qualified name that is
1252/// being declared.
1253///
1254/// \param ParamLists the template parameter lists, from the outermost to the
1255/// innermost template parameter lists.
1256///
1257/// \param NumParamLists the number of template parameter lists in ParamLists.
1258///
John McCalle820e5e2010-04-13 20:37:33 +00001259/// \param IsFriend Whether to apply the slightly different rules for
1260/// matching template parameters to scope specifiers in friend
1261/// declarations.
1262///
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001263/// \param IsExplicitSpecialization will be set true if the entity being
1264/// declared is an explicit specialization, false otherwise.
1265///
Mike Stump11289f42009-09-09 15:08:12 +00001266/// \returns the template parameter list, if any, that corresponds to the
Douglas Gregord8d297c2009-07-21 23:53:31 +00001267/// name that is preceded by the scope specifier @p SS. This template
1268/// parameter list may be have template parameters (if we're declaring a
Mike Stump11289f42009-09-09 15:08:12 +00001269/// template) or may have no template parameters (if we're declaring a
Douglas Gregord8d297c2009-07-21 23:53:31 +00001270/// template specialization), or may be NULL (if we were's declaring isn't
1271/// itself a template).
1272TemplateParameterList *
1273Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1274 const CXXScopeSpec &SS,
1275 TemplateParameterList **ParamLists,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001276 unsigned NumParamLists,
John McCalle820e5e2010-04-13 20:37:33 +00001277 bool IsFriend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001278 bool &IsExplicitSpecialization) {
1279 IsExplicitSpecialization = false;
1280
Douglas Gregord8d297c2009-07-21 23:53:31 +00001281 // Find the template-ids that occur within the nested-name-specifier. These
1282 // template-ids will match up with the template parameter lists.
1283 llvm::SmallVector<const TemplateSpecializationType *, 4>
1284 TemplateIdsInSpecifier;
Douglas Gregor65911492009-11-23 12:11:45 +00001285 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1286 ExplicitSpecializationsInSpecifier;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001287 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1288 NNS; NNS = NNS->getPrefix()) {
John McCall90034062009-12-15 02:19:47 +00001289 const Type *T = NNS->getAsType();
1290 if (!T) break;
1291
1292 // C++0x [temp.expl.spec]p17:
1293 // A member or a member template may be nested within many
1294 // enclosing class templates. In an explicit specialization for
1295 // such a member, the member declaration shall be preceded by a
1296 // template<> for each enclosing class template that is
1297 // explicitly specialized.
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001298 //
1299 // Following the existing practice of GNU and EDG, we allow a typedef of a
1300 // template specialization type.
1301 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1302 T = TT->LookThroughTypedefs().getTypePtr();
John McCall90034062009-12-15 02:19:47 +00001303
Mike Stump11289f42009-09-09 15:08:12 +00001304 if (const TemplateSpecializationType *SpecType
Douglas Gregoraf050cb2010-02-13 05:23:25 +00001305 = dyn_cast<TemplateSpecializationType>(T)) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001306 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1307 if (!Template)
1308 continue; // FIXME: should this be an error? probably...
Mike Stump11289f42009-09-09 15:08:12 +00001309
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001310 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
Douglas Gregord8d297c2009-07-21 23:53:31 +00001311 ClassTemplateSpecializationDecl *SpecDecl
1312 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1313 // If the nested name specifier refers to an explicit specialization,
1314 // we don't need a template<> header.
Douglas Gregor65911492009-11-23 12:11:45 +00001315 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1316 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
Douglas Gregord8d297c2009-07-21 23:53:31 +00001317 continue;
Douglas Gregor65911492009-11-23 12:11:45 +00001318 }
Douglas Gregord8d297c2009-07-21 23:53:31 +00001319 }
Mike Stump11289f42009-09-09 15:08:12 +00001320
Douglas Gregord8d297c2009-07-21 23:53:31 +00001321 TemplateIdsInSpecifier.push_back(SpecType);
1322 }
1323 }
Mike Stump11289f42009-09-09 15:08:12 +00001324
Douglas Gregord8d297c2009-07-21 23:53:31 +00001325 // Reverse the list of template-ids in the scope specifier, so that we can
1326 // more easily match up the template-ids and the template parameter lists.
1327 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregord8d297c2009-07-21 23:53:31 +00001329 SourceLocation FirstTemplateLoc = DeclStartLoc;
1330 if (NumParamLists)
1331 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
Mike Stump11289f42009-09-09 15:08:12 +00001332
Douglas Gregord8d297c2009-07-21 23:53:31 +00001333 // Match the template-ids found in the specifier to the template parameter
1334 // lists.
1335 unsigned Idx = 0;
1336 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1337 Idx != NumTemplateIds; ++Idx) {
Douglas Gregor15301382009-07-30 17:40:51 +00001338 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1339 bool DependentTemplateId = TemplateId->isDependentType();
Douglas Gregord8d297c2009-07-21 23:53:31 +00001340 if (Idx >= NumParamLists) {
1341 // We have a template-id without a corresponding template parameter
1342 // list.
John McCalle820e5e2010-04-13 20:37:33 +00001343
1344 // ...which is fine if this is a friend declaration.
1345 if (IsFriend) {
1346 IsExplicitSpecialization = true;
1347 break;
1348 }
1349
Douglas Gregord8d297c2009-07-21 23:53:31 +00001350 if (DependentTemplateId) {
Mike Stump11289f42009-09-09 15:08:12 +00001351 // FIXME: the location information here isn't great.
1352 Diag(SS.getRange().getBegin(),
Douglas Gregord8d297c2009-07-21 23:53:31 +00001353 diag::err_template_spec_needs_template_parameters)
Douglas Gregor15301382009-07-30 17:40:51 +00001354 << TemplateId
Douglas Gregord8d297c2009-07-21 23:53:31 +00001355 << SS.getRange();
1356 } else {
1357 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1358 << SS.getRange()
Douglas Gregora771f462010-03-31 17:46:05 +00001359 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001360 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001361 }
1362 return 0;
1363 }
Mike Stump11289f42009-09-09 15:08:12 +00001364
Douglas Gregord8d297c2009-07-21 23:53:31 +00001365 // Check the template parameter list against its corresponding template-id.
Douglas Gregor15301382009-07-30 17:40:51 +00001366 if (DependentTemplateId) {
John McCall2408e322010-04-27 00:57:59 +00001367 TemplateParameterList *ExpectedTemplateParams = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00001368
John McCall2408e322010-04-27 00:57:59 +00001369 // Are there cases in (e.g.) friends where this won't match?
1370 if (const InjectedClassNameType *Injected
1371 = TemplateId->getAs<InjectedClassNameType>()) {
1372 CXXRecordDecl *Record = Injected->getDecl();
1373 if (ClassTemplatePartialSpecializationDecl *Partial =
1374 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1375 ExpectedTemplateParams = Partial->getTemplateParameters();
1376 else
1377 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1378 ->getTemplateParameters();
Mike Stump11289f42009-09-09 15:08:12 +00001379 }
Douglas Gregored5731f2009-11-25 17:50:39 +00001380
John McCall2408e322010-04-27 00:57:59 +00001381 if (ExpectedTemplateParams)
1382 TemplateParameterListsAreEqual(ParamLists[Idx],
1383 ExpectedTemplateParams,
1384 true, TPL_TemplateMatch);
1385
Douglas Gregored5731f2009-11-25 17:50:39 +00001386 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
Douglas Gregor15301382009-07-30 17:40:51 +00001387 } else if (ParamLists[Idx]->size() > 0)
Mike Stump11289f42009-09-09 15:08:12 +00001388 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor15301382009-07-30 17:40:51 +00001389 diag::err_template_param_list_matches_nontemplate)
1390 << TemplateId
1391 << ParamLists[Idx]->getSourceRange();
Douglas Gregor5c0405d2009-10-07 22:35:40 +00001392 else
1393 IsExplicitSpecialization = true;
Douglas Gregord8d297c2009-07-21 23:53:31 +00001394 }
Mike Stump11289f42009-09-09 15:08:12 +00001395
Douglas Gregord8d297c2009-07-21 23:53:31 +00001396 // If there were at least as many template-ids as there were template
1397 // parameter lists, then there are no template parameter lists remaining for
1398 // the declaration itself.
1399 if (Idx >= NumParamLists)
1400 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001401
Douglas Gregord8d297c2009-07-21 23:53:31 +00001402 // If there were too many template parameter lists, complain about that now.
1403 if (Idx != NumParamLists - 1) {
1404 while (Idx < NumParamLists - 1) {
Douglas Gregor65911492009-11-23 12:11:45 +00001405 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
Mike Stump11289f42009-09-09 15:08:12 +00001406 Diag(ParamLists[Idx]->getTemplateLoc(),
Douglas Gregor65911492009-11-23 12:11:45 +00001407 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1408 : diag::err_template_spec_extra_headers)
Douglas Gregord8d297c2009-07-21 23:53:31 +00001409 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1410 ParamLists[Idx]->getRAngleLoc());
Douglas Gregor65911492009-11-23 12:11:45 +00001411
1412 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1413 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1414 diag::note_explicit_template_spec_does_not_need_header)
1415 << ExplicitSpecializationsInSpecifier.back();
1416 ExplicitSpecializationsInSpecifier.pop_back();
1417 }
1418
Douglas Gregord8d297c2009-07-21 23:53:31 +00001419 ++Idx;
1420 }
1421 }
Mike Stump11289f42009-09-09 15:08:12 +00001422
Douglas Gregord8d297c2009-07-21 23:53:31 +00001423 // Return the last template parameter list, which corresponds to the
1424 // entity being declared.
1425 return ParamLists[NumParamLists - 1];
1426}
1427
Douglas Gregordc572a32009-03-30 22:58:21 +00001428QualType Sema::CheckTemplateIdType(TemplateName Name,
1429 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00001430 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001431 TemplateDecl *Template = Name.getAsTemplateDecl();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001432 if (!Template) {
1433 // The template name does not resolve to a template, so we just
1434 // build a dependent template-id type.
John McCall6b51f282009-11-23 01:53:49 +00001435 return Context.getTemplateSpecializationType(Name, TemplateArgs);
Douglas Gregorb67535d2009-03-31 00:43:58 +00001436 }
Douglas Gregordc572a32009-03-30 22:58:21 +00001437
Douglas Gregorc40290e2009-03-09 23:48:35 +00001438 // Check that the template argument list is well-formed for this
1439 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001440 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
John McCall6b51f282009-11-23 01:53:49 +00001441 TemplateArgs.size());
1442 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00001443 false, Converted))
Douglas Gregorc40290e2009-03-09 23:48:35 +00001444 return QualType();
1445
Mike Stump11289f42009-09-09 15:08:12 +00001446 assert((Converted.structuredSize() ==
Douglas Gregordc572a32009-03-30 22:58:21 +00001447 Template->getTemplateParameters()->size()) &&
Douglas Gregorc40290e2009-03-09 23:48:35 +00001448 "Converted template argument list is too short!");
1449
1450 QualType CanonType;
John McCall2408e322010-04-27 00:57:59 +00001451 bool IsCurrentInstantiation = false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00001452
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00001453 if (Name.isDependent() ||
1454 TemplateSpecializationType::anyDependentTemplateArguments(
John McCall6b51f282009-11-23 01:53:49 +00001455 TemplateArgs)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001456 // This class template specialization is a dependent
1457 // type. Therefore, its canonical type is another class template
1458 // specialization type that contains all of the converted
1459 // arguments in canonical form. This ensures that, e.g., A<T> and
1460 // A<T, T> have identical types when A is declared as:
1461 //
1462 // template<typename T, typename U = T> struct A;
Douglas Gregor6bc50582009-05-07 06:41:52 +00001463 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
Mike Stump11289f42009-09-09 15:08:12 +00001464 CanonType = Context.getTemplateSpecializationType(CanonName,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001465 Converted.getFlatArguments(),
1466 Converted.flatSize());
Mike Stump11289f42009-09-09 15:08:12 +00001467
Douglas Gregora8e02e72009-07-28 23:00:59 +00001468 // FIXME: CanonType is not actually the canonical type, and unfortunately
John McCall0ad16662009-10-29 08:12:44 +00001469 // it is a TemplateSpecializationType that we will never use again.
Douglas Gregora8e02e72009-07-28 23:00:59 +00001470 // In the future, we need to teach getTemplateSpecializationType to only
1471 // build the canonical type and return that to us.
1472 CanonType = Context.getCanonicalType(CanonType);
John McCall2408e322010-04-27 00:57:59 +00001473
1474 // This might work out to be a current instantiation, in which
1475 // case the canonical type needs to be the InjectedClassNameType.
1476 //
1477 // TODO: in theory this could be a simple hashtable lookup; most
1478 // changes to CurContext don't change the set of current
1479 // instantiations.
1480 if (isa<ClassTemplateDecl>(Template)) {
1481 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1482 // If we get out to a namespace, we're done.
1483 if (Ctx->isFileContext()) break;
1484
1485 // If this isn't a record, keep looking.
1486 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1487 if (!Record) continue;
1488
1489 // Look for one of the two cases with InjectedClassNameTypes
1490 // and check whether it's the same template.
1491 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1492 !Record->getDescribedClassTemplate())
1493 continue;
1494
1495 // Fetch the injected class name type and check whether its
1496 // injected type is equal to the type we just built.
1497 QualType ICNT = Context.getTypeDeclType(Record);
1498 QualType Injected = cast<InjectedClassNameType>(ICNT)
1499 ->getInjectedSpecializationType();
1500
1501 if (CanonType != Injected->getCanonicalTypeInternal())
1502 continue;
1503
1504 // If so, the canonical type of this TST is the injected
1505 // class name type of the record we just found.
1506 assert(ICNT.isCanonical());
1507 CanonType = ICNT;
1508 IsCurrentInstantiation = true;
1509 break;
1510 }
1511 }
Mike Stump11289f42009-09-09 15:08:12 +00001512 } else if (ClassTemplateDecl *ClassTemplate
Douglas Gregordc572a32009-03-30 22:58:21 +00001513 = dyn_cast<ClassTemplateDecl>(Template)) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00001514 // Find the class template specialization declaration that
1515 // corresponds to these arguments.
1516 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001517 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001518 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00001519 Converted.flatSize(),
1520 Context);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001521 void *InsertPos = 0;
1522 ClassTemplateSpecializationDecl *Decl
1523 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1524 if (!Decl) {
1525 // This is the first time we have referenced this class template
1526 // specialization. Create the canonical declaration and add it to
1527 // the set of specializations.
Mike Stump11289f42009-09-09 15:08:12 +00001528 Decl = ClassTemplateSpecializationDecl::Create(Context,
Douglas Gregore9029562010-05-06 00:28:52 +00001529 ClassTemplate->getTemplatedDecl()->getTagKind(),
1530 ClassTemplate->getDeclContext(),
1531 ClassTemplate->getLocation(),
1532 ClassTemplate,
1533 Converted, 0);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001534 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1535 Decl->setLexicalDeclContext(CurContext);
1536 }
1537
1538 CanonType = Context.getTypeDeclType(Decl);
John McCalle78aac42010-03-10 03:28:59 +00001539 assert(isa<RecordType>(CanonType) &&
1540 "type of non-dependent specialization is not a RecordType");
Douglas Gregorc40290e2009-03-09 23:48:35 +00001541 }
Mike Stump11289f42009-09-09 15:08:12 +00001542
Douglas Gregorc40290e2009-03-09 23:48:35 +00001543 // Build the fully-sugared type for this class template
1544 // specialization, which refers back to the class template
1545 // specialization we created or found.
John McCall2408e322010-04-27 00:57:59 +00001546 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType,
1547 IsCurrentInstantiation);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001548}
1549
Douglas Gregor67a65642009-02-17 23:15:12 +00001550Action::TypeResult
Douglas Gregordc572a32009-03-30 22:58:21 +00001551Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001552 SourceLocation LAngleLoc,
Douglas Gregordc572a32009-03-30 22:58:21 +00001553 ASTTemplateArgsPtr TemplateArgsIn,
John McCalld8fe9af2009-09-08 17:47:29 +00001554 SourceLocation RAngleLoc) {
Douglas Gregordc572a32009-03-30 22:58:21 +00001555 TemplateName Template = TemplateD.getAsVal<TemplateName>();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001556
Douglas Gregorc40290e2009-03-09 23:48:35 +00001557 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00001558 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00001559 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregord32e0282009-02-09 23:23:08 +00001560
John McCall6b51f282009-11-23 01:53:49 +00001561 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00001562 TemplateArgsIn.release();
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00001563
1564 if (Result.isNull())
1565 return true;
1566
John McCallbcd03502009-12-07 02:54:59 +00001567 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
John McCall0ad16662009-10-29 08:12:44 +00001568 TemplateSpecializationTypeLoc TL
1569 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1570 TL.setTemplateNameLoc(TemplateLoc);
1571 TL.setLAngleLoc(LAngleLoc);
1572 TL.setRAngleLoc(RAngleLoc);
1573 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1574 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1575
1576 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
John McCalld8fe9af2009-09-08 17:47:29 +00001577}
John McCall06f6fe8d2009-09-04 01:14:41 +00001578
John McCalld8fe9af2009-09-08 17:47:29 +00001579Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1580 TagUseKind TUK,
1581 DeclSpec::TST TagSpec,
1582 SourceLocation TagLoc) {
1583 if (TypeResult.isInvalid())
1584 return Sema::TypeResult();
John McCall06f6fe8d2009-09-04 01:14:41 +00001585
John McCall0ad16662009-10-29 08:12:44 +00001586 // FIXME: preserve source info, ideally without copying the DI.
John McCallbcd03502009-12-07 02:54:59 +00001587 TypeSourceInfo *DI;
John McCall0ad16662009-10-29 08:12:44 +00001588 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
John McCall06f6fe8d2009-09-04 01:14:41 +00001589
John McCalld8fe9af2009-09-08 17:47:29 +00001590 // Verify the tag specifier.
Abramo Bagnara6150c882010-05-11 21:36:43 +00001591 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Mike Stump11289f42009-09-09 15:08:12 +00001592
John McCalld8fe9af2009-09-08 17:47:29 +00001593 if (const RecordType *RT = Type->getAs<RecordType>()) {
1594 RecordDecl *D = RT->getDecl();
1595
1596 IdentifierInfo *Id = D->getIdentifier();
1597 assert(Id && "templated class must have an identifier");
1598
1599 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1600 Diag(TagLoc, diag::err_use_with_wrong_tag)
John McCall7f41d982009-09-11 04:59:25 +00001601 << Type
Douglas Gregora771f462010-03-31 17:46:05 +00001602 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
John McCall7f41d982009-09-11 04:59:25 +00001603 Diag(D->getLocation(), diag::note_previous_use);
John McCall06f6fe8d2009-09-04 01:14:41 +00001604 }
1605 }
1606
Abramo Bagnara6150c882010-05-11 21:36:43 +00001607 ElaboratedTypeKeyword Keyword
1608 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1609 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
John McCalld8fe9af2009-09-08 17:47:29 +00001610
1611 return ElabType.getAsOpaquePtr();
Douglas Gregor8bf42052009-02-09 18:46:07 +00001612}
1613
John McCalle66edc12009-11-24 19:00:30 +00001614Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1615 LookupResult &R,
1616 bool RequiresADL,
John McCall6b51f282009-11-23 01:53:49 +00001617 const TemplateArgumentListInfo &TemplateArgs) {
Douglas Gregora727cb92009-06-30 22:34:41 +00001618 // FIXME: Can we do any checking at this point? I guess we could check the
1619 // template arguments that we have against the template name, if the template
Mike Stump11289f42009-09-09 15:08:12 +00001620 // name refers to a single template. That's not a terribly common case,
Douglas Gregora727cb92009-06-30 22:34:41 +00001621 // though.
John McCalle66edc12009-11-24 19:00:30 +00001622
1623 // These should be filtered out by our callers.
1624 assert(!R.empty() && "empty lookup results when building templateid");
1625 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1626
1627 NestedNameSpecifier *Qualifier = 0;
1628 SourceRange QualifierRange;
1629 if (SS.isSet()) {
1630 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1631 QualifierRange = SS.getRange();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001632 }
John McCall58cc69d2010-01-27 01:50:18 +00001633
1634 // We don't want lookup warnings at this point.
1635 R.suppressDiagnostics();
Douglas Gregor3c8a0cf2009-10-22 07:19:14 +00001636
John McCalle66edc12009-11-24 19:00:30 +00001637 bool Dependent
1638 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1639 &TemplateArgs);
1640 UnresolvedLookupExpr *ULE
John McCall58cc69d2010-01-27 01:50:18 +00001641 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCalle66edc12009-11-24 19:00:30 +00001642 Qualifier, QualifierRange,
1643 R.getLookupName(), R.getNameLoc(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00001644 RequiresADL, TemplateArgs,
1645 R.begin(), R.end());
John McCalle66edc12009-11-24 19:00:30 +00001646
1647 return Owned(ULE);
Douglas Gregora727cb92009-06-30 22:34:41 +00001648}
1649
John McCalle66edc12009-11-24 19:00:30 +00001650// We actually only call this from template instantiation.
1651Sema::OwningExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001652Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
John McCalle66edc12009-11-24 19:00:30 +00001653 DeclarationName Name,
1654 SourceLocation NameLoc,
1655 const TemplateArgumentListInfo &TemplateArgs) {
1656 DeclContext *DC;
1657 if (!(DC = computeDeclContext(SS, false)) ||
1658 DC->isDependentContext() ||
John McCall0b66eb32010-05-01 00:40:08 +00001659 RequireCompleteDeclContext(SS, DC))
John McCalle66edc12009-11-24 19:00:30 +00001660 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001661
Douglas Gregor786123d2010-05-21 23:18:07 +00001662 bool MemberOfUnknownSpecialization;
John McCalle66edc12009-11-24 19:00:30 +00001663 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
Douglas Gregor786123d2010-05-21 23:18:07 +00001664 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1665 MemberOfUnknownSpecialization);
Mike Stump11289f42009-09-09 15:08:12 +00001666
John McCalle66edc12009-11-24 19:00:30 +00001667 if (R.isAmbiguous())
1668 return ExprError();
1669
1670 if (R.empty()) {
1671 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1672 << Name << SS.getRange();
1673 return ExprError();
1674 }
1675
1676 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1677 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1678 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1679 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1680 return ExprError();
1681 }
1682
1683 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
Douglas Gregora727cb92009-06-30 22:34:41 +00001684}
1685
Douglas Gregorb67535d2009-03-31 00:43:58 +00001686/// \brief Form a dependent template name.
1687///
1688/// This action forms a dependent template name given the template
1689/// name and its (presumably dependent) scope specifier. For
1690/// example, given "MetaFun::template apply", the scope specifier \p
1691/// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1692/// of the "template" keyword, and "apply" is the \p Name.
Mike Stump11289f42009-09-09 15:08:12 +00001693Sema::TemplateTy
Douglas Gregorb67535d2009-03-31 00:43:58 +00001694Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001695 CXXScopeSpec &SS,
Douglas Gregor3cf81312009-11-03 23:16:33 +00001696 UnqualifiedId &Name,
Douglas Gregorade9bcd2009-11-20 23:39:24 +00001697 TypeTy *ObjectType,
1698 bool EnteringContext) {
Douglas Gregor9abe2372010-01-19 16:01:07 +00001699 DeclContext *LookupCtx = 0;
1700 if (SS.isSet())
1701 LookupCtx = computeDeclContext(SS, EnteringContext);
1702 if (!LookupCtx && ObjectType)
1703 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1704 if (LookupCtx) {
Douglas Gregorb67535d2009-03-31 00:43:58 +00001705 // C++0x [temp.names]p5:
1706 // If a name prefixed by the keyword template is not the name of
1707 // a template, the program is ill-formed. [Note: the keyword
1708 // template may not be applied to non-template members of class
1709 // templates. -end note ] [ Note: as is the case with the
1710 // typename prefix, the template prefix is allowed in cases
1711 // where it is not strictly necessary; i.e., when the
1712 // nested-name-specifier or the expression on the left of the ->
1713 // or . is not dependent on a template-parameter, or the use
1714 // does not appear in the scope of a template. -end note]
1715 //
1716 // Note: C++03 was more strict here, because it banned the use of
1717 // the "template" keyword prior to a template-name that was not a
1718 // dependent name. C++ DR468 relaxed this requirement (the
1719 // "template" keyword is now permitted). We follow the C++0x
1720 // rules, even in C++03 mode, retroactively applying the DR.
1721 TemplateTy Template;
Douglas Gregor786123d2010-05-21 23:18:07 +00001722 bool MemberOfUnknownSpecialization;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001723 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
Douglas Gregor786123d2010-05-21 23:18:07 +00001724 EnteringContext, Template,
1725 MemberOfUnknownSpecialization);
Douglas Gregor9abe2372010-01-19 16:01:07 +00001726 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1727 isa<CXXRecordDecl>(LookupCtx) &&
1728 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
Douglas Gregord2e6a452010-01-14 17:47:39 +00001729 // This is a dependent template.
1730 } else if (TNK == TNK_Non_template) {
Douglas Gregor3cf81312009-11-03 23:16:33 +00001731 Diag(Name.getSourceRange().getBegin(),
1732 diag::err_template_kw_refers_to_non_template)
1733 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001734 << Name.getSourceRange()
1735 << TemplateKWLoc;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001736 return TemplateTy();
Douglas Gregord2e6a452010-01-14 17:47:39 +00001737 } else {
1738 // We found something; return it.
1739 return Template;
Douglas Gregorb67535d2009-03-31 00:43:58 +00001740 }
Douglas Gregorb67535d2009-03-31 00:43:58 +00001741 }
1742
Mike Stump11289f42009-09-09 15:08:12 +00001743 NestedNameSpecifier *Qualifier
Douglas Gregorb7bfe792009-09-02 22:59:36 +00001744 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
Douglas Gregor3cf81312009-11-03 23:16:33 +00001745
1746 switch (Name.getKind()) {
1747 case UnqualifiedId::IK_Identifier:
1748 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1749 Name.Identifier));
1750
Douglas Gregor71395fa2009-11-04 00:56:37 +00001751 case UnqualifiedId::IK_OperatorFunctionId:
1752 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1753 Name.OperatorFunctionId.Operator));
Alexis Hunted0530f2009-11-28 08:58:14 +00001754
1755 case UnqualifiedId::IK_LiteralOperatorId:
1756 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1757
Douglas Gregor3cf81312009-11-03 23:16:33 +00001758 default:
1759 break;
1760 }
1761
1762 Diag(Name.getSourceRange().getBegin(),
1763 diag::err_template_kw_refers_to_non_template)
1764 << GetNameFromUnqualifiedId(Name)
Douglas Gregorb22ee882010-05-05 05:58:24 +00001765 << Name.getSourceRange()
1766 << TemplateKWLoc;
Douglas Gregor3cf81312009-11-03 23:16:33 +00001767 return TemplateTy();
Douglas Gregorb67535d2009-03-31 00:43:58 +00001768}
1769
Mike Stump11289f42009-09-09 15:08:12 +00001770bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
John McCall0ad16662009-10-29 08:12:44 +00001771 const TemplateArgumentLoc &AL,
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001772 TemplateArgumentListBuilder &Converted) {
John McCall0ad16662009-10-29 08:12:44 +00001773 const TemplateArgument &Arg = AL.getArgument();
1774
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001775 // Check template type parameter.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001776 switch(Arg.getKind()) {
1777 case TemplateArgument::Type:
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001778 // C++ [temp.arg.type]p1:
1779 // A template-argument for a template-parameter which is a
1780 // type shall be a type-id.
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001781 break;
1782 case TemplateArgument::Template: {
1783 // We have a template type parameter but the template argument
1784 // is a template without any arguments.
1785 SourceRange SR = AL.getSourceRange();
1786 TemplateName Name = Arg.getAsTemplate();
1787 Diag(SR.getBegin(), diag::err_template_missing_args)
1788 << Name << SR;
1789 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1790 Diag(Decl->getLocation(), diag::note_template_decl_here);
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001791
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001792 return true;
1793 }
1794 default: {
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001795 // We have a template type parameter but the template argument
1796 // is not a type.
John McCall0d07eb32009-10-29 18:45:58 +00001797 SourceRange SR = AL.getSourceRange();
1798 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001799 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00001800
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001801 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001802 }
Jeffrey Yasskin823015d2010-04-08 00:03:06 +00001803 }
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001804
John McCallbcd03502009-12-07 02:54:59 +00001805 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001806 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001807
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001808 // Add the converted template type argument.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00001809 Converted.Append(
John McCall0ad16662009-10-29 08:12:44 +00001810 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
Anders Carlssonc8cbb2d2009-06-13 00:33:33 +00001811 return false;
1812}
1813
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001814/// \brief Substitute template arguments into the default template argument for
1815/// the given template type parameter.
1816///
1817/// \param SemaRef the semantic analysis object for which we are performing
1818/// the substitution.
1819///
1820/// \param Template the template that we are synthesizing template arguments
1821/// for.
1822///
1823/// \param TemplateLoc the location of the template name that started the
1824/// template-id we are checking.
1825///
1826/// \param RAngleLoc the location of the right angle bracket ('>') that
1827/// terminates the template-id.
1828///
1829/// \param Param the template template parameter whose default we are
1830/// substituting into.
1831///
1832/// \param Converted the list of template arguments provided for template
1833/// parameters that precede \p Param in the template parameter list.
1834///
1835/// \returns the substituted template argument, or NULL if an error occurred.
John McCallbcd03502009-12-07 02:54:59 +00001836static TypeSourceInfo *
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001837SubstDefaultTemplateArgument(Sema &SemaRef,
1838 TemplateDecl *Template,
1839 SourceLocation TemplateLoc,
1840 SourceLocation RAngleLoc,
1841 TemplateTypeParmDecl *Param,
1842 TemplateArgumentListBuilder &Converted) {
John McCallbcd03502009-12-07 02:54:59 +00001843 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001844
1845 // If the argument type is dependent, instantiate it now based
1846 // on the previously-computed template arguments.
1847 if (ArgType->getType()->isDependentType()) {
1848 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1849 /*TakeArgs=*/false);
1850
1851 MultiLevelTemplateArgumentList AllTemplateArgs
1852 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1853
1854 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1855 Template, Converted.getFlatArguments(),
1856 Converted.flatSize(),
1857 SourceRange(TemplateLoc, RAngleLoc));
1858
1859 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1860 Param->getDefaultArgumentLoc(),
1861 Param->getDeclName());
1862 }
1863
1864 return ArgType;
1865}
1866
1867/// \brief Substitute template arguments into the default template argument for
1868/// the given non-type template parameter.
1869///
1870/// \param SemaRef the semantic analysis object for which we are performing
1871/// the substitution.
1872///
1873/// \param Template the template that we are synthesizing template arguments
1874/// for.
1875///
1876/// \param TemplateLoc the location of the template name that started the
1877/// template-id we are checking.
1878///
1879/// \param RAngleLoc the location of the right angle bracket ('>') that
1880/// terminates the template-id.
1881///
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001882/// \param Param the non-type template parameter whose default we are
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001883/// substituting into.
1884///
1885/// \param Converted the list of template arguments provided for template
1886/// parameters that precede \p Param in the template parameter list.
1887///
1888/// \returns the substituted template argument, or NULL if an error occurred.
1889static Sema::OwningExprResult
1890SubstDefaultTemplateArgument(Sema &SemaRef,
1891 TemplateDecl *Template,
1892 SourceLocation TemplateLoc,
1893 SourceLocation RAngleLoc,
1894 NonTypeTemplateParmDecl *Param,
1895 TemplateArgumentListBuilder &Converted) {
1896 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1897 /*TakeArgs=*/false);
1898
1899 MultiLevelTemplateArgumentList AllTemplateArgs
1900 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1901
1902 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1903 Template, Converted.getFlatArguments(),
1904 Converted.flatSize(),
1905 SourceRange(TemplateLoc, RAngleLoc));
1906
1907 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1908}
1909
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001910/// \brief Substitute template arguments into the default template argument for
1911/// the given template template parameter.
1912///
1913/// \param SemaRef the semantic analysis object for which we are performing
1914/// the substitution.
1915///
1916/// \param Template the template that we are synthesizing template arguments
1917/// for.
1918///
1919/// \param TemplateLoc the location of the template name that started the
1920/// template-id we are checking.
1921///
1922/// \param RAngleLoc the location of the right angle bracket ('>') that
1923/// terminates the template-id.
1924///
1925/// \param Param the template template parameter whose default we are
1926/// substituting into.
1927///
1928/// \param Converted the list of template arguments provided for template
1929/// parameters that precede \p Param in the template parameter list.
1930///
1931/// \returns the substituted template argument, or NULL if an error occurred.
1932static TemplateName
1933SubstDefaultTemplateArgument(Sema &SemaRef,
1934 TemplateDecl *Template,
1935 SourceLocation TemplateLoc,
1936 SourceLocation RAngleLoc,
1937 TemplateTemplateParmDecl *Param,
1938 TemplateArgumentListBuilder &Converted) {
1939 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1940 /*TakeArgs=*/false);
1941
1942 MultiLevelTemplateArgumentList AllTemplateArgs
1943 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1944
1945 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1946 Template, Converted.getFlatArguments(),
1947 Converted.flatSize(),
1948 SourceRange(TemplateLoc, RAngleLoc));
1949
1950 return SemaRef.SubstTemplateName(
1951 Param->getDefaultArgument().getArgument().getAsTemplate(),
1952 Param->getDefaultArgument().getTemplateNameLoc(),
1953 AllTemplateArgs);
1954}
1955
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001956/// \brief If the given template parameter has a default template
1957/// argument, substitute into that default template argument and
1958/// return the corresponding template argument.
1959TemplateArgumentLoc
1960Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1961 SourceLocation TemplateLoc,
1962 SourceLocation RAngleLoc,
1963 Decl *Param,
1964 TemplateArgumentListBuilder &Converted) {
1965 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1966 if (!TypeParm->hasDefaultArgument())
1967 return TemplateArgumentLoc();
1968
John McCallbcd03502009-12-07 02:54:59 +00001969 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
Douglas Gregor5c80a27b2009-11-25 18:55:14 +00001970 TemplateLoc,
1971 RAngleLoc,
1972 TypeParm,
1973 Converted);
1974 if (DI)
1975 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1976
1977 return TemplateArgumentLoc();
1978 }
1979
1980 if (NonTypeTemplateParmDecl *NonTypeParm
1981 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1982 if (!NonTypeParm->hasDefaultArgument())
1983 return TemplateArgumentLoc();
1984
1985 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1986 TemplateLoc,
1987 RAngleLoc,
1988 NonTypeParm,
1989 Converted);
1990 if (Arg.isInvalid())
1991 return TemplateArgumentLoc();
1992
1993 Expr *ArgE = Arg.takeAs<Expr>();
1994 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1995 }
1996
1997 TemplateTemplateParmDecl *TempTempParm
1998 = cast<TemplateTemplateParmDecl>(Param);
1999 if (!TempTempParm->hasDefaultArgument())
2000 return TemplateArgumentLoc();
2001
2002 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2003 TemplateLoc,
2004 RAngleLoc,
2005 TempTempParm,
2006 Converted);
2007 if (TName.isNull())
2008 return TemplateArgumentLoc();
2009
2010 return TemplateArgumentLoc(TemplateArgument(TName),
2011 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2012 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2013}
2014
Douglas Gregorda0fb532009-11-11 19:31:23 +00002015/// \brief Check that the given template argument corresponds to the given
2016/// template parameter.
2017bool Sema::CheckTemplateArgument(NamedDecl *Param,
2018 const TemplateArgumentLoc &Arg,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002019 TemplateDecl *Template,
2020 SourceLocation TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002021 SourceLocation RAngleLoc,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002022 TemplateArgumentListBuilder &Converted,
2023 CheckTemplateArgumentKind CTAK) {
Douglas Gregoreebed722009-11-11 19:41:09 +00002024 // Check template type parameters.
2025 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002026 return CheckTemplateTypeArgument(TTP, Arg, Converted);
Douglas Gregorda0fb532009-11-11 19:31:23 +00002027
Douglas Gregoreebed722009-11-11 19:41:09 +00002028 // Check non-type template parameters.
2029 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
Douglas Gregorda0fb532009-11-11 19:31:23 +00002030 // Do substitution on the type of the non-type template parameter
2031 // with the template arguments we've seen thus far.
2032 QualType NTTPType = NTTP->getType();
2033 if (NTTPType->isDependentType()) {
2034 // Do substitution on the type of the non-type template parameter.
2035 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2036 NTTP, Converted.getFlatArguments(),
2037 Converted.flatSize(),
2038 SourceRange(TemplateLoc, RAngleLoc));
2039
2040 TemplateArgumentList TemplateArgs(Context, Converted,
2041 /*TakeArgs=*/false);
2042 NTTPType = SubstType(NTTPType,
2043 MultiLevelTemplateArgumentList(TemplateArgs),
2044 NTTP->getLocation(),
2045 NTTP->getDeclName());
2046 // If that worked, check the non-type template parameter type
2047 // for validity.
2048 if (!NTTPType.isNull())
2049 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2050 NTTP->getLocation());
2051 if (NTTPType.isNull())
2052 return true;
2053 }
2054
2055 switch (Arg.getArgument().getKind()) {
2056 case TemplateArgument::Null:
2057 assert(false && "Should never see a NULL template argument here");
2058 return true;
2059
2060 case TemplateArgument::Expression: {
2061 Expr *E = Arg.getArgument().getAsExpr();
2062 TemplateArgument Result;
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002063 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
Douglas Gregorda0fb532009-11-11 19:31:23 +00002064 return true;
2065
2066 Converted.Append(Result);
2067 break;
2068 }
2069
2070 case TemplateArgument::Declaration:
2071 case TemplateArgument::Integral:
2072 // We've already checked this template argument, so just copy
2073 // it to the list of converted arguments.
2074 Converted.Append(Arg.getArgument());
2075 break;
2076
2077 case TemplateArgument::Template:
2078 // We were given a template template argument. It may not be ill-formed;
2079 // see below.
2080 if (DependentTemplateName *DTN
2081 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2082 // We have a template argument such as \c T::template X, which we
2083 // parsed as a template template argument. However, since we now
2084 // know that we need a non-type template argument, convert this
2085 // template name into an expression.
John McCalle66edc12009-11-24 19:00:30 +00002086 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2087 DTN->getQualifier(),
Douglas Gregorda0fb532009-11-11 19:31:23 +00002088 Arg.getTemplateQualifierRange(),
John McCalle66edc12009-11-24 19:00:30 +00002089 DTN->getIdentifier(),
2090 Arg.getTemplateNameLoc());
Douglas Gregorda0fb532009-11-11 19:31:23 +00002091
2092 TemplateArgument Result;
2093 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2094 return true;
2095
2096 Converted.Append(Result);
2097 break;
2098 }
2099
2100 // We have a template argument that actually does refer to a class
2101 // template, template alias, or template template parameter, and
2102 // therefore cannot be a non-type template argument.
2103 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2104 << Arg.getSourceRange();
2105
2106 Diag(Param->getLocation(), diag::note_template_param_here);
2107 return true;
2108
2109 case TemplateArgument::Type: {
2110 // We have a non-type template parameter but the template
2111 // argument is a type.
2112
2113 // C++ [temp.arg]p2:
2114 // In a template-argument, an ambiguity between a type-id and
2115 // an expression is resolved to a type-id, regardless of the
2116 // form of the corresponding template-parameter.
2117 //
2118 // We warn specifically about this case, since it can be rather
2119 // confusing for users.
2120 QualType T = Arg.getArgument().getAsType();
2121 SourceRange SR = Arg.getSourceRange();
2122 if (T->isFunctionType())
2123 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2124 else
2125 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2126 Diag(Param->getLocation(), diag::note_template_param_here);
2127 return true;
2128 }
2129
2130 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002131 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002132 break;
2133 }
2134
2135 return false;
2136 }
2137
2138
2139 // Check template template parameters.
2140 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2141
2142 // Substitute into the template parameter list of the template
2143 // template parameter, since previously-supplied template arguments
2144 // may appear within the template template parameter.
2145 {
2146 // Set up a template instantiation context.
2147 LocalInstantiationScope Scope(*this);
2148 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2149 TempParm, Converted.getFlatArguments(),
2150 Converted.flatSize(),
2151 SourceRange(TemplateLoc, RAngleLoc));
2152
2153 TemplateArgumentList TemplateArgs(Context, Converted,
2154 /*TakeArgs=*/false);
2155 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2156 SubstDecl(TempParm, CurContext,
2157 MultiLevelTemplateArgumentList(TemplateArgs)));
2158 if (!TempParm)
2159 return true;
2160
2161 // FIXME: TempParam is leaked.
2162 }
2163
2164 switch (Arg.getArgument().getKind()) {
2165 case TemplateArgument::Null:
2166 assert(false && "Should never see a NULL template argument here");
2167 return true;
2168
2169 case TemplateArgument::Template:
2170 if (CheckTemplateArgument(TempParm, Arg))
2171 return true;
2172
2173 Converted.Append(Arg.getArgument());
2174 break;
2175
2176 case TemplateArgument::Expression:
2177 case TemplateArgument::Type:
2178 // We have a template template parameter but the template
2179 // argument does not refer to a template.
2180 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2181 return true;
2182
2183 case TemplateArgument::Declaration:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002184 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002185 "Declaration argument with template template parameter");
2186 break;
2187 case TemplateArgument::Integral:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002188 llvm_unreachable(
Douglas Gregorda0fb532009-11-11 19:31:23 +00002189 "Integral argument with template template parameter");
2190 break;
2191
2192 case TemplateArgument::Pack:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00002193 llvm_unreachable("Caller must expand template argument packs");
Douglas Gregorda0fb532009-11-11 19:31:23 +00002194 break;
2195 }
2196
2197 return false;
2198}
2199
Douglas Gregord32e0282009-02-09 23:23:08 +00002200/// \brief Check that the given template argument list is well-formed
2201/// for specializing the given template.
2202bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2203 SourceLocation TemplateLoc,
John McCall6b51f282009-11-23 01:53:49 +00002204 const TemplateArgumentListInfo &TemplateArgs,
Douglas Gregore3f1f352009-07-01 00:28:38 +00002205 bool PartialTemplateArgs,
Anders Carlsson8aa89d42009-06-05 03:43:12 +00002206 TemplateArgumentListBuilder &Converted) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002207 TemplateParameterList *Params = Template->getTemplateParameters();
2208 unsigned NumParams = Params->size();
John McCall6b51f282009-11-23 01:53:49 +00002209 unsigned NumArgs = TemplateArgs.size();
Douglas Gregord32e0282009-02-09 23:23:08 +00002210 bool Invalid = false;
2211
John McCall6b51f282009-11-23 01:53:49 +00002212 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2213
Mike Stump11289f42009-09-09 15:08:12 +00002214 bool HasParameterPack =
Anders Carlsson15201f12009-06-13 02:08:00 +00002215 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
Mike Stump11289f42009-09-09 15:08:12 +00002216
Anders Carlsson15201f12009-06-13 02:08:00 +00002217 if ((NumArgs > NumParams && !HasParameterPack) ||
Douglas Gregore3f1f352009-07-01 00:28:38 +00002218 (NumArgs < Params->getMinRequiredArguments() &&
2219 !PartialTemplateArgs)) {
Douglas Gregord32e0282009-02-09 23:23:08 +00002220 // FIXME: point at either the first arg beyond what we can handle,
2221 // or the '>', depending on whether we have too many or too few
2222 // arguments.
2223 SourceRange Range;
2224 if (NumArgs > NumParams)
Douglas Gregorc40290e2009-03-09 23:48:35 +00002225 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
Douglas Gregord32e0282009-02-09 23:23:08 +00002226 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2227 << (NumArgs > NumParams)
2228 << (isa<ClassTemplateDecl>(Template)? 0 :
2229 isa<FunctionTemplateDecl>(Template)? 1 :
2230 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2231 << Template << Range;
Douglas Gregorf8f86832009-02-11 18:16:40 +00002232 Diag(Template->getLocation(), diag::note_template_decl_here)
2233 << Params->getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002234 Invalid = true;
2235 }
Mike Stump11289f42009-09-09 15:08:12 +00002236
2237 // C++ [temp.arg]p1:
Douglas Gregord32e0282009-02-09 23:23:08 +00002238 // [...] The type and form of each template-argument specified in
2239 // a template-id shall match the type and form specified for the
2240 // corresponding parameter declared by the template in its
2241 // template-parameter-list.
2242 unsigned ArgIdx = 0;
2243 for (TemplateParameterList::iterator Param = Params->begin(),
2244 ParamEnd = Params->end();
2245 Param != ParamEnd; ++Param, ++ArgIdx) {
Douglas Gregore3f1f352009-07-01 00:28:38 +00002246 if (ArgIdx > NumArgs && PartialTemplateArgs)
2247 break;
Mike Stump11289f42009-09-09 15:08:12 +00002248
Douglas Gregoreebed722009-11-11 19:41:09 +00002249 // If we have a template parameter pack, check every remaining template
2250 // argument against that template parameter pack.
2251 if ((*Param)->isTemplateParameterPack()) {
2252 Converted.BeginPack();
2253 for (; ArgIdx < NumArgs; ++ArgIdx) {
2254 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2255 TemplateLoc, RAngleLoc, Converted)) {
2256 Invalid = true;
2257 break;
2258 }
2259 }
2260 Converted.EndPack();
2261 continue;
2262 }
2263
Douglas Gregor84d49a22009-11-11 21:54:23 +00002264 if (ArgIdx < NumArgs) {
2265 // Check the template argument we were given.
2266 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2267 TemplateLoc, RAngleLoc, Converted))
2268 return true;
2269
2270 continue;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002271 }
Douglas Gregorda0fb532009-11-11 19:31:23 +00002272
Douglas Gregor84d49a22009-11-11 21:54:23 +00002273 // We have a default template argument that we will use.
2274 TemplateArgumentLoc Arg;
2275
2276 // Retrieve the default template argument from the template
2277 // parameter. For each kind of template parameter, we substitute the
2278 // template arguments provided thus far and any "outer" template arguments
2279 // (when the template parameter was part of a nested template) into
2280 // the default argument.
2281 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2282 if (!TTP->hasDefaultArgument()) {
2283 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2284 break;
2285 }
2286
John McCallbcd03502009-12-07 02:54:59 +00002287 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
Douglas Gregor84d49a22009-11-11 21:54:23 +00002288 Template,
2289 TemplateLoc,
2290 RAngleLoc,
2291 TTP,
2292 Converted);
2293 if (!ArgType)
2294 return true;
2295
2296 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2297 ArgType);
2298 } else if (NonTypeTemplateParmDecl *NTTP
2299 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2300 if (!NTTP->hasDefaultArgument()) {
2301 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2302 break;
2303 }
2304
2305 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2306 TemplateLoc,
2307 RAngleLoc,
2308 NTTP,
2309 Converted);
2310 if (E.isInvalid())
2311 return true;
2312
2313 Expr *Ex = E.takeAs<Expr>();
2314 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2315 } else {
2316 TemplateTemplateParmDecl *TempParm
2317 = cast<TemplateTemplateParmDecl>(*Param);
2318
2319 if (!TempParm->hasDefaultArgument()) {
2320 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2321 break;
2322 }
2323
2324 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2325 TemplateLoc,
2326 RAngleLoc,
2327 TempParm,
2328 Converted);
2329 if (Name.isNull())
2330 return true;
2331
2332 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2333 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2334 TempParm->getDefaultArgument().getTemplateNameLoc());
2335 }
2336
2337 // Introduce an instantiation record that describes where we are using
2338 // the default template argument.
2339 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2340 Converted.getFlatArguments(),
2341 Converted.flatSize(),
2342 SourceRange(TemplateLoc, RAngleLoc));
2343
2344 // Check the default template argument.
Douglas Gregoreebed722009-11-11 19:41:09 +00002345 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
Douglas Gregorda0fb532009-11-11 19:31:23 +00002346 RAngleLoc, Converted))
2347 return true;
Douglas Gregord32e0282009-02-09 23:23:08 +00002348 }
2349
2350 return Invalid;
2351}
2352
2353/// \brief Check a template argument against its corresponding
2354/// template type parameter.
2355///
2356/// This routine implements the semantics of C++ [temp.arg.type]. It
2357/// returns true if an error occurred, and false otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002358bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
John McCallbcd03502009-12-07 02:54:59 +00002359 TypeSourceInfo *ArgInfo) {
2360 assert(ArgInfo && "invalid TypeSourceInfo");
John McCall0ad16662009-10-29 08:12:44 +00002361 QualType Arg = ArgInfo->getType();
2362
Douglas Gregord32e0282009-02-09 23:23:08 +00002363 // C++ [temp.arg.type]p2:
2364 // A local type, a type with no linkage, an unnamed type or a type
2365 // compounded from any of these types shall not be used as a
2366 // template-argument for a template type-parameter.
2367 //
Douglas Gregor959d5a02010-05-22 16:17:30 +00002368 // FIXME: Perform the unnamed type check.
2369 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
Douglas Gregord32e0282009-02-09 23:23:08 +00002370 const TagType *Tag = 0;
John McCall9dd450b2009-09-21 23:43:11 +00002371 if (const EnumType *EnumT = Arg->getAs<EnumType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002372 Tag = EnumT;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002373 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
Douglas Gregord32e0282009-02-09 23:23:08 +00002374 Tag = RecordT;
John McCall0ad16662009-10-29 08:12:44 +00002375 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002376 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
John McCall0ad16662009-10-29 08:12:44 +00002377 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2378 << QualType(Tag, 0) << SR;
2379 } else if (Tag && !Tag->getDecl()->getDeclName() &&
Douglas Gregor65b2c4c2009-03-10 18:33:27 +00002380 !Tag->getDecl()->getTypedefForAnonDecl()) {
John McCall0ad16662009-10-29 08:12:44 +00002381 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002382 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2383 return true;
Douglas Gregor959d5a02010-05-22 16:17:30 +00002384 } else if (Arg->isVariablyModifiedType()) {
2385 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2386 << Arg;
2387 return true;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002388 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00002389 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
Douglas Gregord32e0282009-02-09 23:23:08 +00002390 }
2391
2392 return false;
2393}
2394
Douglas Gregorccb07762009-02-11 19:52:55 +00002395/// \brief Checks whether the given template argument is the address
2396/// of an object or function according to C++ [temp.arg.nontype]p1.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002397static bool
2398CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2399 NonTypeTemplateParmDecl *Param,
2400 QualType ParamType,
2401 Expr *ArgIn,
2402 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002403 bool Invalid = false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002404 Expr *Arg = ArgIn;
2405 QualType ArgType = Arg->getType();
Douglas Gregorccb07762009-02-11 19:52:55 +00002406
2407 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002408 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002409 Arg = Cast->getSubExpr();
2410
2411 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002412 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002413 // A template-argument for a non-type, non-template
2414 // template-parameter shall be one of: [...]
2415 //
2416 // -- the address of an object or function with external
2417 // linkage, including function templates and function
2418 // template-ids but excluding non-static class members,
2419 // expressed as & id-expression where the & is optional if
2420 // the name refers to a function or array, or if the
2421 // corresponding template-parameter is a reference; or
2422 DeclRefExpr *DRE = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002423
Douglas Gregorccb07762009-02-11 19:52:55 +00002424 // Ignore (and complain about) any excess parentheses.
2425 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2426 if (!Invalid) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002427 S.Diag(Arg->getSourceRange().getBegin(),
2428 diag::err_template_arg_extra_parens)
Douglas Gregorccb07762009-02-11 19:52:55 +00002429 << Arg->getSourceRange();
2430 Invalid = true;
2431 }
2432
2433 Arg = Parens->getSubExpr();
2434 }
2435
Douglas Gregorb242683d2010-04-01 18:32:35 +00002436 bool AddressTaken = false;
2437 SourceLocation AddrOpLoc;
Douglas Gregorccb07762009-02-11 19:52:55 +00002438 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002439 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002440 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
Douglas Gregorb242683d2010-04-01 18:32:35 +00002441 AddressTaken = true;
2442 AddrOpLoc = UnOp->getOperatorLoc();
2443 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002444 } else
2445 DRE = dyn_cast<DeclRefExpr>(Arg);
2446
Douglas Gregorb242683d2010-04-01 18:32:35 +00002447 if (!DRE) {
Douglas Gregor064fdb22010-04-14 23:11:21 +00002448 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2449 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002450 S.Diag(Param->getLocation(), diag::note_template_param_here);
2451 return true;
2452 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002453
2454 // Stop checking the precise nature of the argument if it is value dependent,
2455 // it should be checked when instantiated.
Douglas Gregorb242683d2010-04-01 18:32:35 +00002456 if (Arg->isValueDependent()) {
2457 Converted = TemplateArgument(ArgIn->Retain());
Chandler Carruth724a8a12010-01-31 10:01:20 +00002458 return false;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002459 }
Chandler Carruth724a8a12010-01-31 10:01:20 +00002460
Douglas Gregorb242683d2010-04-01 18:32:35 +00002461 if (!isa<ValueDecl>(DRE->getDecl())) {
2462 S.Diag(Arg->getSourceRange().getBegin(),
2463 diag::err_template_arg_not_object_or_func_form)
Douglas Gregorccb07762009-02-11 19:52:55 +00002464 << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002465 S.Diag(Param->getLocation(), diag::note_template_param_here);
2466 return true;
2467 }
2468
2469 NamedDecl *Entity = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002470
2471 // Cannot refer to non-static data members
Douglas Gregorb242683d2010-04-01 18:32:35 +00002472 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2473 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
Douglas Gregorccb07762009-02-11 19:52:55 +00002474 << Field << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002475 S.Diag(Param->getLocation(), diag::note_template_param_here);
2476 return true;
2477 }
Douglas Gregorccb07762009-02-11 19:52:55 +00002478
2479 // Cannot refer to non-static member functions
2480 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
Douglas Gregorb242683d2010-04-01 18:32:35 +00002481 if (!Method->isStatic()) {
2482 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
Douglas Gregorccb07762009-02-11 19:52:55 +00002483 << Method << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002484 S.Diag(Param->getLocation(), diag::note_template_param_here);
2485 return true;
2486 }
Mike Stump11289f42009-09-09 15:08:12 +00002487
Douglas Gregorccb07762009-02-11 19:52:55 +00002488 // Functions must have external linkage.
2489 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002490 if (!isExternalLinkage(Func->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002491 S.Diag(Arg->getSourceRange().getBegin(),
2492 diag::err_template_arg_function_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002493 << Func << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002494 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002495 << true;
2496 return true;
2497 }
2498
2499 // Okay: we've named a function with external linkage.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002500 Entity = Func;
Douglas Gregorccb07762009-02-11 19:52:55 +00002501
Douglas Gregorb242683d2010-04-01 18:32:35 +00002502 // If the template parameter has pointer type, the function decays.
2503 if (ParamType->isPointerType() && !AddressTaken)
2504 ArgType = S.Context.getPointerType(Func->getType());
2505 else if (AddressTaken && ParamType->isReferenceType()) {
2506 // If we originally had an address-of operator, but the
2507 // parameter has reference type, complain and (if things look
2508 // like they will work) drop the address-of operator.
2509 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2510 ParamType.getNonReferenceType())) {
2511 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2512 << ParamType;
2513 S.Diag(Param->getLocation(), diag::note_template_param_here);
2514 return true;
2515 }
2516
2517 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2518 << ParamType
2519 << FixItHint::CreateRemoval(AddrOpLoc);
2520 S.Diag(Param->getLocation(), diag::note_template_param_here);
2521
2522 ArgType = Func->getType();
2523 }
2524 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
Douglas Gregor7dc5c172010-02-03 09:33:45 +00002525 if (!isExternalLinkage(Var->getLinkage())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002526 S.Diag(Arg->getSourceRange().getBegin(),
2527 diag::err_template_arg_object_not_extern)
Douglas Gregorccb07762009-02-11 19:52:55 +00002528 << Var << Arg->getSourceRange();
Douglas Gregorb242683d2010-04-01 18:32:35 +00002529 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
Douglas Gregorccb07762009-02-11 19:52:55 +00002530 << true;
2531 return true;
2532 }
2533
Douglas Gregorb242683d2010-04-01 18:32:35 +00002534 // A value of reference type is not an object.
2535 if (Var->getType()->isReferenceType()) {
2536 S.Diag(Arg->getSourceRange().getBegin(),
2537 diag::err_template_arg_reference_var)
2538 << Var->getType() << Arg->getSourceRange();
2539 S.Diag(Param->getLocation(), diag::note_template_param_here);
2540 return true;
2541 }
2542
Douglas Gregorccb07762009-02-11 19:52:55 +00002543 // Okay: we've named an object with external linkage
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002544 Entity = Var;
Douglas Gregorb242683d2010-04-01 18:32:35 +00002545
2546 // If the template parameter has pointer type, we must have taken
2547 // the address of this object.
2548 if (ParamType->isReferenceType()) {
2549 if (AddressTaken) {
2550 // If we originally had an address-of operator, but the
2551 // parameter has reference type, complain and (if things look
2552 // like they will work) drop the address-of operator.
2553 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2554 ParamType.getNonReferenceType())) {
2555 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2556 << ParamType;
2557 S.Diag(Param->getLocation(), diag::note_template_param_here);
2558 return true;
2559 }
2560
2561 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2562 << ParamType
2563 << FixItHint::CreateRemoval(AddrOpLoc);
2564 S.Diag(Param->getLocation(), diag::note_template_param_here);
2565
2566 ArgType = Var->getType();
2567 }
2568 } else if (!AddressTaken && ParamType->isPointerType()) {
2569 if (Var->getType()->isArrayType()) {
2570 // Array-to-pointer decay.
2571 ArgType = S.Context.getArrayDecayedType(Var->getType());
2572 } else {
2573 // If the template parameter has pointer type but the address of
2574 // this object was not taken, complain and (possibly) recover by
2575 // taking the address of the entity.
2576 ArgType = S.Context.getPointerType(Var->getType());
2577 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2578 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2579 << ParamType;
2580 S.Diag(Param->getLocation(), diag::note_template_param_here);
2581 return true;
2582 }
2583
2584 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2585 << ParamType
2586 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2587
2588 S.Diag(Param->getLocation(), diag::note_template_param_here);
2589 }
2590 }
2591 } else {
2592 // We found something else, but we don't know specifically what it is.
2593 S.Diag(Arg->getSourceRange().getBegin(),
2594 diag::err_template_arg_not_object_or_func)
2595 << Arg->getSourceRange();
2596 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2597 return true;
Douglas Gregorccb07762009-02-11 19:52:55 +00002598 }
Mike Stump11289f42009-09-09 15:08:12 +00002599
Douglas Gregorb242683d2010-04-01 18:32:35 +00002600 if (ParamType->isPointerType() &&
2601 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2602 S.IsQualificationConversion(ArgType, ParamType)) {
2603 // For pointer-to-object types, qualification conversions are
2604 // permitted.
2605 } else {
2606 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2607 if (!ParamRef->getPointeeType()->isFunctionType()) {
2608 // C++ [temp.arg.nontype]p5b3:
2609 // For a non-type template-parameter of type reference to
2610 // object, no conversions apply. The type referred to by the
2611 // reference may be more cv-qualified than the (otherwise
2612 // identical) type of the template- argument. The
2613 // template-parameter is bound directly to the
2614 // template-argument, which shall be an lvalue.
2615
2616 // FIXME: Other qualifiers?
2617 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2618 unsigned ArgQuals = ArgType.getCVRQualifiers();
2619
2620 if ((ParamQuals | ArgQuals) != ParamQuals) {
2621 S.Diag(Arg->getSourceRange().getBegin(),
2622 diag::err_template_arg_ref_bind_ignores_quals)
2623 << ParamType << Arg->getType()
2624 << Arg->getSourceRange();
2625 S.Diag(Param->getLocation(), diag::note_template_param_here);
2626 return true;
2627 }
2628 }
2629 }
2630
2631 // At this point, the template argument refers to an object or
2632 // function with external linkage. We now need to check whether the
2633 // argument and parameter types are compatible.
2634 if (!S.Context.hasSameUnqualifiedType(ArgType,
2635 ParamType.getNonReferenceType())) {
2636 // We can't perform this conversion or binding.
2637 if (ParamType->isReferenceType())
2638 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2639 << ParamType << Arg->getType() << Arg->getSourceRange();
2640 else
2641 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2642 << Arg->getType() << ParamType << Arg->getSourceRange();
2643 S.Diag(Param->getLocation(), diag::note_template_param_here);
2644 return true;
2645 }
2646 }
2647
2648 // Create the template argument.
2649 Converted = TemplateArgument(Entity->getCanonicalDecl());
Douglas Gregor53ce1782010-04-24 18:20:53 +00002650 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
Douglas Gregorb242683d2010-04-01 18:32:35 +00002651 return false;
Douglas Gregorccb07762009-02-11 19:52:55 +00002652}
2653
2654/// \brief Checks whether the given template argument is a pointer to
2655/// member constant according to C++ [temp.arg.nontype]p1.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002656bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2657 TemplateArgument &Converted) {
Douglas Gregorccb07762009-02-11 19:52:55 +00002658 bool Invalid = false;
2659
2660 // See through any implicit casts we added to fix the type.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002661 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
Douglas Gregorccb07762009-02-11 19:52:55 +00002662 Arg = Cast->getSubExpr();
2663
2664 // C++ [temp.arg.nontype]p1:
Mike Stump11289f42009-09-09 15:08:12 +00002665 //
Douglas Gregorccb07762009-02-11 19:52:55 +00002666 // A template-argument for a non-type, non-template
2667 // template-parameter shall be one of: [...]
2668 //
2669 // -- a pointer to member expressed as described in 5.3.1.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002670 DeclRefExpr *DRE = 0;
Douglas Gregorccb07762009-02-11 19:52:55 +00002671
2672 // Ignore (and complain about) any excess parentheses.
2673 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2674 if (!Invalid) {
Mike Stump11289f42009-09-09 15:08:12 +00002675 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002676 diag::err_template_arg_extra_parens)
2677 << Arg->getSourceRange();
2678 Invalid = true;
2679 }
2680
2681 Arg = Parens->getSubExpr();
2682 }
2683
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002684 // A pointer-to-member constant written &Class::member.
2685 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002686 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2687 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2688 if (DRE && !DRE->getQualifier())
2689 DRE = 0;
2690 }
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002691 }
2692 // A constant of pointer-to-member type.
2693 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2694 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2695 if (VD->getType()->isMemberPointerType()) {
2696 if (isa<NonTypeTemplateParmDecl>(VD) ||
2697 (isa<VarDecl>(VD) &&
2698 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2699 if (Arg->isTypeDependent() || Arg->isValueDependent())
2700 Converted = TemplateArgument(Arg->Retain());
2701 else
2702 Converted = TemplateArgument(VD->getCanonicalDecl());
2703 return Invalid;
2704 }
2705 }
2706 }
2707
2708 DRE = 0;
2709 }
2710
Douglas Gregorccb07762009-02-11 19:52:55 +00002711 if (!DRE)
2712 return Diag(Arg->getSourceRange().getBegin(),
2713 diag::err_template_arg_not_pointer_to_member_form)
2714 << Arg->getSourceRange();
2715
2716 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2717 assert((isa<FieldDecl>(DRE->getDecl()) ||
2718 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2719 "Only non-static member pointers can make it here");
2720
2721 // Okay: this is the address of a non-static member, and therefore
2722 // a member pointer constant.
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00002723 if (Arg->isTypeDependent() || Arg->isValueDependent())
2724 Converted = TemplateArgument(Arg->Retain());
2725 else
2726 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
Douglas Gregorccb07762009-02-11 19:52:55 +00002727 return Invalid;
2728 }
2729
2730 // We found something else, but we don't know specifically what it is.
Mike Stump11289f42009-09-09 15:08:12 +00002731 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002732 diag::err_template_arg_not_pointer_to_member_form)
2733 << Arg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002734 Diag(DRE->getDecl()->getLocation(),
Douglas Gregorccb07762009-02-11 19:52:55 +00002735 diag::note_template_arg_refers_here);
2736 return true;
2737}
2738
Douglas Gregord32e0282009-02-09 23:23:08 +00002739/// \brief Check a template argument against its corresponding
2740/// non-type template parameter.
2741///
Douglas Gregor463421d2009-03-03 04:44:36 +00002742/// This routine implements the semantics of C++ [temp.arg.nontype].
2743/// It returns true if an error occurred, and false otherwise. \p
2744/// InstantiatedParamType is the type of the non-type template
2745/// parameter after it has been instantiated.
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002746///
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002747/// If no error was detected, Converted receives the converted template argument.
Douglas Gregord32e0282009-02-09 23:23:08 +00002748bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
Mike Stump11289f42009-09-09 15:08:12 +00002749 QualType InstantiatedParamType, Expr *&Arg,
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002750 TemplateArgument &Converted,
2751 CheckTemplateArgumentKind CTAK) {
Douglas Gregorc40290e2009-03-09 23:48:35 +00002752 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2753
Douglas Gregor86560402009-02-10 23:36:10 +00002754 // If either the parameter has a dependent type or the argument is
2755 // type-dependent, there's nothing we can check now.
Douglas Gregorc40290e2009-03-09 23:48:35 +00002756 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2757 // FIXME: Produce a cloned, canonical expression?
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002758 Converted = TemplateArgument(Arg);
Douglas Gregor86560402009-02-10 23:36:10 +00002759 return false;
Douglas Gregorc40290e2009-03-09 23:48:35 +00002760 }
Douglas Gregor86560402009-02-10 23:36:10 +00002761
2762 // C++ [temp.arg.nontype]p5:
2763 // The following conversions are performed on each expression used
2764 // as a non-type template-argument. If a non-type
2765 // template-argument cannot be converted to the type of the
2766 // corresponding template-parameter then the program is
2767 // ill-formed.
2768 //
2769 // -- for a non-type template-parameter of integral or
2770 // enumeration type, integral promotions (4.5) and integral
2771 // conversions (4.7) are applied.
Douglas Gregor463421d2009-03-03 04:44:36 +00002772 QualType ParamType = InstantiatedParamType;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002773 QualType ArgType = Arg->getType();
Douglas Gregor86560402009-02-10 23:36:10 +00002774 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
Douglas Gregor86560402009-02-10 23:36:10 +00002775 // C++ [temp.arg.nontype]p1:
2776 // A template-argument for a non-type, non-template
2777 // template-parameter shall be one of:
2778 //
2779 // -- an integral constant-expression of integral or enumeration
2780 // type; or
2781 // -- the name of a non-type template-parameter; or
2782 SourceLocation NonConstantLoc;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002783 llvm::APSInt Value;
Douglas Gregor86560402009-02-10 23:36:10 +00002784 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002785 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002786 diag::err_template_arg_not_integral_or_enumeral)
2787 << ArgType << Arg->getSourceRange();
2788 Diag(Param->getLocation(), diag::note_template_param_here);
2789 return true;
2790 } else if (!Arg->isValueDependent() &&
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002791 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002792 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2793 << ArgType << Arg->getSourceRange();
2794 return true;
2795 }
2796
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002797 // From here on out, all we care about are the unqualified forms
2798 // of the parameter and argument types.
2799 ParamType = ParamType.getUnqualifiedType();
2800 ArgType = ArgType.getUnqualifiedType();
Douglas Gregor86560402009-02-10 23:36:10 +00002801
2802 // Try to convert the argument to the parameter's type.
Douglas Gregor4d0c38a2009-11-04 21:50:46 +00002803 if (Context.hasSameType(ParamType, ArgType)) {
Douglas Gregor86560402009-02-10 23:36:10 +00002804 // Okay: no conversion necessary
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00002805 } else if (CTAK == CTAK_Deduced) {
2806 // C++ [temp.deduct.type]p17:
2807 // If, in the declaration of a function template with a non-type
2808 // template-parameter, the non-type template- parameter is used
2809 // in an expression in the function parameter-list and, if the
2810 // corresponding template-argument is deduced, the
2811 // template-argument type shall match the type of the
2812 // template-parameter exactly, except that a template-argument
2813 // deduced from an array bound may be of any integral type.
2814 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2815 << ArgType << ParamType;
2816 Diag(Param->getLocation(), diag::note_template_param_here);
2817 return true;
Douglas Gregor86560402009-02-10 23:36:10 +00002818 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2819 !ParamType->isEnumeralType()) {
2820 // This is an integral promotion or conversion.
Eli Friedman06ed2a52009-10-20 08:27:19 +00002821 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
Douglas Gregor86560402009-02-10 23:36:10 +00002822 } else {
2823 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002824 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor86560402009-02-10 23:36:10 +00002825 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002826 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor86560402009-02-10 23:36:10 +00002827 Diag(Param->getLocation(), diag::note_template_param_here);
2828 return true;
2829 }
2830
Douglas Gregor52aba872009-03-14 00:20:21 +00002831 QualType IntegerType = Context.getCanonicalType(ParamType);
John McCall9dd450b2009-09-21 23:43:11 +00002832 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002833 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
Douglas Gregor52aba872009-03-14 00:20:21 +00002834
2835 if (!Arg->isValueDependent()) {
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002836 llvm::APSInt OldValue = Value;
2837
2838 // Coerce the template argument's value to the value it will have
2839 // based on the template parameter's type.
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002840 unsigned AllowedBits = Context.getTypeSize(IntegerType);
Douglas Gregora14cb9f2010-03-26 00:39:40 +00002841 if (Value.getBitWidth() != AllowedBits)
2842 Value.extOrTrunc(AllowedBits);
2843 Value.setIsSigned(IntegerType->isSignedIntegerType());
Douglas Gregorbb3d7862010-03-26 02:38:37 +00002844
2845 // Complain if an unsigned parameter received a negative value.
2846 if (IntegerType->isUnsignedIntegerType()
2847 && (OldValue.isSigned() && OldValue.isNegative())) {
2848 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2849 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2850 << Arg->getSourceRange();
2851 Diag(Param->getLocation(), diag::note_template_param_here);
2852 }
2853
2854 // Complain if we overflowed the template parameter's type.
2855 unsigned RequiredBits;
2856 if (IntegerType->isUnsignedIntegerType())
2857 RequiredBits = OldValue.getActiveBits();
2858 else if (OldValue.isUnsigned())
2859 RequiredBits = OldValue.getActiveBits() + 1;
2860 else
2861 RequiredBits = OldValue.getMinSignedBits();
2862 if (RequiredBits > AllowedBits) {
2863 Diag(Arg->getSourceRange().getBegin(),
2864 diag::warn_template_arg_too_large)
2865 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2866 << Arg->getSourceRange();
2867 Diag(Param->getLocation(), diag::note_template_param_here);
2868 }
Douglas Gregor52aba872009-03-14 00:20:21 +00002869 }
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002870
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002871 // Add the value of this argument to the list of converted
2872 // arguments. We use the bitwidth and signedness of the template
2873 // parameter.
2874 if (Arg->isValueDependent()) {
2875 // The argument is value-dependent. Create a new
2876 // TemplateArgument with the converted expression.
2877 Converted = TemplateArgument(Arg);
2878 return false;
Douglas Gregor264ec4f2009-02-17 01:05:43 +00002879 }
2880
John McCall0ad16662009-10-29 08:12:44 +00002881 Converted = TemplateArgument(Value,
Mike Stump11289f42009-09-09 15:08:12 +00002882 ParamType->isEnumeralType() ? ParamType
Douglas Gregor74eba0b2009-06-11 18:10:32 +00002883 : IntegerType);
Douglas Gregor86560402009-02-10 23:36:10 +00002884 return false;
2885 }
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002886
John McCall16df1e52010-03-30 21:47:33 +00002887 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2888
Douglas Gregorb242683d2010-04-01 18:32:35 +00002889 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2890 // from a template argument of type std::nullptr_t to a non-type
2891 // template parameter of type pointer to object, pointer to
2892 // function, or pointer-to-member, respectively.
2893 if (ArgType->isNullPtrType() &&
2894 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2895 Converted = TemplateArgument((NamedDecl *)0);
2896 return false;
2897 }
2898
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002899 // Handle pointer-to-function, reference-to-function, and
2900 // pointer-to-member-function all in (roughly) the same way.
2901 if (// -- For a non-type template-parameter of type pointer to
2902 // function, only the function-to-pointer conversion (4.3) is
2903 // applied. If the template-argument represents a set of
2904 // overloaded functions (or a pointer to such), the matching
2905 // function is selected from the set (13.4).
2906 (ParamType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002907 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002908 // -- For a non-type template-parameter of type reference to
2909 // function, no conversions apply. If the template-argument
2910 // represents a set of overloaded functions, the matching
2911 // function is selected from the set (13.4).
2912 (ParamType->isReferenceType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002913 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002914 // -- For a non-type template-parameter of type pointer to
2915 // member function, no conversions apply. If the
2916 // template-argument represents a set of overloaded member
2917 // functions, the matching member function is selected from
2918 // the set (13.4).
2919 (ParamType->isMemberPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002920 ParamType->getAs<MemberPointerType>()->getPointeeType()
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002921 ->isFunctionType())) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00002922
Douglas Gregor064fdb22010-04-14 23:11:21 +00002923 if (Arg->getType() == Context.OverloadTy) {
2924 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2925 true,
2926 FoundResult)) {
2927 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2928 return true;
2929
2930 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2931 ArgType = Arg->getType();
2932 } else
Douglas Gregor171c45a2009-02-18 21:56:37 +00002933 return true;
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002934 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002935
Douglas Gregorb242683d2010-04-01 18:32:35 +00002936 if (!ParamType->isMemberPointerType())
2937 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2938 ParamType,
2939 Arg, Converted);
2940
2941 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2942 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2943 Arg->isLvalue(Context) == Expr::LV_Valid);
2944 } else if (!Context.hasSameUnqualifiedType(ArgType,
2945 ParamType.getNonReferenceType())) {
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002946 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00002947 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002948 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00002949 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002950 Diag(Param->getLocation(), diag::note_template_param_here);
2951 return true;
2952 }
Mike Stump11289f42009-09-09 15:08:12 +00002953
Douglas Gregorb242683d2010-04-01 18:32:35 +00002954 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00002955 }
2956
Chris Lattner696197c2009-02-20 21:37:53 +00002957 if (ParamType->isPointerType()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002958 // -- for a non-type template-parameter of type pointer to
2959 // object, qualification conversions (4.4) and the
2960 // array-to-pointer conversion (4.2) are applied.
Sebastian Redl576fd422009-05-10 18:38:11 +00002961 // C++0x also allows a value of std::nullptr_t.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002962 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002963 "Only object pointers allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002964
Douglas Gregorb242683d2010-04-01 18:32:35 +00002965 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2966 ParamType,
2967 Arg, Converted);
Douglas Gregora9faa442009-02-11 00:44:29 +00002968 }
Mike Stump11289f42009-09-09 15:08:12 +00002969
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002970 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002971 // -- For a non-type template-parameter of type reference to
2972 // object, no conversions apply. The type referred to by the
2973 // reference may be more cv-qualified than the (otherwise
2974 // identical) type of the template-argument. The
2975 // template-parameter is bound directly to the
2976 // template-argument, which must be an lvalue.
Douglas Gregor64259f52009-03-24 20:32:41 +00002977 assert(ParamRefType->getPointeeType()->isObjectType() &&
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002978 "Only object references allowed here");
Douglas Gregora9faa442009-02-11 00:44:29 +00002979
Douglas Gregor064fdb22010-04-14 23:11:21 +00002980 if (Arg->getType() == Context.OverloadTy) {
2981 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2982 ParamRefType->getPointeeType(),
2983 true,
2984 FoundResult)) {
2985 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2986 return true;
2987
2988 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2989 ArgType = Arg->getType();
2990 } else
Douglas Gregorb242683d2010-04-01 18:32:35 +00002991 return true;
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002992 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00002993
Douglas Gregorb242683d2010-04-01 18:32:35 +00002994 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2995 ParamType,
2996 Arg, Converted);
Douglas Gregor6f233ef2009-02-11 01:18:59 +00002997 }
Douglas Gregor0e558532009-02-11 16:16:59 +00002998
2999 // -- For a non-type template-parameter of type pointer to data
3000 // member, qualification conversions (4.4) are applied.
3001 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3002
Douglas Gregor1515f762009-02-11 18:22:40 +00003003 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
Douglas Gregor0e558532009-02-11 16:16:59 +00003004 // Types match exactly: nothing more to do here.
3005 } else if (IsQualificationConversion(ArgType, ParamType)) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003006 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
3007 Arg->isLvalue(Context) == Expr::LV_Valid);
Douglas Gregor0e558532009-02-11 16:16:59 +00003008 } else {
3009 // We can't perform this conversion.
Mike Stump11289f42009-09-09 15:08:12 +00003010 Diag(Arg->getSourceRange().getBegin(),
Douglas Gregor0e558532009-02-11 16:16:59 +00003011 diag::err_template_arg_not_convertible)
Douglas Gregor463421d2009-03-03 04:44:36 +00003012 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
Douglas Gregor0e558532009-02-11 16:16:59 +00003013 Diag(Param->getLocation(), diag::note_template_param_here);
Mike Stump11289f42009-09-09 15:08:12 +00003014 return true;
Douglas Gregor0e558532009-02-11 16:16:59 +00003015 }
3016
Douglas Gregor49ba3ca2009-11-12 18:38:13 +00003017 return CheckTemplateArgumentPointerToMember(Arg, Converted);
Douglas Gregord32e0282009-02-09 23:23:08 +00003018}
3019
3020/// \brief Check a template argument against its corresponding
3021/// template template parameter.
3022///
3023/// This routine implements the semantics of C++ [temp.arg.template].
3024/// It returns true if an error occurred, and false otherwise.
3025bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003026 const TemplateArgumentLoc &Arg) {
3027 TemplateName Name = Arg.getArgument().getAsTemplate();
3028 TemplateDecl *Template = Name.getAsTemplateDecl();
3029 if (!Template) {
3030 // Any dependent template name is fine.
3031 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3032 return false;
3033 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003034
3035 // C++ [temp.arg.template]p1:
3036 // A template-argument for a template template-parameter shall be
3037 // the name of a class template, expressed as id-expression. Only
3038 // primary class templates are considered when matching the
3039 // template template argument with the corresponding parameter;
3040 // partial specializations are not considered even if their
3041 // parameter lists match that of the template template parameter.
Douglas Gregord5222052009-06-12 19:43:02 +00003042 //
3043 // Note that we also allow template template parameters here, which
3044 // will happen when we are dealing with, e.g., class template
3045 // partial specializations.
Mike Stump11289f42009-09-09 15:08:12 +00003046 if (!isa<ClassTemplateDecl>(Template) &&
Douglas Gregord5222052009-06-12 19:43:02 +00003047 !isa<TemplateTemplateParmDecl>(Template)) {
Mike Stump11289f42009-09-09 15:08:12 +00003048 assert(isa<FunctionTemplateDecl>(Template) &&
Douglas Gregor85e0f662009-02-10 00:24:35 +00003049 "Only function templates are possible here");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003050 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003051 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003052 << Template;
3053 }
3054
3055 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3056 Param->getTemplateParameters(),
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003057 true,
3058 TPL_TemplateTemplateArgumentMatch,
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003059 Arg.getLocation());
Douglas Gregord32e0282009-02-09 23:23:08 +00003060}
3061
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003062/// \brief Given a non-type template argument that refers to a
3063/// declaration and the type of its corresponding non-type template
3064/// parameter, produce an expression that properly refers to that
3065/// declaration.
3066Sema::OwningExprResult
3067Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3068 QualType ParamType,
3069 SourceLocation Loc) {
3070 assert(Arg.getKind() == TemplateArgument::Declaration &&
3071 "Only declaration template arguments permitted here");
3072 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3073
3074 if (VD->getDeclContext()->isRecord() &&
3075 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3076 // If the value is a class member, we might have a pointer-to-member.
3077 // Determine whether the non-type template template parameter is of
3078 // pointer-to-member type. If so, we need to build an appropriate
3079 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3080 // would refer to the member itself.
3081 if (ParamType->isMemberPointerType()) {
3082 QualType ClassType
3083 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3084 NestedNameSpecifier *Qualifier
3085 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3086 CXXScopeSpec SS;
3087 SS.setScopeRep(Qualifier);
3088 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3089 VD->getType().getNonReferenceType(),
3090 Loc,
3091 &SS);
3092 if (RefExpr.isInvalid())
3093 return ExprError();
3094
3095 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003096
3097 // We might need to perform a trailing qualification conversion, since
3098 // the element type on the parameter could be more qualified than the
3099 // element type in the expression we constructed.
3100 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3101 ParamType.getUnqualifiedType())) {
3102 Expr *RefE = RefExpr.takeAs<Expr>();
3103 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3104 CastExpr::CK_NoOp);
3105 RefExpr = Owned(RefE);
3106 }
3107
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003108 assert(!RefExpr.isInvalid() &&
3109 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
Douglas Gregorfabf95d2010-04-30 21:46:38 +00003110 ParamType.getUnqualifiedType()));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003111 return move(RefExpr);
3112 }
3113 }
3114
3115 QualType T = VD->getType().getNonReferenceType();
3116 if (ParamType->isPointerType()) {
Douglas Gregorb242683d2010-04-01 18:32:35 +00003117 // When the non-type template parameter is a pointer, take the
3118 // address of the declaration.
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003119 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3120 if (RefExpr.isInvalid())
3121 return ExprError();
Douglas Gregorb242683d2010-04-01 18:32:35 +00003122
3123 if (T->isFunctionType() || T->isArrayType()) {
3124 // Decay functions and arrays.
3125 Expr *RefE = (Expr *)RefExpr.get();
3126 DefaultFunctionArrayConversion(RefE);
3127 if (RefE != RefExpr.get()) {
3128 RefExpr.release();
3129 RefExpr = Owned(RefE);
3130 }
3131
3132 return move(RefExpr);
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003133 }
3134
Douglas Gregorb242683d2010-04-01 18:32:35 +00003135 // Take the address of everything else
3136 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
Douglas Gregord5cb1dd2010-03-28 02:42:43 +00003137 }
3138
3139 // If the non-type template parameter has reference type, qualify the
3140 // resulting declaration reference with the extra qualifiers on the
3141 // type that the reference refers to.
3142 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3143 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3144
3145 return BuildDeclRefExpr(VD, T, Loc);
3146}
3147
3148/// \brief Construct a new expression that refers to the given
3149/// integral template argument with the given source-location
3150/// information.
3151///
3152/// This routine takes care of the mapping from an integral template
3153/// argument (which may have any integral type) to the appropriate
3154/// literal value.
3155Sema::OwningExprResult
3156Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3157 SourceLocation Loc) {
3158 assert(Arg.getKind() == TemplateArgument::Integral &&
3159 "Operation is only value for integral template arguments");
3160 QualType T = Arg.getIntegralType();
3161 if (T->isCharType() || T->isWideCharType())
3162 return Owned(new (Context) CharacterLiteral(
3163 Arg.getAsIntegral()->getZExtValue(),
3164 T->isWideCharType(),
3165 T,
3166 Loc));
3167 if (T->isBooleanType())
3168 return Owned(new (Context) CXXBoolLiteralExpr(
3169 Arg.getAsIntegral()->getBoolValue(),
3170 T,
3171 Loc));
3172
3173 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3174}
3175
3176
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003177/// \brief Determine whether the given template parameter lists are
3178/// equivalent.
3179///
Mike Stump11289f42009-09-09 15:08:12 +00003180/// \param New The new template parameter list, typically written in the
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003181/// source code as part of a new template declaration.
3182///
3183/// \param Old The old template parameter list, typically found via
3184/// name lookup of the template declared with this template parameter
3185/// list.
3186///
3187/// \param Complain If true, this routine will produce a diagnostic if
3188/// the template parameter lists are not equivalent.
3189///
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003190/// \param Kind describes how we are to match the template parameter lists.
Douglas Gregor85e0f662009-02-10 00:24:35 +00003191///
3192/// \param TemplateArgLoc If this source location is valid, then we
3193/// are actually checking the template parameter list of a template
3194/// argument (New) against the template parameter list of its
3195/// corresponding template template parameter (Old). We produce
3196/// slightly different diagnostics in this scenario.
3197///
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003198/// \returns True if the template parameter lists are equal, false
3199/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00003200bool
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003201Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3202 TemplateParameterList *Old,
3203 bool Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003204 TemplateParameterListEqualKind Kind,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003205 SourceLocation TemplateArgLoc) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003206 if (Old->size() != New->size()) {
3207 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003208 unsigned NextDiag = diag::err_template_param_list_different_arity;
3209 if (TemplateArgLoc.isValid()) {
3210 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3211 NextDiag = diag::note_template_param_list_different_arity;
Mike Stump11289f42009-09-09 15:08:12 +00003212 }
Douglas Gregor85e0f662009-02-10 00:24:35 +00003213 Diag(New->getTemplateLoc(), NextDiag)
3214 << (New->size() > Old->size())
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003215 << (Kind != TPL_TemplateMatch)
Douglas Gregor85e0f662009-02-10 00:24:35 +00003216 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003217 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003218 << (Kind != TPL_TemplateMatch)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003219 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3220 }
3221
3222 return false;
3223 }
3224
3225 for (TemplateParameterList::iterator OldParm = Old->begin(),
3226 OldParmEnd = Old->end(), NewParm = New->begin();
3227 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3228 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
Douglas Gregor23061de2009-06-24 16:50:40 +00003229 if (Complain) {
3230 unsigned NextDiag = diag::err_template_param_different_kind;
3231 if (TemplateArgLoc.isValid()) {
3232 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3233 NextDiag = diag::note_template_param_different_kind;
3234 }
3235 Diag((*NewParm)->getLocation(), NextDiag)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003236 << (Kind != TPL_TemplateMatch);
Douglas Gregor23061de2009-06-24 16:50:40 +00003237 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003238 << (Kind != TPL_TemplateMatch);
Douglas Gregor85e0f662009-02-10 00:24:35 +00003239 }
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003240 return false;
3241 }
3242
Douglas Gregor2e87ca22010-06-04 08:34:32 +00003243 if (TemplateTypeParmDecl *OldTTP
3244 = dyn_cast<TemplateTypeParmDecl>(*OldParm)) {
3245 // Template type parameters are equivalent if either both are template
3246 // type parameter packs or neither are (since we know we're at the same
3247 // index).
3248 TemplateTypeParmDecl *NewTTP = cast<TemplateTypeParmDecl>(*NewParm);
3249 if (OldTTP->isParameterPack() != NewTTP->isParameterPack()) {
3250 // FIXME: Implement the rules in C++0x [temp.arg.template]p5 that
3251 // allow one to match a template parameter pack in the template
3252 // parameter list of a template template parameter to one or more
3253 // template parameters in the template parameter list of the
3254 // corresponding template template argument.
3255 if (Complain) {
3256 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3257 if (TemplateArgLoc.isValid()) {
3258 Diag(TemplateArgLoc,
3259 diag::err_template_arg_template_params_mismatch);
3260 NextDiag = diag::note_template_parameter_pack_non_pack;
3261 }
3262 Diag(NewTTP->getLocation(), NextDiag)
3263 << 0 << NewTTP->isParameterPack();
3264 Diag(OldTTP->getLocation(), diag::note_template_parameter_pack_here)
3265 << 0 << OldTTP->isParameterPack();
3266 }
3267 return false;
3268 }
Mike Stump11289f42009-09-09 15:08:12 +00003269 } else if (NonTypeTemplateParmDecl *OldNTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003270 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3271 // The types of non-type template parameters must agree.
3272 NonTypeTemplateParmDecl *NewNTTP
3273 = cast<NonTypeTemplateParmDecl>(*NewParm);
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003274
3275 // If we are matching a template template argument to a template
3276 // template parameter and one of the non-type template parameter types
3277 // is dependent, then we must wait until template instantiation time
3278 // to actually compare the arguments.
3279 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3280 (OldNTTP->getType()->isDependentType() ||
3281 NewNTTP->getType()->isDependentType()))
3282 continue;
3283
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003284 if (Context.getCanonicalType(OldNTTP->getType()) !=
3285 Context.getCanonicalType(NewNTTP->getType())) {
3286 if (Complain) {
Douglas Gregor85e0f662009-02-10 00:24:35 +00003287 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3288 if (TemplateArgLoc.isValid()) {
Mike Stump11289f42009-09-09 15:08:12 +00003289 Diag(TemplateArgLoc,
Douglas Gregor85e0f662009-02-10 00:24:35 +00003290 diag::err_template_arg_template_params_mismatch);
3291 NextDiag = diag::note_template_nontype_parm_different_type;
3292 }
3293 Diag(NewNTTP->getLocation(), NextDiag)
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003294 << NewNTTP->getType()
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003295 << (Kind != TPL_TemplateMatch);
Mike Stump11289f42009-09-09 15:08:12 +00003296 Diag(OldNTTP->getLocation(),
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003297 diag::note_template_nontype_parm_prev_declaration)
3298 << OldNTTP->getType();
3299 }
3300 return false;
3301 }
3302 } else {
3303 // The template parameter lists of template template
3304 // parameters must agree.
Mike Stump11289f42009-09-09 15:08:12 +00003305 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003306 "Only template template parameters handled here");
Mike Stump11289f42009-09-09 15:08:12 +00003307 TemplateTemplateParmDecl *OldTTP
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003308 = cast<TemplateTemplateParmDecl>(*OldParm);
3309 TemplateTemplateParmDecl *NewTTP
3310 = cast<TemplateTemplateParmDecl>(*NewParm);
3311 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3312 OldTTP->getTemplateParameters(),
3313 Complain,
Douglas Gregor19ac2d62009-11-12 16:20:59 +00003314 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
Douglas Gregor85e0f662009-02-10 00:24:35 +00003315 TemplateArgLoc))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003316 return false;
3317 }
3318 }
3319
3320 return true;
3321}
3322
3323/// \brief Check whether a template can be declared within this scope.
3324///
3325/// If the template declaration is valid in this scope, returns
3326/// false. Otherwise, issues a diagnostic and returns true.
Mike Stump11289f42009-09-09 15:08:12 +00003327bool
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003328Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003329 // Find the nearest enclosing declaration scope.
3330 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3331 (S->getFlags() & Scope::TemplateParamScope) != 0)
3332 S = S->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00003333
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003334 // C++ [temp]p2:
3335 // A template-declaration can appear only as a namespace scope or
3336 // class scope declaration.
3337 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003338 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3339 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
Mike Stump11289f42009-09-09 15:08:12 +00003340 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003341 << TemplateParams->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003342
Eli Friedmandfbd0c42009-07-31 01:43:05 +00003343 while (Ctx && isa<LinkageSpecDecl>(Ctx))
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003344 Ctx = Ctx->getParent();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003345
3346 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3347 return false;
3348
Mike Stump11289f42009-09-09 15:08:12 +00003349 return Diag(TemplateParams->getTemplateLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003350 diag::err_template_outside_namespace_or_class_scope)
3351 << TemplateParams->getSourceRange();
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003352}
Douglas Gregor67a65642009-02-17 23:15:12 +00003353
Douglas Gregor54888652009-10-07 00:13:32 +00003354/// \brief Determine what kind of template specialization the given declaration
3355/// is.
3356static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3357 if (!D)
3358 return TSK_Undeclared;
3359
Douglas Gregorbbe8f462009-10-08 15:14:33 +00003360 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3361 return Record->getTemplateSpecializationKind();
Douglas Gregor54888652009-10-07 00:13:32 +00003362 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3363 return Function->getTemplateSpecializationKind();
Douglas Gregor86d142a2009-10-08 07:24:58 +00003364 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3365 return Var->getTemplateSpecializationKind();
3366
Douglas Gregor54888652009-10-07 00:13:32 +00003367 return TSK_Undeclared;
3368}
3369
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003370/// \brief Check whether a specialization is well-formed in the current
3371/// context.
Douglas Gregorf47b9112009-02-25 22:02:03 +00003372///
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003373/// This routine determines whether a template specialization can be declared
3374/// in the current context (C++ [temp.expl.spec]p2).
Douglas Gregor54888652009-10-07 00:13:32 +00003375///
3376/// \param S the semantic analysis object for which this check is being
3377/// performed.
3378///
3379/// \param Specialized the entity being specialized or instantiated, which
3380/// may be a kind of template (class template, function template, etc.) or
3381/// a member of a class template (member function, static data member,
3382/// member class).
3383///
3384/// \param PrevDecl the previous declaration of this entity, if any.
3385///
3386/// \param Loc the location of the explicit specialization or instantiation of
3387/// this entity.
3388///
3389/// \param IsPartialSpecialization whether this is a partial specialization of
3390/// a class template.
3391///
Douglas Gregor54888652009-10-07 00:13:32 +00003392/// \returns true if there was an error that we cannot recover from, false
3393/// otherwise.
3394static bool CheckTemplateSpecializationScope(Sema &S,
3395 NamedDecl *Specialized,
3396 NamedDecl *PrevDecl,
3397 SourceLocation Loc,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003398 bool IsPartialSpecialization) {
Douglas Gregor54888652009-10-07 00:13:32 +00003399 // Keep these "kind" numbers in sync with the %select statements in the
3400 // various diagnostics emitted by this routine.
3401 int EntityKind = 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003402 bool isTemplateSpecialization = false;
3403 if (isa<ClassTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003404 EntityKind = IsPartialSpecialization? 1 : 0;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003405 isTemplateSpecialization = true;
3406 } else if (isa<FunctionTemplateDecl>(Specialized)) {
Douglas Gregor54888652009-10-07 00:13:32 +00003407 EntityKind = 2;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003408 isTemplateSpecialization = true;
3409 } else if (isa<CXXMethodDecl>(Specialized))
Douglas Gregor54888652009-10-07 00:13:32 +00003410 EntityKind = 3;
3411 else if (isa<VarDecl>(Specialized))
3412 EntityKind = 4;
3413 else if (isa<RecordDecl>(Specialized))
3414 EntityKind = 5;
3415 else {
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003416 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3417 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregor54888652009-10-07 00:13:32 +00003418 return true;
3419 }
3420
Douglas Gregorf47b9112009-02-25 22:02:03 +00003421 // C++ [temp.expl.spec]p2:
3422 // An explicit specialization shall be declared in the namespace
3423 // of which the template is a member, or, for member templates, in
3424 // the namespace of which the enclosing class or enclosing class
3425 // template is a member. An explicit specialization of a member
3426 // function, member class or static data member of a class
3427 // template shall be declared in the namespace of which the class
3428 // template is a member. Such a declaration may also be a
3429 // definition. If the declaration is not a definition, the
3430 // specialization may be defined later in the name- space in which
3431 // the explicit specialization was declared, or in a namespace
3432 // that encloses the one in which the explicit specialization was
3433 // declared.
Douglas Gregor54888652009-10-07 00:13:32 +00003434 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3435 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003436 << Specialized;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003437 return true;
3438 }
Douglas Gregore4b05162009-10-07 17:21:34 +00003439
Douglas Gregor40fb7442009-10-07 17:30:37 +00003440 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3441 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003442 << Specialized;
Douglas Gregor40fb7442009-10-07 17:30:37 +00003443 return true;
3444 }
3445
Douglas Gregore4b05162009-10-07 17:21:34 +00003446 // C++ [temp.class.spec]p6:
3447 // A class template partial specialization may be declared or redeclared
3448 // in any namespace scope in which its definition may be defined (14.5.1
3449 // and 14.5.2).
Douglas Gregor54888652009-10-07 00:13:32 +00003450 bool ComplainedAboutScope = false;
Douglas Gregore4b05162009-10-07 17:21:34 +00003451 DeclContext *SpecializedContext
Douglas Gregor54888652009-10-07 00:13:32 +00003452 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
Douglas Gregore4b05162009-10-07 17:21:34 +00003453 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003454 if ((!PrevDecl ||
3455 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3456 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3457 // There is no prior declaration of this entity, so this
3458 // specialization must be in the same context as the template
3459 // itself.
3460 if (!DC->Equals(SpecializedContext)) {
3461 if (isa<TranslationUnitDecl>(SpecializedContext))
3462 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3463 << EntityKind << Specialized;
3464 else if (isa<NamespaceDecl>(SpecializedContext))
3465 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3466 << EntityKind << Specialized
3467 << cast<NamedDecl>(SpecializedContext);
3468
3469 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3470 ComplainedAboutScope = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003471 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003472 }
Douglas Gregor54888652009-10-07 00:13:32 +00003473
3474 // Make sure that this redeclaration (or definition) occurs in an enclosing
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003475 // namespace.
Douglas Gregor54888652009-10-07 00:13:32 +00003476 // Note that HandleDeclarator() performs this check for explicit
3477 // specializations of function templates, static data members, and member
3478 // functions, so we skip the check here for those kinds of entities.
3479 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
Douglas Gregore4b05162009-10-07 17:21:34 +00003480 // Should we refactor that check, so that it occurs later?
3481 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003482 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3483 isa<FunctionDecl>(Specialized))) {
Douglas Gregor54888652009-10-07 00:13:32 +00003484 if (isa<TranslationUnitDecl>(SpecializedContext))
3485 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3486 << EntityKind << Specialized;
3487 else if (isa<NamespaceDecl>(SpecializedContext))
3488 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3489 << EntityKind << Specialized
3490 << cast<NamedDecl>(SpecializedContext);
3491
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003492 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
Douglas Gregorf47b9112009-02-25 22:02:03 +00003493 }
Douglas Gregor54888652009-10-07 00:13:32 +00003494
3495 // FIXME: check for specialization-after-instantiation errors and such.
3496
Douglas Gregorf47b9112009-02-25 22:02:03 +00003497 return false;
3498}
Douglas Gregor54888652009-10-07 00:13:32 +00003499
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003500/// \brief Check the non-type template arguments of a class template
3501/// partial specialization according to C++ [temp.class.spec]p9.
3502///
Douglas Gregor09a30232009-06-12 22:08:06 +00003503/// \param TemplateParams the template parameters of the primary class
3504/// template.
3505///
3506/// \param TemplateArg the template arguments of the class template
3507/// partial specialization.
3508///
3509/// \param MirrorsPrimaryTemplate will be set true if the class
3510/// template partial specialization arguments are identical to the
3511/// implicit template arguments of the primary template. This is not
3512/// necessarily an error (C++0x), and it is left to the caller to diagnose
3513/// this condition when it is an error.
3514///
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003515/// \returns true if there was an error, false otherwise.
3516bool Sema::CheckClassTemplatePartialSpecializationArgs(
3517 TemplateParameterList *TemplateParams,
Anders Carlsson40c1d492009-06-13 18:20:51 +00003518 const TemplateArgumentListBuilder &TemplateArgs,
Douglas Gregor09a30232009-06-12 22:08:06 +00003519 bool &MirrorsPrimaryTemplate) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003520 // FIXME: the interface to this function will have to change to
3521 // accommodate variadic templates.
Douglas Gregor09a30232009-06-12 22:08:06 +00003522 MirrorsPrimaryTemplate = true;
Mike Stump11289f42009-09-09 15:08:12 +00003523
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003524 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
Mike Stump11289f42009-09-09 15:08:12 +00003525
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003526 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003527 // Determine whether the template argument list of the partial
3528 // specialization is identical to the implicit argument list of
3529 // the primary template. The caller may need to diagnostic this as
3530 // an error per C++ [temp.class.spec]p9b3.
3531 if (MirrorsPrimaryTemplate) {
Mike Stump11289f42009-09-09 15:08:12 +00003532 if (TemplateTypeParmDecl *TTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003533 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3534 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
Anders Carlsson40c1d492009-06-13 18:20:51 +00003535 Context.getCanonicalType(ArgList[I].getAsType()))
Douglas Gregor09a30232009-06-12 22:08:06 +00003536 MirrorsPrimaryTemplate = false;
3537 } else if (TemplateTemplateParmDecl *TTP
3538 = dyn_cast<TemplateTemplateParmDecl>(
3539 TemplateParams->getParam(I))) {
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003540 TemplateName Name = ArgList[I].getAsTemplate();
Mike Stump11289f42009-09-09 15:08:12 +00003541 TemplateTemplateParmDecl *ArgDecl
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003542 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
Douglas Gregor09a30232009-06-12 22:08:06 +00003543 if (!ArgDecl ||
3544 ArgDecl->getIndex() != TTP->getIndex() ||
3545 ArgDecl->getDepth() != TTP->getDepth())
3546 MirrorsPrimaryTemplate = false;
3547 }
3548 }
3549
Mike Stump11289f42009-09-09 15:08:12 +00003550 NonTypeTemplateParmDecl *Param
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003551 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
Douglas Gregor09a30232009-06-12 22:08:06 +00003552 if (!Param) {
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003553 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003554 }
3555
Anders Carlsson40c1d492009-06-13 18:20:51 +00003556 Expr *ArgExpr = ArgList[I].getAsExpr();
Douglas Gregor09a30232009-06-12 22:08:06 +00003557 if (!ArgExpr) {
3558 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003559 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003560 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003561
3562 // C++ [temp.class.spec]p8:
3563 // A non-type argument is non-specialized if it is the name of a
3564 // non-type parameter. All other non-type arguments are
3565 // specialized.
3566 //
3567 // Below, we check the two conditions that only apply to
3568 // specialized non-type arguments, so skip any non-specialized
3569 // arguments.
3570 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
Mike Stump11289f42009-09-09 15:08:12 +00003571 if (NonTypeTemplateParmDecl *NTTP
Douglas Gregor09a30232009-06-12 22:08:06 +00003572 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00003573 if (MirrorsPrimaryTemplate &&
Douglas Gregor09a30232009-06-12 22:08:06 +00003574 (Param->getIndex() != NTTP->getIndex() ||
3575 Param->getDepth() != NTTP->getDepth()))
3576 MirrorsPrimaryTemplate = false;
3577
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003578 continue;
Douglas Gregor09a30232009-06-12 22:08:06 +00003579 }
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003580
3581 // C++ [temp.class.spec]p9:
3582 // Within the argument list of a class template partial
3583 // specialization, the following restrictions apply:
3584 // -- A partially specialized non-type argument expression
3585 // shall not involve a template parameter of the partial
3586 // specialization except when the argument expression is a
3587 // simple identifier.
3588 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00003589 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003590 diag::err_dependent_non_type_arg_in_partial_spec)
3591 << ArgExpr->getSourceRange();
3592 return true;
3593 }
3594
3595 // -- The type of a template parameter corresponding to a
3596 // specialized non-type argument shall not be dependent on a
3597 // parameter of the specialization.
3598 if (Param->getType()->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003599 Diag(ArgExpr->getLocStart(),
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003600 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3601 << Param->getType()
3602 << ArgExpr->getSourceRange();
3603 Diag(Param->getLocation(), diag::note_template_param_here);
3604 return true;
3605 }
Douglas Gregor09a30232009-06-12 22:08:06 +00003606
3607 MirrorsPrimaryTemplate = false;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003608 }
3609
3610 return false;
3611}
3612
Douglas Gregorc854c662010-02-26 06:03:23 +00003613/// \brief Retrieve the previous declaration of the given declaration.
3614static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3615 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3616 return VD->getPreviousDeclaration();
3617 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3618 return FD->getPreviousDeclaration();
3619 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3620 return TD->getPreviousDeclaration();
3621 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3622 return TD->getPreviousDeclaration();
3623 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3624 return FTD->getPreviousDeclaration();
3625 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3626 return CTD->getPreviousDeclaration();
3627 return 0;
3628}
3629
Douglas Gregorc08f4892009-03-25 00:13:59 +00003630Sema::DeclResult
John McCall9bb74a52009-07-31 02:45:11 +00003631Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3632 TagUseKind TUK,
Mike Stump11289f42009-09-09 15:08:12 +00003633 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003634 CXXScopeSpec &SS,
Douglas Gregordc572a32009-03-30 22:58:21 +00003635 TemplateTy TemplateD,
Douglas Gregor67a65642009-02-17 23:15:12 +00003636 SourceLocation TemplateNameLoc,
3637 SourceLocation LAngleLoc,
Douglas Gregorc40290e2009-03-09 23:48:35 +00003638 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregor67a65642009-02-17 23:15:12 +00003639 SourceLocation RAngleLoc,
3640 AttributeList *Attr,
3641 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor2208a292009-09-26 20:57:03 +00003642 assert(TUK != TUK_Reference && "References are not specializations");
John McCall06f6fe8d2009-09-04 01:14:41 +00003643
Douglas Gregor67a65642009-02-17 23:15:12 +00003644 // Find the class template we're specializing
Douglas Gregordc572a32009-03-30 22:58:21 +00003645 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00003646 ClassTemplateDecl *ClassTemplate
Douglas Gregordd6c0352009-11-12 00:46:20 +00003647 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3648
3649 if (!ClassTemplate) {
3650 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3651 << (Name.getAsTemplateDecl() &&
3652 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3653 return true;
3654 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003655
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003656 bool isExplicitSpecialization = false;
Douglas Gregor2373c592009-05-31 09:31:02 +00003657 bool isPartialSpecialization = false;
3658
Douglas Gregorf47b9112009-02-25 22:02:03 +00003659 // Check the validity of the template headers that introduce this
3660 // template.
Douglas Gregor2208a292009-09-26 20:57:03 +00003661 // FIXME: We probably shouldn't complain about these headers for
3662 // friend declarations.
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003663 TemplateParameterList *TemplateParams
Mike Stump11289f42009-09-09 15:08:12 +00003664 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3665 (TemplateParameterList**)TemplateParameterLists.get(),
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003666 TemplateParameterLists.size(),
John McCalle820e5e2010-04-13 20:37:33 +00003667 TUK == TUK_Friend,
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003668 isExplicitSpecialization);
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003669 if (TemplateParams && TemplateParams->size() > 0) {
3670 isPartialSpecialization = true;
Douglas Gregorf47b9112009-02-25 22:02:03 +00003671
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003672 // C++ [temp.class.spec]p10:
3673 // The template parameter list of a specialization shall not
3674 // contain default template argument values.
3675 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3676 Decl *Param = TemplateParams->getParam(I);
3677 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3678 if (TTP->hasDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003679 Diag(TTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003680 diag::err_default_arg_in_partial_spec);
John McCall0ad16662009-10-29 08:12:44 +00003681 TTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003682 }
3683 } else if (NonTypeTemplateParmDecl *NTTP
3684 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3685 if (Expr *DefArg = NTTP->getDefaultArgument()) {
Mike Stump11289f42009-09-09 15:08:12 +00003686 Diag(NTTP->getDefaultArgumentLoc(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003687 diag::err_default_arg_in_partial_spec)
3688 << DefArg->getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003689 NTTP->removeDefaultArgument();
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003690 DefArg->Destroy(Context);
3691 }
3692 } else {
3693 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003694 if (TTP->hasDefaultArgument()) {
3695 Diag(TTP->getDefaultArgument().getLocation(),
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003696 diag::err_default_arg_in_partial_spec)
Douglas Gregor9167f8b2009-11-11 01:00:40 +00003697 << TTP->getDefaultArgument().getSourceRange();
Abramo Bagnara656e3002010-06-09 09:26:05 +00003698 TTP->removeDefaultArgument();
Douglas Gregord5222052009-06-12 19:43:02 +00003699 }
3700 }
3701 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003702 } else if (TemplateParams) {
3703 if (TUK == TUK_Friend)
3704 Diag(KWLoc, diag::err_template_spec_friend)
Douglas Gregora771f462010-03-31 17:46:05 +00003705 << FixItHint::CreateRemoval(
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00003706 SourceRange(TemplateParams->getTemplateLoc(),
3707 TemplateParams->getRAngleLoc()))
3708 << SourceRange(LAngleLoc, RAngleLoc);
3709 else
3710 isExplicitSpecialization = true;
3711 } else if (TUK != TUK_Friend) {
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003712 Diag(KWLoc, diag::err_template_spec_needs_header)
Douglas Gregora771f462010-03-31 17:46:05 +00003713 << FixItHint::CreateInsertion(KWLoc, "template<> ");
Douglas Gregor5c0405d2009-10-07 22:35:40 +00003714 isExplicitSpecialization = true;
3715 }
Douglas Gregorf47b9112009-02-25 22:02:03 +00003716
Douglas Gregor67a65642009-02-17 23:15:12 +00003717 // Check that the specialization uses the same tag kind as the
3718 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00003719 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3720 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
Douglas Gregord9034f02009-05-14 16:41:31 +00003721 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00003722 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00003723 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00003724 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregor170512f2009-04-01 23:51:29 +00003725 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00003726 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregor170512f2009-04-01 23:51:29 +00003727 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00003728 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregor67a65642009-02-17 23:15:12 +00003729 diag::note_previous_use);
3730 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3731 }
3732
Douglas Gregorc40290e2009-03-09 23:48:35 +00003733 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00003734 TemplateArgumentListInfo TemplateArgs;
3735 TemplateArgs.setLAngleLoc(LAngleLoc);
3736 TemplateArgs.setRAngleLoc(RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00003737 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003738
Douglas Gregor67a65642009-02-17 23:15:12 +00003739 // Check that the template argument list is well-formed for this
3740 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003741 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3742 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00003743 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3744 TemplateArgs, false, Converted))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003745 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003746
Mike Stump11289f42009-09-09 15:08:12 +00003747 assert((Converted.structuredSize() ==
Douglas Gregor67a65642009-02-17 23:15:12 +00003748 ClassTemplate->getTemplateParameters()->size()) &&
3749 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00003750
Douglas Gregor2373c592009-05-31 09:31:02 +00003751 // Find the class template (partial) specialization declaration that
Douglas Gregor67a65642009-02-17 23:15:12 +00003752 // corresponds to these arguments.
3753 llvm::FoldingSetNodeID ID;
Douglas Gregord5222052009-06-12 19:43:02 +00003754 if (isPartialSpecialization) {
Douglas Gregor09a30232009-06-12 22:08:06 +00003755 bool MirrorsPrimaryTemplate;
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003756 if (CheckClassTemplatePartialSpecializationArgs(
3757 ClassTemplate->getTemplateParameters(),
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003758 Converted, MirrorsPrimaryTemplate))
Douglas Gregor8cfd2ba2009-06-12 21:21:02 +00003759 return true;
3760
Douglas Gregor09a30232009-06-12 22:08:06 +00003761 if (MirrorsPrimaryTemplate) {
3762 // C++ [temp.class.spec]p9b3:
3763 //
Mike Stump11289f42009-09-09 15:08:12 +00003764 // -- The argument list of the specialization shall not be identical
3765 // to the implicit argument list of the primary template.
Douglas Gregor09a30232009-06-12 22:08:06 +00003766 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
John McCall9bb74a52009-07-31 02:45:11 +00003767 << (TUK == TUK_Definition)
Douglas Gregora771f462010-03-31 17:46:05 +00003768 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
John McCall9bb74a52009-07-31 02:45:11 +00003769 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
Douglas Gregor09a30232009-06-12 22:08:06 +00003770 ClassTemplate->getIdentifier(),
3771 TemplateNameLoc,
3772 Attr,
Douglas Gregor1d5e9f92009-08-25 17:23:04 +00003773 TemplateParams,
Douglas Gregor09a30232009-06-12 22:08:06 +00003774 AS_none);
3775 }
3776
Douglas Gregor2208a292009-09-26 20:57:03 +00003777 // FIXME: Diagnose friend partial specializations
3778
Douglas Gregor92354b62010-02-09 00:37:32 +00003779 if (!Name.isDependent() &&
3780 !TemplateSpecializationType::anyDependentTemplateArguments(
3781 TemplateArgs.getArgumentArray(),
3782 TemplateArgs.size())) {
3783 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3784 << ClassTemplate->getDeclName();
3785 isPartialSpecialization = false;
3786 } else {
3787 // FIXME: Template parameter list matters, too
3788 ClassTemplatePartialSpecializationDecl::Profile(ID,
3789 Converted.getFlatArguments(),
3790 Converted.flatSize(),
3791 Context);
3792 }
3793 }
3794
3795 if (!isPartialSpecialization)
Anders Carlsson8aa89d42009-06-05 03:43:12 +00003796 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003797 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00003798 Converted.flatSize(),
3799 Context);
Douglas Gregor67a65642009-02-17 23:15:12 +00003800 void *InsertPos = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00003801 ClassTemplateSpecializationDecl *PrevDecl = 0;
3802
3803 if (isPartialSpecialization)
3804 PrevDecl
Mike Stump11289f42009-09-09 15:08:12 +00003805 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor2373c592009-05-31 09:31:02 +00003806 InsertPos);
3807 else
3808 PrevDecl
3809 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
Douglas Gregor67a65642009-02-17 23:15:12 +00003810
3811 ClassTemplateSpecializationDecl *Specialization = 0;
3812
Douglas Gregorf47b9112009-02-25 22:02:03 +00003813 // Check whether we can declare a class template specialization in
3814 // the current scope.
Douglas Gregor2208a292009-09-26 20:57:03 +00003815 if (TUK != TUK_Friend &&
Douglas Gregor54888652009-10-07 00:13:32 +00003816 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00003817 TemplateNameLoc,
3818 isPartialSpecialization))
Douglas Gregorc08f4892009-03-25 00:13:59 +00003819 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00003820
Douglas Gregor15301382009-07-30 17:40:51 +00003821 // The canonical type
3822 QualType CanonType;
Douglas Gregor2208a292009-09-26 20:57:03 +00003823 if (PrevDecl &&
3824 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
Douglas Gregor92354b62010-02-09 00:37:32 +00003825 TUK == TUK_Friend)) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003826 // Since the only prior class template specialization with these
Douglas Gregor2208a292009-09-26 20:57:03 +00003827 // arguments was referenced but not declared, or we're only
3828 // referencing this specialization as a friend, reuse that
Douglas Gregor67a65642009-02-17 23:15:12 +00003829 // declaration node as our own, updating its source location to
3830 // reflect our new declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003831 Specialization = PrevDecl;
Douglas Gregor1e249f82009-02-25 22:18:32 +00003832 Specialization->setLocation(TemplateNameLoc);
Douglas Gregor67a65642009-02-17 23:15:12 +00003833 PrevDecl = 0;
Douglas Gregor15301382009-07-30 17:40:51 +00003834 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor2373c592009-05-31 09:31:02 +00003835 } else if (isPartialSpecialization) {
Douglas Gregor15301382009-07-30 17:40:51 +00003836 // Build the canonical type that describes the converted template
3837 // arguments of the class template partial specialization.
Douglas Gregor92354b62010-02-09 00:37:32 +00003838 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3839 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
Douglas Gregor15301382009-07-30 17:40:51 +00003840 Converted.getFlatArguments(),
3841 Converted.flatSize());
3842
Douglas Gregor2373c592009-05-31 09:31:02 +00003843 // Create a new class template partial specialization declaration node.
Douglas Gregor2373c592009-05-31 09:31:02 +00003844 ClassTemplatePartialSpecializationDecl *PrevPartial
3845 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
Douglas Gregor407e9612010-04-30 05:56:50 +00003846 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3847 : ClassTemplate->getPartialSpecializations().size();
Mike Stump11289f42009-09-09 15:08:12 +00003848 ClassTemplatePartialSpecializationDecl *Partial
Douglas Gregore9029562010-05-06 00:28:52 +00003849 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
Douglas Gregor2373c592009-05-31 09:31:02 +00003850 ClassTemplate->getDeclContext(),
Anders Carlsson1b28c3e2009-06-05 04:06:48 +00003851 TemplateNameLoc,
3852 TemplateParams,
3853 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003854 Converted,
John McCall6b51f282009-11-23 01:53:49 +00003855 TemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00003856 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00003857 PrevPartial,
3858 SequenceNumber);
John McCall3e11ebe2010-03-15 10:12:16 +00003859 SetNestedNameSpecifier(Partial, SS);
Douglas Gregor2373c592009-05-31 09:31:02 +00003860
3861 if (PrevPartial) {
3862 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3863 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3864 } else {
3865 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3866 }
3867 Specialization = Partial;
Douglas Gregor91772d12009-06-13 00:26:55 +00003868
Douglas Gregor21610382009-10-29 00:04:11 +00003869 // If we are providing an explicit specialization of a member class
3870 // template specialization, make a note of that.
3871 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3872 PrevPartial->setMemberSpecialization();
3873
Douglas Gregor91772d12009-06-13 00:26:55 +00003874 // Check that all of the template parameters of the class template
3875 // partial specialization are deducible from the template
3876 // arguments. If not, this class template partial specialization
3877 // will never be used.
3878 llvm::SmallVector<bool, 8> DeducibleParams;
3879 DeducibleParams.resize(TemplateParams->size());
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003880 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
Douglas Gregor21610382009-10-29 00:04:11 +00003881 TemplateParams->getDepth(),
Douglas Gregore1d2ef32009-09-14 21:25:05 +00003882 DeducibleParams);
Douglas Gregor91772d12009-06-13 00:26:55 +00003883 unsigned NumNonDeducible = 0;
3884 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3885 if (!DeducibleParams[I])
3886 ++NumNonDeducible;
3887
3888 if (NumNonDeducible) {
3889 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3890 << (NumNonDeducible > 1)
3891 << SourceRange(TemplateNameLoc, RAngleLoc);
3892 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3893 if (!DeducibleParams[I]) {
3894 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3895 if (Param->getDeclName())
Mike Stump11289f42009-09-09 15:08:12 +00003896 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003897 diag::note_partial_spec_unused_parameter)
3898 << Param->getDeclName();
3899 else
Mike Stump11289f42009-09-09 15:08:12 +00003900 Diag(Param->getLocation(),
Douglas Gregor91772d12009-06-13 00:26:55 +00003901 diag::note_partial_spec_unused_parameter)
3902 << std::string("<anonymous>");
3903 }
3904 }
3905 }
Douglas Gregor67a65642009-02-17 23:15:12 +00003906 } else {
3907 // Create a new class template specialization declaration node for
Douglas Gregor2208a292009-09-26 20:57:03 +00003908 // this explicit specialization or friend declaration.
Douglas Gregor67a65642009-02-17 23:15:12 +00003909 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00003910 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregor67a65642009-02-17 23:15:12 +00003911 ClassTemplate->getDeclContext(),
3912 TemplateNameLoc,
Mike Stump11289f42009-09-09 15:08:12 +00003913 ClassTemplate,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00003914 Converted,
Douglas Gregor67a65642009-02-17 23:15:12 +00003915 PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00003916 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregor67a65642009-02-17 23:15:12 +00003917
3918 if (PrevDecl) {
3919 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3920 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3921 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003922 ClassTemplate->getSpecializations().InsertNode(Specialization,
Douglas Gregor67a65642009-02-17 23:15:12 +00003923 InsertPos);
3924 }
Douglas Gregor15301382009-07-30 17:40:51 +00003925
3926 CanonType = Context.getTypeDeclType(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003927 }
3928
Douglas Gregor06db9f52009-10-12 20:18:28 +00003929 // C++ [temp.expl.spec]p6:
3930 // If a template, a member template or the member of a class template is
3931 // explicitly specialized then that specialization shall be declared
3932 // before the first use of that specialization that would cause an implicit
3933 // instantiation to take place, in every translation unit in which such a
3934 // use occurs; no diagnostic is required.
3935 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
Douglas Gregorc854c662010-02-26 06:03:23 +00003936 bool Okay = false;
3937 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3938 // Is there any previous explicit specialization declaration?
3939 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3940 Okay = true;
3941 break;
3942 }
3943 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003944
Douglas Gregorc854c662010-02-26 06:03:23 +00003945 if (!Okay) {
3946 SourceRange Range(TemplateNameLoc, RAngleLoc);
3947 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3948 << Context.getTypeDeclType(Specialization) << Range;
3949
3950 Diag(PrevDecl->getPointOfInstantiation(),
3951 diag::note_instantiation_required_here)
3952 << (PrevDecl->getTemplateSpecializationKind()
Douglas Gregor06db9f52009-10-12 20:18:28 +00003953 != TSK_ImplicitInstantiation);
Douglas Gregorc854c662010-02-26 06:03:23 +00003954 return true;
3955 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00003956 }
3957
Douglas Gregor2208a292009-09-26 20:57:03 +00003958 // If this is not a friend, note that this is an explicit specialization.
3959 if (TUK != TUK_Friend)
3960 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00003961
3962 // Check that this isn't a redefinition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003963 if (TUK == TUK_Definition) {
Douglas Gregor0a5a2212010-02-11 01:04:33 +00003964 if (RecordDecl *Def = Specialization->getDefinition()) {
Douglas Gregor67a65642009-02-17 23:15:12 +00003965 SourceRange Range(TemplateNameLoc, RAngleLoc);
Mike Stump11289f42009-09-09 15:08:12 +00003966 Diag(TemplateNameLoc, diag::err_redefinition)
Douglas Gregor2373c592009-05-31 09:31:02 +00003967 << Context.getTypeDeclType(Specialization) << Range;
Douglas Gregor67a65642009-02-17 23:15:12 +00003968 Diag(Def->getLocation(), diag::note_previous_definition);
3969 Specialization->setInvalidDecl();
Douglas Gregorc08f4892009-03-25 00:13:59 +00003970 return true;
Douglas Gregor67a65642009-02-17 23:15:12 +00003971 }
3972 }
3973
Douglas Gregord56a91e2009-02-26 22:19:44 +00003974 // Build the fully-sugared type for this class template
3975 // specialization as the user wrote in the specialization
3976 // itself. This means that we'll pretty-print the type retrieved
3977 // from the specialization's declaration the way that the user
3978 // actually wrote the specialization, rather than formatting the
3979 // name based on the "canonical" representation used to store the
3980 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00003981 TypeSourceInfo *WrittenTy
3982 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3983 TemplateArgs, CanonType);
Douglas Gregor2208a292009-09-26 20:57:03 +00003984 if (TUK != TUK_Friend)
3985 Specialization->setTypeAsWritten(WrittenTy);
Douglas Gregorc40290e2009-03-09 23:48:35 +00003986 TemplateArgsIn.release();
Douglas Gregor67a65642009-02-17 23:15:12 +00003987
Douglas Gregor1e249f82009-02-25 22:18:32 +00003988 // C++ [temp.expl.spec]p9:
3989 // A template explicit specialization is in the scope of the
3990 // namespace in which the template was defined.
3991 //
3992 // We actually implement this paragraph where we set the semantic
3993 // context (in the creation of the ClassTemplateSpecializationDecl),
3994 // but we also maintain the lexical context where the actual
3995 // definition occurs.
Douglas Gregor67a65642009-02-17 23:15:12 +00003996 Specialization->setLexicalDeclContext(CurContext);
Mike Stump11289f42009-09-09 15:08:12 +00003997
Douglas Gregor67a65642009-02-17 23:15:12 +00003998 // We may be starting the definition of this specialization.
John McCall9bb74a52009-07-31 02:45:11 +00003999 if (TUK == TUK_Definition)
Douglas Gregor67a65642009-02-17 23:15:12 +00004000 Specialization->startDefinition();
4001
Douglas Gregor2208a292009-09-26 20:57:03 +00004002 if (TUK == TUK_Friend) {
4003 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4004 TemplateNameLoc,
John McCall15ad0962010-03-25 18:04:51 +00004005 WrittenTy,
Douglas Gregor2208a292009-09-26 20:57:03 +00004006 /*FIXME:*/KWLoc);
4007 Friend->setAccess(AS_public);
4008 CurContext->addDecl(Friend);
4009 } else {
4010 // Add the specialization into its lexical context, so that it can
4011 // be seen when iterating through the list of declarations in that
4012 // context. However, specializations are not found by name lookup.
4013 CurContext->addDecl(Specialization);
4014 }
Chris Lattner83f095c2009-03-28 19:18:32 +00004015 return DeclPtrTy::make(Specialization);
Douglas Gregor67a65642009-02-17 23:15:12 +00004016}
Douglas Gregor333489b2009-03-27 23:10:48 +00004017
Mike Stump11289f42009-09-09 15:08:12 +00004018Sema::DeclPtrTy
4019Sema::ActOnTemplateDeclarator(Scope *S,
Douglas Gregorb52fabb2009-06-23 23:11:28 +00004020 MultiTemplateParamsArg TemplateParameterLists,
4021 Declarator &D) {
4022 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4023}
4024
Mike Stump11289f42009-09-09 15:08:12 +00004025Sema::DeclPtrTy
4026Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004027 MultiTemplateParamsArg TemplateParameterLists,
4028 Declarator &D) {
4029 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4030 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4031 "Not a function declarator!");
4032 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Mike Stump11289f42009-09-09 15:08:12 +00004033
Douglas Gregor17a7c122009-06-24 00:54:41 +00004034 if (FTI.hasPrototype) {
Mike Stump11289f42009-09-09 15:08:12 +00004035 // FIXME: Diagnose arguments without names in C.
Douglas Gregor17a7c122009-06-24 00:54:41 +00004036 }
Mike Stump11289f42009-09-09 15:08:12 +00004037
Douglas Gregor17a7c122009-06-24 00:54:41 +00004038 Scope *ParentScope = FnBodyScope->getParent();
Mike Stump11289f42009-09-09 15:08:12 +00004039
4040 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
Douglas Gregor17a7c122009-06-24 00:54:41 +00004041 move(TemplateParameterLists),
4042 /*IsFunctionDefinition=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004043 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregord8d297c2009-07-21 23:53:31 +00004044 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
Mike Stump11289f42009-09-09 15:08:12 +00004045 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004046 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
Douglas Gregord8d297c2009-07-21 23:53:31 +00004047 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4048 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004049 return DeclPtrTy();
Douglas Gregor17a7c122009-06-24 00:54:41 +00004050}
4051
John McCall4f7ced62010-02-11 01:33:53 +00004052/// \brief Strips various properties off an implicit instantiation
4053/// that has just been explicitly specialized.
4054static void StripImplicitInstantiation(NamedDecl *D) {
4055 D->invalidateAttrs();
4056
4057 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4058 FD->setInlineSpecified(false);
4059 }
4060}
4061
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004062/// \brief Diagnose cases where we have an explicit template specialization
4063/// before/after an explicit template instantiation, producing diagnostics
4064/// for those cases where they are required and determining whether the
4065/// new specialization/instantiation will have any effect.
4066///
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004067/// \param NewLoc the location of the new explicit specialization or
4068/// instantiation.
4069///
4070/// \param NewTSK the kind of the new explicit specialization or instantiation.
4071///
4072/// \param PrevDecl the previous declaration of the entity.
4073///
4074/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4075///
4076/// \param PrevPointOfInstantiation if valid, indicates where the previus
4077/// declaration was instantiated (either implicitly or explicitly).
4078///
4079/// \param SuppressNew will be set to true to indicate that the new
4080/// specialization or instantiation has no effect and should be ignored.
4081///
4082/// \returns true if there was an error that should prevent the introduction of
4083/// the new declaration into the AST, false otherwise.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004084bool
4085Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4086 TemplateSpecializationKind NewTSK,
4087 NamedDecl *PrevDecl,
4088 TemplateSpecializationKind PrevTSK,
4089 SourceLocation PrevPointOfInstantiation,
4090 bool &SuppressNew) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004091 SuppressNew = false;
4092
4093 switch (NewTSK) {
4094 case TSK_Undeclared:
4095 case TSK_ImplicitInstantiation:
4096 assert(false && "Don't check implicit instantiations here");
4097 return false;
4098
4099 case TSK_ExplicitSpecialization:
4100 switch (PrevTSK) {
4101 case TSK_Undeclared:
4102 case TSK_ExplicitSpecialization:
4103 // Okay, we're just specializing something that is either already
4104 // explicitly specialized or has merely been mentioned without any
4105 // instantiation.
4106 return false;
4107
4108 case TSK_ImplicitInstantiation:
4109 if (PrevPointOfInstantiation.isInvalid()) {
4110 // The declaration itself has not actually been instantiated, so it is
4111 // still okay to specialize it.
John McCall4f7ced62010-02-11 01:33:53 +00004112 StripImplicitInstantiation(PrevDecl);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004113 return false;
4114 }
4115 // Fall through
4116
4117 case TSK_ExplicitInstantiationDeclaration:
4118 case TSK_ExplicitInstantiationDefinition:
4119 assert((PrevTSK == TSK_ImplicitInstantiation ||
4120 PrevPointOfInstantiation.isValid()) &&
4121 "Explicit instantiation without point of instantiation?");
4122
4123 // C++ [temp.expl.spec]p6:
4124 // If a template, a member template or the member of a class template
4125 // is explicitly specialized then that specialization shall be declared
4126 // before the first use of that specialization that would cause an
4127 // implicit instantiation to take place, in every translation unit in
4128 // which such a use occurs; no diagnostic is required.
Douglas Gregorc854c662010-02-26 06:03:23 +00004129 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4130 // Is there any previous explicit specialization declaration?
4131 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4132 return false;
4133 }
4134
Douglas Gregor1d957a32009-10-27 18:42:08 +00004135 Diag(NewLoc, diag::err_specialization_after_instantiation)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004136 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004137 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004138 << (PrevTSK != TSK_ImplicitInstantiation);
4139
4140 return true;
4141 }
4142 break;
4143
4144 case TSK_ExplicitInstantiationDeclaration:
4145 switch (PrevTSK) {
4146 case TSK_ExplicitInstantiationDeclaration:
4147 // This explicit instantiation declaration is redundant (that's okay).
4148 SuppressNew = true;
4149 return false;
4150
4151 case TSK_Undeclared:
4152 case TSK_ImplicitInstantiation:
4153 // We're explicitly instantiating something that may have already been
4154 // implicitly instantiated; that's fine.
4155 return false;
4156
4157 case TSK_ExplicitSpecialization:
4158 // C++0x [temp.explicit]p4:
4159 // For a given set of template parameters, if an explicit instantiation
4160 // of a template appears after a declaration of an explicit
4161 // specialization for that template, the explicit instantiation has no
4162 // effect.
John McCall6b21eb52010-03-02 23:09:38 +00004163 SuppressNew = true;
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004164 return false;
4165
4166 case TSK_ExplicitInstantiationDefinition:
4167 // C++0x [temp.explicit]p10:
4168 // If an entity is the subject of both an explicit instantiation
4169 // declaration and an explicit instantiation definition in the same
4170 // translation unit, the definition shall follow the declaration.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004171 Diag(NewLoc,
4172 diag::err_explicit_instantiation_declaration_after_definition);
4173 Diag(PrevPointOfInstantiation,
4174 diag::note_explicit_instantiation_definition_here);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004175 assert(PrevPointOfInstantiation.isValid() &&
4176 "Explicit instantiation without point of instantiation?");
4177 SuppressNew = true;
4178 return false;
4179 }
4180 break;
4181
4182 case TSK_ExplicitInstantiationDefinition:
4183 switch (PrevTSK) {
4184 case TSK_Undeclared:
4185 case TSK_ImplicitInstantiation:
4186 // We're explicitly instantiating something that may have already been
4187 // implicitly instantiated; that's fine.
4188 return false;
4189
4190 case TSK_ExplicitSpecialization:
4191 // C++ DR 259, C++0x [temp.explicit]p4:
4192 // For a given set of template parameters, if an explicit
4193 // instantiation of a template appears after a declaration of
4194 // an explicit specialization for that template, the explicit
4195 // instantiation has no effect.
4196 //
4197 // In C++98/03 mode, we only give an extension warning here, because it
Douglas Gregor06aa50412010-04-09 21:02:29 +00004198 // is not harmful to try to explicitly instantiate something that
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004199 // has been explicitly specialized.
Douglas Gregor1d957a32009-10-27 18:42:08 +00004200 if (!getLangOptions().CPlusPlus0x) {
4201 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004202 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004203 Diag(PrevDecl->getLocation(),
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004204 diag::note_previous_template_specialization);
4205 }
4206 SuppressNew = true;
4207 return false;
4208
4209 case TSK_ExplicitInstantiationDeclaration:
4210 // We're explicity instantiating a definition for something for which we
4211 // were previously asked to suppress instantiations. That's fine.
4212 return false;
4213
4214 case TSK_ExplicitInstantiationDefinition:
4215 // C++0x [temp.spec]p5:
4216 // For a given template and a given set of template-arguments,
4217 // - an explicit instantiation definition shall appear at most once
4218 // in a program,
Douglas Gregor1d957a32009-10-27 18:42:08 +00004219 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004220 << PrevDecl;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004221 Diag(PrevPointOfInstantiation,
4222 diag::note_previous_explicit_instantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004223 SuppressNew = true;
4224 return false;
4225 }
4226 break;
4227 }
4228
4229 assert(false && "Missing specialization/instantiation case?");
4230
4231 return false;
4232}
4233
John McCallb9c78482010-04-08 09:05:18 +00004234/// \brief Perform semantic analysis for the given dependent function
4235/// template specialization. The only possible way to get a dependent
4236/// function template specialization is with a friend declaration,
4237/// like so:
4238///
4239/// template <class T> void foo(T);
4240/// template <class T> class A {
4241/// friend void foo<>(T);
4242/// };
4243///
4244/// There really isn't any useful analysis we can do here, so we
4245/// just store the information.
4246bool
4247Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4248 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4249 LookupResult &Previous) {
4250 // Remove anything from Previous that isn't a function template in
4251 // the correct context.
4252 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4253 LookupResult::Filter F = Previous.makeFilter();
4254 while (F.hasNext()) {
4255 NamedDecl *D = F.next()->getUnderlyingDecl();
4256 if (!isa<FunctionTemplateDecl>(D) ||
4257 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4258 F.erase();
4259 }
4260 F.done();
4261
4262 // Should this be diagnosed here?
4263 if (Previous.empty()) return true;
4264
4265 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4266 ExplicitTemplateArgs);
4267 return false;
4268}
4269
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004270/// \brief Perform semantic analysis for the given function template
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004271/// specialization.
4272///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004273/// This routine performs all of the semantic analysis required for an
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004274/// explicit function template specialization. On successful completion,
4275/// the function declaration \p FD will become a function template
4276/// specialization.
4277///
4278/// \param FD the function declaration, which will be updated to become a
4279/// function template specialization.
4280///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004281/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4282/// if any. Note that this may be valid info even when 0 arguments are
4283/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4284/// as it anyway contains info on the angle brackets locations.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004285///
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004286/// \param PrevDecl the set of declarations that may be specialized by
4287/// this function specialization.
4288bool
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004289Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
John McCall6b51f282009-11-23 01:53:49 +00004290 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall1f82f242009-11-18 22:49:29 +00004291 LookupResult &Previous) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004292 // The set of function template specializations that could match this
4293 // explicit function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00004294 UnresolvedSet<8> Candidates;
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004295
4296 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
John McCall1f82f242009-11-18 22:49:29 +00004297 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4298 I != E; ++I) {
4299 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4300 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004301 // Only consider templates found within the same semantic lookup scope as
4302 // FD.
4303 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4304 continue;
4305
4306 // C++ [temp.expl.spec]p11:
4307 // A trailing template-argument can be left unspecified in the
4308 // template-id naming an explicit function template specialization
4309 // provided it can be deduced from the function argument type.
4310 // Perform template argument deduction to determine whether we may be
4311 // specializing this template.
4312 // FIXME: It is somewhat wasteful to build
John McCallbc077cf2010-02-08 23:07:23 +00004313 TemplateDeductionInfo Info(Context, FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004314 FunctionDecl *Specialization = 0;
4315 if (TemplateDeductionResult TDK
John McCall6b51f282009-11-23 01:53:49 +00004316 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004317 FD->getType(),
4318 Specialization,
4319 Info)) {
4320 // FIXME: Template argument deduction failed; record why it failed, so
4321 // that we can provide nifty diagnostics.
4322 (void)TDK;
4323 continue;
4324 }
4325
4326 // Record this candidate.
John McCall58cc69d2010-01-27 01:50:18 +00004327 Candidates.addDecl(Specialization, I.getAccess());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004328 }
4329 }
4330
Douglas Gregor5de279c2009-09-26 03:41:46 +00004331 // Find the most specialized function template.
John McCall58cc69d2010-01-27 01:50:18 +00004332 UnresolvedSetIterator Result
4333 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4334 TPOC_Other, FD->getLocation(),
Douglas Gregor89336232010-03-29 23:34:08 +00004335 PDiag(diag::err_function_template_spec_no_match)
Douglas Gregor5de279c2009-09-26 03:41:46 +00004336 << FD->getDeclName(),
Douglas Gregor89336232010-03-29 23:34:08 +00004337 PDiag(diag::err_function_template_spec_ambiguous)
John McCall6b51f282009-11-23 01:53:49 +00004338 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
Douglas Gregor89336232010-03-29 23:34:08 +00004339 PDiag(diag::note_function_template_spec_matched));
John McCall58cc69d2010-01-27 01:50:18 +00004340 if (Result == Candidates.end())
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004341 return true;
John McCall58cc69d2010-01-27 01:50:18 +00004342
4343 // Ignore access information; it doesn't figure into redeclaration checking.
4344 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor06aa50412010-04-09 21:02:29 +00004345 Specialization->setLocation(FD->getLocation());
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004346
4347 // FIXME: Check if the prior specialization has a point of instantiation.
Douglas Gregor06db9f52009-10-12 20:18:28 +00004348 // If so, we have run afoul of .
John McCall816d75b2010-03-24 07:46:06 +00004349
4350 // If this is a friend declaration, then we're not really declaring
4351 // an explicit specialization.
4352 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004353
Douglas Gregor54888652009-10-07 00:13:32 +00004354 // Check the scope of this explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004355 if (!isFriend &&
4356 CheckTemplateSpecializationScope(*this,
Douglas Gregor54888652009-10-07 00:13:32 +00004357 Specialization->getPrimaryTemplate(),
4358 Specialization, FD->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004359 false))
Douglas Gregor54888652009-10-07 00:13:32 +00004360 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004361
4362 // C++ [temp.expl.spec]p6:
4363 // If a template, a member template or the member of a class template is
Douglas Gregor1d957a32009-10-27 18:42:08 +00004364 // explicitly specialized then that specialization shall be declared
Douglas Gregor06db9f52009-10-12 20:18:28 +00004365 // before the first use of that specialization that would cause an implicit
4366 // instantiation to take place, in every translation unit in which such a
4367 // use occurs; no diagnostic is required.
4368 FunctionTemplateSpecializationInfo *SpecInfo
4369 = Specialization->getTemplateSpecializationInfo();
4370 assert(SpecInfo && "Function template specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004371
4372 bool SuppressNew = false;
John McCall816d75b2010-03-24 07:46:06 +00004373 if (!isFriend &&
4374 CheckSpecializationInstantiationRedecl(FD->getLocation(),
John McCall4f7ced62010-02-11 01:33:53 +00004375 TSK_ExplicitSpecialization,
4376 Specialization,
4377 SpecInfo->getTemplateSpecializationKind(),
4378 SpecInfo->getPointOfInstantiation(),
4379 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004380 return true;
Douglas Gregor54888652009-10-07 00:13:32 +00004381
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004382 // Mark the prior declaration as an explicit specialization, so that later
4383 // clients know that this is an explicit specialization.
John McCall816d75b2010-03-24 07:46:06 +00004384 if (!isFriend)
4385 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004386
4387 // Turn the given function declaration into a function template
4388 // specialization, with the template arguments from the previous
4389 // specialization.
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004390 // Take copies of (semantic and syntactic) template argument lists.
4391 const TemplateArgumentList* TemplArgs = new (Context)
4392 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4393 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4394 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
Douglas Gregord5058122010-02-11 01:19:42 +00004395 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
Abramo Bagnara02ccd282010-05-20 15:32:11 +00004396 TemplArgs, /*InsertPos=*/0,
4397 SpecInfo->getTemplateSpecializationKind(),
4398 TemplArgsAsWritten);
4399
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004400 // The "previous declaration" for this function template specialization is
4401 // the prior function template specialization.
John McCall1f82f242009-11-18 22:49:29 +00004402 Previous.clear();
4403 Previous.addDecl(Specialization);
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004404 return false;
4405}
4406
Douglas Gregor86d142a2009-10-08 07:24:58 +00004407/// \brief Perform semantic analysis for the given non-template member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004408/// specialization.
4409///
4410/// This routine performs all of the semantic analysis required for an
4411/// explicit member function specialization. On successful completion,
4412/// the function declaration \p FD will become a member function
4413/// specialization.
4414///
Douglas Gregor86d142a2009-10-08 07:24:58 +00004415/// \param Member the member declaration, which will be updated to become a
4416/// specialization.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004417///
John McCall1f82f242009-11-18 22:49:29 +00004418/// \param Previous the set of declarations, one of which may be specialized
4419/// by this function specialization; the set will be modified to contain the
4420/// redeclared member.
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004421bool
John McCall1f82f242009-11-18 22:49:29 +00004422Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004423 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
John McCalle820e5e2010-04-13 20:37:33 +00004424
Douglas Gregor86d142a2009-10-08 07:24:58 +00004425 // Try to find the member we are instantiating.
4426 NamedDecl *Instantiation = 0;
4427 NamedDecl *InstantiatedFrom = 0;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004428 MemberSpecializationInfo *MSInfo = 0;
4429
John McCall1f82f242009-11-18 22:49:29 +00004430 if (Previous.empty()) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004431 // Nowhere to look anyway.
4432 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004433 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4434 I != E; ++I) {
4435 NamedDecl *D = (*I)->getUnderlyingDecl();
4436 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004437 if (Context.hasSameType(Function->getType(), Method->getType())) {
4438 Instantiation = Method;
4439 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004440 MSInfo = Method->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004441 break;
4442 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004443 }
4444 }
Douglas Gregor86d142a2009-10-08 07:24:58 +00004445 } else if (isa<VarDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004446 VarDecl *PrevVar;
4447 if (Previous.isSingleResult() &&
4448 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
Douglas Gregor86d142a2009-10-08 07:24:58 +00004449 if (PrevVar->isStaticDataMember()) {
John McCall1f82f242009-11-18 22:49:29 +00004450 Instantiation = PrevVar;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004451 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004452 MSInfo = PrevVar->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004453 }
4454 } else if (isa<RecordDecl>(Member)) {
John McCall1f82f242009-11-18 22:49:29 +00004455 CXXRecordDecl *PrevRecord;
4456 if (Previous.isSingleResult() &&
4457 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4458 Instantiation = PrevRecord;
Douglas Gregor86d142a2009-10-08 07:24:58 +00004459 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
Douglas Gregor06db9f52009-10-12 20:18:28 +00004460 MSInfo = PrevRecord->getMemberSpecializationInfo();
Douglas Gregor86d142a2009-10-08 07:24:58 +00004461 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004462 }
4463
4464 if (!Instantiation) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00004465 // There is no previous declaration that matches. Since member
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004466 // specializations are always out-of-line, the caller will complain about
4467 // this mismatch later.
4468 return false;
4469 }
John McCalle820e5e2010-04-13 20:37:33 +00004470
4471 // If this is a friend, just bail out here before we start turning
4472 // things into explicit specializations.
4473 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4474 // Preserve instantiation information.
4475 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4476 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4477 cast<CXXMethodDecl>(InstantiatedFrom),
4478 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4479 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4480 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4481 cast<CXXRecordDecl>(InstantiatedFrom),
4482 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4483 }
4484
4485 Previous.clear();
4486 Previous.addDecl(Instantiation);
4487 return false;
4488 }
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004489
Douglas Gregor86d142a2009-10-08 07:24:58 +00004490 // Make sure that this is a specialization of a member.
4491 if (!InstantiatedFrom) {
4492 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4493 << Member;
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004494 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4495 return true;
4496 }
4497
Douglas Gregor06db9f52009-10-12 20:18:28 +00004498 // C++ [temp.expl.spec]p6:
4499 // If a template, a member template or the member of a class template is
4500 // explicitly specialized then that spe- cialization shall be declared
4501 // before the first use of that specialization that would cause an implicit
4502 // instantiation to take place, in every translation unit in which such a
4503 // use occurs; no diagnostic is required.
4504 assert(MSInfo && "Member specialization info missing?");
John McCall4f7ced62010-02-11 01:33:53 +00004505
4506 bool SuppressNew = false;
4507 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4508 TSK_ExplicitSpecialization,
4509 Instantiation,
4510 MSInfo->getTemplateSpecializationKind(),
4511 MSInfo->getPointOfInstantiation(),
4512 SuppressNew))
Douglas Gregor06db9f52009-10-12 20:18:28 +00004513 return true;
Douglas Gregor06db9f52009-10-12 20:18:28 +00004514
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004515 // Check the scope of this explicit specialization.
4516 if (CheckTemplateSpecializationScope(*this,
Douglas Gregor86d142a2009-10-08 07:24:58 +00004517 InstantiatedFrom,
4518 Instantiation, Member->getLocation(),
Douglas Gregorba8e1ac2009-10-14 23:50:59 +00004519 false))
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004520 return true;
Douglas Gregord801b062009-10-07 23:56:10 +00004521
Douglas Gregor86d142a2009-10-08 07:24:58 +00004522 // Note that this is an explicit instantiation of a member.
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004523 // the original declaration to note that it is an explicit specialization
4524 // (if it was previously an implicit instantiation). This latter step
4525 // makes bookkeeping easier.
Douglas Gregor86d142a2009-10-08 07:24:58 +00004526 if (isa<FunctionDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004527 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4528 if (InstantiationFunction->getTemplateSpecializationKind() ==
4529 TSK_ImplicitInstantiation) {
4530 InstantiationFunction->setTemplateSpecializationKind(
4531 TSK_ExplicitSpecialization);
4532 InstantiationFunction->setLocation(Member->getLocation());
4533 }
4534
Douglas Gregor86d142a2009-10-08 07:24:58 +00004535 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4536 cast<CXXMethodDecl>(InstantiatedFrom),
4537 TSK_ExplicitSpecialization);
4538 } else if (isa<VarDecl>(Member)) {
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004539 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4540 if (InstantiationVar->getTemplateSpecializationKind() ==
4541 TSK_ImplicitInstantiation) {
4542 InstantiationVar->setTemplateSpecializationKind(
4543 TSK_ExplicitSpecialization);
4544 InstantiationVar->setLocation(Member->getLocation());
4545 }
4546
Douglas Gregor86d142a2009-10-08 07:24:58 +00004547 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4548 cast<VarDecl>(InstantiatedFrom),
4549 TSK_ExplicitSpecialization);
4550 } else {
4551 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004552 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4553 if (InstantiationClass->getTemplateSpecializationKind() ==
4554 TSK_ImplicitInstantiation) {
4555 InstantiationClass->setTemplateSpecializationKind(
4556 TSK_ExplicitSpecialization);
4557 InstantiationClass->setLocation(Member->getLocation());
4558 }
4559
Douglas Gregor86d142a2009-10-08 07:24:58 +00004560 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
Douglas Gregorbbe8f462009-10-08 15:14:33 +00004561 cast<CXXRecordDecl>(InstantiatedFrom),
4562 TSK_ExplicitSpecialization);
Douglas Gregor86d142a2009-10-08 07:24:58 +00004563 }
4564
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004565 // Save the caller the trouble of having to figure out which declaration
4566 // this specialization matches.
John McCall1f82f242009-11-18 22:49:29 +00004567 Previous.clear();
4568 Previous.addDecl(Instantiation);
Douglas Gregor5c0405d2009-10-07 22:35:40 +00004569 return false;
4570}
4571
Douglas Gregore47f5a72009-10-14 23:41:34 +00004572/// \brief Check the scope of an explicit instantiation.
4573static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4574 SourceLocation InstLoc,
4575 bool WasQualifiedName) {
4576 DeclContext *ExpectedContext
4577 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4578 DeclContext *CurContext = S.CurContext->getLookupContext();
4579
4580 // C++0x [temp.explicit]p2:
4581 // An explicit instantiation shall appear in an enclosing namespace of its
4582 // template.
4583 //
4584 // This is DR275, which we do not retroactively apply to C++98/03.
4585 if (S.getLangOptions().CPlusPlus0x &&
4586 !CurContext->Encloses(ExpectedContext)) {
4587 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004588 S.Diag(InstLoc,
4589 S.getLangOptions().CPlusPlus0x?
4590 diag::err_explicit_instantiation_out_of_scope
4591 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004592 << D << NS;
4593 else
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004594 S.Diag(InstLoc,
4595 S.getLangOptions().CPlusPlus0x?
4596 diag::err_explicit_instantiation_must_be_global
4597 : diag::warn_explicit_instantiation_out_of_scope_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004598 << D;
4599 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4600 return;
4601 }
4602
4603 // C++0x [temp.explicit]p2:
4604 // If the name declared in the explicit instantiation is an unqualified
4605 // name, the explicit instantiation shall appear in the namespace where
4606 // its template is declared or, if that namespace is inline (7.3.1), any
4607 // namespace from its enclosing namespace set.
4608 if (WasQualifiedName)
4609 return;
4610
4611 if (CurContext->Equals(ExpectedContext))
4612 return;
4613
Douglas Gregorc97d7a22010-05-11 17:39:34 +00004614 S.Diag(InstLoc,
4615 S.getLangOptions().CPlusPlus0x?
4616 diag::err_explicit_instantiation_unqualified_wrong_namespace
4617 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
Douglas Gregore47f5a72009-10-14 23:41:34 +00004618 << D << ExpectedContext;
4619 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4620}
4621
4622/// \brief Determine whether the given scope specifier has a template-id in it.
4623static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4624 if (!SS.isSet())
4625 return false;
4626
4627 // C++0x [temp.explicit]p2:
4628 // If the explicit instantiation is for a member function, a member class
4629 // or a static data member of a class template specialization, the name of
4630 // the class template specialization in the qualified-id for the member
4631 // name shall be a simple-template-id.
4632 //
4633 // C++98 has the same restriction, just worded differently.
4634 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4635 NNS; NNS = NNS->getPrefix())
4636 if (Type *T = NNS->getAsType())
4637 if (isa<TemplateSpecializationType>(T))
4638 return true;
4639
4640 return false;
4641}
4642
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004643// Explicit instantiation of a class template specialization
Douglas Gregora1f49972009-05-13 00:25:59 +00004644Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004645Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004646 SourceLocation ExternLoc,
4647 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004648 unsigned TagSpec,
Douglas Gregora1f49972009-05-13 00:25:59 +00004649 SourceLocation KWLoc,
4650 const CXXScopeSpec &SS,
4651 TemplateTy TemplateD,
4652 SourceLocation TemplateNameLoc,
4653 SourceLocation LAngleLoc,
4654 ASTTemplateArgsPtr TemplateArgsIn,
Douglas Gregora1f49972009-05-13 00:25:59 +00004655 SourceLocation RAngleLoc,
4656 AttributeList *Attr) {
4657 // Find the class template we're specializing
4658 TemplateName Name = TemplateD.getAsVal<TemplateName>();
Mike Stump11289f42009-09-09 15:08:12 +00004659 ClassTemplateDecl *ClassTemplate
Douglas Gregora1f49972009-05-13 00:25:59 +00004660 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4661
4662 // Check that the specialization uses the same tag kind as the
4663 // original template.
Abramo Bagnara6150c882010-05-11 21:36:43 +00004664 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4665 assert(Kind != TTK_Enum &&
4666 "Invalid enum tag in class template explicit instantiation!");
Douglas Gregord9034f02009-05-14 16:41:31 +00004667 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
Mike Stump11289f42009-09-09 15:08:12 +00004668 Kind, KWLoc,
Douglas Gregord9034f02009-05-14 16:41:31 +00004669 *ClassTemplate->getIdentifier())) {
Mike Stump11289f42009-09-09 15:08:12 +00004670 Diag(KWLoc, diag::err_use_with_wrong_tag)
Douglas Gregora1f49972009-05-13 00:25:59 +00004671 << ClassTemplate
Douglas Gregora771f462010-03-31 17:46:05 +00004672 << FixItHint::CreateReplacement(KWLoc,
Douglas Gregora1f49972009-05-13 00:25:59 +00004673 ClassTemplate->getTemplatedDecl()->getKindName());
Mike Stump11289f42009-09-09 15:08:12 +00004674 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
Douglas Gregora1f49972009-05-13 00:25:59 +00004675 diag::note_previous_use);
4676 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4677 }
4678
Douglas Gregore47f5a72009-10-14 23:41:34 +00004679 // C++0x [temp.explicit]p2:
4680 // There are two forms of explicit instantiation: an explicit instantiation
4681 // definition and an explicit instantiation declaration. An explicit
4682 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor54888652009-10-07 00:13:32 +00004683 TemplateSpecializationKind TSK
4684 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4685 : TSK_ExplicitInstantiationDeclaration;
4686
Douglas Gregora1f49972009-05-13 00:25:59 +00004687 // Translate the parser's template argument list in our AST format.
John McCall6b51f282009-11-23 01:53:49 +00004688 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
Douglas Gregorb53edfb2009-11-10 19:49:08 +00004689 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
Douglas Gregora1f49972009-05-13 00:25:59 +00004690
4691 // Check that the template argument list is well-formed for this
4692 // template.
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004693 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4694 TemplateArgs.size());
John McCall6b51f282009-11-23 01:53:49 +00004695 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4696 TemplateArgs, false, Converted))
Douglas Gregora1f49972009-05-13 00:25:59 +00004697 return true;
4698
Mike Stump11289f42009-09-09 15:08:12 +00004699 assert((Converted.structuredSize() ==
Douglas Gregora1f49972009-05-13 00:25:59 +00004700 ClassTemplate->getTemplateParameters()->size()) &&
4701 "Converted template argument list is too short!");
Mike Stump11289f42009-09-09 15:08:12 +00004702
Douglas Gregora1f49972009-05-13 00:25:59 +00004703 // Find the class template specialization declaration that
4704 // corresponds to these arguments.
4705 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00004706 ClassTemplateSpecializationDecl::Profile(ID,
Anders Carlsson5947ddf2009-06-23 01:26:57 +00004707 Converted.getFlatArguments(),
Douglas Gregor00044172009-07-29 16:09:57 +00004708 Converted.flatSize(),
4709 Context);
Douglas Gregora1f49972009-05-13 00:25:59 +00004710 void *InsertPos = 0;
4711 ClassTemplateSpecializationDecl *PrevDecl
4712 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4713
Douglas Gregor54888652009-10-07 00:13:32 +00004714 // C++0x [temp.explicit]p2:
4715 // [...] An explicit instantiation shall appear in an enclosing
4716 // namespace of its template. [...]
4717 //
4718 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004719 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4720 SS.isSet());
Douglas Gregor54888652009-10-07 00:13:32 +00004721
Douglas Gregora1f49972009-05-13 00:25:59 +00004722 ClassTemplateSpecializationDecl *Specialization = 0;
4723
Douglas Gregor0681a352009-11-25 06:01:46 +00004724 bool ReusedDecl = false;
Douglas Gregora1f49972009-05-13 00:25:59 +00004725 if (PrevDecl) {
Douglas Gregor12e49d32009-10-15 22:53:21 +00004726 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004727 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
Douglas Gregor12e49d32009-10-15 22:53:21 +00004728 PrevDecl,
4729 PrevDecl->getSpecializationKind(),
4730 PrevDecl->getPointOfInstantiation(),
4731 SuppressNew))
Douglas Gregora1f49972009-05-13 00:25:59 +00004732 return DeclPtrTy::make(PrevDecl);
Douglas Gregora1f49972009-05-13 00:25:59 +00004733
Douglas Gregor12e49d32009-10-15 22:53:21 +00004734 if (SuppressNew)
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004735 return DeclPtrTy::make(PrevDecl);
Douglas Gregor12e49d32009-10-15 22:53:21 +00004736
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004737 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4738 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4739 // Since the only prior class template specialization with these
4740 // arguments was referenced but not declared, reuse that
4741 // declaration node as our own, updating its source location to
4742 // reflect our new declaration.
4743 Specialization = PrevDecl;
4744 Specialization->setLocation(TemplateNameLoc);
4745 PrevDecl = 0;
Douglas Gregor0681a352009-11-25 06:01:46 +00004746 ReusedDecl = true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004747 }
Douglas Gregor12e49d32009-10-15 22:53:21 +00004748 }
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004749
4750 if (!Specialization) {
Douglas Gregora1f49972009-05-13 00:25:59 +00004751 // Create a new class template specialization declaration node for
4752 // this explicit specialization.
4753 Specialization
Douglas Gregore9029562010-05-06 00:28:52 +00004754 = ClassTemplateSpecializationDecl::Create(Context, Kind,
Douglas Gregora1f49972009-05-13 00:25:59 +00004755 ClassTemplate->getDeclContext(),
4756 TemplateNameLoc,
4757 ClassTemplate,
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004758 Converted, PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00004759 SetNestedNameSpecifier(Specialization, SS);
Douglas Gregora1f49972009-05-13 00:25:59 +00004760
Douglas Gregor4aa04b12009-09-11 21:19:12 +00004761 if (PrevDecl) {
4762 // Remove the previous declaration from the folding set, since we want
4763 // to introduce a new declaration.
4764 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4765 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4766 }
4767
4768 // Insert the new specialization.
4769 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
Douglas Gregora1f49972009-05-13 00:25:59 +00004770 }
4771
4772 // Build the fully-sugared type for this explicit instantiation as
4773 // the user wrote in the explicit instantiation itself. This means
4774 // that we'll pretty-print the type retrieved from the
4775 // specialization's declaration the way that the user actually wrote
4776 // the explicit instantiation, rather than formatting the name based
4777 // on the "canonical" representation used to store the template
4778 // arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00004779 TypeSourceInfo *WrittenTy
4780 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4781 TemplateArgs,
Douglas Gregora1f49972009-05-13 00:25:59 +00004782 Context.getTypeDeclType(Specialization));
4783 Specialization->setTypeAsWritten(WrittenTy);
4784 TemplateArgsIn.release();
4785
Douglas Gregor0681a352009-11-25 06:01:46 +00004786 if (!ReusedDecl) {
4787 // Add the explicit instantiation into its lexical context. However,
4788 // since explicit instantiations are never found by name lookup, we
4789 // just put it into the declaration context directly.
4790 Specialization->setLexicalDeclContext(CurContext);
4791 CurContext->addDecl(Specialization);
4792 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004793
4794 // C++ [temp.explicit]p3:
Douglas Gregora1f49972009-05-13 00:25:59 +00004795 // A definition of a class template or class member template
4796 // shall be in scope at the point of the explicit instantiation of
4797 // the class template or class member template.
4798 //
4799 // This check comes when we actually try to perform the
4800 // instantiation.
Douglas Gregor12e49d32009-10-15 22:53:21 +00004801 ClassTemplateSpecializationDecl *Def
4802 = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004803 Specialization->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004804 if (!Def)
Douglas Gregoref6ab412009-10-27 06:26:26 +00004805 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
Douglas Gregor88d292c2010-05-13 16:44:06 +00004806 else if (TSK == TSK_ExplicitInstantiationDefinition)
4807 MarkVTableUsed(TemplateNameLoc, Specialization, true);
4808
Douglas Gregor1d957a32009-10-27 18:42:08 +00004809 // Instantiate the members of this class template specialization.
4810 Def = cast_or_null<ClassTemplateSpecializationDecl>(
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004811 Specialization->getDefinition());
Rafael Espindola8d04f062010-03-22 23:12:48 +00004812 if (Def) {
Rafael Espindolafa1708fd2010-03-23 19:55:22 +00004813 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4814
4815 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4816 // TSK_ExplicitInstantiationDefinition
4817 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4818 TSK == TSK_ExplicitInstantiationDefinition)
4819 Def->setTemplateSpecializationKind(TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004820
Douglas Gregor12e49d32009-10-15 22:53:21 +00004821 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
Rafael Espindola8d04f062010-03-22 23:12:48 +00004822 }
Douglas Gregora1f49972009-05-13 00:25:59 +00004823
4824 return DeclPtrTy::make(Specialization);
4825}
4826
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004827// Explicit instantiation of a member class of a class template.
4828Sema::DeclResult
Mike Stump11289f42009-09-09 15:08:12 +00004829Sema::ActOnExplicitInstantiation(Scope *S,
Douglas Gregor43e75172009-09-04 06:33:52 +00004830 SourceLocation ExternLoc,
4831 SourceLocation TemplateLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004832 unsigned TagSpec,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004833 SourceLocation KWLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004834 CXXScopeSpec &SS,
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004835 IdentifierInfo *Name,
4836 SourceLocation NameLoc,
4837 AttributeList *Attr) {
4838
Douglas Gregord6ab8742009-05-28 23:31:59 +00004839 bool Owned = false;
John McCall7f41d982009-09-11 04:59:25 +00004840 bool IsDependent = false;
John McCall9bb74a52009-07-31 02:45:11 +00004841 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
Douglas Gregore93e46c2009-07-22 23:48:44 +00004842 KWLoc, SS, Name, NameLoc, Attr, AS_none,
John McCall7f41d982009-09-11 04:59:25 +00004843 MultiTemplateParamsArg(*this, 0, 0),
4844 Owned, IsDependent);
4845 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4846
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004847 if (!TagD)
4848 return true;
4849
4850 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4851 if (Tag->isEnum()) {
4852 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4853 << Context.getTypeDeclType(Tag);
4854 return true;
4855 }
4856
Douglas Gregorb8006faf2009-05-27 17:30:49 +00004857 if (Tag->isInvalidDecl())
4858 return true;
Douglas Gregore47f5a72009-10-14 23:41:34 +00004859
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004860 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4861 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4862 if (!Pattern) {
4863 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4864 << Context.getTypeDeclType(Record);
4865 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4866 return true;
4867 }
4868
Douglas Gregore47f5a72009-10-14 23:41:34 +00004869 // C++0x [temp.explicit]p2:
4870 // If the explicit instantiation is for a class or member class, the
4871 // elaborated-type-specifier in the declaration shall include a
4872 // simple-template-id.
4873 //
4874 // C++98 has the same restriction, just worded differently.
4875 if (!ScopeSpecifierHasTemplateId(SS))
4876 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4877 << Record << SS.getRange();
4878
4879 // C++0x [temp.explicit]p2:
4880 // There are two forms of explicit instantiation: an explicit instantiation
4881 // definition and an explicit instantiation declaration. An explicit
4882 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor5d851972009-10-14 21:46:58 +00004883 TemplateSpecializationKind TSK
4884 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4885 : TSK_ExplicitInstantiationDeclaration;
4886
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004887 // C++0x [temp.explicit]p2:
4888 // [...] An explicit instantiation shall appear in an enclosing
4889 // namespace of its template. [...]
4890 //
4891 // This is C++ DR 275.
Douglas Gregore47f5a72009-10-14 23:41:34 +00004892 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004893
4894 // Verify that it is okay to explicitly instantiate here.
Douglas Gregor8f003d02009-10-15 18:07:02 +00004895 CXXRecordDecl *PrevDecl
4896 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004897 if (!PrevDecl && Record->getDefinition())
Douglas Gregor8f003d02009-10-15 18:07:02 +00004898 PrevDecl = Record;
4899 if (PrevDecl) {
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004900 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4901 bool SuppressNew = false;
4902 assert(MSInfo && "No member specialization information?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00004903 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00004904 PrevDecl,
4905 MSInfo->getTemplateSpecializationKind(),
4906 MSInfo->getPointOfInstantiation(),
4907 SuppressNew))
4908 return true;
4909 if (SuppressNew)
4910 return TagD;
4911 }
4912
Douglas Gregor12e49d32009-10-15 22:53:21 +00004913 CXXRecordDecl *RecordDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004914 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor12e49d32009-10-15 22:53:21 +00004915 if (!RecordDef) {
Douglas Gregor68edf132009-10-15 12:53:22 +00004916 // C++ [temp.explicit]p3:
4917 // A definition of a member class of a class template shall be in scope
4918 // at the point of an explicit instantiation of the member class.
4919 CXXRecordDecl *Def
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004920 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Douglas Gregor68edf132009-10-15 12:53:22 +00004921 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00004922 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4923 << 0 << Record->getDeclName() << Record->getDeclContext();
Douglas Gregor68edf132009-10-15 12:53:22 +00004924 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4925 << Pattern;
4926 return true;
Douglas Gregor1d957a32009-10-27 18:42:08 +00004927 } else {
4928 if (InstantiateClass(NameLoc, Record, Def,
4929 getTemplateInstantiationArgs(Record),
4930 TSK))
4931 return true;
4932
Douglas Gregor0a5a2212010-02-11 01:04:33 +00004933 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00004934 if (!RecordDef)
4935 return true;
4936 }
4937 }
4938
4939 // Instantiate all of the members of the class.
4940 InstantiateClassMembers(NameLoc, RecordDef,
4941 getTemplateInstantiationArgs(Record), TSK);
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004942
Douglas Gregor88d292c2010-05-13 16:44:06 +00004943 if (TSK == TSK_ExplicitInstantiationDefinition)
4944 MarkVTableUsed(NameLoc, RecordDef, true);
4945
Mike Stump87c57ac2009-05-16 07:39:55 +00004946 // FIXME: We don't have any representation for explicit instantiations of
4947 // member classes. Such a representation is not needed for compilation, but it
4948 // should be available for clients that want to see all of the declarations in
4949 // the source code.
Douglas Gregor2ec748c2009-05-14 00:28:11 +00004950 return TagD;
4951}
4952
Douglas Gregor450f00842009-09-25 18:43:00 +00004953Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4954 SourceLocation ExternLoc,
4955 SourceLocation TemplateLoc,
4956 Declarator &D) {
4957 // Explicit instantiations always require a name.
4958 DeclarationName Name = GetNameForDeclarator(D);
4959 if (!Name) {
4960 if (!D.isInvalidType())
4961 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4962 diag::err_explicit_instantiation_requires_name)
4963 << D.getDeclSpec().getSourceRange()
4964 << D.getSourceRange();
4965
4966 return true;
4967 }
4968
4969 // The scope passed in may not be a decl scope. Zip up the scope tree until
4970 // we find one that is.
4971 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4972 (S->getFlags() & Scope::TemplateParamScope) != 0)
4973 S = S->getParent();
4974
4975 // Determine the type of the declaration.
John McCall8cb7bdf2010-06-04 23:28:52 +00004976 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
4977 QualType R = T->getType();
Douglas Gregor450f00842009-09-25 18:43:00 +00004978 if (R.isNull())
4979 return true;
4980
4981 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4982 // Cannot explicitly instantiate a typedef.
4983 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4984 << Name;
4985 return true;
4986 }
4987
Douglas Gregor3c74d412009-10-14 20:14:33 +00004988 // C++0x [temp.explicit]p1:
4989 // [...] An explicit instantiation of a function template shall not use the
4990 // inline or constexpr specifiers.
4991 // Presumably, this also applies to member functions of class templates as
4992 // well.
4993 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4994 Diag(D.getDeclSpec().getInlineSpecLoc(),
4995 diag::err_explicit_instantiation_inline)
Douglas Gregora771f462010-03-31 17:46:05 +00004996 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
Douglas Gregor3c74d412009-10-14 20:14:33 +00004997
4998 // FIXME: check for constexpr specifier.
4999
Douglas Gregore47f5a72009-10-14 23:41:34 +00005000 // C++0x [temp.explicit]p2:
5001 // There are two forms of explicit instantiation: an explicit instantiation
5002 // definition and an explicit instantiation declaration. An explicit
5003 // instantiation declaration begins with the extern keyword. [...]
Douglas Gregor450f00842009-09-25 18:43:00 +00005004 TemplateSpecializationKind TSK
5005 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5006 : TSK_ExplicitInstantiationDeclaration;
Douglas Gregore47f5a72009-10-14 23:41:34 +00005007
John McCall27b18f82009-11-17 02:14:36 +00005008 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
5009 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
Douglas Gregor450f00842009-09-25 18:43:00 +00005010
5011 if (!R->isFunctionType()) {
5012 // C++ [temp.explicit]p1:
5013 // A [...] static data member of a class template can be explicitly
5014 // instantiated from the member definition associated with its class
5015 // template.
John McCall27b18f82009-11-17 02:14:36 +00005016 if (Previous.isAmbiguous())
5017 return true;
Douglas Gregor450f00842009-09-25 18:43:00 +00005018
John McCall67c00872009-12-02 08:25:40 +00005019 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
Douglas Gregor450f00842009-09-25 18:43:00 +00005020 if (!Prev || !Prev->isStaticDataMember()) {
5021 // We expect to see a data data member here.
5022 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5023 << Name;
5024 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5025 P != PEnd; ++P)
John McCall9f3059a2009-10-09 21:13:30 +00005026 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
Douglas Gregor450f00842009-09-25 18:43:00 +00005027 return true;
5028 }
5029
5030 if (!Prev->getInstantiatedFromStaticDataMember()) {
5031 // FIXME: Check for explicit specialization?
5032 Diag(D.getIdentifierLoc(),
5033 diag::err_explicit_instantiation_data_member_not_instantiated)
5034 << Prev;
5035 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5036 // FIXME: Can we provide a note showing where this was declared?
5037 return true;
5038 }
5039
Douglas Gregore47f5a72009-10-14 23:41:34 +00005040 // C++0x [temp.explicit]p2:
5041 // If the explicit instantiation is for a member function, a member class
5042 // or a static data member of a class template specialization, the name of
5043 // the class template specialization in the qualified-id for the member
5044 // name shall be a simple-template-id.
5045 //
5046 // C++98 has the same restriction, just worded differently.
5047 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5048 Diag(D.getIdentifierLoc(),
5049 diag::err_explicit_instantiation_without_qualified_id)
5050 << Prev << D.getCXXScopeSpec().getRange();
5051
5052 // Check the scope of this explicit instantiation.
5053 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5054
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005055 // Verify that it is okay to explicitly instantiate here.
5056 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5057 assert(MSInfo && "Missing static data member specialization info?");
5058 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005059 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
Douglas Gregord6ba93d2009-10-15 15:54:05 +00005060 MSInfo->getTemplateSpecializationKind(),
5061 MSInfo->getPointOfInstantiation(),
5062 SuppressNew))
5063 return true;
5064 if (SuppressNew)
5065 return DeclPtrTy();
5066
Douglas Gregor450f00842009-09-25 18:43:00 +00005067 // Instantiate static data member.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005068 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005069 if (TSK == TSK_ExplicitInstantiationDefinition)
Douglas Gregora8b89d22009-10-15 14:05:49 +00005070 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5071 /*DefinitionRequired=*/true);
Douglas Gregor450f00842009-09-25 18:43:00 +00005072
5073 // FIXME: Create an ExplicitInstantiation node?
5074 return DeclPtrTy();
5075 }
5076
Douglas Gregor0e876e02009-09-25 23:53:26 +00005077 // If the declarator is a template-id, translate the parser's template
5078 // argument list into our AST format.
Douglas Gregord90fd522009-09-25 21:45:23 +00005079 bool HasExplicitTemplateArgs = false;
John McCall6b51f282009-11-23 01:53:49 +00005080 TemplateArgumentListInfo TemplateArgs;
Douglas Gregor7861a802009-11-03 01:35:08 +00005081 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5082 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
John McCall6b51f282009-11-23 01:53:49 +00005083 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5084 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
Douglas Gregord90fd522009-09-25 21:45:23 +00005085 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5086 TemplateId->getTemplateArgs(),
Douglas Gregord90fd522009-09-25 21:45:23 +00005087 TemplateId->NumArgs);
John McCall6b51f282009-11-23 01:53:49 +00005088 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
Douglas Gregord90fd522009-09-25 21:45:23 +00005089 HasExplicitTemplateArgs = true;
Douglas Gregorf343fd82009-10-01 23:51:25 +00005090 TemplateArgsPtr.release();
Douglas Gregord90fd522009-09-25 21:45:23 +00005091 }
Douglas Gregor0e876e02009-09-25 23:53:26 +00005092
Douglas Gregor450f00842009-09-25 18:43:00 +00005093 // C++ [temp.explicit]p1:
5094 // A [...] function [...] can be explicitly instantiated from its template.
5095 // A member function [...] of a class template can be explicitly
5096 // instantiated from the member definition associated with its class
5097 // template.
John McCall58cc69d2010-01-27 01:50:18 +00005098 UnresolvedSet<8> Matches;
Douglas Gregor450f00842009-09-25 18:43:00 +00005099 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5100 P != PEnd; ++P) {
5101 NamedDecl *Prev = *P;
Douglas Gregord90fd522009-09-25 21:45:23 +00005102 if (!HasExplicitTemplateArgs) {
5103 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5104 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5105 Matches.clear();
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005106
John McCall58cc69d2010-01-27 01:50:18 +00005107 Matches.addDecl(Method, P.getAccess());
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005108 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5109 break;
Douglas Gregord90fd522009-09-25 21:45:23 +00005110 }
Douglas Gregor450f00842009-09-25 18:43:00 +00005111 }
5112 }
5113
5114 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5115 if (!FunTmpl)
5116 continue;
5117
John McCallbc077cf2010-02-08 23:07:23 +00005118 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
Douglas Gregor450f00842009-09-25 18:43:00 +00005119 FunctionDecl *Specialization = 0;
5120 if (TemplateDeductionResult TDK
Douglas Gregorea0a0a92010-01-11 18:40:55 +00005121 = DeduceTemplateArguments(FunTmpl,
John McCall6b51f282009-11-23 01:53:49 +00005122 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
Douglas Gregor450f00842009-09-25 18:43:00 +00005123 R, Specialization, Info)) {
5124 // FIXME: Keep track of almost-matches?
5125 (void)TDK;
5126 continue;
5127 }
5128
John McCall58cc69d2010-01-27 01:50:18 +00005129 Matches.addDecl(Specialization, P.getAccess());
Douglas Gregor450f00842009-09-25 18:43:00 +00005130 }
5131
5132 // Find the most specialized function template specialization.
John McCall58cc69d2010-01-27 01:50:18 +00005133 UnresolvedSetIterator Result
5134 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
Douglas Gregor450f00842009-09-25 18:43:00 +00005135 D.getIdentifierLoc(),
Douglas Gregor89336232010-03-29 23:34:08 +00005136 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5137 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5138 PDiag(diag::note_explicit_instantiation_candidate));
Douglas Gregor450f00842009-09-25 18:43:00 +00005139
John McCall58cc69d2010-01-27 01:50:18 +00005140 if (Result == Matches.end())
Douglas Gregor450f00842009-09-25 18:43:00 +00005141 return true;
John McCall58cc69d2010-01-27 01:50:18 +00005142
5143 // Ignore access control bits, we don't need them for redeclaration checking.
5144 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
Douglas Gregor450f00842009-09-25 18:43:00 +00005145
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005146 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
Douglas Gregor450f00842009-09-25 18:43:00 +00005147 Diag(D.getIdentifierLoc(),
5148 diag::err_explicit_instantiation_member_function_not_instantiated)
5149 << Specialization
5150 << (Specialization->getTemplateSpecializationKind() ==
5151 TSK_ExplicitSpecialization);
5152 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5153 return true;
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005154 }
Douglas Gregore47f5a72009-10-14 23:41:34 +00005155
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005156 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
Douglas Gregor8f003d02009-10-15 18:07:02 +00005157 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5158 PrevDecl = Specialization;
5159
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005160 if (PrevDecl) {
5161 bool SuppressNew = false;
Douglas Gregor1d957a32009-10-27 18:42:08 +00005162 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005163 PrevDecl,
5164 PrevDecl->getTemplateSpecializationKind(),
5165 PrevDecl->getPointOfInstantiation(),
5166 SuppressNew))
5167 return true;
5168
5169 // FIXME: We may still want to build some representation of this
5170 // explicit specialization.
5171 if (SuppressNew)
5172 return DeclPtrTy();
5173 }
Anders Carlsson65e6d132009-11-24 05:34:41 +00005174
5175 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005176
5177 if (TSK == TSK_ExplicitInstantiationDefinition)
5178 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5179 false, /*DefinitionRequired=*/true);
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005180
Douglas Gregore47f5a72009-10-14 23:41:34 +00005181 // C++0x [temp.explicit]p2:
5182 // If the explicit instantiation is for a member function, a member class
5183 // or a static data member of a class template specialization, the name of
5184 // the class template specialization in the qualified-id for the member
5185 // name shall be a simple-template-id.
5186 //
5187 // C++98 has the same restriction, just worded differently.
Douglas Gregor3d7e69f2009-10-15 17:21:20 +00005188 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
Douglas Gregor7861a802009-11-03 01:35:08 +00005189 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
Douglas Gregore47f5a72009-10-14 23:41:34 +00005190 D.getCXXScopeSpec().isSet() &&
5191 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5192 Diag(D.getIdentifierLoc(),
5193 diag::err_explicit_instantiation_without_qualified_id)
5194 << Specialization << D.getCXXScopeSpec().getRange();
5195
5196 CheckExplicitInstantiationScope(*this,
5197 FunTmpl? (NamedDecl *)FunTmpl
5198 : Specialization->getInstantiatedFromMemberFunction(),
5199 D.getIdentifierLoc(),
5200 D.getCXXScopeSpec().isSet());
5201
Douglas Gregor450f00842009-09-25 18:43:00 +00005202 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5203 return DeclPtrTy();
5204}
5205
Douglas Gregor333489b2009-03-27 23:10:48 +00005206Sema::TypeResult
John McCall7f41d982009-09-11 04:59:25 +00005207Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5208 const CXXScopeSpec &SS, IdentifierInfo *Name,
5209 SourceLocation TagLoc, SourceLocation NameLoc) {
5210 // This has to hold, because SS is expected to be defined.
5211 assert(Name && "Expected a name in a dependent tag");
5212
5213 NestedNameSpecifier *NNS
5214 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5215 if (!NNS)
5216 return true;
5217
Abramo Bagnara6150c882010-05-11 21:36:43 +00005218 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
Daniel Dunbarf4b37e12010-04-01 16:50:48 +00005219
Douglas Gregorba41d012010-04-24 16:38:41 +00005220 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5221 Diag(NameLoc, diag::err_dependent_tag_decl)
Abramo Bagnara6150c882010-05-11 21:36:43 +00005222 << (TUK == TUK_Definition) << Kind << SS.getRange();
Douglas Gregorba41d012010-04-24 16:38:41 +00005223 return true;
5224 }
Abramo Bagnara6150c882010-05-11 21:36:43 +00005225
5226 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5227 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
John McCall7f41d982009-09-11 04:59:25 +00005228}
5229
5230Sema::TypeResult
Douglas Gregor333489b2009-03-27 23:10:48 +00005231Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5232 const IdentifierInfo &II, SourceLocation IdLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005233 NestedNameSpecifier *NNS
Douglas Gregor333489b2009-03-27 23:10:48 +00005234 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5235 if (!NNS)
5236 return true;
5237
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005238 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005239 TypenameLoc, SS.getRange(), IdLoc);
Douglas Gregorfe3d7d02009-04-01 21:51:26 +00005240 if (T.isNull())
5241 return true;
John McCall99b2fe52010-04-29 23:50:39 +00005242
5243 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5244 if (isa<DependentNameType>(T)) {
5245 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005246 TL.setKeywordLoc(TypenameLoc);
5247 TL.setQualifierRange(SS.getRange());
5248 TL.setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005249 } else {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005250 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005251 TL.setKeywordLoc(TypenameLoc);
5252 TL.setQualifierRange(SS.getRange());
5253 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005254 }
5255
5256 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor333489b2009-03-27 23:10:48 +00005257}
5258
Douglas Gregordce2b622009-04-01 00:28:59 +00005259Sema::TypeResult
5260Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5261 SourceLocation TemplateLoc, TypeTy *Ty) {
John McCallf7bcc812010-05-28 23:32:21 +00005262 TypeSourceInfo *InnerTSI = 0;
5263 QualType T = GetTypeFromParser(Ty, &InnerTSI);
Mike Stump11289f42009-09-09 15:08:12 +00005264 NestedNameSpecifier *NNS
Douglas Gregordce2b622009-04-01 00:28:59 +00005265 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
John McCallf7bcc812010-05-28 23:32:21 +00005266
5267 assert(isa<TemplateSpecializationType>(T) &&
5268 "Expected a template specialization type");
Douglas Gregordce2b622009-04-01 00:28:59 +00005269
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005270 if (computeDeclContext(SS, false)) {
5271 // If we can compute a declaration context, then the "typename"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005272 // keyword was superfluous. Just build an ElaboratedType to keep
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005273 // track of the nested-name-specifier.
John McCallf7bcc812010-05-28 23:32:21 +00005274
5275 // Push the inner type, preserving its source locations if possible.
5276 TypeLocBuilder Builder;
5277 if (InnerTSI)
5278 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5279 else
5280 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(TemplateLoc);
5281
Abramo Bagnara6150c882010-05-11 21:36:43 +00005282 T = Context.getElaboratedType(ETK_Typename, NNS, T);
John McCallf7bcc812010-05-28 23:32:21 +00005283 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5284 TL.setKeywordLoc(TypenameLoc);
5285 TL.setQualifierRange(SS.getRange());
5286
5287 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
John McCall99b2fe52010-04-29 23:50:39 +00005288 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregor12bbfe12009-09-02 13:05:45 +00005289 }
Mike Stump11289f42009-09-09 15:08:12 +00005290
John McCallf7bcc812010-05-28 23:32:21 +00005291 T = Context.getDependentNameType(ETK_Typename, NNS,
5292 cast<TemplateSpecializationType>(T));
John McCall99b2fe52010-04-29 23:50:39 +00005293 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5294 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
John McCallf7bcc812010-05-28 23:32:21 +00005295 TL.setKeywordLoc(TypenameLoc);
5296 TL.setQualifierRange(SS.getRange());
5297
5298 // FIXME: the inner type is a template here; remember its full source info
5299 TL.setNameLoc(InnerTSI ? InnerTSI->getTypeLoc().getBeginLoc() : TemplateLoc);
John McCall99b2fe52010-04-29 23:50:39 +00005300 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
Douglas Gregordce2b622009-04-01 00:28:59 +00005301}
5302
Douglas Gregor333489b2009-03-27 23:10:48 +00005303/// \brief Build the type that describes a C++ typename specifier,
5304/// e.g., "typename T::type".
5305QualType
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005306Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5307 NestedNameSpecifier *NNS, const IdentifierInfo &II,
Abramo Bagnarad7548482010-05-19 21:37:53 +00005308 SourceLocation KeywordLoc, SourceRange NNSRange,
5309 SourceLocation IILoc) {
John McCall0b66eb32010-05-01 00:40:08 +00005310 CXXScopeSpec SS;
5311 SS.setScopeRep(NNS);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005312 SS.setRange(NNSRange);
Douglas Gregor333489b2009-03-27 23:10:48 +00005313
John McCall0b66eb32010-05-01 00:40:08 +00005314 DeclContext *Ctx = computeDeclContext(SS);
5315 if (!Ctx) {
5316 // If the nested-name-specifier is dependent and couldn't be
5317 // resolved to a type, build a typename type.
5318 assert(NNS->isDependent());
5319 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005320 }
Douglas Gregor333489b2009-03-27 23:10:48 +00005321
John McCall0b66eb32010-05-01 00:40:08 +00005322 // If the nested-name-specifier refers to the current instantiation,
5323 // the "typename" keyword itself is superfluous. In C++03, the
5324 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5325 // allows such extraneous "typename" keywords, and we retroactively
5326 // apply this DR to C++03 code. In any case we continue.
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005327
John McCall0b66eb32010-05-01 00:40:08 +00005328 if (RequireCompleteDeclContext(SS, Ctx))
5329 return QualType();
Douglas Gregor333489b2009-03-27 23:10:48 +00005330
5331 DeclarationName Name(&II);
Abramo Bagnarad7548482010-05-19 21:37:53 +00005332 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
John McCall27b18f82009-11-17 02:14:36 +00005333 LookupQualifiedName(Result, Ctx);
Douglas Gregor333489b2009-03-27 23:10:48 +00005334 unsigned DiagID = 0;
5335 Decl *Referenced = 0;
John McCall27b18f82009-11-17 02:14:36 +00005336 switch (Result.getResultKind()) {
Douglas Gregor333489b2009-03-27 23:10:48 +00005337 case LookupResult::NotFound:
Douglas Gregore40876a2009-10-13 21:16:44 +00005338 DiagID = diag::err_typename_nested_not_found;
Douglas Gregor333489b2009-03-27 23:10:48 +00005339 break;
Douglas Gregord0d2ee02010-01-15 01:44:47 +00005340
5341 case LookupResult::NotFoundInCurrentInstantiation:
5342 // Okay, it's a member of an unknown instantiation.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00005343 return Context.getDependentNameType(Keyword, NNS, &II);
Douglas Gregor333489b2009-03-27 23:10:48 +00005344
5345 case LookupResult::Found:
John McCall9f3059a2009-10-09 21:13:30 +00005346 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00005347 // We found a type. Build an ElaboratedType, since the
5348 // typename-specifier was just sugar.
5349 return Context.getElaboratedType(ETK_Typename, NNS,
5350 Context.getTypeDeclType(Type));
Douglas Gregor333489b2009-03-27 23:10:48 +00005351 }
5352
5353 DiagID = diag::err_typename_nested_not_type;
John McCall9f3059a2009-10-09 21:13:30 +00005354 Referenced = Result.getFoundDecl();
Douglas Gregor333489b2009-03-27 23:10:48 +00005355 break;
5356
John McCalle61f2ba2009-11-18 02:36:19 +00005357 case LookupResult::FoundUnresolvedValue:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00005358 llvm_unreachable("unresolved using decl in non-dependent context");
John McCalle61f2ba2009-11-18 02:36:19 +00005359 return QualType();
5360
Douglas Gregor333489b2009-03-27 23:10:48 +00005361 case LookupResult::FoundOverloaded:
5362 DiagID = diag::err_typename_nested_not_type;
5363 Referenced = *Result.begin();
5364 break;
5365
John McCall6538c932009-10-10 05:48:19 +00005366 case LookupResult::Ambiguous:
Douglas Gregor333489b2009-03-27 23:10:48 +00005367 return QualType();
5368 }
5369
5370 // If we get here, it's because name lookup did not find a
5371 // type. Emit an appropriate diagnostic and return an error.
Abramo Bagnarad7548482010-05-19 21:37:53 +00005372 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5373 IILoc);
5374 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
Douglas Gregor333489b2009-03-27 23:10:48 +00005375 if (Referenced)
5376 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5377 << Name;
5378 return QualType();
5379}
Douglas Gregor15acfb92009-08-06 16:20:37 +00005380
5381namespace {
5382 // See Sema::RebuildTypeInCurrentInstantiation
Benjamin Kramer337e3a52009-11-28 19:45:26 +00005383 class CurrentInstantiationRebuilder
Mike Stump11289f42009-09-09 15:08:12 +00005384 : public TreeTransform<CurrentInstantiationRebuilder> {
Douglas Gregor15acfb92009-08-06 16:20:37 +00005385 SourceLocation Loc;
5386 DeclarationName Entity;
Mike Stump11289f42009-09-09 15:08:12 +00005387
Douglas Gregor15acfb92009-08-06 16:20:37 +00005388 public:
Douglas Gregor14cf7522010-04-30 18:55:50 +00005389 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5390
Mike Stump11289f42009-09-09 15:08:12 +00005391 CurrentInstantiationRebuilder(Sema &SemaRef,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005392 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00005393 DeclarationName Entity)
5394 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
Douglas Gregor15acfb92009-08-06 16:20:37 +00005395 Loc(Loc), Entity(Entity) { }
Mike Stump11289f42009-09-09 15:08:12 +00005396
5397 /// \brief Determine whether the given type \p T has already been
Douglas Gregor15acfb92009-08-06 16:20:37 +00005398 /// transformed.
5399 ///
5400 /// For the purposes of type reconstruction, a type has already been
5401 /// transformed if it is NULL or if it is not dependent.
5402 bool AlreadyTransformed(QualType T) {
5403 return T.isNull() || !T->isDependentType();
5404 }
Mike Stump11289f42009-09-09 15:08:12 +00005405
5406 /// \brief Returns the location of the entity whose type is being
Douglas Gregor15acfb92009-08-06 16:20:37 +00005407 /// rebuilt.
5408 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +00005409
Douglas Gregor15acfb92009-08-06 16:20:37 +00005410 /// \brief Returns the name of the entity whose type is being rebuilt.
5411 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +00005412
Douglas Gregoref6ab412009-10-27 06:26:26 +00005413 /// \brief Sets the "base" location and entity when that
5414 /// information is known based on another transformation.
5415 void setBase(SourceLocation Loc, DeclarationName Entity) {
5416 this->Loc = Loc;
5417 this->Entity = Entity;
5418 }
5419
Douglas Gregor15acfb92009-08-06 16:20:37 +00005420 /// \brief Transforms an expression by returning the expression itself
5421 /// (an identity function).
5422 ///
5423 /// FIXME: This is completely unsafe; we will need to actually clone the
5424 /// expressions.
5425 Sema::OwningExprResult TransformExpr(Expr *E) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00005426 return getSema().Owned(E->Retain());
Douglas Gregor15acfb92009-08-06 16:20:37 +00005427 }
Mike Stump11289f42009-09-09 15:08:12 +00005428
Douglas Gregor15acfb92009-08-06 16:20:37 +00005429 /// \brief Transforms a typename type by determining whether the type now
5430 /// refers to a member of the current instantiation, and then
Abramo Bagnara6150c882010-05-11 21:36:43 +00005431 /// type-checking and building an ElaboratedType (when possible).
5432 QualType TransformDependentNameType(TypeLocBuilder &TLB,
5433 DependentNameTypeLoc TL,
5434 QualType ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005435 };
5436}
5437
Mike Stump11289f42009-09-09 15:08:12 +00005438QualType
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005439CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5440 DependentNameTypeLoc TL,
Douglas Gregorfe17d252010-02-16 19:09:40 +00005441 QualType ObjectType) {
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005442 DependentNameType *T = TL.getTypePtr();
John McCall550e0c22009-10-21 00:40:46 +00005443
Douglas Gregor15acfb92009-08-06 16:20:37 +00005444 NestedNameSpecifier *NNS
5445 = TransformNestedNameSpecifier(T->getQualifier(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00005446 TL.getQualifierRange(),
Douglas Gregorfe17d252010-02-16 19:09:40 +00005447 ObjectType);
Douglas Gregor15acfb92009-08-06 16:20:37 +00005448 if (!NNS)
5449 return QualType();
5450
5451 // If the nested-name-specifier did not change, and we cannot compute the
5452 // context corresponding to the nested-name-specifier, then this
5453 // typename type will not change; exit early.
5454 CXXScopeSpec SS;
Abramo Bagnarad7548482010-05-19 21:37:53 +00005455 SS.setRange(TL.getQualifierRange());
Douglas Gregor15acfb92009-08-06 16:20:37 +00005456 SS.setScopeRep(NNS);
John McCall0ad16662009-10-29 08:12:44 +00005457
5458 QualType Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005459 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
John McCall0ad16662009-10-29 08:12:44 +00005460 Result = QualType(T, 0);
Mike Stump11289f42009-09-09 15:08:12 +00005461
5462 // Rebuild the typename type, which will probably turn into a
Abramo Bagnara6150c882010-05-11 21:36:43 +00005463 // ElaboratedType.
John McCall0ad16662009-10-29 08:12:44 +00005464 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
Mike Stump11289f42009-09-09 15:08:12 +00005465 QualType NewTemplateId
Douglas Gregor15acfb92009-08-06 16:20:37 +00005466 = TransformType(QualType(TemplateId, 0));
5467 if (NewTemplateId.isNull())
5468 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005469
Douglas Gregor15acfb92009-08-06 16:20:37 +00005470 if (NNS == T->getQualifier() &&
5471 NewTemplateId == QualType(TemplateId, 0))
John McCall0ad16662009-10-29 08:12:44 +00005472 Result = QualType(T, 0);
5473 else
Abramo Bagnarad7548482010-05-19 21:37:53 +00005474 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
Douglas Gregor02085352010-03-31 20:19:30 +00005475 NNS, NewTemplateId);
John McCall0ad16662009-10-29 08:12:44 +00005476 } else
Abramo Bagnarad7548482010-05-19 21:37:53 +00005477 Result = getDerived().RebuildDependentNameType(T->getKeyword(), NNS,
5478 T->getIdentifier(),
5479 TL.getKeywordLoc(),
5480 TL.getQualifierRange(),
5481 TL.getNameLoc());
Mike Stump11289f42009-09-09 15:08:12 +00005482
Douglas Gregor281c4862010-03-07 23:26:22 +00005483 if (Result.isNull())
5484 return QualType();
5485
Abramo Bagnarad7548482010-05-19 21:37:53 +00005486 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5487 QualType NamedT = ElabT->getNamedType();
5488 if (isa<TemplateSpecializationType>(NamedT)) {
5489 TemplateSpecializationTypeLoc NamedTLoc
5490 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5491 // FIXME: fill locations
5492 NamedTLoc.initializeLocal(TL.getNameLoc());
5493 } else {
5494 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5495 }
5496 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5497 NewTL.setKeywordLoc(TL.getKeywordLoc());
5498 NewTL.setQualifierRange(TL.getQualifierRange());
5499 }
5500 else {
5501 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5502 NewTL.setKeywordLoc(TL.getKeywordLoc());
5503 NewTL.setQualifierRange(TL.getQualifierRange());
5504 NewTL.setNameLoc(TL.getNameLoc());
5505 }
John McCall0ad16662009-10-29 08:12:44 +00005506 return Result;
Douglas Gregor15acfb92009-08-06 16:20:37 +00005507}
5508
5509/// \brief Rebuilds a type within the context of the current instantiation.
5510///
Mike Stump11289f42009-09-09 15:08:12 +00005511/// The type \p T is part of the type of an out-of-line member definition of
Douglas Gregor15acfb92009-08-06 16:20:37 +00005512/// a class template (or class template partial specialization) that was parsed
Mike Stump11289f42009-09-09 15:08:12 +00005513/// and constructed before we entered the scope of the class template (or
Douglas Gregor15acfb92009-08-06 16:20:37 +00005514/// partial specialization thereof). This routine will rebuild that type now
5515/// that we have entered the declarator's scope, which may produce different
5516/// canonical types, e.g.,
5517///
5518/// \code
5519/// template<typename T>
5520/// struct X {
5521/// typedef T* pointer;
5522/// pointer data();
5523/// };
5524///
5525/// template<typename T>
5526/// typename X<T>::pointer X<T>::data() { ... }
5527/// \endcode
5528///
Douglas Gregorc1d2d8a2010-03-31 17:34:00 +00005529/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
Douglas Gregor15acfb92009-08-06 16:20:37 +00005530/// since we do not know that we can look into X<T> when we parsed the type.
5531/// This function will rebuild the type, performing the lookup of "pointer"
Abramo Bagnara6150c882010-05-11 21:36:43 +00005532/// in X<T> and returning an ElaboratedType whose canonical type is the same
Douglas Gregor15acfb92009-08-06 16:20:37 +00005533/// as the canonical type of T*, allowing the return types of the out-of-line
5534/// definition and the declaration to match.
John McCall99b2fe52010-04-29 23:50:39 +00005535TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5536 SourceLocation Loc,
5537 DeclarationName Name) {
5538 if (!T || !T->getType()->isDependentType())
Douglas Gregor15acfb92009-08-06 16:20:37 +00005539 return T;
Mike Stump11289f42009-09-09 15:08:12 +00005540
Douglas Gregor15acfb92009-08-06 16:20:37 +00005541 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5542 return Rebuilder.TransformType(T);
Benjamin Kramer854d7de2009-08-11 22:33:06 +00005543}
Douglas Gregorbe999392009-09-15 16:23:51 +00005544
John McCall99b2fe52010-04-29 23:50:39 +00005545bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5546 if (SS.isInvalid()) return true;
John McCall2408e322010-04-27 00:57:59 +00005547
5548 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5549 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5550 DeclarationName());
5551 NestedNameSpecifier *Rebuilt =
5552 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
John McCall99b2fe52010-04-29 23:50:39 +00005553 if (!Rebuilt) return true;
5554
5555 SS.setScopeRep(Rebuilt);
5556 return false;
John McCall2408e322010-04-27 00:57:59 +00005557}
5558
Douglas Gregorbe999392009-09-15 16:23:51 +00005559/// \brief Produces a formatted string that describes the binding of
5560/// template parameters to template arguments.
5561std::string
5562Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5563 const TemplateArgumentList &Args) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005564 // FIXME: For variadic templates, we'll need to get the structured list.
5565 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5566 Args.flat_size());
5567}
5568
5569std::string
5570Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5571 const TemplateArgument *Args,
5572 unsigned NumArgs) {
Douglas Gregorbe999392009-09-15 16:23:51 +00005573 std::string Result;
5574
Douglas Gregore62e6a02009-11-11 19:13:48 +00005575 if (!Params || Params->size() == 0 || NumArgs == 0)
Douglas Gregorbe999392009-09-15 16:23:51 +00005576 return Result;
5577
5578 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
Douglas Gregore62e6a02009-11-11 19:13:48 +00005579 if (I >= NumArgs)
5580 break;
5581
Douglas Gregorbe999392009-09-15 16:23:51 +00005582 if (I == 0)
5583 Result += "[with ";
5584 else
5585 Result += ", ";
5586
5587 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5588 Result += Id->getName();
5589 } else {
5590 Result += '$';
5591 Result += llvm::utostr(I);
5592 }
5593
5594 Result += " = ";
5595
5596 switch (Args[I].getKind()) {
5597 case TemplateArgument::Null:
5598 Result += "<no value>";
5599 break;
5600
5601 case TemplateArgument::Type: {
5602 std::string TypeStr;
5603 Args[I].getAsType().getAsStringInternal(TypeStr,
5604 Context.PrintingPolicy);
5605 Result += TypeStr;
5606 break;
5607 }
5608
5609 case TemplateArgument::Declaration: {
5610 bool Unnamed = true;
5611 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5612 if (ND->getDeclName()) {
5613 Unnamed = false;
5614 Result += ND->getNameAsString();
5615 }
5616 }
5617
5618 if (Unnamed) {
5619 Result += "<anonymous>";
5620 }
5621 break;
5622 }
5623
Douglas Gregor9167f8b2009-11-11 01:00:40 +00005624 case TemplateArgument::Template: {
5625 std::string Str;
5626 llvm::raw_string_ostream OS(Str);
5627 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5628 Result += OS.str();
5629 break;
5630 }
5631
Douglas Gregorbe999392009-09-15 16:23:51 +00005632 case TemplateArgument::Integral: {
5633 Result += Args[I].getAsIntegral()->toString(10);
5634 break;
5635 }
5636
5637 case TemplateArgument::Expression: {
Douglas Gregor33dcc2e2010-04-29 04:55:13 +00005638 // FIXME: This is non-optimal, since we're regurgitating the
5639 // expression we were given.
5640 std::string Str;
5641 {
5642 llvm::raw_string_ostream OS(Str);
5643 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5644 Context.PrintingPolicy);
5645 }
5646 Result += Str;
Douglas Gregorbe999392009-09-15 16:23:51 +00005647 break;
5648 }
5649
5650 case TemplateArgument::Pack:
5651 // FIXME: Format template argument packs
5652 Result += "<template argument pack>";
5653 break;
5654 }
5655 }
5656
5657 Result += ']';
5658 return Result;
5659}